code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include "common_gl.h"
#include "common_math.h"
#include "dynamicMesh.h"
#include "component.h"
#include "utilities.h"
#include "objloader.h"
#include "shader.h"
#include "pass.h"
#include "c_json/json.h"
static GLuint vao;
static GLuint color_ul, model_ul, view_ul, proj_ul;
static ShaderProgram* prog;
Texture* tex;
// new
static void uniformSetup(DynamicMeshManager* dmm, GLuint progID);
static void instanceSetup(DynamicMeshManager* dmm, DynamicMeshInstShader* vmem, MDIDrawInfo** di, int diCount, PassFrameParams* pfp);
void initDynamicMeshes() {
PassDrawable* pd;
// vao = makeVAO(vao_opts);
glexit("dynamic mesh vao");
// shader
prog = loadCombinedProgram("dynamicMeshInstanced");
model_ul = glGetUniformLocation(prog->id, "mModel");
view_ul = glGetUniformLocation(prog->id, "mView");
proj_ul = glGetUniformLocation(prog->id, "mProj");
color_ul = glGetUniformLocation(prog->id, "color");
glexit("dynamic mesh shader");
//tex = loadBitmapTexture("./assets/textures/gazebo-small.png");
//glActiveTexture(GL_TEXTURE0 + 8);
//glBindTexture(GL_TEXTURE_2D, tex->tex_id);
glexit("");
}
DynamicMesh* DynamicMesh_FromGLTF(gltf_file* gf, int meshIndex) {
DynamicMesh* m = pcalloc(m);
gltf_mesh* mesh = VEC_ITEM(&gf->meshes, meshIndex);
// TODO: fuse all primitives, convert to GL_TRIANGLES
VEC_EACH(&mesh->primitives, prim_i, prim) {
if(prim->mode != GL_TRIANGLES) {
continue;
}
m->polyMode = GL_TRIANGLES;
m->vertexCnt = prim->position->count;
m->vertices = calloc(1, m->vertexCnt * sizeof(*m->vertices));
Vector* positions = malloc(prim->position->bufferView->length);
gltf_readAccessor(prim->position, positions);
Vector* normals = malloc(prim->normal->bufferView->length);
gltf_readAccessor(prim->normal, normals);
uint16_t* texcoords = malloc(prim->texCoord0->bufferView->length);
gltf_readAccessor(prim->texCoord0, texcoords);
for(int i = 0; i < m->vertexCnt; i++) {
m->vertices[i].v = positions[i];
m->vertices[i].n = normals[i];
m->vertices[i].t.u = texcoords[i * 2];
m->vertices[i].t.v = texcoords[i * 2 + 1];
}
free(positions);
free(normals);
free(texcoords);
}
MemPoolT_init(&m->instances, sizeof(DynamicMeshInstance), 8192*8);
}
DynamicMesh* DynamicMeshFromOBJ(OBJContents* obj) {
int i;
DynamicMesh* m;
m = calloc(1, sizeof(*m));
m->vertexCnt = 3 * obj->faceCnt;
m->vertices = calloc(1, m->vertexCnt * sizeof(*m->vertices));
for(i = 0; i < m->vertexCnt; i++) {
vCopy(&obj->faces[i].v, &m->vertices[i].v);
vCopy(&obj->faces[i].n, &m->vertices[i].n);
if(vMag(&obj->faces[i].n) < 0.1) {
//printf("\n\n----broken normal: %d \n\n", i);
}
m->vertices[i].t.u = obj->faces[i].t.x * 65535;
m->vertices[i].t.v = obj->faces[i].t.y * 65535;
}
// index buffer
// TODO: fix above code to deduplicate vertices
m->indexWidth = 2;
m->indexCnt = m->vertexCnt;
m->indices.w16 = malloc(sizeof(*m->indices.w16) * m->indexCnt);
CHECK_OOM(m->indices.w16);
for(i = 0; i < m->vertexCnt; i++) m->indices.w16[i] = i;
printf("-----loaded---------------\n");
m->curFrameIndex = 0;
// HACK: hardcoded limit
MemPoolT_init(&m->instances, sizeof(DynamicMeshInstance), 8192 * 8);
VEC_INIT(&m->instMatrices);
return m;
}
DynamicMeshManager* dynamicMeshManager_alloc(GlobalSettings* gs) {
DynamicMeshManager* mm;
pcalloc(mm);
dynamicMeshManager_init(mm, gs);
return mm;
}
void dynamicMeshManager_init(DynamicMeshManager* dmm, GlobalSettings* gs) {
VEC_INIT(&dmm->meshes);
HT_init(&dmm->lookup, 6);
// VAO
static VAOConfig vao_opts[] = {
// per vertex
{0, 3, GL_FLOAT, 0, GL_FALSE}, // position
{0, 3, GL_FLOAT, 0, GL_FALSE}, // normal
{0, 2, GL_UNSIGNED_SHORT, 0, GL_TRUE}, // tex
// per instance
{1, 1, GL_MATRIX_EXT, 1, GL_FALSE}, // model-world matrix
/*
{1, 4, GL_FLOAT, 1, GL_FALSE}, // position
{1, 4, GL_FLOAT, 1, GL_FALSE}, // position
{1, 4, GL_FLOAT, 1, GL_FALSE}, // position
{1, 4, GL_FLOAT, 1, GL_FALSE}, // position
*/
{1, 4, GL_UNSIGNED_SHORT, 1, GL_FALSE}, // texture indices: diffuse, normal, metallic, roughness
{0, 0, 0}
};
dmm->maxInstances = gs->DynamicMeshManager_maxInstances;
printf("-->max: %d\n", dmm->maxInstances);
dmm->mdi = MultiDrawIndirect_alloc(vao_opts, dmm->maxInstances, "dynamicMeshManager");
dmm->mdi->isIndexed = 1;
dmm->mdi->indexSize = 2;
dmm->mdi->primMode = GL_TRIANGLES;
dmm->mdi->uniformSetup = (void*)uniformSetup;
dmm->mdi->instanceSetup = (void*)instanceSetup;
dmm->mdi->data = dmm;
}
void dynamicMeshManager_initGL(DynamicMeshManager* dmm, GlobalSettings* gs) {
MultiDrawIndirect_initGL(dmm->mdi);
}
// returns the index of the instance
DynamicMeshInstance* dynamicMeshManager_addInstance(DynamicMeshManager* mm, int meshIndex, const DynamicMeshInstance* smi) {
DynamicMesh* msh;
DynamicMeshInstance* s, *perm;
if(meshIndex >= VEC_LEN(&mm->meshes)) {
fprintf(stderr, "mesh manager addInstance out of bounds: %d, %d\n", (int)VEC_LEN(&mm->meshes), meshIndex);
return -1;
}
mm->totalInstances++;
assert(mm->totalInstances <= mm->maxInstances);
//printf("adding instance: %d ", meshIndex);
msh = VEC_DATA(&mm->meshes)[meshIndex];
perm = MemPoolT_malloc(&msh->instances);
*perm = *smi;
VEC_INC(&msh->instMatrices);
//printf("add instance: %d", mm->totalInstances, VEC_LEN(&msh->instances[0]));
return perm;
}
// returns the index of the instance
int dynamicMeshManager_lookupName(DynamicMeshManager* mm, char* name) {
int64_t index;
if(!HT_get(&mm->lookup, name, &index)) {
printf("dynamic mesh found: %s -> %d\n", name, index);
return index;
}
printf("dynamic mesh not found: %s\n", name);
return -1;
}
// returns the index if the mesh
int dynamicMeshManager_addMesh(DynamicMeshManager* mm, char* name, DynamicMesh* sm) {
int index;
MDIDrawInfo* di = pcalloc(di);
*di = (MDIDrawInfo){
.vertices = sm->vertices,
.vertexCount = sm->vertexCnt,
.indices = sm->indices.w16,
.indexCount = sm->indexCnt,
};
MultiDrawIndirect_addMesh(mm->mdi, di);
VEC_PUSH(&mm->meshes, sm);
//mm->totalVertices += sm->vertexCnt;
//mm->totalIndices += sm->indexCnt;
index = VEC_LEN(&mm->meshes);
HT_set(&mm->lookup, name, index -1);
return index - 1;
}
// should only used for initial setup
void dynamicMeshManager_updateGeometry(DynamicMeshManager* mm) {
MultiDrawIndirect_updateGeometry(mm->mdi);
}
static void instanceSetup(DynamicMeshManager* dmm, DynamicMeshInstShader* vmem, MDIDrawInfo** di, int diCount, PassFrameParams* pfp) {
//void dynamicMeshManager_updateMatrices(DynamicMeshManager* dmm, PassFrameParams* pfp) {
int mesh_index, i, j;
size_t off = 0;
// make sure the matrix buffer has enough space
if(dmm->matBufAlloc < dmm->totalInstances) {
Matrix* p = realloc(dmm->matBuf, dmm->totalInstances * 2 * sizeof(*dmm->matBuf));
if(!p) {
printf(stderr, "OOM for matrix buffer in dmm\n");
}
dmm->matBuf = p;
dmm->matBufAlloc = dmm->totalInstances * 2;
}
// update dm matbuf offsets
for(j = 0; j < diCount; j++) { // j is mesh index
DynamicMesh* dm = VEC_ITEM(&dmm->meshes, j);
di[j]->numToDraw = 0;
dm->matBufOffset = off;
off += dm->instances.fill;
// printf("[%d], fill: %d, off: %d \n", j, dm->instances.fill, off);
}
/*
// update dm matbuf offsets
for(mesh_index = 0; mesh_index < VEC_LEN(&dmm->meshes); mesh_index++) {
DynamicMesh* dm = VEC_ITEM(&dmm->meshes, mesh_index);
dm->numToDraw = 0; // clear this out while we're at it
dm->matBufOffset = off;
off += VEC_LEN(&dm->instances);
}
*/
// walk the components
ComponentManager* posComp = CES_getCompManager(dmm->ces, "position");
ComponentManager* meshComp = CES_getCompManager(dmm->ces, "meshIndex");
ComponentManager* rotComp = CES_getCompManager(dmm->ces, "rotation");
int instIndex = 0;
CompManIter cindex, pindex, rindex;
ComponentManager_start(meshComp, &cindex);
ComponentManager_start(posComp, &pindex);
ComponentManager_start(rotComp, &rindex);
uint32_t eid;
uint16_t* meshIndex;
while(meshIndex = ComponentManager_next(meshComp, &cindex, &eid)) {
Vector* pos;
//printf("\nseeking in mesh man for %d\n", eid);
if(!(pos = ComponentManager_nextEnt(posComp, &pindex, eid))) {
// printf("continued\n");
continue;
}
// printf("mesh eid %d %d %d\n", eid, cindex, pindex);
DynamicMesh* dm = VEC_ITEM(&dmm->meshes, *meshIndex);
Matrix m = IDENT_MATRIX, tmp = IDENT_MATRIX;
float d = vDist(pos, &pfp->dp->eyePos);
// if(d > 500) continue;
mTransv(pos, &m);
C_Rotation* rot;
// printf("\nseeking 2 in mesh man for %d\n", eid);
if(rot = ComponentManager_nextEnt(rotComp, &rindex, eid)) {
mRotv(&rot->axis, rot->theta, &m);
}
mRot3f(1, 0, 0, F_PI / 2, &m);
mRot3f(1, 0, 0, dm->defaultRotX, &m);
mRot3f(0, 1, 0, dm->defaultRotY, &m);
mRot3f(0, 0, 1, dm->defaultRotZ, &m);
mScale3f(dm->defaultScale, dm->defaultScale, dm->defaultScale, &m);
dmm->matBuf[dm->matBufOffset + di[*meshIndex]->numToDraw] = m;
di[*meshIndex]->numToDraw++;
}
for(mesh_index = 0; mesh_index < VEC_LEN(&dmm->meshes); mesh_index++) {
DynamicMesh* dm = VEC_ITEM(&dmm->meshes, mesh_index);
// TODO make instances switch per frame
for(i = 0; i < di[mesh_index]->numToDraw; i++) {
// DynamicMeshInstance* dmi = &VEC_ITEM(&dm->instances, i);
// printf("vmem %p\n", vmem);
vmem->m = dmm->matBuf[dm->matBufOffset + i];
vmem->diffuseIndex = dm->texIndex;
vmem->normalIndex = 0;
vmem++;
}
// printf("[%d], numtodraw: %d\n", mesh_index, di[mesh_index]->numToDraw);
}
/*
pre-component version
for(mesh_index = 0; mesh_index < VEC_LEN(&dmm->meshes); mesh_index++) {
DynamicMesh* dm = VEC_ITEM(&dmm->meshes, mesh_index);
dm->numToDraw = 0;
// TODO make instances switch per frame
for(i = 0; i < VEC_LEN(&dm->instances[0]); i++) {
DynamicMeshInstance* dmi = &VEC_ITEM(&dm->instances, i);
Matrix m = IDENT_MATRIX, tmp = IDENT_MATRIX;
float d = vDist(&dmi->pos, &pfp->dp->eyePos);
// printf("d %f -- ", d);
// printf("%f, %f, %f -- ", dmi->pos.x, dmi->pos.y, dmi->pos.z);
// printf("%f, %f, %f\n", pfp->dp->eyePos.x, pfp->dp->eyePos.y, pfp->dp->eyePos.z);
if(d > 500) continue;
dm->numToDraw++;
mTransv(&dmi->pos, &m);
//mTransv(&noise, &m);
// z-up hack for now
mRot3f(1, 0, 0, F_PI / 2, &m);
mRot3f(1, 0, 0, dm->defaultRotX, &m);
mRot3f(0, 1, 0, dm->defaultRotY, &m);
mRot3f(0, 0, 1, dm->defaultRotZ, &m);
mScale3f(dm->defaultScale, dm->defaultScale, dm->defaultScale, &m);
//mScalev(&dmi->scale, &m);
// only write sequentially. random access is very bad.
vmem->m = m;
vmem->diffuseIndex = dm->texIndex;
vmem->normalIndex = 0;
vmem++;
}
//vmem += VEC_LEN(&dm->instances);
// printf("num to draw %d\n", dm->numToDraw);
}
*/
}
RenderPass* DynamicMeshManager_CreateShadowPass(DynamicMeshManager* m) {
RenderPass* rp;
PassDrawable* pd;
static ShaderProgram* prog = NULL;
if(!prog) {
prog = loadCombinedProgram("dynamicMeshInstanced_shadow");
}
pd = MultiDrawIndirect_CreateDrawable(m->mdi, prog);
rp = calloc(1, sizeof(*rp));
RenderPass_init(rp);
RenderPass_addDrawable(rp, pd);
//rp->fboIndex = LIGHTING;
return rp;
}
RenderPass* DynamicMeshManager_CreateRenderPass(DynamicMeshManager* m) {
RenderPass* rp;
PassDrawable* pd;
pd = DynamicMeshManager_CreateDrawable(m);
rp = calloc(1, sizeof(*rp));
RenderPass_init(rp);
RenderPass_addDrawable(rp, pd);
//rp->fboIndex = LIGHTING;
return rp;
}
PassDrawable* DynamicMeshManager_CreateDrawable(DynamicMeshManager* m) {
return MultiDrawIndirect_CreateDrawable(m->mdi, prog);
}
static void uniformSetup(DynamicMeshManager* dmm, GLuint progID) {
// matrices and uniforms
GLuint tex_ul;
glActiveTexture(GL_TEXTURE0 + 15);
glBindTexture(GL_TEXTURE_2D_ARRAY, dmm->tm->tex_id);
glActiveTexture(GL_TEXTURE0 + 16);
glBindTexture(GL_TEXTURE_2D_ARRAY, dmm->tmNorm->tex_id);
glActiveTexture(GL_TEXTURE0 + 17);
glBindTexture(GL_TEXTURE_2D_ARRAY, dmm->tmMat->tex_id);
tex_ul = glGetUniformLocation(progID, "sTexture");
glProgramUniform1i(progID, tex_ul, 15);
tex_ul = glGetUniformLocation(progID, "sNormalTextures");
glProgramUniform1i(progID, tex_ul, 16);
tex_ul = glGetUniformLocation(progID, "sMaterialTextures");
glProgramUniform1i(progID, tex_ul, 17);
glexit("");
}
static void smm_preFrame(PassFrameParams* pfp, SlowMeshManager* mm);
static void smm_draw(SlowMeshManager* mm, GLuint progID, PassDrawParams* pdp);
static void smm_postFrame(SlowMeshManager* mm);
RenderPass* SlowMeshManager_CreateRenderPass(SlowMeshManager* mm, ShaderProgram* prog) {
RenderPass* rp;
PassDrawable* pd;
pd = SlowMeshManager_CreateDrawable(mm, prog);
rp = calloc(1, sizeof(*rp));
RenderPass_init(rp);
RenderPass_addDrawable(rp, pd);
return rp;
}
PassDrawable* SlowMeshManager_CreateDrawable(SlowMeshManager* mm, ShaderProgram* prog) {
PassDrawable* pd;
pd = Pass_allocDrawable("SlowMeshManager");
pd->data = mm;
pd->preFrame = smm_preFrame;
pd->draw = (PassDrawFn)smm_draw;
pd->postFrame = smm_postFrame;
pd->prog = prog;
return pd;
}
static void smm_preFrame(PassFrameParams* pfp, SlowMeshManager* mm) {
int index_offset = 0;
int vertex_offset = 0;
int instance_offset = 0;
int mesh_index;
void* vmem = PCBuffer_beginWrite(&mm->instVB);
if(!vmem) {
printf("attempted to update invalid MDI\n");
return;
}
/*
// BUG: bounds checking on pcbuffer inside instanceSetup()
if(mdi->instanceSetup) {
(*mdi->instanceSetup)(mdi->data, vmem, VEC_DATA(&mdi->meshes), VEC_LEN(&mdi->meshes), pfp);
}
*/
// BUG: bounds checking on pcbuffer
// set up the indirect draw commands
if(mm->isIndexed) {
DrawElementsIndirectCommand* cmdsi = PCBuffer_beginWrite(&mm->indirectCmds);
for(mesh_index = 0; mesh_index < VEC_LEN(&mm->meshes); mesh_index++) {
SlowMeshDrawInfo* di = VEC_ITEM(&mm->meshes, mesh_index);
cmdsi[mesh_index].firstIndex = index_offset; // offset of this mesh into the instances
cmdsi[mesh_index].count = di->mesh->indexCnt; // number of polys
// offset into instanced vertex attributes
cmdsi[mesh_index].baseInstance = (mm->maxInstances * ((mm->instVB.nextRegion) % PC_BUFFER_DEPTH)) + instance_offset;
// number of instances
cmdsi[mesh_index].instanceCount = di->numToDraw;
cmdsi[mesh_index].baseVertex = vertex_offset;
index_offset += di->mesh->indexCnt;
vertex_offset += di->mesh->vertexCnt;
instance_offset += di->numToDraw;
}
}
else {
printf("non-indexed meshes not supported by slow mesh manager.\n");
}
}
static void smm_draw(SlowMeshManager* mm, GLuint progID, PassDrawParams* pdp) {
size_t cmdOffset;
glBindVertexArray(mm->vao);
glBindBuffer(GL_ARRAY_BUFFER, mm->geomVBO);
if(mm->isIndexed)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mm->ibo);
PCBuffer_bind(&mm->instVB);
PCBuffer_bind(&mm->indirectCmds);
cmdOffset = PCBuffer_getOffset(&mm->indirectCmds);
if(mm->isIndexed) {
glMultiDrawElementsIndirect(mm->primMode, GL_UNSIGNED_SHORT, cmdOffset, VEC_LEN(&mm->meshes), 0);
}
else {
printf("slow mesh manager does not support non-indexed meshes");
}
glexit("multidrawarraysindirect");
}
static void smm_postFrame(SlowMeshManager* mm) {
PCBuffer_afterDraw(&mm->instVB);
PCBuffer_afterDraw(&mm->indirectCmds);
}
SlowMeshManager* SlowMeshManager_alloc(int maxInstances, int maxMeshes, VAOConfig* vaocfg) {
SlowMeshManager* mm = pcalloc(mm);
SlowMeshManager_init(mm, maxInstances, maxMeshes, vaocfg);
return mm;
}
void SlowMeshManager_init(SlowMeshManager* mm, int maxInstances, int maxMeshes, VAOConfig* vaocfg) {
VEC_INIT(&mm->meshes);
mm->maxMeshes = maxMeshes;
mm->maxInstances = maxInstances;
mm->vaoConfig = vaocfg;
mm->isIndexed = 1; // only indexed meshes
mm->indexSize = 2; // only 16-bit indices
mm->primMode = GL_TRIANGLES; // only triangles
}
void SlowMeshManager_initGL(SlowMeshManager* mm) {
mm->vao = makeVAO(mm->vaoConfig);
glBindVertexArray(mm->vao);
mm->vaoGeomStride = calcVAOStride(0, mm->vaoConfig);
mm->vaoInstStride = calcVAOStride(1, mm->vaoConfig);
PCBuffer_startInit(&mm->instVB, mm->maxInstances * mm->vaoInstStride, GL_ARRAY_BUFFER);
updateVAO(1, mm->vaoConfig);
PCBuffer_finishInit(&mm->instVB);
PCBuffer_startInit(
&mm->indirectCmds,
mm->maxMeshes * sizeof(DrawElementsIndirectCommand), // carefull here
GL_DRAW_INDIRECT_BUFFER
);
PCBuffer_finishInit(&mm->indirectCmds);
}
void SlowMeshManager_RefreshGeometry(SlowMeshManager* mm) {
int offset;
glBindVertexArray(mm->vao);
// recreate geometry buffer
if(glIsBuffer(mm->geomVBO)) glDeleteBuffers(1, &mm->geomVBO);
glGenBuffers(1, &mm->geomVBO);
glBindBuffer(GL_ARRAY_BUFFER, mm->geomVBO);
glBufferStorage(GL_ARRAY_BUFFER, mm->totalVertices * mm->vaoGeomStride, NULL, GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT);
glexit("");
// update geometry data
void* buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
glexit("");
offset = 0;
VEC_EACH(&mm->meshes, i, di) {
memcpy(buf + offset, di->mesh->vertices, di->mesh->vertexCnt * mm->vaoGeomStride);
offset += di->mesh->vertexCnt * mm->vaoGeomStride;
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// index buffers
if(mm->isIndexed) {
if(glIsBuffer(mm->ibo)) glDeleteBuffers(1, &mm->ibo);
glGenBuffers(1, &mm->ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mm->ibo);
glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, mm->totalIndices * mm->indexSize, NULL, GL_MAP_WRITE_BIT);
uint16_t* ib = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY);
offset = 0;
VEC_EACH(&mm->meshes, i, di) {
memcpy(ib + offset, di->mesh->indices.w8, di->mesh->indexCnt * mm->indexSize);
offset += di->mesh->indexCnt;
}
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
else {
printf("!!! slowmeshmanager only supports indexed meshes\n");
}
glexit("");
}
void SlowMeshManager_AddMesh(SlowMeshManager* mm, DynamicMesh* dm) {
SlowMeshDrawInfo* di = pcalloc(di);
di->mesh = dm;
VEC_PUSH(&mm->meshes, di);
mm->totalVertices += dm->vertexCnt;
mm->totalIndices += dm->indexCnt;
}
// and all instances
void SlowMeshManager_RemoveMesh(SlowMeshManager* mm, DynamicMesh* dm) {
VEC_EACH(&mm->meshes, i, di) {
if(di->mesh == dm) {
free(di);
mm->totalVertices -= dm->vertexCnt;
mm->totalIndices -= dm->indexCnt;
VEC_RM(&mm->meshes, i);
// TODO: remove instances
}
}
}
DynamicMeshInstance* SlowMeshManager_AddInstance(SlowMeshManager* mm, DynamicMesh* dm, DynamicMeshInstance* inst) {
DynamicMeshInstance* perm = MemPoolT_malloc(&dm->instances);
mm->totalInstances++;
*perm = *inst;
return perm;
}
void SlowMeshManager_RemoveInstance(SlowMeshManager* mm, DynamicMesh* dm, DynamicMeshInstance* inst) {
fprintf(stderr, "NYI\n");
mm->totalInstances--;
}
| yzziizzy/EACSMB | src/dynamicMesh.c | C | agpl-3.0 | 19,231 |
<script tal:condition="baseconfiguration/getActivatezoom" change:javascript="head 'modules.catalog.lib.js.jquery-jqzoom'"></script>
<script change:javascript="src 'modules.catalog.lib.js.productAdditionalVisualsManagement'"></script>
<tal:block tal:condition="displayConfig/showShareBlock" change:block="" module="sharethis" name="Sharepage" />
<tal:block change:block="" module="order" name="CartMessages" />
<tal:block change:block="" module="website" name="messages" container="" />
<div class="website-block">
<!-- Product information -->
<div class="column-33 margin-left float-right">
<tal:block change:include="module 'catalog'; template 'Catalog-Inc-Mininavigation'; type 'html'; primaryshelf primaryshelf; contextShopId contextShopId"/>
<tal:block tal:condition="displayConfig/showAnimPictogramBlock" change:block="" module="marketing" name="AnimationsPictograms" productId="${product/getId}" shopId="${shop/getId}" />
<ul tal:condition="product/getPictogramCount" class="associated-pictograms">
<li tal:repeat="pictogram product/getPictogramArray"><img change:media="document pictogram; format 'modules.catalog.frontoffice/pic35x35'" /></li>
</ul>
<h1 change:h="" tal:content="product/getLabelAsHtml"></h1>
<div class="product-ref">
<strong>${trans:m.catalog.frontoffice.detail-reference,ucf,lab}</strong> ${product/getCodeReferenceAsHtml}
</div>
<tal:block tal:condition="product/hasPublishedBrand" tal:define="brand product/getBrand; brandVisual brand/getVisual">
<strong>${trans:m.catalog.frontoffice.brand,ucf,lab}</strong>
<a change:link="document brand">
<tal:block tal:condition="not:brandVisual">${brand/getLabelAsHtml}</tal:block>
<img tal:condition="brandVisual" change:media="document brandVisual; format 'modules.catalog.frontoffice/brandrandompic'" />
</a>
</tal:block>
<form class="product-form" change:link="module catalog; action AddToList" method="post">
<ol>
<li>
<input type="hidden" name="backurl" change:currentPageLink="" />
<input type="hidden" tal:attributes="value product/getId" name="productId" />
<input type="hidden" tal:attributes="value customitems" name="customitems" />
<input type="submit" name="addToList" class="button" value="${trans:m.catalog.frontoffice.add-to-list,ucf,attr}" title="${trans:m.catalog.frontoffice.add-to-list,ucf,attr}" />
</li>
</ol>
</form>
<form class="product-form" change:link="module featurepackb; action UpdateList" method="post">
<ol>
<li>
<input type="hidden" name="listName" value="featurepackb_comparison" />
<input type="hidden" name="backurl" change:currentPageLink="" />
<input type="hidden" value="${product/getId}" name="productIds[]" />
<input type="hidden" value="add" name="mode" />
<input type="submit" name="addToList" class="button" value="${trans:m.featurepackb.fo.add-to-comparison-list,ucf}" title="${trans:m.featurepackb.fo.add-to-comparison-list,ucf}" />
</li>
</ol>
</form>
<!-- Disponibilité -->
<p tal:define="availability product/getAvailability" tal:condition="availability" class="normal availability">${availability}</p>
<ul>
<!-- Prix HT -->
<tal:block tal:condition="displayConfig/showPricesWithoutTax">
<li>
<strong>${trans:m.catalog.frontoffice.priceht,ucf,lab}</strong>
<span class="priceht">
<tal:block tal:condition="defaultPrice/isDiscount"><del>${defaultPrice/getFormattedOldValueWithoutTax}</del></tal:block>
${defaultPrice/getFormattedValueWithoutTax}
</span>
</li>
<li>
<strong>${trans:m.catalog.frontoffice.differenceht,ucf,lab}</strong>
<span class="priceht">${differencePrice/getFormattedValueWithoutTax}</span>
</li>
</tal:block>
<!-- Prix TTC -->
<tal:block tal:condition="displayConfig/showPricesWithTax">
<li>
<strong>${trans:m.catalog.frontoffice.pricettc,ucf,lab}</strong>
<span class="pricettc">
<tal:block tal:condition="defaultPrice/isDiscount"><del>${defaultPrice/getFormattedOldValueWithTax}</del></tal:block>
${defaultPrice/getFormattedValueWithTax}
</span>
</li>
<li>
<strong>${trans:m.catalog.frontoffice.differencettc,ucf,lab}</strong>
<span class="pricettc">${differencePrice/getFormattedValueWithTax}</span>
</li>
</tal:block>
</ul>
<small tal:condition="defaultPrice/getFormattedEcoTax">
${trans:m.catalog.frontoffice.labelecotaxe,ucf} ${trans:m.catalog.frontoffice.ecotaxe,ucf,lab} <tal:block tal:replace="defaultPrice/getFormattedEcoTax"/>
</small>
<!-- ajouter au panier -->
<form tal:condition="php: product.canBeOrdered(shop)" class="product-form" change:link="module order; action AddToCart; customitems customitems" method="post">
<fieldset>
<label for="product-quantity">${trans:m.catalog.frontoffice.detail-quantity,ucf,lab}</label>
<input class="textfield" id="product-quantity" type="text" size="3" name="quantity" value="1" />
</fieldset>
<p class="buttons">
<tal:block change:addtocartbutton="shop shop; product product" />
</p>
</form>
<tal:block change:block="" module="catalog" name="ProductAlert" />
</div>
<!-- End - Product information -->
<!-- Product Pics -->
<div class="column-66 margin-right product-pics" tal:define="visuals php: product.getAllVisuals(shop); uniqueId product/getId">
<tal:block tal:repeat="imageMini visuals">
<tal:block tal:define="global mainVisualBlockDOMId">mainVisualBlock_${uniqueId}-${imageMini/getId}</tal:block>
<tal:block tal:condition="not: repeat/imageMini/start"><tal:block tal:define="global style">display: none;</tal:block></tal:block>
<div class="product-big" tal:attributes="id mainVisualBlockDOMId; style style">
<tal:block tal:condition="baseconfiguration/getActivatezoom">
<tal:block tal:define="global visualUrl php: MediaHelper::getPublicUrl(imageMini)"/>
<tal:block tal:define="global visualFormatedUrl php: MediaHelper::getPublicFormatedUrl(imageMini, 'modules.catalog.frontoffice/detailproduct')"/>
<img tal:attributes="src visualFormatedUrl; alt visualUrl" class="jqzoom image" />
</tal:block>
<tal:block tal:condition="not: baseconfiguration/getActivatezoom">
<img change:media="document imageMini; format 'modules.catalog.frontoffice/detailproduct'"/>
</tal:block>
</div>
</tal:block>
<div class="altpics" tal:condition="php: count(visuals) GT 1">
<ul class="product-altpics">
<tal:block tal:repeat="visual visuals">
<tal:block tal:define="global productVisualBlockDOMId">productVisualBlock_${uniqueId}-${visual/getId}</tal:block>
<li tal:attributes="id productVisualBlockDOMId"><a href="#"><img change:media="document visual; format 'modules.catalog.frontoffice/pic80x80'"/></a></li>
</tal:block>
</ul>
</div>
</div>
<!-- End - Product Pics -->
</div>
<!-- Additionnal product information -->
<div class="row-100">
<div class="product-description" tal:condition="product/getDescription">${product/getDescriptionAsHtml}</div>
</div>
<!-- End - Additionnal product information -->
<div class="cleaner"></div>
<!-- KitItems products information -->
<div class="product-crossselling">
<h2 change:h="">${trans:m.catalog.frontoffice.kitItems,ucf}</h2>
<div class="ecom-list">
<ol class="table-view">
<li tal:repeat="kititem product/getKititemArray">
<ul class="sub-list">
<li change:productvisual="name 'visual'; mode 'list'; product kititem" tal:condition="visual">
<a change:link="document kititem; catalogParam[customitems] customitems"><img change:media="document visual; format 'modules.catalog.frontoffice/pic120x120'" /></a>
</li>
<li>
<h3 change:h="">
<a change:link="document kititem; catalogParam[shopId] contextShopId; catalogParam[topicId] contextTopicId; catalogParam[customitems] customitems">
${kititem/getTitleAsHtml}<br/>
<tal:block tal:condition="kititem/getCurrentProduct">${trans:m.catalog.frontoffice.configure-kit-item,ucf}</tal:block>
</a>
</h3>
</li>
</ul>
</li>
</ol>
</div>
</div>
<!-- End - KitItems products information -->
| RBSChange/modules.featurepackb | override/catalog/templates/Catalog-Block-Kitproduct-Success.all.all.html | HTML | agpl-3.0 | 8,234 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
class DeliveryCarrier(models.Model):
_name = 'delivery.carrier'
_inherits = {'product.product': 'product_id'}
_description = "Carrier"
_order = 'sequence, id'
''' A Shipping Provider
In order to add your own external provider, follow these steps:
1. Create your model MyProvider that _inherit 'delivery.carrier'
2. Extend the selection of the field "delivery_type" with a pair
('<my_provider>', 'My Provider')
3. Add your methods:
<my_provider>_get_shipping_price_from_so
<my_provider>_send_shipping
<my_provider>_open_tracking_page
<my_provider>_cancel_shipment
(they are documented hereunder)
'''
# -------------------------------- #
# Internals for shipping providers #
# -------------------------------- #
sequence = fields.Integer(help="Determine the display order", default=10)
# This field will be overwritten by internal shipping providers by adding their own type (ex: 'fedex')
delivery_type = fields.Selection([('fixed', 'Fixed Price'), ('base_on_rule', 'Based on Rules')], string='Provider', default='fixed', required=True)
product_type = fields.Selection(related='product_id.type', default='service')
product_sale_ok = fields.Boolean(related='product_id.sale_ok', default=False)
product_id = fields.Many2one('product.product', string='Delivery Product', required=True, ondelete="cascade")
price = fields.Float(compute='get_price')
available = fields.Boolean(compute='get_price')
free_if_more_than = fields.Boolean('Free if Order total is more than', help="If the order is more expensive than a certain amount, the customer can benefit from a free shipping", default=False)
amount = fields.Float(string='Amount', help="Amount of the order to benefit from a free shipping, expressed in the company currency")
country_ids = fields.Many2many('res.country', 'delivery_carrier_country_rel', 'carrier_id', 'country_id', 'Countries')
state_ids = fields.Many2many('res.country.state', 'delivery_carrier_state_rel', 'carrier_id', 'state_id', 'States')
zip_from = fields.Char('Zip From')
zip_to = fields.Char('Zip To')
price_rule_ids = fields.One2many('delivery.price.rule', 'carrier_id', 'Pricing Rules', copy=True)
fixed_price = fields.Float(compute='_compute_fixed_price', inverse='_set_product_fixed_price', store=True, string='Fixed Price',help="Keep empty if the pricing depends on the advanced pricing per destination")
integration_level = fields.Selection([('rate', 'Get Rate'), ('rate_and_ship', 'Get Rate and Create Shipment')], string="Integration Level", default='rate_and_ship', help="Action while validating Delivery Orders")
prod_environment = fields.Boolean("Environment", help="Set to True if your credentials are certified for production.")
margin = fields.Integer(help='This percentage will be added to the shipping price.')
_sql_constraints = [
('margin_not_under_100_percent', 'CHECK (margin >= -100)', 'Margin cannot be lower than -100%'),
]
@api.one
def toggle_prod_environment(self):
self.prod_environment = not self.prod_environment
@api.multi
def install_more_provider(self):
return {
'name': 'New Providers',
'view_mode': 'kanban',
'res_model': 'ir.module.module',
'domain': [['name', 'ilike', 'delivery_']],
'type': 'ir.actions.act_window',
'help': _('''<p class="oe_view_nocontent">
Buy Odoo Enterprise now to get more providers.
</p>'''),
}
@api.multi
def name_get(self):
display_delivery = self.env.context.get('display_delivery', False)
order_id = self.env.context.get('order_id', False)
if display_delivery and order_id:
order = self.env['sale.order'].browse(order_id)
currency = order.pricelist_id.currency_id.name or ''
res = []
for carrier_id in self.ids:
try:
r = self.read([carrier_id], ['name', 'price'])[0]
res.append((r['id'], r['name'] + ' (' + (str(r['price'])) + ' ' + currency + ')'))
except ValidationError:
r = self.read([carrier_id], ['name'])[0]
res.append((r['id'], r['name']))
else:
res = super(DeliveryCarrier, self).name_get()
return res
@api.depends('product_id.list_price', 'product_id.product_tmpl_id.list_price')
def _compute_fixed_price(self):
for carrier in self:
carrier.fixed_price = carrier.product_id.list_price
def _set_product_fixed_price(self):
for carrier in self:
carrier.product_id.list_price = carrier.fixed_price
@api.one
def get_price(self):
SaleOrder = self.env['sale.order']
self.available = False
self.price = False
order_id = self.env.context.get('order_id')
if order_id:
# FIXME: temporary hack until we refactor the delivery API in master
order = SaleOrder.browse(order_id)
if self.delivery_type not in ['fixed', 'base_on_rule']:
try:
computed_price = self.get_shipping_price_from_so(order)[0]
self.available = True
except ValidationError as e:
# No suitable delivery method found, probably configuration error
_logger.info("Carrier %s: %s, not found", self.name, e.name)
computed_price = 0.0
else:
carrier = self.verify_carrier(order.partner_shipping_id)
if carrier:
try:
computed_price = carrier.get_price_available(order)
self.available = True
except UserError as e:
# No suitable delivery method found, probably configuration error
_logger.info("Carrier %s: %s", carrier.name, e.name)
computed_price = 0.0
else:
computed_price = 0.0
self.price = computed_price * (1.0 + (float(self.margin) / 100.0))
# -------------------------- #
# API for external providers #
# -------------------------- #
# TODO define and handle exceptions that could be thrown by providers
def get_shipping_price_from_so(self, orders):
''' For every sale order, compute the price of the shipment
:param orders: A recordset of sale orders
:return list: A list of floats, containing the estimated price for the shipping of the sale order
'''
self.ensure_one()
if hasattr(self, '%s_get_shipping_price_from_so' % self.delivery_type):
return getattr(self, '%s_get_shipping_price_from_so' % self.delivery_type)(orders)
def send_shipping(self, pickings):
''' Send the package to the service provider
:param pickings: A recordset of pickings
:return list: A list of dictionaries (one per picking) containing of the form::
{ 'exact_price': price,
'tracking_number': number }
'''
self.ensure_one()
if hasattr(self, '%s_send_shipping' % self.delivery_type):
return getattr(self, '%s_send_shipping' % self.delivery_type)(pickings)
def get_tracking_link(self, pickings):
''' Ask the tracking link to the service provider
:param pickings: A recordset of pickings
:return list: A list of string URLs, containing the tracking links for every picking
'''
self.ensure_one()
if hasattr(self, '%s_get_tracking_link' % self.delivery_type):
return getattr(self, '%s_get_tracking_link' % self.delivery_type)(pickings)
def cancel_shipment(self, pickings):
''' Cancel a shipment
:param pickings: A recordset of pickings
'''
self.ensure_one()
if hasattr(self, '%s_cancel_shipment' % self.delivery_type):
return getattr(self, '%s_cancel_shipment' % self.delivery_type)(pickings)
@api.onchange('state_ids')
def onchange_states(self):
self.country_ids = [(6, 0, self.country_ids.ids + self.state_ids.mapped('country_id.id'))]
@api.onchange('country_ids')
def onchange_countries(self):
self.state_ids = [(6, 0, self.state_ids.filtered(lambda state: state.id in self.country_ids.mapped('state_ids').ids).ids)]
@api.multi
def verify_carrier(self, contact):
self.ensure_one()
if self.country_ids and contact.country_id not in self.country_ids:
return False
if self.state_ids and contact.state_id not in self.state_ids:
return False
if self.zip_from and (contact.zip or '') < self.zip_from:
return False
if self.zip_to and (contact.zip or '') > self.zip_to:
return False
return self
@api.multi
def create_price_rules(self):
PriceRule = self.env['delivery.price.rule']
for record in self:
# If using advanced pricing per destination: do not change
if record.delivery_type == 'base_on_rule':
continue
# Not using advanced pricing per destination: override lines
if record.delivery_type == 'base_on_rule' and not (record.fixed_price is not False or record.free_if_more_than):
record.price_rule_ids.unlink()
# Check that float, else 0.0 is False
if not (record.fixed_price is not False or record.free_if_more_than):
continue
if record.delivery_type == 'fixed':
PriceRule.search([('carrier_id', '=', record.id)]).unlink()
line_data = {
'carrier_id': record.id,
'variable': 'price',
'operator': '>=',
}
# Create the delivery price rules
if record.free_if_more_than:
line_data.update({
'max_value': record.amount,
'standard_price': 0.0,
'list_base_price': 0.0,
})
PriceRule.create(line_data)
if record.fixed_price is not False:
line_data.update({
'max_value': 0.0,
'standard_price': record.fixed_price,
'list_base_price': record.fixed_price,
})
PriceRule.create(line_data)
return True
@api.model
def create(self, vals):
res = super(DeliveryCarrier, self).create(vals)
res.create_price_rules()
return res
@api.multi
def write(self, vals):
res = super(DeliveryCarrier, self).write(vals)
self.create_price_rules()
return res
@api.multi
def get_price_available(self, order):
self.ensure_one()
total = weight = volume = quantity = 0
total_delivery = 0.0
for line in order.order_line:
if line.state == 'cancel':
continue
if line.is_delivery:
total_delivery += line.price_total
if not line.product_id or line.is_delivery:
continue
qty = line.product_uom._compute_quantity(line.product_uom_qty, line.product_id.uom_id)
weight += (line.product_id.weight or 0.0) * qty
volume += (line.product_id.volume or 0.0) * qty
quantity += qty
total = (order.amount_total or 0.0) - total_delivery
total = order.currency_id.with_context(date=order.date_order).compute(total, order.company_id.currency_id)
return self.get_price_from_picking(total, weight, volume, quantity)
def get_price_from_picking(self, total, weight, volume, quantity):
price = 0.0
criteria_found = False
price_dict = {'price': total, 'volume': volume, 'weight': weight, 'wv': volume * weight, 'quantity': quantity}
for line in self.price_rule_ids:
test = safe_eval(line.variable + line.operator + str(line.max_value), price_dict)
if test:
price = line.list_base_price + line.list_price * price_dict[line.variable_factor]
criteria_found = True
break
if not criteria_found:
raise UserError(_("Selected product in the delivery method doesn't fulfill any of the delivery carrier(s) criteria."))
return price
| hip-odoo/odoo | addons/delivery/models/delivery_carrier.py | Python | agpl-3.0 | 13,010 |
/**
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.silverpeas.domains.ldapdriver;
import java.util.Collection;
import com.stratelia.webactiv.beans.admin.UserDetail;
import com.stratelia.webactiv.beans.admin.UserFull;
import com.stratelia.webactiv.util.exception.SilverpeasException;
/**
* Interface de définition des méthodes pour la synchronisation des utilisateurs d'un domaine LDAP
* @c.bonin
*/
public interface LDAPSynchroUserItf {
public void processUsers(Collection<UserDetail> listUserCreate,
Collection<UserDetail> listUserUpdate, Collection<UserDetail> listUserDelete)
throws SilverpeasException;
public UserFull getCacheUserFull(UserDetail user) throws SilverpeasException;
}
| NicolasEYSSERIC/Silverpeas-Core | lib-core/src/main/java/com/stratelia/silverpeas/domains/ldapdriver/LDAPSynchroUserItf.java | Java | agpl-3.0 | 1,827 |
package DavidScape.io.packets;
import DavidScape.players.Player;
import DavidScape.players.items.PlayerItems;
/**
* @author Encouragin <ZLyricale@live.nl>
*/
public class ItemOnItem implements Packet {
/**
* Handles item on item packet.
*
* @param Player p The player which the packet will be created for.
* @param packetId the packet id which is activated (Which handles this class)
* @param packetSize the amount of bytes being received for the packet.
*/
public void handlePacket(Player player, int packetId, int packetSize) {
if (player == null)
return;
/**
* These are the correct stream methods
* for item on item packet.
*/
int usedWith = player.stream.readSignedWordBigEndian();
int itemUsed = player.stream.readSignedWordA();
PlayerItems pi = new PlayerItems();
player.wc.resetWoodcutting();
player.mi.resetMining();
if (player.jailed) {
player.frames.sendMessage(player, "You have been jailed! You can't do anything except yell!");
return;
}
//======================================= CRAFTING =====================================
if (itemUsed == 1755 && usedWith == 1623 || itemUsed == 1623 && usedWith == 1755) {
player.requestAnim(888, 0);
pi.deleteItem(player, 1623, pi.getItemSlot(player, 1623), 1);
pi.addItem(player, 1607, 1);
player.addSkillXP(125 * player.skillLvl[12], 12);
player.frames.sendMessage(player, "You cut the sapphire.");
}
if (itemUsed == 1755 && usedWith == 1621 || itemUsed == 1621 && usedWith == 1755) {
if (player.skillLvl[12] >= 30) {
player.requestAnim(889, 0);
pi.deleteItem(player, 1621, pi.getItemSlot(player, 1621), 1);
pi.addItem(player, 1605, 1);
player.addSkillXP(172 * player.skillLvl[12], 12);
player.frames.sendMessage(player, "You cut the emerald.");
} else {
player.frames.sendMessage(player, "You need level 30 crafting to cut this gem.");
}
}
//Start of Godsword Making
if (itemUsed == 11702 && usedWith == 11690 || itemUsed == 11690 && usedWith == 11702) {
pi.deleteItem(player, 11702, pi.getItemSlot(player, 11702), 1);
pi.deleteItem(player, 11690, pi.getItemSlot(player, 11690), 1);
player.addSkillXP(100, 12);
pi.addItem(player, 11694, 1);
player.frames.sendMessage(player, "You attach the Godsword Blade and Hilt together...");
player.frames.sendMessage(player, "...and get an Armadyl Godsword!");
}
if (itemUsed == 11704 && usedWith == 11690 || itemUsed == 11690 && usedWith == 11704) {
pi.deleteItem(player, 11704, pi.getItemSlot(player, 11704), 1);
pi.deleteItem(player, 11690, pi.getItemSlot(player, 11690), 1);
player.addSkillXP(100, 12);
pi.addItem(player, 11696, 1);
player.frames.sendMessage(player, "You attach the Godsword Blade and Hilt together...");
player.frames.sendMessage(player, "...and get a Bandos Godsword!");
}
if (itemUsed == 11706 && usedWith == 11690 || itemUsed == 11690 && usedWith == 11706) {
pi.deleteItem(player, 11706, pi.getItemSlot(player, 11706), 1);
pi.deleteItem(player, 11690, pi.getItemSlot(player, 11690), 1);
player.addSkillXP(100, 12);
pi.addItem(player, 11698, 1);
player.frames.sendMessage(player, "You attach the Godsword Blade and Hilt together...");
player.frames.sendMessage(player, "...and get a Saradomin Godsword!");
}
if (itemUsed == 11708 && usedWith == 11690 || itemUsed == 11690 && usedWith == 11708) {
pi.deleteItem(player, 11708, pi.getItemSlot(player, 11708), 1);
pi.deleteItem(player, 11690, pi.getItemSlot(player, 11690), 1);
player.addSkillXP(100, 12);
pi.addItem(player, 11700, 1);
player.frames.sendMessage(player, "You attach the Godsword Blade and Hilt together...");
player.frames.sendMessage(player, "...and get a Zamorak Godsword!");
}
//End of Godsword Making
if (itemUsed == 1755 && usedWith == 1619 || itemUsed == 1619 && usedWith == 1755) {
if (player.skillLvl[12] >= 50) {
player.requestAnim(887, 0);
pi.deleteItem(player, 1619, pi.getItemSlot(player, 1619), 1);
pi.addItem(player, 1603, 1);
player.addSkillXP(25 * player.skillLvl[12], 12);
player.frames.sendMessage(player, "You cut the ruby.");
} else {
player.frames.sendMessage(player, "You need level 50 crafting to cut this gem.");
}
}
if (itemUsed == 1755 && usedWith == 1617 || itemUsed == 1617 && usedWith == 1755) {
if (player.skillLvl[12] >= 60) {
player.requestAnim(886, 0);
pi.deleteItem(player, 1617, pi.getItemSlot(player, 1617), 1);
pi.addItem(player, 1601, 1);
player.addSkillXP(50 * player.skillLvl[12], 12);
player.frames.sendMessage(player, "You cut the diamond.");
} else {
player.frames.sendMessage(player, "You need level 60 crafting to cut this gem.");
}
}
if (itemUsed == 1755 && usedWith == 1631 || itemUsed == 1631 && usedWith == 1755) {
if (player.skillLvl[12] >= 75) {
player.requestAnim(885, 0);
pi.deleteItem(player, 1631, pi.getItemSlot(player, 1631), 1);
pi.addItem(player, 1615, 1);
player.addSkillXP(100 * player.skillLvl[12], 12);
player.frames.sendMessage(player, "You cut the dragonstone.");
} else {
player.frames.sendMessage(player, "You need level 75 crafting to cut this gem.");
}
}
if (itemUsed == 1755 && usedWith == 6571 || itemUsed == 6571 && usedWith == 1755) {
if (player.skillLvl[12] >= 85) {
player.requestAnim(892, 0);
pi.deleteItem(player, 6571, pi.getItemSlot(player, 6571), 1);
pi.addItem(player, 6573, 1);
player.addSkillXP(200 * player.skillLvl[12], 12);
player.frames.sendMessage(player, "You cut the onyx stone.");
} else {
player.frames.sendMessage(player, "You need level 85 crafting to cut this gem.");
}
}
// ====================================== FLETCHING ==================================
if (itemUsed == 946 && usedWith == 1511 || itemUsed == 1511 && usedWith == 946) {
player.FletchID = 1511;
player.FletchGet = 882;
player.FletchXP = 15;
player.FletchAmount = 28;
player.FletchThat(player, player.FletchXP, player.FletchID, player.FletchGet);
}
if (itemUsed == 946 && usedWith == 1521 || itemUsed == 1521 && usedWith == 946) {
if (player.skillLvl[9] >= 15) {
player.FletchID = 1521;
player.FletchGet = 884;
player.FletchXP = 45;
player.FletchAmount = 28;
player.FletchThat(player, player.FletchXP, player.FletchID, player.FletchGet);
} else {
player.frames.sendMessage(player, "You need level 15 fletching to cut this log.");
}
}
if (itemUsed == 946 && usedWith == 1519 || itemUsed == 1519 && usedWith == 946) {
if (player.skillLvl[9] >= 30) {
player.FletchID = 1519;
player.FletchGet = 886;
player.FletchXP = 60;
player.FletchAmount = 28;
player.FletchThat(player, player.FletchXP, player.FletchID, player.FletchGet);
} else {
player.frames.sendMessage(player, "You need level 30 fletching to cut this log.");
}
}
if (itemUsed == 946 && usedWith == 1517 || itemUsed == 1517 && usedWith == 946) {
if (player.skillLvl[9] >= 45) {
player.FletchID = 1517;
player.FletchGet = 888;
player.FletchXP = 70;
player.FletchAmount = 28;
player.FletchThat(player, player.FletchXP, player.FletchID, player.FletchGet);
} else {
player.frames.sendMessage(player, "You need level 45 fletching to cut this log.");
}
}
if (itemUsed == 946 && usedWith == 1515 || itemUsed == 1515 && usedWith == 946) {
if (player.skillLvl[9] >= 65) {
player.FletchID = 1515;
player.FletchGet = 890;
player.FletchXP = 100;
player.FletchAmount = 28;
player.FletchThat(player, player.FletchXP, player.FletchID, player.FletchGet);
} else {
player.frames.sendMessage(player, "You need level 65 fletching to cut this log.");
}
}
if (itemUsed == 946 && usedWith == 1513 || itemUsed == 1513 && usedWith == 946) {
if (player.skillLvl[9] >= 75) {
player.FletchID = 1513;
player.FletchGet = 892;
player.FletchXP = 150;
player.FletchAmount = 28;
player.FletchThat(player, player.FletchXP, player.FletchID, player.FletchGet);
} else {
player.frames.sendMessage(player, "You need level 75 fletching to cut this log.");
}
}
//============================= FIRE MAKING ====================================
if (itemUsed == 590 && usedWith == 1511 || itemUsed == 1511 && usedWith == 590) {
player.addSkillXP(20 * player.skillLvl[11], 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(2732, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 1511, pi.getItemSlot(player, 1511), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
//player.fmwalk(player.absY, player.absY);
player.firedelay = 50;
}
if (itemUsed == 590 && usedWith == 1521 || itemUsed == 1521 && usedWith == 590) {
if (player.skillLvl[11] >= 15) {
player.addSkillXP(35 * player.skillLvl[11], 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(2732, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 1521, pi.getItemSlot(player, 1521), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
//player.fmwalk(player.absY, player.absY);
player.firedelay = 50;
}
}
if (itemUsed == 590 && usedWith == 1519 || itemUsed == 1519 && usedWith == 590) {
if (player.skillLvl[11] >= 30) {
player.addSkillXP(60 * player.skillLvl[11], 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(2732, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 1519, pi.getItemSlot(player, 1519), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
//player.fmwalk(player.absY, player.absY);
player.firedelay = 50;
}
}
if (itemUsed == 590 && usedWith == 1517 || itemUsed == 1517 && usedWith == 590) {
if (player.skillLvl[11] >= 45) {
player.addSkillXP(80 * player.skillLvl[11], 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(2732, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 1517, pi.getItemSlot(player, 1517), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
//player.fmwalk(player.absY, player.absY);
player.firedelay = 50;
}
}
if (itemUsed == 590 && usedWith == 1515 || itemUsed == 1515 && usedWith == 590) {
if (player.skillLvl[11] >= 60) {
player.addSkillXP(120 * player.skillLvl[11], 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(2732, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 1515, pi.getItemSlot(player, 1515), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
//player.fmwalk(player.absY, player.absY);
player.firedelay = 50;
}
}
if (itemUsed == 590 && usedWith == 1513 || itemUsed == 1513 && usedWith == 590) {
if (player.skillLvl[11] >= 75) {
player.addSkillXP(150 * player.skillLvl[11], 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(2732, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 1513, pi.getItemSlot(player, 1513), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
//player.fmwalk(player.absY, player.absY);
player.firedelay = 50;
}
}
if (itemUsed == 7329 && usedWith == 1511 || itemUsed == 1511 && usedWith == 7329) { // red
pi.deleteItem(player, 7329, pi.getItemSlot(player, 7329), 1);
pi.deleteItem(player, 1511, pi.getItemSlot(player, 1511), 1);
pi.addItem(player, 7404, 1);
player.frames.sendMessage(player, "You rub the firelighter on the logs to make red logs.");
}
if (itemUsed == 7330 && usedWith == 1511 || itemUsed == 1511 && usedWith == 7330) { // green
pi.deleteItem(player, 7330, pi.getItemSlot(player, 7330), 1);
pi.deleteItem(player, 1511, pi.getItemSlot(player, 1511), 1);
pi.addItem(player, 7405, 1);
player.frames.sendMessage(player, "You rub the firelighter on the logs to make green logs.");
}
if (itemUsed == 7331 && usedWith == 1511 || itemUsed == 1511 && usedWith == 7331) { // blue
pi.deleteItem(player, 7331, pi.getItemSlot(player, 7331), 1);
pi.deleteItem(player, 1511, pi.getItemSlot(player, 1511), 1);
pi.addItem(player, 7406, 1);
player.frames.sendMessage(player, "You rub the firelighter on the logs to make blue logs.");
}
if (itemUsed == 10326 && usedWith == 1511 || itemUsed == 1511 && usedWith == 10326) { // purple
pi.deleteItem(player, 10326, pi.getItemSlot(player, 10326), 1);
pi.deleteItem(player, 1511, pi.getItemSlot(player, 1511), 1);
pi.addItem(player, 10329, 1);
player.frames.sendMessage(player, "You rub the firelighter on the logs to make purple logs.");
}
if (itemUsed == 10327 && usedWith == 1511 || itemUsed == 1511 && usedWith == 10327) { // white
pi.deleteItem(player, 10327, pi.getItemSlot(player, 10327), 1);
pi.deleteItem(player, 1511, pi.getItemSlot(player, 1511), 1);
pi.addItem(player, 10328, 1);
player.frames.sendMessage(player, "You rub the firelighter on the logs to make white logs.");
}
if (itemUsed == 590 && usedWith == 7404 || itemUsed == 7404 && usedWith == 590) { // red
player.addSkillXP(50, 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(11404, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 7404, pi.getItemSlot(player, 7404), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
player.fmwalk(player.absY, player.absY);
player.firedelay = 100;
}
if (itemUsed == 590 && usedWith == 7405 || itemUsed == 7405 && usedWith == 590) { // green
player.addSkillXP(50, 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(11405, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 7405, pi.getItemSlot(player, 7405), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
player.fmwalk(player.absY, player.absY);
player.firedelay = 100;
}
if (itemUsed == 590 && usedWith == 7406 || itemUsed == 7406 && usedWith == 590) { // blue
player.addSkillXP(50, 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(11406, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 7406, pi.getItemSlot(player, 7406), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
player.fmwalk(player.absY, player.absY);
player.firedelay = 100;
}
if (itemUsed == 590 && usedWith == 10329 || itemUsed == 10329 && usedWith == 590) { // blue
player.addSkillXP(50, 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(20001, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 10329, pi.getItemSlot(player, 10329), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
player.fmwalk(player.absY, player.absY);
player.firedelay = 100;
}
if (itemUsed == 590 && usedWith == 10328 || itemUsed == 10328 && usedWith == 590) { // blue
player.addSkillXP(50, 11);
player.requestAnim(733, 0);
player.frames.createGlobalObject(20000, player.heightLevel, player.absX, player.absY, 0, 10);
player.objectX = player.absX;
player.objectY = player.absY;
player.objectHeight = player.heightLevel;
pi.deleteItem(player, 10328, pi.getItemSlot(player, 10328), 1);
player.frames.sendMessage(player, "You set the logs on fire.");
player.fmwalk(player.absY, player.absY);
player.firedelay = 100;
}
}
} | moparisthebest/MoparScape | servers/server508/src/main/java/DavidScape/io/packets/ItemOnItem.java | Java | agpl-3.0 | 20,268 |
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
import json
from rest_framework.test import APIClient
from rest_framework import status
from shuup.core.models import Order
from shuup.testing.factories import (
create_order_with_product, get_default_product,
get_default_shop, get_default_supplier
)
def create_order():
shop = get_default_shop()
product = get_default_product()
supplier = get_default_supplier()
order = create_order_with_product(
product,
shop=shop,
supplier=supplier,
quantity=1,
taxless_base_unit_price=10,
)
order.cache_prices()
order.save()
return order
def get_client(admin_user):
client = APIClient()
client.force_authenticate(user=admin_user)
return client
def get_create_payment_url(order_pk):
return "/api/shuup/order/%s/create_payment/" % order_pk
def get_set_fully_paid_url(order_pk):
return "/api/shuup/order/%s/set_fully_paid/" % order_pk
def get_order_url(order_pk):
return "/api/shuup/order/%s/" % order_pk
def test_create_payment(admin_user):
order = create_order()
client = get_client(admin_user)
payment_identifier = "some_identifier"
data = {
"amount_value": 1,
"payment_identifier": payment_identifier,
"description": "some_payment"
}
response = client.post(
get_create_payment_url(order.pk),
data,
format="json"
)
assert response.status_code == status.HTTP_201_CREATED
assert order.get_total_paid_amount().value == 1
response = client.get(
get_order_url(order.pk),
format="json"
)
assert response.status_code == status.HTTP_200_OK
order_data = json.loads(response.content.decode("utf-8"))
payments = order_data["payments"]
assert len(payments) == 1
assert payments[0]["payment_identifier"] == payment_identifier
def test_set_fully_paid(admin_user):
order = create_order()
client = get_client(admin_user)
data = {
"payment_identifier": 1,
"description": "some_payment"
}
order_pk = order.pk
response = client.post(
get_set_fully_paid_url(order_pk),
data,
format="json"
)
assert response.status_code == status.HTTP_201_CREATED
order = Order.objects.get(pk=order_pk)
assert bool(order.is_paid())
currently_paid_amount = order.get_total_paid_amount()
# Make sure that api works with already fully paid orders
response = client.post(
"/api/shuup/order/%s/set_fully_paid/" % order_pk,
data,
format="json"
)
assert response.status_code == status.HTTP_200_OK
order = Order.objects.get(pk=order_pk)
assert bool(order.is_paid())
assert currently_paid_amount == order.get_total_paid_amount()
def test_set_paid_from_partially_paid_order(admin_user):
order = create_order()
client = get_client(admin_user)
data = {
"amount_value": 1,
"payment_identifier": 1,
"description": "some_payment"
}
response = client.post(
get_create_payment_url(order.pk),
data,
format="json"
)
assert response.status_code == status.HTTP_201_CREATED
assert order.get_total_paid_amount().value == 1
data = {
"payment_identifier": 2,
"description": "some_payment"
}
order_pk = order.pk
response = client.post(
get_set_fully_paid_url(order_pk),
data,
format="json"
)
assert response.status_code == status.HTTP_201_CREATED
order = Order.objects.get(pk=order_pk)
assert bool(order.is_paid())
assert bool(order.get_total_paid_amount() == order.taxful_total_price.amount)
| suutari/shoop | shuup_tests/core/test_payments_api.py | Python | agpl-3.0 | 3,959 |
/*
* Copyright (C) 2019 by Sukchan Lee <acetcom@gmail.com>
*
* This file is part of Open5GS.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (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, see <https://www.gnu.org/licenses/>.
*/
#include "ogs-core.h"
#include "core/abts.h"
static void test1_func(abts_case *tc, void *data)
{
char *ptr = ogs_malloc(256);
ABTS_PTR_NOTNULL(tc, ptr);
ogs_free(ptr);
}
static void test2_func(abts_case *tc, void *data)
{
char *ptr = ogs_calloc(2, 10);
int i;
ABTS_PTR_NOTNULL(tc, ptr);
for (i = 0; i < 2*10; i++)
{
ABTS_INT_EQUAL(tc, 0, ptr[i]);
}
ogs_free(ptr);
}
static void test3_func(abts_case *tc, void *data)
{
char *ptr = ogs_realloc(0, 10);
ABTS_PTR_NOTNULL(tc, ptr);
ogs_free(ptr);
ptr = ogs_malloc(20);
ABTS_PTR_NOTNULL(tc, ptr);
ptr = ogs_realloc(ptr, 0);
}
static void test4_func(abts_case *tc, void *data)
{
char *p, *q;
p = ogs_malloc(10);
ABTS_PTR_NOTNULL(tc, p);
memset(p, 1, 10);
q = ogs_realloc(p, 128 - sizeof(ogs_pkbuf_t *) - 1);
ABTS_TRUE(tc, p == q);
p = ogs_realloc(q, 128 - sizeof(ogs_pkbuf_t *));
ABTS_TRUE(tc, p == q);
q = ogs_realloc(p, 128 - sizeof(ogs_pkbuf_t *) + 1);
ABTS_TRUE(tc, p != q);
ABTS_TRUE(tc, memcmp(p, q, 10) == 0);
ogs_free(q);
}
abts_suite *test_memory(abts_suite *suite)
{
suite = ADD_SUITE(suite)
abts_run_test(suite, test1_func, NULL);
abts_run_test(suite, test2_func, NULL);
abts_run_test(suite, test3_func, NULL);
abts_run_test(suite, test4_func, NULL);
return suite;
}
| acetcom/nextepc | tests/core/memory-test.c | C | agpl-3.0 | 2,135 |
package ch.ech.ech0021;
import javax.annotation.Generated;
import org.minimalj.model.Keys;
@Generated(value="org.minimalj.metamodel.generator.ClassGenerator")
public class BirthAddonData {
public static final BirthAddonData $ = Keys.of(BirthAddonData.class);
public NameOfParent nameOfFather;
public NameOfParent nameOfMother;
} | BrunoEberhard/open-ech | src/main/model/ch/ech/ech0021/BirthAddonData.java | Java | agpl-3.0 | 334 |
class GroupsController < ApplicationController
def index
@groups = Queries::ExploreGroups.new.search_for(params[:q]).order('groups.memberships_count DESC')
@total = @groups.count
limit = params.fetch(:limit, 50)
if @total < limit
@pages = 1
else
if @total % limit > 0
@pages = @total / limit + 1
else
@pages = @total / limit
end
end
@page = params.fetch(:page, 1).to_i.clamp(1, @pages)
@offset = @page == 1 ? 0 : ((@page - 1) * limit)
@groups = @groups.limit(limit).offset(@offset)
end
def export
@exporter = GroupExporter.new(load_and_authorize(:group, :export))
respond_to do |format|
format.html
format.csv { send_data @exporter.to_csv }
end
end
def stats
@group = load_and_authorize(:group, :export)
end
end
| loomio/loomio | app/controllers/groups_controller.rb | Ruby | agpl-3.0 | 831 |
package edu.arizona.kfs.fp.businessobject;
import java.sql.Date;
import java.util.LinkedHashMap;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;
public class ProcurementCardLevel3Lodging extends PersistableBusinessObjectBase {
private String documentNumber;
private Integer financialDocumentTransactionLineNumber;
private Date arriveDate;
private Date departureDate;
private String folioNum;
private String propertyPhoneNum;
private String customerServiceNum;
private KualiDecimal prePaidAmt;
private KualiDecimal roomRate;
private KualiDecimal roomTax;
private String programCode;
private KualiDecimal callCharges;
private KualiDecimal foodSvcCharges;
private KualiDecimal miniBarCharges;
private KualiDecimal giftShopCharges;
private KualiDecimal laundryCharges;
private KualiDecimal healthClubCharges;
private KualiDecimal movieCharges;
private KualiDecimal busCtrCharges;
private KualiDecimal parkingCharges;
private String otherCode;
private KualiDecimal otherCharges;
private KualiDecimal adjustmentAmount;
public String getDocumentNumber() {
return documentNumber;
}
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
public Integer getFinancialDocumentTransactionLineNumber() {
return financialDocumentTransactionLineNumber;
}
public void setFinancialDocumentTransactionLineNumber(Integer financialDocumentTransactionLineNumber) {
this.financialDocumentTransactionLineNumber = financialDocumentTransactionLineNumber;
}
public Date getArriveDate() {
return arriveDate;
}
public void setArriveDate(Date arriveDate) {
this.arriveDate = arriveDate;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public String getFolioNum() {
return folioNum;
}
public void setFolioNum(String folioNum) {
this.folioNum = folioNum;
}
public String getPropertyPhoneNum() {
return propertyPhoneNum;
}
public void setPropertyPhoneNum(String propertyPhoneNum) {
this.propertyPhoneNum = propertyPhoneNum;
}
public String getCustomerServiceNum() {
return customerServiceNum;
}
public void setCustomerServiceNum(String customerServiceNum) {
this.customerServiceNum = customerServiceNum;
}
public KualiDecimal getPrePaidAmt() {
return prePaidAmt;
}
public void setPrePaidAmt(KualiDecimal prePaidAmt) {
this.prePaidAmt = prePaidAmt;
}
public KualiDecimal getRoomRate() {
return roomRate;
}
public void setRoomRate(KualiDecimal roomRate) {
this.roomRate = roomRate;
}
public KualiDecimal getRoomTax() {
return roomTax;
}
public void setRoomTax(KualiDecimal roomTax) {
this.roomTax = roomTax;
}
public String getProgramCode() {
return programCode;
}
public void setProgramCode(String programCode) {
this.programCode = programCode;
}
public KualiDecimal getCallCharges() {
return callCharges;
}
public void setCallCharges(KualiDecimal callCharges) {
this.callCharges = callCharges;
}
public KualiDecimal getFoodSvcCharges() {
return foodSvcCharges;
}
public void setFoodSvcCharges(KualiDecimal foodSvcCharges) {
this.foodSvcCharges = foodSvcCharges;
}
public KualiDecimal getMiniBarCharges() {
return miniBarCharges;
}
public void setMiniBarCharges(KualiDecimal miniBarCharges) {
this.miniBarCharges = miniBarCharges;
}
public KualiDecimal getGiftShopCharges() {
return giftShopCharges;
}
public void setGiftShopCharges(KualiDecimal giftShopCharges) {
this.giftShopCharges = giftShopCharges;
}
public KualiDecimal getLaundryCharges() {
return laundryCharges;
}
public void setLaundryCharges(KualiDecimal laundryCharges) {
this.laundryCharges = laundryCharges;
}
public KualiDecimal getHealthClubCharges() {
return healthClubCharges;
}
public void setHealthClubCharges(KualiDecimal healthClubCharges) {
this.healthClubCharges = healthClubCharges;
}
public KualiDecimal getMovieCharges() {
return movieCharges;
}
public void setMovieCharges(KualiDecimal movieCharges) {
this.movieCharges = movieCharges;
}
public KualiDecimal getBusCtrCharges() {
return busCtrCharges;
}
public void setBusCtrCharges(KualiDecimal busCtrCharges) {
this.busCtrCharges = busCtrCharges;
}
public KualiDecimal getParkingCharges() {
return parkingCharges;
}
public void setParkingCharges(KualiDecimal parkingCharges) {
this.parkingCharges = parkingCharges;
}
public String getOtherCode() {
return otherCode;
}
public void setOtherCode(String otherCode) {
this.otherCode = otherCode;
}
public KualiDecimal getOtherCharges() {
return otherCharges;
}
public void setOtherCharges(KualiDecimal otherCharges) {
this.otherCharges = otherCharges;
}
public KualiDecimal getAdjustmentAmount() {
return adjustmentAmount;
}
public void setAdjustmentAmount(KualiDecimal adjustmentAmount) {
this.adjustmentAmount = adjustmentAmount;
}
protected LinkedHashMap<String, String> toStringMapper() {
LinkedHashMap<String, String> m = new LinkedHashMap<String, String>();
m.put("documentNumber", documentNumber);
m.put("financialDocumentTransactionLineNumber", getFinancialDocumentTransactionLineNumber().toString());
return m;
}
}
| ua-eas/kfs | kfs-core/src/main/java/edu/arizona/kfs/fp/businessobject/ProcurementCardLevel3Lodging.java | Java | agpl-3.0 | 5,388 |
'''
@since: 2015-01-07
@author: moschlar
'''
import sqlalchemy.types as sqlat
import tw2.core as twc
import tw2.bootstrap.forms as twb
import tw2.jqplugins.chosen.widgets as twjc
import sprox.widgets.tw2widgets.widgets as sw
from sprox.sa.widgetselector import SAWidgetSelector
from sprox.sa.validatorselector import SAValidatorSelector, Email
from sauce.widgets.widgets import (LargeMixin, SmallMixin, AdvancedWysihtml5,
MediumTextField, SmallTextField, CalendarDateTimePicker)
from sauce.widgets.validators import AdvancedWysihtml5BleachValidator
class ChosenPropertyMultipleSelectField(LargeMixin, twjc.ChosenMultipleSelectField, sw.PropertyMultipleSelectField):
search_contains = True
def _validate(self, value, state=None):
value = super(ChosenPropertyMultipleSelectField, self)._validate(value, state)
if self.required and not value:
raise twc.ValidationError('Please select at least one value')
else:
return value
class ChosenPropertySingleSelectField(SmallMixin, twjc.ChosenSingleSelectField, sw.PropertySingleSelectField):
search_contains = True
class MyWidgetSelector(SAWidgetSelector):
'''Custom WidgetSelector for SAUCE
Primarily uses fields from tw2.bootstrap.forms and tw2.jqplugins.chosen.
'''
text_field_limit = 256
default_multiple_select_field_widget_type = ChosenPropertyMultipleSelectField
default_single_select_field_widget_type = ChosenPropertySingleSelectField
default_name_based_widgets = {
'name': MediumTextField,
'subject': MediumTextField,
'_url': MediumTextField,
'user_name': MediumTextField,
'email_address': MediumTextField,
'_display_name': MediumTextField,
'description': AdvancedWysihtml5,
'message': AdvancedWysihtml5,
}
def __init__(self, *args, **kwargs):
self.default_widgets.update({
sqlat.String: MediumTextField,
sqlat.Integer: SmallTextField,
sqlat.Numeric: SmallTextField,
sqlat.DateTime: CalendarDateTimePicker,
sqlat.Date: twb.CalendarDatePicker,
sqlat.Time: twb.CalendarTimePicker,
sqlat.Binary: twb.FileField,
sqlat.BLOB: twb.FileField,
sqlat.PickleType: MediumTextField,
sqlat.Enum: twjc.ChosenSingleSelectField,
})
super(MyWidgetSelector, self).__init__(*args, **kwargs)
def select(self, field):
widget = super(MyWidgetSelector, self).select(field)
if (issubclass(widget, sw.TextArea)
and hasattr(field.type, 'length')
and (field.type.length is None or field.type.length < self.text_field_limit)):
widget = MediumTextField
return widget
class MyValidatorSelector(SAValidatorSelector):
_name_based_validators = {
'email_address': Email,
'description': AdvancedWysihtml5BleachValidator,
'message': AdvancedWysihtml5BleachValidator,
}
# def select(self, field):
# print 'MyValidatorSelector', 'select', field
# return super(MyValidatorSelector, self).select(field)
| moschlar/SAUCE | sauce/controllers/crc/selectors.py | Python | agpl-3.0 | 3,164 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.cg.document.validation.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.kfs.kns.document.MaintenanceDocument;
import org.kuali.kfs.krad.bo.PersistableBusinessObject;
import org.kuali.kfs.krad.util.GlobalVariables;
import org.kuali.kfs.module.cg.businessobject.Proposal;
import org.kuali.kfs.module.cg.businessobject.ProposalOrganization;
import org.kuali.kfs.module.cg.businessobject.ProposalProjectDirector;
import org.kuali.kfs.module.cg.businessobject.ProposalSubcontractor;
import org.kuali.kfs.sys.KFSKeyConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
/**
* Rules for the Proposal maintenance document.
*/
public class ProposalRule extends CGMaintenanceDocumentRuleBase {
protected static Logger LOG = org.apache.log4j.Logger.getLogger(ProposalRule.class);
protected Proposal newProposalCopy;
@Override
protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument documentCopy) {
LOG.debug("Entering ProposalRule.processCustomSaveDocumentBusinessRules");
processCustomRouteDocumentBusinessRules(documentCopy); // chain call but ignore success
LOG.info("Leaving ProposalRule.processCustomSaveDocumentBusinessRules");
return true; // save despite error messages
}
@Override
protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument documentCopy) {
LOG.debug("Entering ProposalRule.processCustomRouteDocumentBusinessRules");
boolean success = true;
success &= checkEndAfterBegin(newProposalCopy.getProposalBeginningDate(), newProposalCopy.getProposalEndingDate(), KFSPropertyConstants.PROPOSAL_ENDING_DATE);
success &= checkPrimary(newProposalCopy.getProposalOrganizations(), ProposalOrganization.class, KFSPropertyConstants.PROPOSAL_ORGANIZATIONS, Proposal.class);
success &= checkPrimary(newProposalCopy.getProposalProjectDirectors(), ProposalProjectDirector.class, KFSPropertyConstants.PROPOSAL_PROJECT_DIRECTORS, Proposal.class);
success &= checkProjectDirectorsAreDirectors(newProposalCopy.getProposalProjectDirectors(), ProposalProjectDirector.class, KFSPropertyConstants.PROPOSAL_PROJECT_DIRECTORS);
success &= checkProjectDirectorsExist(newProposalCopy.getProposalProjectDirectors(), ProposalProjectDirector.class, KFSPropertyConstants.PROPOSAL_PROJECT_DIRECTORS);
success &= checkProjectDirectorsStatuses(newProposalCopy.getProposalProjectDirectors(), ProposalProjectDirector.class, KFSPropertyConstants.PROPOSAL_PROJECT_DIRECTORS);
success &= checkFederalPassThrough(newProposalCopy.getProposalFederalPassThroughIndicator(), newProposalCopy.getAgency(), newProposalCopy.getFederalPassThroughAgencyNumber(), Proposal.class, KFSPropertyConstants.PROPOSAL_FEDERAL_PASS_THROUGH_INDICATOR);
success &= checkAgencyNotEqualToFederalPassThroughAgency(newProposalCopy.getAgency(), newProposalCopy.getFederalPassThroughAgency(), KFSPropertyConstants.AGENCY_NUMBER, KFSPropertyConstants.FEDERAL_PASS_THROUGH_AGENCY_NUMBER);
LOG.info("Leaving ProposalRule.processCustomRouteDocumentBusinessRules");
return success;
}
/**
* @return
*/
@Override
public boolean processCustomAddCollectionLineBusinessRules(MaintenanceDocument document, String collectionName, PersistableBusinessObject line) {
if (LOG.isDebugEnabled()) {
LOG.debug("Entering ProposalRule.processCustomAddNewCollectionLineBusinessRules( " + collectionName + " )");
}
boolean success = true;
success &= validateAddSubcontractor(line);
if (LOG.isDebugEnabled()) {
LOG.debug("Leaving ProposalRule.processCustomAddNewCollectionLineBusinessRules( " + collectionName + " )");
}
return success;
}
/**
* This method takes a look at the new line being added and applies appropriate validation checks if the line is a new line for
* the {@link Subcontractor} collection. If the validation checks fail, an appropriate error message will be added to the global
* error map and the method will return a value of false.
*
* @param addLine New business object values being added.
* @return True is the value being added passed all applicable validation rules.
*/
protected boolean validateAddSubcontractor(PersistableBusinessObject addLine) {
boolean success = true;
if (addLine.getClass().isAssignableFrom(ProposalSubcontractor.class)) {
ProposalSubcontractor subc = (ProposalSubcontractor) addLine;
if (StringUtils.isBlank(subc.getSubcontractorNumber())) {
String propertyName = KFSPropertyConstants.SUBCONTRACTOR_NUMBER;
String errorKey = KFSKeyConstants.ERROR_PROPOSAL_SUBCONTRACTOR_NUMBER_REQUIRED_FOR_ADD;
GlobalVariables.getMessageMap().putError(propertyName, errorKey);
success = false;
}
}
return success;
}
/**
* Performs convenience cast for Maintenance framework. Note that the {@link MaintenanceDocumentRule} events provide only a deep
* copy of the document (from KualiDocumentEventBase), so these BOs are a copy too. The framework does this to prevent these
* rules from changing any data.
*
* @see org.kuali.rice.kns.rules.MaintenanceDocumentRule#setupConvenienceObjects()
*/
@Override
public void setupConvenienceObjects() {
// oldProposalCopy = (Proposal) super.getOldBo();
newProposalCopy = (Proposal) super.getNewBo();
}
}
| quikkian-ua-devops/will-financials | kfs-cg/src/main/java/org/kuali/kfs/module/cg/document/validation/impl/ProposalRule.java | Java | agpl-3.0 | 6,446 |
# frozen_string_literal: true
module Api
module CollaborationOperations
module Helpers
def parent_resource
host
end
def association_name_for_parent_resource
:collaborations
end
def collaboration
return @collaboration if @collaboration
# just something to keep track of errors for the UI
@collaboration = Collaboration.new
@collaboration.errors.add(:base, 'event or organization not found') unless host
@collaboration.collaborated = host
@collaboration
end
def host
@host ||= find_host
end
def find_host
id, kind = params_for_action.values_at(:host_id, :host_type)
host_op_class = "::Api::#{kind}Operations::Read".safe_constantize
host_op_class&.call(current_user, { id: id })
end
end
end
end
| NullVoxPopuli/aeonvera | app/resources/api/collaborations/operations/helpers.rb | Ruby | agpl-3.0 | 868 |
<?php
namespace ACore\Character\DependencyInjection;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;
class CharacterExtension extends Extension {
public function load(array $configs, ContainerBuilder $container) {
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('config.yml');
$loader->load('services.yml');
}
}
| azerothcore/acore-php-framework | character/src/DependencyInjection/CharacterExtension.php | PHP | agpl-3.0 | 589 |
DELETE FROM `weenie` WHERE `class_Id` = 10391;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (10391, 'housecottage699', 53, '2019-02-10 00:00:00') /* House */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (10391, 1, 128) /* ItemType - Misc */
, (10391, 5, 10) /* EncumbranceVal */
, (10391, 16, 1) /* ItemUseable - No */
, (10391, 93, 52) /* PhysicsState - Ethereal, IgnoreCollisions, NoDraw */
, (10391, 155, 1) /* HouseType - Cottage */
, (10391, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (10391, 1, True ) /* Stuck */
, (10391, 24, True ) /* UiHidden */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (10391, 39, 0.1) /* DefaultScale */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (10391, 1, 'Cottage') /* Name */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (10391, 1, 33557058) /* Setup */
, (10391, 8, 100671873) /* Icon */
, (10391, 30, 152) /* PhysicsScript - RestrictionEffectBlue */
, (10391, 8001, 236978192) /* PCAPRecordedWeenieHeader - Usable, Burden, HouseOwner, HouseRestrictions, PScript */
, (10391, 8003, 148) /* PCAPRecordedObjectDesc - Stuck, Attackable, UiHidden */
, (10391, 8005, 163969) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, Position, AnimationFrame */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (10391, 8040, 3163881770, 110.696, 155.338, 27.9995, -0.9999981, 0, 0, -0.00195593) /* PCAPRecordedLocation */
/* @teleloc 0xBC95012A [110.696000 155.338000 27.999500] -0.999998 0.000000 0.000000 -0.001956 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (10391, 8000, 2076790922) /* PCAPRecordedObjectIID */;
| LtRipley36706/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/House/Cottage/10391 Cottage.sql | SQL | agpl-3.0 | 2,103 |
ActiveAdmin.setup do |config|
config.site_title = "Loomio"
config.authentication_method = :authenticate_admin_user!
config.current_user_method = :current_user
config.logout_link_path = :destroy_user_session_path
config.logout_link_method = :delete
config.root_to = 'groups#index'
config.batch_actions = true
config.comments = false
end
def authenticate_admin_user!
authenticate_user!
redirect_to new_user_session_path unless current_user.is_admin?
end
| loomio/loomio | config/initializers/active_admin.rb | Ruby | agpl-3.0 | 473 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* 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 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.
*/
package everything;
public class Grower extends ClientRunner.SubClient {
@Override
public void run() {
if (getMBRss() > 2048) {
try { Thread.sleep(5000); } catch (InterruptedException e) {}
return;
}
for (int i = 0; i < 1000; i++) {
// add 100 rows to a random partition
try {
byte pval = (byte) (m_rand.nextInt() % 127);
m_client.callProcedure(new Callback(), "Insert你好", pval, 100, "你好");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
}
}
}
}
| kobronson/cs-voltdb | tests/test_apps/everything/src/everything/Grower.java | Java | agpl-3.0 | 1,837 |
class AddAllowedChannelsToUsers < ActiveRecord::Migration
def change
add_column :users, :allowed_channels, :string, :default => '0,'
end
end
| marcnaweb/kandanapp_tmp | db/migrate/20131016121746_add_allowed_channels_to_users.rb | Ruby | agpl-3.0 | 149 |
require "test_helper"
require "declarative/option"
class OptionTest < Minitest::Spec
def Option(*args)
Declarative::Option(*args)
end
# proc
it { Option( ->(*args) { "proc! #{args.inspect}" } ).(1,2).must_equal "proc! [1, 2]" }
it { Option( lambda { "proc!" } ).().must_equal "proc!" }
# proc with instance_exec
it { Option( ->(*args) { "#{self.class} #{args.inspect}" } ).(Object, 1, 2).must_equal "OptionTest [Object, 1, 2]" }
it { Option( ->(*args) { "#{self} #{args.inspect}" }, instance_exec: true ).(Object, 1, 2).must_equal "Object [1, 2]" }
# static
it { Option(true).().must_equal true }
it { Option(nil).().must_equal nil }
it { Option(false).().must_equal false }
# args are ignored.
it { Option(true).(1,2,3).must_equal true }
# instance method
class Hello
def hello(*args); "Hello! #{args.inspect}" end
end
it { Option(:hello).(Hello.new).must_equal "Hello! []" }
it { Option(:hello).(Hello.new, 1, 2).must_equal "Hello! [1, 2]" }
#---
# Callable
class Callio
include Declarative::Callable
def call(); "callable!" end
end
it { Option(Callio.new).().must_equal "callable!" }
#---
#- :callable overrides the marking class
class Callme
def call(*args); "callme! #{args}" end
end
it { Option(Callme.new, callable: Callme).().must_equal "callme! []" }
# { callable: Object } will do
# 1. proc?
# 2. method?
# 3. everything else is treated as callable.
describe "callable: Object" do
let (:options) { { callable: Object } }
it { Option(Callme.new, options).(1).must_equal "callme! [1]" }
# proc is detected before callable.
it { Option(->(*args) { "proc! #{args}" }, options).(1).must_equal "proc! [1]" }
# :method is detected before callable.
it { Option(:hello, options).(Hello.new, 1).must_equal "Hello! [1]" }
end
#---
#- override #callable?
class MyCallableOption < Declarative::Option
def callable?(*); true end
end
it { MyCallableOption.new.(Callme.new).().must_equal "callme! []" }
# proc is detected before callable.
it { MyCallableOption.new.(->(*args) { "proc! #{args.inspect}" }).(1).must_equal "proc! [1]" }
# :method is detected before callable.
it { MyCallableOption.new.(:hello).(Hello.new, 1).must_equal "Hello! [1]" }
end
| NullVoxPopuli/aeonvera | vendor/bundle/ruby/2.4.0/gems/declarative-option-0.1.0/test/option_test.rb | Ruby | agpl-3.0 | 2,337 |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { click, fillIn, render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import { setupIntl } from 'ember-intl/test-support';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { Response } from 'miragejs';
module('Integration | Component | registration', function(hooks) {
setupRenderingTest(hooks);
setupIntl(hooks);
setupMirage(hooks);
test('it renders', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-registration-form]").exists();
assert.dom("[data-test-registration-form-title]").hasText("t:register:()");
});
test('it should render email and company name always', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-registration-input-email]").exists();
assert.dom("[data-test-registration-input-company]").exists();
});
test('it should not render first name and last name by defaults', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-registration-input-email]").exists();
assert.dom("[data-test-registration-input-company]").exists();
assert.dom("[data-test-registration-input-fname]").doesNotExist();
assert.dom("[data-test-registration-input-lname]").doesNotExist();
});
test('it should render first name and last name if enable_name is true', async function(assert) {
this.set('enable_name', false);
await render(hbs`<Registration @enable_name={{this.enable_name}}></Registration>`);
assert.dom("[data-test-registration-input-fname]").doesNotExist();
assert.dom("[data-test-registration-input-lname]").doesNotExist();
this.set('enable_name', true);
await render(hbs`<Registration @enable_name={{this.enable_name}}></Registration>`);
assert.dom("[data-test-registration-input-fname]").exists();
assert.dom("[data-test-registration-input-lname]").exists();
});
test('it should show validation error for empty email', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-register-btn]").exists();
const register_btn = this.element.querySelector("[data-test-register-btn]");
await click(register_btn);
assert.dom("[data-test-registration-input-email-error]").hasText("Email must be a valid email address");
});
test('it should show validation error for invalid email', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-register-btn]").exists();
assert.dom("[data-test-registration-input-email]").exists();
const invalid_emails = [
"test",
"test@test",
"@test2",
"test@test.",
]
const register_btn = this.element.querySelector("[data-test-register-btn]");
const email_input = this.element.querySelector("[data-test-registration-input-email]");
for (let email of invalid_emails) {
fillIn(email_input, email);
await click(register_btn);
assert.dom("[data-test-registration-input-email-error]").hasText("Email must be a valid email address");
}
});
test('it should show not show validation error for valid email', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-register-btn]").exists();
assert.dom("[data-test-registration-input-email]").exists();
const valid_emails = [
"test@test.com",
]
const register_btn = this.element.querySelector("[data-test-register-btn]");
const email_input = this.element.querySelector("[data-test-registration-input-email]");
for (let email of valid_emails) {
fillIn(email_input, email);
await click(register_btn);
assert.dom("[data-test-registration-input-email-error]").doesNotExist();
}
});
test('it should show validation error for empty company', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-register-btn]").exists();
const register_btn = this.element.querySelector("[data-test-register-btn]");
await click(register_btn);
assert.dom("[data-test-registration-input-company-error]").hasText("Company can't be blank");
});
test('it should not show validation error for non-empty company', async function(assert) {
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-register-btn]").exists();
const register_btn = this.element.querySelector("[data-test-register-btn]");
const company_input = this.element.querySelector("[data-test-registration-input-company]");
fillIn(company_input, "Appknox");
await click(register_btn);
assert.dom("[data-test-registration-input-company-error]").doesNotExist();
});
test('it should show validation error for empty firstname and lastname', async function(assert) {
this.set('enable_name', true);
await render(hbs`<Registration @enable_name={{this.enable_name}}></Registration>`);
const register_btn = this.element.querySelector("[data-test-register-btn]");
await click(register_btn);
assert.dom("[data-test-registration-input-name-error]").hasText("Firstname can't be blank");
})
test('it should show success view for valid email and company', async function(assert) {
this.server.post('v2/registration', () => {
return new Response(204);
});
await render(hbs`<Registration></Registration>`);
assert.dom("[data-test-registration-success]").hasStyle({
'display': 'none'
});
assert.dom("[data-test-registration-form]").doesNotHaveStyle({
'display': 'none'
});
assert.dom("[data-test-register-btn]").exists();
const register_btn = this.element.querySelector("[data-test-register-btn]");
const email_input = this.element.querySelector("[data-test-registration-input-email]");
const company_input = this.element.querySelector("[data-test-registration-input-company]");
fillIn(email_input, "appknoxuser@appknox.com");
fillIn(company_input, "Appknox");
await click(register_btn);
assert.dom("[data-test-registration-input-company-error]").doesNotExist();
assert.dom("[data-test-registration-input-email-error]").doesNotExist();
assert.dom("[data-test-registration-success]").doesNotHaveStyle({
'display': 'none'
});
assert.dom("[data-test-registration-form]").hasStyle({
'display': 'none'
});
});
});
| appknox/irene | tests/integration/components/registration-test.js | JavaScript | agpl-3.0 | 6,538 |
/*
* RCairoGraphicsHandler.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
// include pango headers first so we can allow them to have their
// own definition of TRUE and FALSE (R will subsequently need to redefine
// them as Rboolean enumerated values)
#include <pango/pango.h>
#include <pango/pangocairo.h>
#undef TRUE
#undef FALSE
#include <math.h>
#include "RGraphicsHandler.hpp"
using namespace core ;
namespace r {
namespace session {
namespace graphics {
namespace handler {
namespace {
// NOTE: Cairo implementation forked from devX11.c and cairoX11.c
struct CairoDeviceData
{
CairoDeviceData()
: fontscale(0.0), lwdscale(0.0), surface(NULL), context(NULL)
{
}
double fontscale;
double lwdscale;
cairo_surface_t* surface;
cairo_t* context;
};
CairoDeviceData* devDescToCDD(pDevDesc devDesc)
{
DeviceContext* pDC = (DeviceContext*)devDesc->deviceSpecific;
return (CairoDeviceData*) pDC->pDeviceSpecific;
}
// these from devX11.c
double RedGamma = 1.0;
double GreenGamma = 1.0;
double BlueGamma = 1.0;
// this from Defn.h (used by Pango helper functions)
#define streql(s, t) (!strcmp((s), (t)))
void setCairoColor(unsigned int col, cairo_t *cc)
{
unsigned int alpha = R_ALPHA(col);
double red, blue, green;
red = R_RED(col)/255.0;
green = R_GREEN(col)/255.0;
blue = R_BLUE(col)/255.0;
red = pow(red, RedGamma);
green = pow(green, GreenGamma);
blue = pow(blue, BlueGamma);
/* These optimizations should not be necessary, but alpha = 1
seems to cause image fallback in some backends */
if (alpha == 255)
cairo_set_source_rgb(cc, red, green, blue);
else
cairo_set_source_rgba(cc, red, green, blue, alpha/255.0);
}
void setCairoLineType(const pGEcontext gc, CairoDeviceData* pCDD)
{
cairo_t *cc = pCDD->context;
double lwd = gc->lwd;
cairo_line_cap_t lcap = CAIRO_LINE_CAP_SQUARE;
cairo_line_join_t ljoin = CAIRO_LINE_JOIN_ROUND;
switch(gc->lend)
{
case GE_ROUND_CAP: lcap = CAIRO_LINE_CAP_ROUND; break;
case GE_BUTT_CAP: lcap = CAIRO_LINE_CAP_BUTT; break;
case GE_SQUARE_CAP: lcap = CAIRO_LINE_CAP_SQUARE; break;
}
switch(gc->ljoin)
{
case GE_ROUND_JOIN: ljoin = CAIRO_LINE_JOIN_ROUND; break;
case GE_MITRE_JOIN: ljoin = CAIRO_LINE_JOIN_MITER; break;
case GE_BEVEL_JOIN: ljoin = CAIRO_LINE_JOIN_BEVEL; break;
}
cairo_set_line_width(cc, (lwd > 0.01 ? lwd : 0.01) * pCDD->lwdscale);
cairo_set_line_cap(cc, lcap);
cairo_set_line_join(cc, ljoin);
cairo_set_miter_limit(cc, gc->lmitre);
if (gc->lty == 0 || gc->lty == -1)
cairo_set_dash(cc, 0, 0, 0);
else
{
double ls[16], lwd = (gc->lwd > 1) ? gc->lwd : 1;
int l, dt = gc->lty;
for (l = 0; dt != 0; dt >>= 4, l++)
ls[l] = (dt & 0xF) * lwd * pCDD->lwdscale;
cairo_set_dash(cc, ls, l, 0);
}
}
PangoFontDescription *PG_getFont(const pGEcontext gc, double fs)
{
PangoFontDescription *fontdesc;
gint face = gc->fontface;
double size = gc->cex * gc->ps * fs;
if (face < 1 || face > 5) face = 1;
fontdesc = pango_font_description_new();
if (face == 5)
{
pango_font_description_set_family(fontdesc, "symbol");
}
else
{
const char *fm = gc->fontfamily;
if(streql(fm, "mono")) fm = "courier";
else if(streql(fm, "serif")) fm = "times";
else if(streql(fm, "sans")) fm = "helvetica";
pango_font_description_set_family(fontdesc, fm[0] ? fm : "helvetica");
if(face == 2 || face == 4)
pango_font_description_set_weight(fontdesc, PANGO_WEIGHT_BOLD);
if(face == 3 || face == 4)
pango_font_description_set_style(fontdesc, PANGO_STYLE_OBLIQUE);
}
gint scaledSize = PANGO_SCALE * (gint)size;
pango_font_description_set_size(fontdesc, scaledSize);
return fontdesc;
}
PangoLayout *PG_layout(PangoFontDescription *desc, cairo_t *cc, const char *str)
{
// create the layout
PangoLayout *layout = pango_cairo_create_layout(cc);
pango_layout_set_font_description(layout, desc);
pango_layout_set_text(layout, str, -1);
return layout;
}
void PG_text_extents(cairo_t *cc,
PangoLayout *layout,
gint *lbearing,
gint *rbearing,
gint *width,
gint *ascent,
gint *descent,
int ink)
{
PangoRectangle rect, lrect;
pango_layout_line_get_pixel_extents(pango_layout_get_line(layout, 0),
&rect,
&lrect);
if(width)
*width = lrect.width;
if(ink)
{
if(ascent) *ascent = PANGO_ASCENT(rect);
if(descent) *descent = PANGO_DESCENT(rect);
if(lbearing) *lbearing = PANGO_LBEARING(rect);
if(rbearing) *rbearing = PANGO_RBEARING(rect);
}
else
{
if(ascent) *ascent = PANGO_ASCENT(lrect);
if(descent) *descent = PANGO_DESCENT(lrect);
if(lbearing) *lbearing = PANGO_LBEARING(lrect);
if(rbearing) *rbearing = PANGO_RBEARING(lrect);
}
}
bool completeInitialization(CairoDeviceData* pCDD)
{
// check whether we succeeded
cairo_status_t res = cairo_surface_status(pCDD->surface);
if (res != CAIRO_STATUS_SUCCESS)
{
Rf_warning("cairo error '%s'", cairo_status_to_string(res));
return false;
}
// initialize context
pCDD->context = cairo_create(pCDD->surface);
res = cairo_status(pCDD->context);
if (res != CAIRO_STATUS_SUCCESS)
{
Rf_warning("cairo error '%s'", cairo_status_to_string(res));
return false;
}
// initial drawing settings
cairo_set_operator(pCDD->context, CAIRO_OPERATOR_OVER);
cairo_reset_clip(pCDD->context);
cairo_set_antialias(pCDD->context, CAIRO_ANTIALIAS_SUBPIXEL);
// scales
pCDD->fontscale = 1.0;
// set lwdscale as per the behavior of devX11.c (not sure why the line
// width is scaled but we do so here to follow suit)
pCDD->lwdscale = 72.0 / 96.0;
// success
return true;
}
} // anonymous namespace
bool initialize(const FilePath& filePath,
int width,
int height,
bool displayListOn,
DeviceContext* pDC)
{
// initialize file info
pDC->targetPath = filePath;
pDC->width = width;
pDC->height = height;
// initialize cairo context
CairoDeviceData* pCDD = (CairoDeviceData*)pDC->pDeviceSpecific;
pCDD->surface = NULL;
pCDD->context = NULL;
// create surface
pCDD->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
width,
height);
// complete initialization
return completeInitialization(pCDD);
}
DeviceContext* allocate(pDevDesc dev)
{
DeviceContext* pDC = new DeviceContext(dev);
CairoDeviceData* pCDD = new CairoDeviceData();
pDC->pDeviceSpecific = pCDD;
return pDC;
}
void destroy(DeviceContext* pDC)
{
// first cleanup cairo constructs
CairoDeviceData* pCDD = (CairoDeviceData*)pDC->pDeviceSpecific;
if (pCDD->surface != NULL)
{
::cairo_surface_destroy(pCDD->surface);
pCDD->surface = NULL;
}
if (pCDD->context != NULL)
{
::cairo_destroy(pCDD->context);
pCDD->context = NULL;
}
// now free memory
delete pCDD;
delete pDC;
}
void setSize(pDevDesc pDev)
{
dev_desc::setSize(pDev);
}
void setDeviceAttributes(pDevDesc pDev)
{
int resolution = 72;
int pointSize = 12;
pDev->cra[0] = 0.9 * pointSize * resolution/72.0;
pDev->cra[1] = 1.2 * pointSize * resolution/72.0;
pDev->startps = pointSize;
pDev->ipr[0] = pDev->ipr[1] = 1.0/resolution;
pDev->xCharOffset = 0.4900;
pDev->yCharOffset = 0.3333;
pDev->yLineBias = 0.1;
pDev->canClip = TRUE;
pDev->canHAdj = 2;
pDev->canChangeGamma = FALSE;
pDev->startcol = R_RGB(0, 0, 0);
pDev->startfill = R_RGB(255, 255, 255);
pDev->startlty = LTY_SOLID;
pDev->startfont = 1;
pDev->startgamma = 1;
pDev->displayListOn = TRUE;
// no support for events yet
pDev->canGenMouseDown = FALSE;
pDev->canGenMouseMove = FALSE;
pDev->canGenMouseUp = FALSE;
pDev->canGenKeybd = FALSE;
pDev->gettingEvent = FALSE;
}
void onBeforeAddInteractiveDevice(DeviceContext* pDC)
{
}
void onAfterAddInteractiveDevice(DeviceContext* pDC)
{
}
bool resyncDisplayListBeforeWriteToPNG()
{
return true;
}
Error writeToPNG(const FilePath& targetPath,
DeviceContext* pDC,
bool /* keepContextAlive */)
{
CairoDeviceData* pCDD = (CairoDeviceData*)pDC->pDeviceSpecific;
std::string pngFile = targetPath.absolutePath();
cairo_status_t res = cairo_surface_write_to_png (pCDD->surface,
pngFile.c_str());
if (res != CAIRO_STATUS_SUCCESS)
{
std::string err = std::string("Cairo error saving PNG: ") +
cairo_status_to_string(res);
return systemError(boost::system::errc::io_error, err, ERROR_LOCATION);
}
else
{
return Success();
}
}
void circle(double x,
double y,
double r,
const pGEcontext gc,
pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
// tweak radius for legibility -- note that all of the other devices do
// this in some measure: devQuartz doubles the radius, devWindows doubles
// it with minimum of 2, etc. we add 1.0 because this yielded results
// that were optically simillar to devQuartz when running demo(graphics)
r += 1.0;
cairo_new_path(cc);
cairo_arc(cc, x, y, r, 0.0, 2 * M_PI);
if (R_ALPHA(gc->fill) > 0)
{
setCairoColor(gc->fill, cc);
cairo_fill_preserve(cc);
}
if (R_ALPHA(gc->col) > 0 && gc->lty != -1)
{
setCairoColor(gc->col, cc);
setCairoLineType(gc, pCDD);
cairo_stroke(cc);
}
}
void line(double x1,
double y1,
double x2,
double y2,
const pGEcontext gc,
pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
if (R_ALPHA(gc->col) > 0)
{
setCairoColor(gc->col, cc);
setCairoLineType(gc, pCDD);
cairo_new_path(cc);
cairo_move_to(cc, x1, y1);
cairo_line_to(cc, x2, y2);
cairo_stroke(cc);
}
}
void polygon(int n,
double *x,
double *y,
const pGEcontext gc,
pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
cairo_new_path(cc);
cairo_move_to(cc, x[0], y[0]);
for(int i = 0; i < n; i++) cairo_line_to(cc, x[i], y[i]);
cairo_close_path(cc);
if (R_ALPHA(gc->fill) > 0)
{
setCairoColor(gc->fill, cc);
cairo_fill_preserve(cc);
}
if (R_ALPHA(gc->col) > 0 && gc->lty != -1)
{
setCairoColor(gc->col, cc);
setCairoLineType(gc, pCDD);
cairo_stroke(cc);
}
}
void polyline(int n,
double *x,
double *y,
const pGEcontext gc,
pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
if (R_ALPHA(gc->col) > 0)
{
setCairoColor(gc->col, cc);
setCairoLineType(gc, pCDD);
cairo_new_path(cc);
cairo_move_to(cc, x[0], y[0]);
for(int i = 0; i < n; i++) cairo_line_to(cc, x[i], y[i]);
cairo_stroke(cc);
}
}
void rect(double x0,
double y0,
double x1,
double y1,
const pGEcontext gc,
pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
cairo_new_path(cc);
cairo_rectangle(cc, x0, y0, x1 - x0, y1 - y0);
if (R_ALPHA(gc->fill) > 0)
{
setCairoColor(gc->fill, cc);
cairo_fill_preserve(cc);
}
if (R_ALPHA(gc->col) > 0 && gc->lty != -1)
{
setCairoColor(gc->col, cc);
setCairoLineType(gc, pCDD);
cairo_stroke(cc);
}
}
void path(double *x,
double *y,
int npoly,
int *nper,
Rboolean winding,
const pGEcontext gc,
pDevDesc dev)
{
int i, j, n;
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
cairo_new_path(cc);
n = 0;
for (i=0; i < npoly; i++) {
cairo_move_to(cc, x[n], y[n]);
n++;
for(j=1; j < nper[i]; j++) {
cairo_line_to(cc, x[n], y[n]);
n++;
}
cairo_close_path(cc);
}
if (R_ALPHA(gc->fill) > 0) {
if (winding)
cairo_set_fill_rule(cc, CAIRO_FILL_RULE_WINDING);
else
cairo_set_fill_rule(cc, CAIRO_FILL_RULE_EVEN_ODD);
setCairoColor(gc->fill, cc);
cairo_fill_preserve(cc);
}
if (R_ALPHA(gc->col) > 0 && gc->lty != -1) {
setCairoColor(gc->col, cc);
setCairoLineType(gc, pCDD);
cairo_stroke(cc);
}
}
void raster(unsigned int *raster,
int w,
int h,
double x,
double y,
double width,
double height,
double rot,
Rboolean interpolate,
const pGEcontext gc,
pDevDesc dev)
{
const void *vmax = vmaxget();
int i;
cairo_surface_t *image;
unsigned char *imageData;
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
imageData = (unsigned char *) R_alloc(4*w*h, sizeof(unsigned char));
/* The R ABGR needs to be converted to a Cairo ARGB
* AND values need to by premultiplied by alpha
*/
for (i=0; i<w*h; i++) {
int alpha = R_ALPHA(raster[i]);
imageData[i*4 + 3] = alpha;
if (alpha < 255) {
imageData[i*4 + 2] = R_RED(raster[i]) * alpha / 255;
imageData[i*4 + 1] = R_GREEN(raster[i]) * alpha / 255;
imageData[i*4 + 0] = R_BLUE(raster[i]) * alpha / 255;
} else {
imageData[i*4 + 2] = R_RED(raster[i]);
imageData[i*4 + 1] = R_GREEN(raster[i]);
imageData[i*4 + 0] = R_BLUE(raster[i]);
}
}
image = cairo_image_surface_create_for_data(imageData,
CAIRO_FORMAT_ARGB32,
w, h,
4*w);
cairo_save(cc);
cairo_translate(cc, x, y);
cairo_rotate(cc, -rot*M_PI/180);
cairo_scale(cc, width/w, height/h);
/* Flip vertical first */
cairo_translate(cc, 0, h/2.0);
cairo_scale(cc, 1, -1);
cairo_translate(cc, 0, -h/2.0);
cairo_set_source_surface(cc, image, 0, 0);
if (interpolate) {
cairo_pattern_set_filter(cairo_get_source(cc),
CAIRO_FILTER_BILINEAR);
} else {
cairo_pattern_set_filter(cairo_get_source(cc),
CAIRO_FILTER_NEAREST);
}
cairo_paint(cc);
cairo_restore(cc);
cairo_surface_destroy(image);
vmaxset(vmax);
}
SEXP cap(pDevDesc dd)
{
return R_NilValue;
}
void metricInfo(int c,
const pGEcontext gc,
double* ascent,
double* descent,
double* width,
pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
char str[16];
int Unicode = mbcslocale;
PangoFontDescription *desc = PG_getFont(gc, pCDD->fontscale);
PangoLayout *layout;
gint iascent, idescent, iwidth;
if(c == 0) c = 77;
if(c < 0) {c = -c; Unicode = 1;}
if(Unicode) {
Rf_ucstoutf8(str, (unsigned int) c);
} else {
/* Here we assume that c < 256 */
str[0] = c; str[1] = 0;
}
layout = PG_layout(desc, cc, str);
PG_text_extents(cc, layout, NULL, NULL, &iwidth,
&iascent, &idescent, 1);
g_object_unref(layout);
pango_font_description_free(desc);
*ascent = iascent;
*descent = idescent;
*width = iwidth;
#if 0
printf("c = %d, '%s', face %d %f %f %f\n",
c, str, gc->fontface, *width, *ascent, *descent);
#endif
}
double strWidth(const char *str, const pGEcontext gc, pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
gint width;
PangoFontDescription *desc = PG_getFont(gc, pCDD->fontscale);
PangoLayout *layout = PG_layout(desc, cc, str);
PG_text_extents(cc, layout, NULL, NULL, &width, NULL, NULL, 0);
g_object_unref(layout);
pango_font_description_free(desc);
return (double) width;
}
void text(double x,
double y,
const char *str,
double rot,
double hadj,
const pGEcontext gc,
pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
gint ascent, lbearing, width;
PangoLayout *layout;
if (R_ALPHA(gc->col) > 0)
{
PangoFontDescription *desc = PG_getFont(gc, pCDD->fontscale);
cairo_save(cc);
layout = PG_layout(desc, cc, str);
PG_text_extents(cc, layout, &lbearing, NULL, &width,
&ascent, NULL, 0);
cairo_move_to(cc, x, y);
if (rot != 0.0) cairo_rotate(cc, -rot/180.*M_PI);
/* pango has a coord system at top left */
cairo_rel_move_to(cc, -lbearing - width*hadj, -ascent);
setCairoColor(gc->col, cc);
pango_cairo_show_layout(cc, layout);
cairo_restore(cc);
g_object_unref(layout);
pango_font_description_free(desc);
}
}
void clip(double x0, double x1, double y0, double y1, pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
if (x1 < x0) { double h = x1; x1 = x0; x0 = h; };
if (y1 < y0) { double h = y1; y1 = y0; y0 = h; };
cairo_reset_clip(cc);
cairo_new_path(cc);
/* Add 1 per X11_Clip */
cairo_rectangle(cc, x0, y0, x1 - x0 + 1, y1 - y0 + 1);
cairo_clip(cc);
}
void newPage(const pGEcontext gc, pDevDesc dev)
{
CairoDeviceData* pCDD = devDescToCDD(dev);
cairo_t* cc = pCDD->context;
cairo_reset_clip(cc);
/* First clear it */
cairo_set_operator (cc, CAIRO_OPERATOR_CLEAR);
cairo_paint (cc);
cairo_set_operator (cc, CAIRO_OPERATOR_OVER);
setCairoColor(gc->fill, cc);
cairo_new_path(cc);
cairo_paint(cc);
}
void mode(int mode, pDevDesc dev)
{
}
void onBeforeExecute(DeviceContext* pDC)
{
}
} // namespace handler
} // namespace graphics
} // namespace session
} // namespace r
| Sage-Bionetworks/rstudio | src/cpp/r/session/graphics/handler/RCairoGraphicsHandler.cpp | C++ | agpl-3.0 | 19,042 |
package engine;
public enum EntityType {
TAG,
RESOURCE,
USER
} | learning-layers/TagRec | src/engine/EntityType.java | Java | agpl-3.0 | 66 |
""" Code to allow module store to interface with courseware index """
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
from datetime import timedelta
import logging
import re
from six import add_metaclass
from django.conf import settings
from django.utils.translation import ugettext_lazy, ugettext as _
from django.core.urlresolvers import resolve
from contentstore.course_group_config import GroupConfiguration
from course_modes.models import CourseMode
from eventtracking import tracker
from openedx.core.lib.courses import course_image_url
from search.search_engine_base import SearchEngine
from xmodule.annotator_mixin import html_to_text
from xmodule.modulestore import ModuleStoreEnum
from xmodule.library_tools import normalize_key_for_search
# REINDEX_AGE is the default amount of time that we look back for changes
# that might have happened. If we are provided with a time at which the
# indexing is triggered, then we know it is safe to only index items
# recently changed at that time. This is the time period that represents
# how far back from the trigger point to look back in order to index
REINDEX_AGE = timedelta(0, 60) # 60 seconds
log = logging.getLogger('edx.modulestore')
def strip_html_content_to_text(html_content):
""" Gets only the textual part for html content - useful for building text to be searched """
# Removing HTML-encoded non-breaking space characters
text_content = re.sub(r"(\s| |//)+", " ", html_to_text(html_content))
# Removing HTML CDATA
text_content = re.sub(r"<!\[CDATA\[.*\]\]>", "", text_content)
# Removing HTML comments
text_content = re.sub(r"<!--.*-->", "", text_content)
return text_content
def indexing_is_enabled():
"""
Checks to see if the indexing feature is enabled
"""
return settings.FEATURES.get('ENABLE_COURSEWARE_INDEX', False)
class SearchIndexingError(Exception):
""" Indicates some error(s) occured during indexing """
def __init__(self, message, error_list):
super(SearchIndexingError, self).__init__(message)
self.error_list = error_list
@add_metaclass(ABCMeta)
class SearchIndexerBase(object):
"""
Base class to perform indexing for courseware or library search from different modulestores
"""
__metaclass__ = ABCMeta
INDEX_NAME = None
DOCUMENT_TYPE = None
ENABLE_INDEXING_KEY = None
INDEX_EVENT = {
'name': None,
'category': None
}
@classmethod
def indexing_is_enabled(cls):
"""
Checks to see if the indexing feature is enabled
"""
return settings.FEATURES.get(cls.ENABLE_INDEXING_KEY, False)
@classmethod
@abstractmethod
def normalize_structure_key(cls, structure_key):
""" Normalizes structure key for use in indexing """
@classmethod
@abstractmethod
def _fetch_top_level(cls, modulestore, structure_key):
""" Fetch the item from the modulestore location """
@classmethod
@abstractmethod
def _get_location_info(cls, normalized_structure_key):
""" Builds location info dictionary """
@classmethod
def _id_modifier(cls, usage_id):
""" Modifies usage_id to submit to index """
return usage_id
@classmethod
def remove_deleted_items(cls, searcher, structure_key, exclude_items):
"""
remove any item that is present in the search index that is not present in updated list of indexed items
as we find items we can shorten the set of items to keep
"""
response = searcher.search(
doc_type=cls.DOCUMENT_TYPE,
field_dictionary=cls._get_location_info(structure_key),
exclude_dictionary={"id": list(exclude_items)}
)
result_ids = [result["data"]["id"] for result in response["results"]]
searcher.remove(cls.DOCUMENT_TYPE, result_ids)
@classmethod
def index(cls, modulestore, structure_key, triggered_at=None, reindex_age=REINDEX_AGE):
"""
Process course for indexing
Arguments:
modulestore - modulestore object to use for operations
structure_key (CourseKey|LibraryKey) - course or library identifier
triggered_at (datetime) - provides time at which indexing was triggered;
useful for index updates - only things changed recently from that date
(within REINDEX_AGE above ^^) will have their index updated, others skip
updating their index but are still walked through in order to identify
which items may need to be removed from the index
If None, then a full reindex takes place
Returns:
Number of items that have been added to the index
"""
error_list = []
searcher = SearchEngine.get_search_engine(cls.INDEX_NAME)
if not searcher:
return
structure_key = cls.normalize_structure_key(structure_key)
location_info = cls._get_location_info(structure_key)
# Wrap counter in dictionary - otherwise we seem to lose scope inside the embedded function `prepare_item_index`
indexed_count = {
"count": 0
}
# indexed_items is a list of all the items that we wish to remain in the
# index, whether or not we are planning to actually update their index.
# This is used in order to build a query to remove those items not in this
# list - those are ready to be destroyed
indexed_items = set()
# items_index is a list of all the items index dictionaries.
# it is used to collect all indexes and index them using bulk API,
# instead of per item index API call.
items_index = []
def get_item_location(item):
"""
Gets the version agnostic item location
"""
return item.location.version_agnostic().replace(branch=None)
def prepare_item_index(item, skip_index=False, groups_usage_info=None):
"""
Add this item to the items_index and indexed_items list
Arguments:
item - item to add to index, its children will be processed recursively
skip_index - simply walk the children in the tree, the content change is
older than the REINDEX_AGE window and would have been already indexed.
This should really only be passed from the recursive child calls when
this method has determined that it is safe to do so
Returns:
item_content_groups - content groups assigned to indexed item
"""
is_indexable = hasattr(item, "index_dictionary")
item_index_dictionary = item.index_dictionary() if is_indexable else None
# if it's not indexable and it does not have children, then ignore
if not item_index_dictionary and not item.has_children:
return
item_content_groups = None
if item.category == "split_test":
split_partition = item.get_selected_partition()
for split_test_child in item.get_children():
if split_partition:
for group in split_partition.groups:
group_id = unicode(group.id)
child_location = item.group_id_to_child.get(group_id, None)
if child_location == split_test_child.location:
groups_usage_info.update({
unicode(get_item_location(split_test_child)): [group_id],
})
for component in split_test_child.get_children():
groups_usage_info.update({
unicode(get_item_location(component)): [group_id]
})
if groups_usage_info:
item_location = get_item_location(item)
item_content_groups = groups_usage_info.get(unicode(item_location), None)
item_id = unicode(cls._id_modifier(item.scope_ids.usage_id))
indexed_items.add(item_id)
if item.has_children:
# determine if it's okay to skip adding the children herein based upon how recently any may have changed
skip_child_index = skip_index or \
(triggered_at is not None and (triggered_at - item.subtree_edited_on) > reindex_age)
children_groups_usage = []
for child_item in item.get_children():
if modulestore.has_published_version(child_item):
children_groups_usage.append(
prepare_item_index(
child_item,
skip_index=skip_child_index,
groups_usage_info=groups_usage_info
)
)
if None in children_groups_usage:
item_content_groups = None
if skip_index or not item_index_dictionary:
return
item_index = {}
# if it has something to add to the index, then add it
try:
item_index.update(location_info)
item_index.update(item_index_dictionary)
item_index['id'] = item_id
if item.start:
item_index['start_date'] = item.start
item_index['content_groups'] = item_content_groups if item_content_groups else None
item_index.update(cls.supplemental_fields(item))
items_index.append(item_index)
indexed_count["count"] += 1
return item_content_groups
except Exception as err: # pylint: disable=broad-except
# broad exception so that index operation does not fail on one item of many
log.warning('Could not index item: %s - %r', item.location, err)
error_list.append(_('Could not index item: {}').format(item.location))
try:
with modulestore.branch_setting(ModuleStoreEnum.RevisionOption.published_only):
structure = cls._fetch_top_level(modulestore, structure_key)
groups_usage_info = cls.fetch_group_usage(modulestore, structure)
# First perform any additional indexing from the structure object
cls.supplemental_index_information(modulestore, structure)
# Now index the content
for item in structure.get_children():
prepare_item_index(item, groups_usage_info=groups_usage_info)
searcher.index(cls.DOCUMENT_TYPE, items_index)
cls.remove_deleted_items(searcher, structure_key, indexed_items)
except Exception as err: # pylint: disable=broad-except
# broad exception so that index operation does not prevent the rest of the application from working
log.exception(
"Indexing error encountered, courseware index may be out of date %s - %r",
structure_key,
err
)
error_list.append(_('General indexing error occurred'))
if error_list:
raise SearchIndexingError('Error(s) present during indexing', error_list)
return indexed_count["count"]
@classmethod
def _do_reindex(cls, modulestore, structure_key):
"""
(Re)index all content within the given structure (course or library),
tracking the fact that a full reindex has taken place
"""
indexed_count = cls.index(modulestore, structure_key)
if indexed_count:
cls._track_index_request(cls.INDEX_EVENT['name'], cls.INDEX_EVENT['category'], indexed_count)
return indexed_count
@classmethod
def _track_index_request(cls, event_name, category, indexed_count):
"""Track content index requests.
Arguments:
event_name (str): Name of the event to be logged.
category (str): category of indexed items
indexed_count (int): number of indexed items
Returns:
None
"""
data = {
"indexed_count": indexed_count,
'category': category,
}
tracker.emit(
event_name,
data
)
@classmethod
def fetch_group_usage(cls, modulestore, structure): # pylint: disable=unused-argument
"""
Base implementation of fetch group usage on course/library.
"""
return None
@classmethod
def supplemental_index_information(cls, modulestore, structure):
"""
Perform any supplemental indexing given that the structure object has
already been loaded. Base implementation performs no operation.
Arguments:
modulestore - modulestore object used during the indexing operation
structure - structure object loaded during the indexing job
Returns:
None
"""
pass
@classmethod
def supplemental_fields(cls, item): # pylint: disable=unused-argument
"""
Any supplemental fields that get added to the index for the specified
item. Base implementation returns an empty dictionary
"""
return {}
class CoursewareSearchIndexer(SearchIndexerBase):
"""
Class to perform indexing for courseware search from different modulestores
"""
INDEX_NAME = "courseware_index"
DOCUMENT_TYPE = "courseware_content"
ENABLE_INDEXING_KEY = 'ENABLE_COURSEWARE_INDEX'
INDEX_EVENT = {
'name': 'edx.course.index.reindexed',
'category': 'courseware_index'
}
UNNAMED_MODULE_NAME = ugettext_lazy("(Unnamed)")
@classmethod
def normalize_structure_key(cls, structure_key):
""" Normalizes structure key for use in indexing """
return structure_key
@classmethod
def _fetch_top_level(cls, modulestore, structure_key):
""" Fetch the item from the modulestore location """
return modulestore.get_course(structure_key, depth=None)
@classmethod
def _get_location_info(cls, normalized_structure_key):
""" Builds location info dictionary """
return {"course": unicode(normalized_structure_key), "org": normalized_structure_key.org}
@classmethod
def do_course_reindex(cls, modulestore, course_key):
"""
(Re)index all content within the given course, tracking the fact that a full reindex has taken place
"""
return cls._do_reindex(modulestore, course_key)
@classmethod
def fetch_group_usage(cls, modulestore, structure):
groups_usage_dict = {}
groups_usage_info = GroupConfiguration.get_content_groups_usage_info(modulestore, structure).items()
groups_usage_info.extend(
GroupConfiguration.get_content_groups_items_usage_info(
modulestore,
structure
).items()
)
if groups_usage_info:
for name, group in groups_usage_info:
for module in group:
view, args, kwargs = resolve(module['url']) # pylint: disable=unused-variable
usage_key_string = unicode(kwargs['usage_key_string'])
if groups_usage_dict.get(usage_key_string, None):
groups_usage_dict[usage_key_string].append(name)
else:
groups_usage_dict[usage_key_string] = [name]
return groups_usage_dict
@classmethod
def supplemental_index_information(cls, modulestore, structure):
"""
Perform additional indexing from loaded structure object
"""
CourseAboutSearchIndexer.index_about_information(modulestore, structure)
@classmethod
def supplemental_fields(cls, item):
"""
Add location path to the item object
Once we've established the path of names, the first name is the course
name, and the next 3 names are the navigable path within the edx
application. Notice that we stop at that level because a full path to
deep children would be confusing.
"""
location_path = []
parent = item
while parent is not None:
path_component_name = parent.display_name
if not path_component_name:
path_component_name = unicode(cls.UNNAMED_MODULE_NAME)
location_path.append(path_component_name)
parent = parent.get_parent()
location_path.reverse()
return {
"course_name": location_path[0],
"location": location_path[1:4]
}
class LibrarySearchIndexer(SearchIndexerBase):
"""
Base class to perform indexing for library search from different modulestores
"""
INDEX_NAME = "library_index"
DOCUMENT_TYPE = "library_content"
ENABLE_INDEXING_KEY = 'ENABLE_LIBRARY_INDEX'
INDEX_EVENT = {
'name': 'edx.library.index.reindexed',
'category': 'library_index'
}
@classmethod
def normalize_structure_key(cls, structure_key):
""" Normalizes structure key for use in indexing """
return normalize_key_for_search(structure_key)
@classmethod
def _fetch_top_level(cls, modulestore, structure_key):
""" Fetch the item from the modulestore location """
return modulestore.get_library(structure_key, depth=None)
@classmethod
def _get_location_info(cls, normalized_structure_key):
""" Builds location info dictionary """
return {"library": unicode(normalized_structure_key)}
@classmethod
def _id_modifier(cls, usage_id):
""" Modifies usage_id to submit to index """
return usage_id.replace(library_key=(usage_id.library_key.replace(version_guid=None, branch=None)))
@classmethod
def do_library_reindex(cls, modulestore, library_key):
"""
(Re)index all content within the given library, tracking the fact that a full reindex has taken place
"""
return cls._do_reindex(modulestore, library_key)
class AboutInfo(object):
""" About info structure to contain
1) Property name to use
2) Where to add in the index (using flags above)
3) Where to source the properties value
"""
# Bitwise Flags for where to index the information
#
# ANALYSE - states that the property text contains content that we wish to be able to find matched within
# e.g. "joe" should yield a result for "I'd like to drink a cup of joe"
#
# PROPERTY - states that the property text should be a property of the indexed document, to be returned with the
# results: search matches will only be made on exact string matches
# e.g. "joe" will only match on "joe"
#
# We are using bitwise flags because one may want to add the property to EITHER or BOTH parts of the index
# e.g. university name is desired to be analysed, so that a search on "Oxford" will match
# property values "University of Oxford" and "Oxford Brookes University",
# but it is also a useful property, because within a (future) filtered search a user
# may have chosen to filter courses from "University of Oxford"
#
# see https://wiki.python.org/moin/BitwiseOperators for information about bitwise shift operator used below
#
ANALYSE = 1 << 0 # Add the information to the analysed content of the index
PROPERTY = 1 << 1 # Add the information as a property of the object being indexed (not analysed)
def __init__(self, property_name, index_flags, source_from):
self.property_name = property_name
self.index_flags = index_flags
self.source_from = source_from
def get_value(self, **kwargs):
""" get the value for this piece of information, using the correct source """
return self.source_from(self, **kwargs)
def from_about_dictionary(self, **kwargs):
""" gets the value from the kwargs provided 'about_dictionary' """
about_dictionary = kwargs.get('about_dictionary', None)
if not about_dictionary:
raise ValueError("Context dictionary does not contain expected argument 'about_dictionary'")
return about_dictionary.get(self.property_name, None)
def from_course_property(self, **kwargs):
""" gets the value from the kwargs provided 'course' """
course = kwargs.get('course', None)
if not course:
raise ValueError("Context dictionary does not contain expected argument 'course'")
return getattr(course, self.property_name, None)
def from_course_mode(self, **kwargs):
""" fetches the available course modes from the CourseMode model """
course = kwargs.get('course', None)
if not course:
raise ValueError("Context dictionary does not contain expected argument 'course'")
return [mode.slug for mode in CourseMode.modes_for_course(course.id)]
# Source location options - either from the course or the about info
FROM_ABOUT_INFO = from_about_dictionary
FROM_COURSE_PROPERTY = from_course_property
FROM_COURSE_MODE = from_course_mode
class CourseAboutSearchIndexer(object):
"""
Class to perform indexing of about information from course object
"""
DISCOVERY_DOCUMENT_TYPE = "course_info"
INDEX_NAME = CoursewareSearchIndexer.INDEX_NAME
# List of properties to add to the index - each item in the list is an instance of AboutInfo object
ABOUT_INFORMATION_TO_INCLUDE = [
AboutInfo("advertised_start", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("announcement", AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("start", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("end", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("effort", AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("display_name", AboutInfo.ANALYSE, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("overview", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("title", AboutInfo.ANALYSE | AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("university", AboutInfo.ANALYSE | AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("number", AboutInfo.ANALYSE | AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("short_description", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("description", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("key_dates", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("video", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("course_staff_short", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("course_staff_extended", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("requirements", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("syllabus", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("textbook", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("faq", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("more_info", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("ocw_links", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
AboutInfo("enrollment_start", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("enrollment_end", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("org", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
AboutInfo("modes", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_MODE),
AboutInfo("language", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
]
@classmethod
def index_about_information(cls, modulestore, course):
"""
Add the given course to the course discovery index
Arguments:
modulestore - modulestore object to use for operations
course - course object from which to take properties, locate about information
"""
searcher = SearchEngine.get_search_engine(cls.INDEX_NAME)
if not searcher:
return
course_id = unicode(course.id)
course_info = {
'id': course_id,
'course': course_id,
'content': {},
'image_url': course_image_url(course),
}
# load data for all of the 'about' modules for this course into a dictionary
about_dictionary = {
item.location.name: item.data
for item in modulestore.get_items(course.id, qualifiers={"category": "about"})
}
about_context = {
"course": course,
"about_dictionary": about_dictionary,
}
for about_information in cls.ABOUT_INFORMATION_TO_INCLUDE:
# Broad exception handler so that a single bad property does not scupper the collection of others
try:
section_content = about_information.get_value(**about_context)
except: # pylint: disable=bare-except
section_content = None
log.warning(
"Course discovery could not collect property %s for course %s",
about_information.property_name,
course_id,
exc_info=True,
)
if section_content:
if about_information.index_flags & AboutInfo.ANALYSE:
analyse_content = section_content
if isinstance(section_content, basestring):
analyse_content = strip_html_content_to_text(section_content)
course_info['content'][about_information.property_name] = analyse_content
if about_information.index_flags & AboutInfo.PROPERTY:
course_info[about_information.property_name] = section_content
# Broad exception handler to protect around and report problems with indexing
try:
searcher.index(cls.DISCOVERY_DOCUMENT_TYPE, [course_info])
except: # pylint: disable=bare-except
log.exception(
"Course discovery indexing error encountered, course discovery index may be out of date %s",
course_id,
)
raise
log.debug(
"Successfully added %s course to the course discovery index",
course_id
)
@classmethod
def _get_location_info(cls, normalized_structure_key):
""" Builds location info dictionary """
return {"course": unicode(normalized_structure_key), "org": normalized_structure_key.org}
@classmethod
def remove_deleted_items(cls, structure_key):
""" Remove item from Course About Search_index """
searcher = SearchEngine.get_search_engine(cls.INDEX_NAME)
if not searcher:
return
response = searcher.search(
doc_type=cls.DISCOVERY_DOCUMENT_TYPE,
field_dictionary=cls._get_location_info(structure_key)
)
result_ids = [result["data"]["id"] for result in response["results"]]
searcher.remove(cls.DISCOVERY_DOCUMENT_TYPE, result_ids)
| naresh21/synergetics-edx-platform | cms/djangoapps/contentstore/courseware_index.py | Python | agpl-3.0 | 27,600 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Avanzosc - Avanced Open Source Consulting
# Copyright (C) 2011 - 2013 Avanzosc <http://www.avanzosc.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
import stock_production_lot_ext
import stock_picking_ext
import stock_move_ext
import purchase_order_ext
import stock_move_split_ext
| avanzosc/avanzosc6.1 | avanzosc_net_weight_in_lots/__init__.py | Python | agpl-3.0 | 1,119 |
# coding: utf-8
# The Hazard Library
# Copyright (C) 2012 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Module exports :class:`AtkinsonWald2007`.
"""
from __future__ import division
import numpy as np
from openquake.hazardlib.gsim.base import IPE
from openquake.hazardlib import const
from openquake.hazardlib.imt import MMI
class AtkinsonWald2007(IPE):
"""
Implements IPE developed by Atkinson and Wald (2007)
California, USA
MS!
"""
DEFINED_FOR_TECTONIC_REGION_TYPE = const.TRT.ACTIVE_SHALLOW_CRUST
DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([
MMI
])
DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = const.IMC.AVERAGE_HORIZONTAL
DEFINED_FOR_STANDARD_DEVIATION_TYPES = set([
const.StdDev.TOTAL
])
# TODO !
REQUIRES_SITES_PARAMETERS = set(('vs30', ))
REQUIRES_RUPTURE_PARAMETERS = set(('mag',))
REQUIRES_DISTANCES = set(('rrup', ))
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
h = 14.0
R = np.sqrt(dists.rrup**2 + h**2)
B = np.zeros_like(dists.rrup)
B[R > 30.] = np.log10(R / 30.)[R > 30.]
mean_mmi = 12.27 + 2.270 * (rup.mag - 6) + 0.1304 * (rup.mag - 6)**2 - 1.30 * np.log10(R) - 0.0007070 * R + 1.95 * B - 0.577 * rup.mag * np.log10(R)
mean_mmi += self.compute_site_term(sites)
mean_mmi = mean_mmi.clip(min=1, max=12)
stddevs = np.zeros_like(dists.rrup)
stddevs.fill(0.4)
stddevs = stddevs.reshape(1, len(stddevs))
return mean_mmi, stddevs
def compute_site_term(self, sites):
# TODO !
return 0
| ROB-Seismology/oq-hazardlib | openquake/hazardlib/gsim/atkinson_wald_2007.py | Python | agpl-3.0 | 2,419 |
<?php
namespace MailBundle\Form\Admin\MailingList\Entry;
use CommonBundle\Entity\User\Person;
use MailBundle\Entity\MailingList as MailingListEntity;
/**
* Add MailingList
*
* @author Pieter Maene <pieter.maene@litus.cc>
*/
class MailingList extends \CommonBundle\Component\Form\Admin\Form
{
protected $hydrator = 'MailBundle\Hydrator\MailingList\Entry\MailingList';
/**
* @var Person The authenticated person
*/
protected $person = null;
/**
* @var MailingListEntity The current list
*/
protected $list = null;
public function init()
{
parent::init();
$this->add(
array(
'type' => 'select',
'name' => 'entry',
'label' => 'List',
'required' => true,
'options' => array(
'options' => $this->createEntriesArray(),
'input' => array(
'validators' => array(
array(
'name' => 'EntryMailingList',
'options' => array(
'list' => $this->getList(),
),
),
),
),
),
)
);
$this->add(
array(
'type' => 'submit',
'name' => 'list_add',
'value' => 'Add',
'attributes' => array(
'class' => 'mail_add',
),
)
);
}
private function createEntriesArray()
{
$editor = false;
foreach ($this->getPerson()->getFlattenedRoles() as $role) {
if ($role->getName() == 'editor') {
$editor = true;
break;
}
}
$lists = $this->getEntityManager()
->getRepository('MailBundle\Entity\MailingList\Named')
->findBy(array(), array('name' => 'ASC'));
if (!$editor) {
$listsArray = array();
foreach ($lists as $list) {
if ($list->canBeEditedBy($this->getPerson())) {
$listsArray[] = $list;
}
}
} else {
$listsArray = $lists;
}
foreach ($listsArray as $key => $value) {
$lists = $this->getEntityManager()
->getRepository('MailBundle\Entity\MailingList\Entry\MailingList')
->findBy(
array(
'list' => $this->getList(),
'entry' => $value,
)
);
if ($value === $this->getList() || count($lists) > 0) {
unset($listsArray[$key]);
}
}
$lists = array();
foreach ($listsArray as $list) {
$lists[$list->getId()] = $list->getName();
}
return $lists;
}
/**
* @param MailingListEntity $list
* @return self
*/
public function setList(MailingListEntity $list)
{
$this->list = $list;
return $this;
}
/**
* @return MailingListEntity
*/
public function getList()
{
return $this->list;
}
/**
* @param Person $person
* @return self
*/
public function setPerson(Person $person)
{
$this->person = $person;
return $this;
}
/**
* @return Person
*/
public function getPerson()
{
return $this->person;
}
}
| LitusProject/Litus | module/MailBundle/Form/Admin/MailingList/Entry/MailingList.php | PHP | agpl-3.0 | 3,684 |
package client
import (
"bytes"
"errors"
"io"
"sort"
"strings"
"testing"
"time"
"github.com/grafana/loki/pkg/loghttp"
"github.com/grafana/loki/pkg/logproto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFileClient_QueryRangeLogQueries(t *testing.T) {
input := []string{
`level=info event="loki started" caller=main.go ts=1625995076`,
`level=info event="runtime loader started" caller=main.go ts=1625995077`,
`level=error event="unable to read rules directory" file="/tmp/rules" caller=rules.go ts=1625995090`,
`level=error event="failed to apply wal" error="/tmp/wal/ corrupted" caller=wal.go ts=1625996090`,
`level=info event="loki ready" caller=main.go ts=1625996095`,
}
reversed := make([]string, len(input))
copy(reversed, input)
sort.Slice(reversed, func(i, j int) bool {
return i > j
})
now := time.Now()
cases := []struct {
name string
limit int
start, end time.Time
direction logproto.Direction
step, interval time.Duration
expectedStatus loghttp.QueryStatus
expected []string
}{
{
name: "return-all-logs-backward",
limit: 10, // more than input
start: now.Add(-1 * time.Hour),
end: now,
direction: logproto.BACKWARD,
step: 0, // let client decide based on start and end
interval: 0,
expectedStatus: loghttp.QueryStatusSuccess,
expected: reversed,
},
{
name: "return-all-logs-forward",
limit: 10, // more than input
start: now.Add(-1 * time.Hour),
end: now,
direction: logproto.FORWARD,
step: 0, // let the client decide based on start and end
interval: 0,
expectedStatus: loghttp.QueryStatusSuccess,
expected: input,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
client := NewFileClient(io.NopCloser(strings.NewReader(strings.Join(input, "\n"))))
resp, err := client.QueryRange(
`{foo="bar"}`, // label matcher doesn't matter.
c.limit,
c.start,
c.end,
c.direction,
c.step,
c.interval,
true,
)
require.NoError(t, err)
require.Equal(t, loghttp.QueryStatusSuccess, resp.Status)
assert.Equal(t, string(resp.Data.ResultType), loghttp.ResultTypeStream)
assertStreams(t, resp.Data.Result, c.expected)
})
}
}
func TestFileClient_Query(t *testing.T) {
input := []string{
`level=info event="loki started" caller=main.go ts=1625995076`,
`level=info event="runtime loader started" caller=main.go ts=1625995077`,
`level=error event="unable to read rules directory" file="/tmp/rules" caller=rules.go ts=1625995090`,
`level=error event="failed to apply wal" error="/tmp/wal/ corrupted" caller=wal.go ts=1625996090`,
`level=info event="loki ready" caller=main.go ts=1625996095`,
}
reversed := make([]string, len(input))
copy(reversed, input)
sort.Slice(reversed, func(i, j int) bool {
return i > j
})
now := time.Now()
cases := []struct {
name string
limit int
ts time.Time
direction logproto.Direction
expectedStatus loghttp.QueryStatus
expected []string
}{
{
name: "return-all-logs-backward",
limit: 10, // more than input
ts: now.Add(-1 * time.Hour),
direction: logproto.BACKWARD,
expectedStatus: loghttp.QueryStatusSuccess,
expected: reversed,
},
{
name: "return-all-logs-forward",
limit: 10, // more than input
ts: now.Add(-1 * time.Hour),
direction: logproto.FORWARD,
expectedStatus: loghttp.QueryStatusSuccess,
expected: input,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
client := NewFileClient(io.NopCloser(strings.NewReader(strings.Join(input, "\n"))))
resp, err := client.Query(
`{foo="bar"}`, // label matcher doesn't matter.
c.limit,
c.ts,
c.direction,
true,
)
require.NoError(t, err)
require.Equal(t, loghttp.QueryStatusSuccess, resp.Status)
assert.Equal(t, string(resp.Data.ResultType), loghttp.ResultTypeStream)
assertStreams(t, resp.Data.Result, c.expected)
})
}
}
func TestFileClient_ListLabelNames(t *testing.T) {
c := newEmptyClient(t)
values, err := c.ListLabelNames(true, time.Now(), time.Now())
require.NoError(t, err)
assert.Equal(t, &loghttp.LabelResponse{
Data: []string{defaultLabelKey},
Status: loghttp.QueryStatusSuccess,
}, values)
}
func TestFileClient_ListLabelValues(t *testing.T) {
c := newEmptyClient(t)
values, err := c.ListLabelValues(defaultLabelKey, true, time.Now(), time.Now())
require.NoError(t, err)
assert.Equal(t, &loghttp.LabelResponse{
Data: []string{defaultLabelValue},
Status: loghttp.QueryStatusSuccess,
}, values)
}
func TestFileClient_Series(t *testing.T) {
c := newEmptyClient(t)
got, err := c.Series(nil, time.Now(), time.Now(), true)
require.NoError(t, err)
exp := &loghttp.SeriesResponse{
Data: []loghttp.LabelSet{
{defaultLabelKey: defaultLabelValue},
},
Status: loghttp.QueryStatusSuccess,
}
assert.Equal(t, exp, got)
}
func TestFileClient_LiveTail(t *testing.T) {
c := newEmptyClient(t)
x, err := c.LiveTailQueryConn("", time.Second, 0, time.Now(), true)
require.Error(t, err)
require.Nil(t, x)
assert.True(t, errors.Is(err, ErrNotSupported))
}
func TestFileClient_GetOrgID(t *testing.T) {
c := newEmptyClient(t)
assert.Equal(t, defaultOrgID, c.GetOrgID())
}
func newEmptyClient(t *testing.T) *FileClient {
t.Helper()
return NewFileClient(io.NopCloser(&bytes.Buffer{}))
}
func assertStreams(t *testing.T, result loghttp.ResultValue, logLines []string) {
t.Helper()
streams, ok := result.(loghttp.Streams)
require.True(t, ok, "response type should be `loghttp.Streams`")
require.Len(t, streams, 1, "there should be only one stream for FileClient")
got := streams[0]
sort.Slice(got.Entries, func(i, j int) bool {
return got.Entries[i].Timestamp.UnixNano() < got.Entries[j].Timestamp.UnixNano()
})
require.Equal(t, len(got.Entries), len(logLines))
for i, entry := range got.Entries {
assert.Equal(t, entry.Line, logLines[i])
}
}
| grafana/loki | pkg/logcli/client/file_test.go | GO | agpl-3.0 | 6,233 |
# Brimir is a helpdesk system to handle email support requests.
# Copyright (C) 2012-2015 Ivaldi https://ivaldi.nl/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class ApplicationController < ActionController::Base
rescue_from DeviseLdapAuthenticatable::LdapException do |exception|
render text: exception, status: 500
end
protect_from_forgery with: :null_session
before_action :load_tenant
before_action :authenticate_user!
before_action :set_locale
before_action :load_labels, if: :user_signed_in?
check_authorization unless: :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
if Rails.env == :production
redirect_to root_url, alert: exception.message
else
# for tests and development, we want unauthorized status codes
render text: exception, status: :unauthorized
end
end
protected
def load_labels
@labels = Label.viewable_by(current_user).ordered
end
def set_locale
@time_zones = ActiveSupport::TimeZone.all.map(&:name).sort
@locales = []
Dir.open("#{Rails.root}/config/locales").each do |file|
unless ['.', '..'].include?(file) || file[0] == '.'
code = file[0...-4] # strip of .yml
@locales << [I18n.translate(:language_name, locale: code), code]
end
end
if user_signed_in? && !current_user.locale.blank?
I18n.locale = current_user.locale
else
locale = http_accept_language.compatible_language_from(@locales)
if Tenant.current_tenant.ignore_user_agent_locale? || locale.blank?
I18n.locale = Tenant.current_tenant.default_locale
else
I18n.locale = locale
end
end
if I18n.locale == :fa
@rtl = true
else
@rtl = false
end
end
def load_tenant
if request.subdomain.blank?
Tenant.current_domain = request.domain
else
Tenant.current_domain = "#{request.subdomain}.#{request.domain}"
end
end
end
| hadifarnoud/brimir | app/controllers/application_controller.rb | Ruby | agpl-3.0 | 2,555 |
/* Copyright (c) 2015 - 2016 CoNWeT Lab., Universidad Politécnica de Madrid
*
* This file belongs to the business-ecosystem-logic-proxy of the
* Business API Ecosystem
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Francisco de la Vega <fdelavega@conwet.com>
* Jaime Pajuelo <jpajuelo@conwet.com>
* Aitor Magán <amagan@conwet.com>
*/
(function() {
'use strict';
angular.module('app').factory('CustomerAccount', ['$q', '$resource', 'URLS', 'Customer', CustomerAccountService]);
function CustomerAccountService($q, $resource, URLS, Customer) {
var CustomerAccount = $resource(
URLS.CUSTOMER_MANAGEMENT + '/customerAccount/:id',
{},
{
update: { method: 'PUT' },
updatePartial: { method: 'PATCH' }
}
);
CustomerAccount.prototype.serialize = function serialize() {
return {
id: this.id,
href: this.href,
name: this.name
};
};
var EVENTS = {};
var TYPES = {};
var TEMPLATES = {
CUSTOMER_ACCOUNT: {
name: '',
accountType: 'shipping address',
customer: {}
}
};
return {
EVENTS: EVENTS,
TEMPLATES: TEMPLATES,
TYPES: TYPES,
create: create,
detail: detail,
launch: launch
};
function create(data) {
var deferred = $q.defer();
var resource = angular.extend({}, data, {
name: data.customer.name,
customer: data.customer.serialize()
});
CustomerAccount.save(
resource,
function(customerAccount) {
customerAccount.customer = data.customer;
deferred.resolve(customerAccount);
},
function(response) {
deferred.reject(response);
}
);
return deferred.promise;
}
function detail(id) {
var deferred = $q.defer();
var params = {
id: id
};
CustomerAccount.get(
params,
function(customerAccount) {
Customer.detail(customerAccount.customer.id).then(
function(customer) {
customerAccount.customer = customer;
deferred.resolve(customerAccount);
},
function(response) {
deferred.reject(response);
}
);
},
function(response) {
deferred.reject(response);
}
);
return deferred.promise;
}
function launch() {
var customerAccount = new CustomerAccount(angular.copy(TEMPLATES.CUSTOMER_ACCOUNT));
customerAccount.customer = Customer.launch();
return customerAccount;
}
}
})();
| FIWARE-TMForum/business-ecosystem-logic-proxy | public/resources/core/js/services/customer-account.service.js | JavaScript | agpl-3.0 | 3,853 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The source code</title>
<link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../resources/prettify/prettify.js"></script>
<style type="text/css">
.highlight { display: block; background-color: #ddd; }
</style>
<script type="text/javascript">
function highlight() {
document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
}
</script>
</head>
<body onload="prettyPrint(); highlight();">
<pre class="prettyprint lang-js">/*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314)
*/
<span id='Ext-util-Point'>/**
</span> * Represents a 2D point with x and y properties, useful for comparison and instantiation
* from an event:
*
* var point = Ext.util.Point.fromEvent(e);
*
*/
Ext.define('Ext.util.Point', {
/* Begin Definitions */
extend: 'Ext.util.Region',
statics: {
<span id='Ext-util-Point-static-method-fromEvent'> /**
</span> * Returns a new instance of Ext.util.Point base on the pageX / pageY values of the given event
* @static
* @param {Ext.EventObject/Event} e The event
* @return {Ext.util.Point}
*/
fromEvent: function(e) {
e = e.browserEvent || e;
e = (e.changedTouches && e.changedTouches.length > 0) ? e.changedTouches[0] : e;
return new this(e.pageX, e.pageY);
}
},
/* End Definitions */
<span id='Ext-util-Point-method-constructor'> /**
</span> * Creates a point from two coordinates.
* @param {Number} x X coordinate.
* @param {Number} y Y coordinate.
*/
constructor: function(x, y) {
this.callParent([y, x, y, x]);
},
<span id='Ext-util-Point-method-toString'> /**
</span> * Returns a human-eye-friendly string that represents this point,
* useful for debugging
* @return {String}
*/
toString: function() {
return "Point[" + this.x + "," + this.y + "]";
},
<span id='Ext-util-Point-method-equals'> /**
</span> * Compare this point and another point
* @param {Ext.util.Point/Object} p The point to compare with, either an instance
* of Ext.util.Point or an object with left and top properties
* @return {Boolean} Returns whether they are equivalent
*/
equals: function(p) {
return (this.x == p.x && this.y == p.y);
},
<span id='Ext-util-Point-method-isWithin'> /**
</span> * Whether the given point is not away from this point within the given threshold amount.
* @param {Ext.util.Point/Object} p The point to check with, either an instance
* of Ext.util.Point or an object with left and top properties
* @param {Object/Number} threshold Can be either an object with x and y properties or a number
* @return {Boolean}
*/
isWithin: function(p, threshold) {
if (!Ext.isObject(threshold)) {
threshold = {
x: threshold,
y: threshold
};
}
return (this.x <= p.x + threshold.x && this.x >= p.x - threshold.x &&
this.y <= p.y + threshold.y && this.y >= p.y - threshold.y);
},
<span id='Ext-util-Point-method-isContainedBy'> /**
</span> * Determins whether this Point contained by the passed Region, Component or element.
* @param {Ext.util.Region/Ext.Component/Ext.dom.Element/HTMLElement} region
* The rectangle to check that this Point is within.
* @return {Boolean}
*/
isContainedBy: function(region) {
if (!(region instanceof Ext.util.Region)) {
region = Ext.get(region.el || region).getRegion();
}
return region.contains(this);
},
<span id='Ext-util-Point-method-roundedEquals'> /**
</span> * Compare this point with another point when the x and y values of both points are rounded. E.g:
* [100.3,199.8] will equals to [100, 200]
* @param {Ext.util.Point/Object} p The point to compare with, either an instance
* of Ext.util.Point or an object with x and y properties
* @return {Boolean}
*/
roundedEquals: function(p) {
return (Math.round(this.x) == Math.round(p.x) && Math.round(this.y) == Math.round(p.y));
}
}, function() {
<span id='Ext-util-Point-method-translate'> /**
</span> * @method
* Alias for {@link #translateBy}
* @inheritdoc Ext.util.Region#translateBy
*/
this.prototype.translate = Ext.util.Region.prototype.translateBy;
});
</pre>
</body>
</html>
| Sundsvallskommun/OpenEMap-Admin-WebUserInterface | jsduck/docs/source/Point.html | HTML | agpl-3.0 | 5,405 |
DELETE FROM `weenie` WHERE `class_Id` = 33864;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (33864, 'ace33864-frostwave', 33, '2019-02-10 00:00:00') /* ProjectileSpell */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (33864, 1, 0) /* ItemType - None */
, (33864, 93, 1179700) /* PhysicsState - Ethereal, IgnoreCollisions, NoDraw, Inelastic, Cloaked */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (33864, 1, True ) /* Stuck */
, (33864, 24, True ) /* UiHidden */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (33864, 78, 1) /* Friction */
, (33864, 79, 0) /* Elasticity */
, (33864, 8010, 2.382) /* PCAPRecordedVelocityX */
, (33864, 8011, -0.056) /* PCAPRecordedVelocityY */
, (33864, 8012, -1.591) /* PCAPRecordedVelocityZ */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (33864, 1, 'Frost Wave') /* Name */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (33864, 1, 33560056) /* Setup */
, (33864, 3, 536870966) /* SoundTable */
, (33864, 8, 100667494) /* Icon */
, (33864, 28, 28) /* Spell - FrostBolt1 */
, (33864, 8001, 4194304) /* PCAPRecordedWeenieHeader - Spell */
, (33864, 8003, 148) /* PCAPRecordedObjectDesc - Stuck, Attackable, UiHidden */
, (33864, 8005, 35589) /* PCAPRecordedPhysicsDesc - CSetup, Velocity, Friction, Elasticity, STable, Position */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (33864, 8040, 808386587, 92.22298, 60.21601, 127.2884, 0.6987424, 0, 0, -0.7153733) /* PCAPRecordedLocation */
/* @teleloc 0x302F001B [92.222980 60.216010 127.288400] 0.698742 0.000000 0.000000 -0.715373 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (33864, 8000, 2930592996) /* PCAPRecordedObjectIID */;
| LtRipley36706/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/ProjectileSpell/None/33864 Frost Wave.sql | SQL | agpl-3.0 | 2,111 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Books
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Review.php,v 1.2 2010/11/18 15:13:37 bart Exp $
*/
/**
* @see Zend_Gdata_Extension
*/
require_once 'Zend/Gdata/Extension.php';
/**
* User-provided review
*
* @category Zend
* @package Zend_Gdata
* @subpackage Books
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Books_Extension_Review extends Zend_Gdata_Extension
{
protected $_rootNamespace = 'gbs';
protected $_rootElement = 'review';
protected $_lang = null;
protected $_type = null;
/**
* Constructor for Zend_Gdata_Books_Extension_Review which
* User-provided review
*
* @param string|null $lang Review language.
* @param string|null $type Type of text construct (typically text, html,
* or xhtml).
* @param string|null $value Text content of the review.
*/
public function __construct($lang = null, $type = null, $value = null)
{
$this->registerAllNamespaces(Zend_Gdata_Books::$namespaces);
parent::__construct();
$this->_lang = $lang;
$this->_type = $type;
$this->_text = $value;
}
/**
* Retrieves DOMElement which corresponds to this element and all
* child properties. This is used to build this object back into a DOM
* and eventually XML text for sending to the server upon updates, or
* for application storage/persistance.
*
* @param DOMDocument $doc The DOMDocument used to construct DOMElements
* @return DOMElement The DOMElement representing this element and all
* child properties.
*/
public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
{
$element = parent::getDOM($doc);
if ($this->_lang !== null) {
$element->setAttribute('lang', $this->_lang);
}
if ($this->_type !== null) {
$element->setAttribute('type', $this->_type);
}
return $element;
}
/**
* Extracts XML attributes from the DOM and converts them to the
* appropriate object members.
*
* @param DOMNode $attribute The DOMNode attribute to be handled.
*/
protected function takeAttributeFromDOM($attribute)
{
switch ($attribute->localName) {
case 'lang':
$this->_lang = $attribute->nodeValue;
break;
case 'type':
$this->_type = $attribute->nodeValue;
break;
default:
parent::takeAttributeFromDOM($attribute);
}
}
/**
* Returns the language of link title
*
* @return string The lang
*/
public function getLang()
{
return $this->_lang;
}
/**
* Returns the type of text construct (typically 'text', 'html' or 'xhtml')
*
* @return string The type
*/
public function getType()
{
return $this->_type;
}
/**
* Sets the language of link title
*
* @param string $lang language of link title
* @return Zend_Gdata_Books_Extension_Review Provides a fluent interface
*/
public function setLang($lang)
{
$this->_lang = $lang;
return $this;
}
/**
* Sets the type of text construct (typically 'text', 'html' or 'xhtml')
*
* @param string $type type of text construct (typically 'text', 'html' or 'xhtml')
* @return Zend_Gdata_Books_Extension_Review Provides a fluent interface
*/
public function setType($type)
{
$this->_type = $type;
return $this;
}
}
| Nivocer/webenq | libraries/Zend/Gdata/Books/Extension/Review.php | PHP | agpl-3.0 | 4,364 |
<?php
namespace SendForm\NewItem;
function removeRecipientPage ($mysqli, $user, $username,
$what_upper, $what_lower, $recipients, $base, $contactsBase) {
$base = '../../../../';
$fnsDir = __DIR__.'/../..';
include_once "$fnsDir/ItemList/escapedPageQuery.php";
$escapedPageQuery = \ItemList\escapedPageQuery();
include_once "$fnsDir/ItemList/pageParams.php";
$pageParams = \ItemList\pageParams();
$pageParams['username'] = $username;
$yesHref = 'submit.php?'.htmlspecialchars(http_build_query($pageParams));
include_once "$fnsDir/Contacts/indexWithUsernameOnUser.php";
$contacts = \Contacts\indexWithUsernameOnUser($mysqli, $user->id_users);
include_once __DIR__.'/../recipientsPanels.php';
\SendForm\recipientsPanels($recipients, $contacts, $pageParams,
$content, $additionalPanels, $base, $contactsBase, '../');
include_once "$fnsDir/Page/confirmDialog.php";
include_once "$fnsDir/Page/create.php";
include_once "$fnsDir/Page/text.php";
$content =
\Page\create(
[
'title' => "New $what_upper",
'href' => "../../$escapedPageQuery",
],
'Send',
\Page\text("Send the new $what_lower to:").$content
)
.$additionalPanels
.\Page\confirmDialog('Are you sure you want to remove the recipient'
.' "<b>'.htmlspecialchars($username).'</b>"?',
'Yes, remove recipient', $yesHref, "../$escapedPageQuery");
include_once "$fnsDir/compressed_css_link.php";
include_once "$fnsDir/echo_user_page.php";
echo_user_page($user, 'Remove Recipient?', $content, $base, [
'head' => compressed_css_link('confirmDialog', $base),
]);
}
| zvini/website | www/fns/SendForm/NewItem/removeRecipientPage.php | PHP | agpl-3.0 | 1,752 |
/*
Clashing Coders RPG Platform - The platform used for Creamfinance's first coding contest.
Copyright (C) 2016 Florian Proksch
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var Player = require('./player');
var World = module.exports = function World(level, players) {
//Mixin level definitions
for (var key in level) {
this[key] = level[key];
}
this.width = this.map_definition.width;
this.height = this.map_definition.height;
this.map = new Array(this.height);
this.tileset = {};
this.log = [];
this.messages = [];
this.players = new Array(this.player_definition.length);
for (var i = 0, imax = this.player_definition.length; i < imax; i += 1) {
this.players[i] = new Player(this.player_definition[i]);
}
for (var i = 0, imax = this.map_definition.height; i < imax; i += 1) {
this.map[i] = new Array(this.map_definition.width);
for (var j = 0, jmax = this.map_definition.width; j < jmax; j += 1) {
this.map[i][j] = new this.map_definition.tileDefinition[i][j]();
this.tileset[this.map[i][j].display] = {
type: this.map[i][j].type,
traversable: this.map_definition.tileDefinition[i][j].prototype.traversable,
weight: this.map_definition.tileDefinition[i][j].prototype.weight,
};
}
}
for (var i = 0, imax = this.map_definition.objectDefinition.length; i < imax; i += 1) {
var object_definition = this.map_definition.objectDefinition[i];
this.map[object_definition.x][object_definition.y].object = new object_definition.object();
}
this.init();
}
World.prototype.action = function (player, action, data) {
var ret = this.processAction(player, action, data);
var inv = {};
for (var k in player.inventory) {
inv[k] = player.inventory[k];
}
return ret;
};
| Creamfinance/clashing-coders-rpg | game/world.js | JavaScript | agpl-3.0 | 2,538 |
using Autofac;
using Quest.Common.Messages;
using Quest.Common.Messages.Telephony;
using Quest.Common.ServiceBus;
using Quest.Lib.Processor;
using Quest.Lib.ServiceBus;
using Quest.Lib.Trace;
using Quest.Lib.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;
namespace Quest.Lib.Telephony.AspectCTIPS
{
public class AspectProcessor : ServiceBusProcessor
{
public List<String> Channels { get; set; }
/// <summary>
/// CTI listeners
/// </summary>
private List<CTIPSChannel> _ctiChannels;
/// <summary>
/// passed to ctichannels and used to broadcast messages on the servicebus
/// </summary>
private readonly MQChannel _mq;
private Timer _primarytimer = new Timer();
//private SystemConfig _config;
private readonly ILifetimeScope _scope;
//public string channelConfig { get; set; }
public AspectProcessor(
ILifetimeScope scope,
IServiceBusClient serviceBusClient,
MessageHandler msgHandler,
TimedEventQueue eventQueue) : base(eventQueue, serviceBusClient, msgHandler)
{
_scope = scope;
_mq = new MQChannel(serviceBusClient);
}
private Response MakeCallHandler(NewMessageArgs t)
{
if (t.Payload is MakeCall request)
{
_ctiChannels.ForEach(x => x.Dial(request));
}
return null;
}
protected override void OnStop()
{
Stop();
}
protected override void OnPrepare()
{
MsgHandler.AddHandler<MakeCall>(MakeCallHandler);
}
protected override void OnStart()
{
try
{
Logger.Write(string.Format("Controller starting", ToString()), TraceEventType.Information, "AspectServer");
//_config = SystemConfig.Load(channelConfig);
// start off the CTI links
_ctiChannels = new List<CTIPSChannel>();
foreach (var ch in Channels)
{
try
{
var cfg = _scope.ResolveNamed<CTIChannelConfig>(ch);
if (cfg.Enabled)
{
CTIPSChannel channel = new CTIPSChannel();
channel.Initialise(cfg, _mq);
channel.Start();
_ctiChannels.Add(channel);
}
}
catch (Exception ex)
{
Logger.Write(string.Format("Error: {0}", ex.ToString()), TraceEventType.Information, "AspectServer");
}
}
Logger.Write(string.Format("Controller \"who is primary\" timer started", ToString()), TraceEventType.Information, "AspectServer");
_primarytimer.Interval = 5000;
_primarytimer.Elapsed += _primarytimer_Elapsed;
_primarytimer.Start();
}
catch (Exception ex)
{
Logger.Write(string.Format("Error: {0}", ex.ToString()), TraceEventType.Information, "AspectServer");
}
}
/// <summary>
/// check state of each channel and set primary channel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void _primarytimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
var currentPrimaries = _ctiChannels.FindAll(x => x.IsPrimary == true).ToList();
var candidatePrimary = _ctiChannels.FirstOrDefault(x => x.IsRunning == true);
//Logger.Write(string.Format("Controller \"who is primary\" timer fired: primaries {0}, candidate primary {1}", currentPrimaries.Count, candidatePrimary), TraceEventType.Information, "AspectServer");
// no primary available
if (candidatePrimary == null)
{
// deselect an possible primary
_ctiChannels.ForEach(x => x.IsPrimary = false);
Logger.Write(string.Format("No channels online !! "), TraceEventType.Information, "AspectServer");
return;
}
// selectedPrimary!=null
if (currentPrimaries.Count == 0)
{
Logger.Write(string.Format("Channel {0} is now PRIMARY", candidatePrimary), TraceEventType.Information, "AspectServer");
candidatePrimary.IsPrimary = true;
return;
}
// more than 1 primary ? how did that happen?
if (ReferenceEquals(candidatePrimary, currentPrimaries[0]))
{
//Logger.Write(string.Format("Channel {0} is (and was) PRIMARY", currentPrimaries[0]), TraceEventType.Information, "AspectServer");
}
else
{
Logger.Write(string.Format("Channel {0} is now PRIMARY", currentPrimaries[0]), TraceEventType.Information, "AspectServer");
}
_ctiChannels.ForEach(x => x.IsPrimary = false);
candidatePrimary.IsPrimary = true;
currentPrimaries = _ctiChannels.FindAll(x => x.IsPrimary == true).ToList();
candidatePrimary = _ctiChannels.FirstOrDefault(x => x.IsRunning == true);
//Logger.Write(string.Format("Controller \"who is primary\" timer complete: primaries {0}, candidate primary {1}", currentPrimaries.Count, candidatePrimary), TraceEventType.Information, "AspectServer");
}
catch (Exception ex)
{
Logger.Write(string.Format("Error: {0}", ex.ToString()), TraceEventType.Information, "AspectServer");
}
}
public override void Stop()
{
try
{
// start off the CTI links
foreach (var chan in _ctiChannels)
{
try
{
chan.Stop();
}
catch (Exception ex)
{
Logger.Write(string.Format("Error: {0}", ex.ToString()), TraceEventType.Information, "AspectServer");
}
}
}
catch (Exception ex)
{
Logger.Write(string.Format("Error: {0}", ex.ToString()), TraceEventType.Information, "AspectServer");
}
}
}
} | Extentsoftware/Quest | src/Quest.Lib/Telephony/Aspect/AspectProcessor.cs | C# | agpl-3.0 | 6,854 |
#!/usr/bin/env python3
"""
A simple bot to gather some census data in IRC channels.
It is intended to sit in a channel and collect the data for statistics.
:author: tpltnt
:license: AGPLv3
"""
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
class CensusBot(irc.bot.SingleServerIRCBot):
"""
The class implementing the census bot.
"""
def __init__(self, channel, nickname, server, port=6667):
"""
The constructor for the CensusBot class.
:param channel: name of the channel to join
:type channel: str
:param nickname: nick of the bot (to use)
:type nickname: str
:param server: FQDN of the server to use
:type server: str
:param port: port to use when connecting to the server
:type port: int
"""
if 0 != channel.find('#'):
channel = '#' + channel
irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
self.channel = channel
def on_nickname_in_use(self, connection, event):
"""
Change own nickname if already in use.
:param connection: connection to the server
:type connection: irc.client.ServerConnection
:param event: event to react to
:type event:
:raises: TypeError
"""
if not isinstance(connection, ServerConnection):
raise TypeError("'connection' is not of type 'ServerConnection'")
connection.nick(connection.get_nickname() + "_")
def main():
import sys
if len(sys.argv) != 4:
print("Usage: " + sys.argv[0] + " <server[:port]> <channel> <nickname>")
sys.exit(1)
server = sys.argv[1].split(":", 1)
host = server[0]
if len(server) == 2:
try:
port = int(server[1])
except ValueError:
print("Error: Erroneous port.")
sys.exit(1)
else:
port = 6667
channel = sys.argv[2]
nickname = sys.argv[3]
bot = CensusBot(channel, nickname, server, port)
bot.start()
if __name__ == "__main__":
main()
| tpltnt/ircensus | ircensus_channel_bot.py | Python | agpl-3.0 | 2,132 |
# encoding: utf-8
#
# rshot (http://rshot.net) - a social digital photo gallery.
# (c) 2011-2012 Raphael Kallensee
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Picture < ActiveRecord::Base
# relationships
belongs_to :album
belongs_to :profile
has_one :picture_metadata, :dependent => :destroy
# acts as ...
acts_as_taggable_on :tags
acts_as_commentable
# attribute protection
attr_accessible :title, :photo, :album_id, :tag_list
# photo attachment (Paperclip)
has_attached_file :photo,
:styles => {
:thumb => ["75x75#", :jpg],
:small => ["250x250#", :jpg],
:medium => ["820x820>", :jpg],
:large => ["1920x1920>", :jpg] },
:convert_options => { :all => '-auto-orient' },
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename"
## the following helps to obfuscate the URL. It'll change on every update of the model.
##:path => ":rails_root/public/system/:attachment/:id/:style/:basename.:extension",
##:url => "/system/:hash.:extension",
#:url => "/system/:attachment/:id/:style/:filename",
#:hash_secret => "tkb#H_oi?I+0-&RP;_Kd9/OF",
#:hash_data => ":class/:attachment/:id/:style/:updated_at"
before_save :set_tag_ownership
after_save :extract_and_save_metadata!
# validators
validates_attachment :photo, :presence => true,
:size => { :less_than => 10.megabytes }
validates_presence_of :profile_id
validates :title, :length => { :maximum => 150 }
# scopes
scope :next, lambda { |att| where("id > ?", att).limit(1).order("id") }
scope :previous, lambda { |att| where("id < ?", att).limit(1).order("id DESC") }
scope :by_profile, lambda { |att| where("profile_id = ?", att) }
scope :by_album, lambda { |att| where("album_id = ?", att) }
def album_name
unless album.nil?
album.title
end
end
def self.random
offset = rand(self.count)
rand_record = self.first(:offset => offset)
end
def metadata
if picture_metadata.nil?
build_picture_metadata
end
picture_metadata
end
def extract_and_save_metadata!
if picture_metadata.nil?
build_picture_metadata
end
begin
exifdata = EXIFR::JPEG.new(photo.path)
rescue EXIFR::MalformedJPEG
return false
end
if exifdata.exif?
picture_metadata.make = exifdata.make unless exifdata.make.nil?
unless exifdata.model.nil? && exifdata.make.nil?
if exifdata.model.include? exifdata.make
picture_metadata.model = exifdata.model
else
picture_metadata.model = exifdata.make + " " + exifdata.model
end
end
# assign metadata to model if present
#picture_metadata.lens = exifdata.lens unless exifdata.lens.nil? # TODO - tag currently not supported by EXIFR
picture_metadata.date_time = exifdata.date_time unless exifdata.date_time.nil?
picture_metadata.date_time_original = exifdata.date_time_original unless exifdata.date_time_original.nil?
picture_metadata.date_time_digitized = exifdata.date_time_digitized unless exifdata.date_time_digitized.nil?
picture_metadata.exposure_time = exifdata.exposure_time.to_s unless exifdata.exposure_time.nil?
picture_metadata.focal_length = exifdata.focal_length.to_f unless exifdata.focal_length.nil?
picture_metadata.focal_length_in_35mm_film = exifdata.focal_length_in_35mm_film.to_f unless exifdata.focal_length_in_35mm_film.nil?
picture_metadata.aperture = exifdata.f_number.to_f unless exifdata.f_number.nil?
picture_metadata.iso = exifdata.iso_speed_ratings.to_i unless exifdata.iso_speed_ratings.nil?
picture_metadata.exposure_bias_value = exifdata.exposure_bias_value.to_f unless exifdata.exposure_bias_value.nil?
picture_metadata.white_balance = exifdata.white_balance.to_i unless exifdata.white_balance.nil?
picture_metadata.exposure_program = exifdata.exposure_program.to_i unless exifdata.exposure_program.nil?
picture_metadata.flash = exifdata.flash.to_i unless exifdata.flash.nil?
picture_metadata.width = exifdata.width.to_i unless exifdata.width.nil?
picture_metadata.height = exifdata.height.to_i unless exifdata.height.nil?
picture_metadata.software = exifdata.software.to_s unless exifdata.software.nil?
picture_metadata.exposure_mode = exifdata.exposure_mode.to_i unless exifdata.exposure_mode.nil?
picture_metadata.metering_mode = exifdata.metering_mode.to_i unless exifdata.metering_mode.nil?
picture_metadata.orientation = exifdata.orientation.to_i unless exifdata.orientation.nil?
picture_metadata.artist = exifdata.artist.to_s unless exifdata.artist.nil?
picture_metadata.copyright = exifdata.copyright.to_s unless exifdata.copyright.nil?
picture_metadata.description = exifdata.image_description.to_s unless exifdata.image_description.nil?
picture_metadata.user_comment = exifdata.user_comment.to_s unless exifdata.user_comment.nil?
picture_metadata.brightness_value = exifdata.brightness_value.to_s unless exifdata.brightness_value.nil?
picture_metadata.exposure_bias_value = exifdata.exposure_bias_value.to_s unless exifdata.exposure_bias_value.nil?
picture_metadata.max_aperture_value = exifdata.max_aperture_value.to_f unless exifdata.max_aperture_value.nil?
picture_metadata.subject_distance = exifdata.subject_distance.to_s unless exifdata.subject_distance.nil?
picture_metadata.light_source = exifdata.light_source.to_i unless exifdata.light_source.nil?
picture_metadata.flash_energy = exifdata.flash_energy.to_f unless exifdata.flash_energy.nil?
picture_metadata.gps_latitude = exifdata.gps.latitude unless exifdata.gps.nil?
picture_metadata.gps_longitude = exifdata.gps.longitude unless exifdata.gps.nil?
picture_metadata.gps_altitude = exifdata.gps.altitude unless exifdata.gps.nil?
picture_metadata.gps_direction = exifdata.gps.image_direction unless exifdata.gps.nil?
#picture_metadata.exifraw = exifdata.exif unless exifdata.exif.nil? # TODO - store plain serialized EXIF data
picture_metadata.save
return true
end
end
def set_tag_ownership
# set the owner of tags of the current tag_list
set_owner_tag_list_on(self.profile, :tags, self.tag_list)
# clear the list to avoid duplicate taggings
self.tag_list = nil
end
end
| rkallensee/rshot | app/models/picture.rb | Ruby | agpl-3.0 | 7,073 |
import * as React from 'react'
import { onlyInParentGroup, ScoreHistory, ScoreHistoryEntry } from '../../../../definitions/ScoreSystem'
import { text } from '../../../utils/text'
import { BatchScores, ScoreDetails } from '../../../../calculators/calcScore'
import { MultiLangStringSet } from '../../../../definitions/auxiliary/MultiLang'
interface PropTypes {
scoreDetails: ScoreDetails
history: ScoreHistory
name: string
}
const scoreStyle = {
fontWeight: 'bolder',
} as React.CSSProperties
const LabelTexts: {[key: string]: MultiLangStringSet} = {
education: {
en: 'Level of education',
zh_hans: '学历',
},
language: {
en: 'Official languages proficiency',
zh_hans: '官方语言能力',
},
age: {
en: 'Age',
zh_hans: '年龄',
},
canadaWork: {
en: 'Canada work experience',
zh_hans: '加拿大工作经验',
},
transferable: {
en: 'Skill Transferability factors'
},
additions: {
en: 'Additional',
zh_hans: '额外加分',
},
'language-primary:listening': {
en: 'Primary language: Listening',
zh_hans: '第一语言:听力',
},
'language-primary:writing': {
en: 'Primary language: Writing',
zh_hans: '第一语言:写作',
},
'language-primary:speaking': {
en: 'Primary language: Speaking',
zh_hans: '第一语言:口语',
},
'language-primary:reading': {
en: 'Primary language: Reading',
zh_hans: '第一语言:阅读',
},
'language-secondary:listening': {
en: 'Secondary language: Listening',
zh_hans: '第二语言:听力',
},
'language-secondary:writing': {
en: 'Secondary language: Writing',
zh_hans: '第二语言:写作',
},
'language-secondary:speaking': {
en: 'Secondary language: Speaking',
zh_hans: '第二语言:口语',
},
'language-secondary:reading': {
en: 'Secondary language: Reading',
zh_hans: '第二语言:阅读',
},
union: {
en: 'Union status',
zh_hans: '婚姻状况',
},
'spouse-bonus': {
en: 'Spouse bonus',
zh_hans: '配偶加分',
},
'transferability:language+education': {
en: 'Language + Education',
},
'transferability:canada_work+education': {
en: 'Canada work experience + Education'
},
'transferability:work+education': {
en: 'Work experience + Education'
},
'transferability:foreign_work+canada_work': {
en: 'Foreign work experience + Canada work experience'
},
'transferability:language+certification': {
en: 'Language + Trade certification'
},
'additional:sibling': {
en: 'Sibling'
},
'additional:french': {
en: 'French'
},
'additional:canada-education': {
en: 'Canadian education'
},
'additional:job-offer': {
en: 'Job offer'
},
'additional:provincial-nomination': {
en: 'Provincial or territorial nomination'
}
}
const Row = (props: { text: string, score: number, level: number }) => (
<tr>
<td style={{
paddingLeft: `${props.level * 1}em`,
fontWeight: props.level === 0 ? 'bold' : 'normal',
}}>
{props.text}
</td>
<td style={{
textAlign: 'right',
}}>
{props.score}
</td>
</tr>
)
const HistoryEntry = (props: { entry: ScoreHistoryEntry }) => (
<div>
<span style={scoreStyle}>
{props.entry.lowestScore}
</span>
{'@'}
{[
props.entry.date.year,
props.entry.date.month,
props.entry.date.day,
].join('-')}
</div>
)
class ScoreBox extends React.PureComponent<PropTypes, {}> {
render() {
const scoreDetails = this.props.scoreDetails
return (
<div>
<div style={{fontSize: '1.2em'}}>
{this.props.name}
</div>
<table>
<thead>
<tr>
<th>
{
text({
en: 'Your score',
zh_hans: '分数',
})
}
</th>
<th style={scoreStyle}>
{scoreDetails.score}
</th>
</tr>
</thead>
<tbody>
{
Object.keys(scoreDetails.groups).map(group => {
const conditionGroup = scoreDetails.groups[group]
let batchesForDisplay: BatchScores
if (Object.keys(conditionGroup.batches).length === 1
&& Object.keys(conditionGroup.batches)[0] === onlyInParentGroup
) {
batchesForDisplay = {}
}
else {
batchesForDisplay = conditionGroup.batches
}
return [
<Row
key={group}
text={text(LabelTexts[group])}
score={conditionGroup.score}
level={0}
/>,
Object.keys(batchesForDisplay).sort().map(batch =>
<Row
key={batch}
text={text(LabelTexts[batch])}
score={conditionGroup.batches[batch]}
level={1}
/>
)
]
}
)
}
</tbody>
</table>
<div>
{
text({
en: 'Previous lowest scores for entry: ',
zh_hans: '过往分数线: ',
})
}
{
this.props.history.map(entry =>
<HistoryEntry
key={[entry.date.year, entry.date.month, entry.date.day].join('-')}
entry={entry}
/>
)
}
</div>
</div>
)
}
}
export default ScoreBox
| wikimigrate/wikimigrate | src/client/web/components/PathwayDisplay/ScoreBox.tsx | TypeScript | agpl-3.0 | 7,047 |
#!/bin/bash
arvados-cwl-runner --submit --no-wait cwl/scatter_hupgp-gff-to-fastj.cwl yml/scatter_hupgp-gff-to-fastj_Arvados-test.yml
#arvados-cwl-runner --disable-reuse --submit --no-wait scatter_hupgp-gff-to-fastj.cwl cwl-run/scatter_hupgp-gff-to-fastj_Arvados-test.yml
#arvados-cwl-runner --disable-reuse --local scatter_hupgp-gff-to-fastj.cwl cwl-run/scatter_hupgp-gff-to-fastj_Arvados-test.yml
#arvados-cwl-runner --local scatter_hupgp-gff-to-fastj.cwl cwl-run/scatter_hupgp-gff-to-fastj_Arvados-test.yml
| curoverse/l7g | cwl-version/experimental/l7g-convert-fastj/hupgp-gff/cwl-run/submit-scatter-test-job.sh | Shell | agpl-3.0 | 511 |
# Amara, universalsubtitles.org
#
# Copyright (C) 2017 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see
# http://www.gnu.org/licenses/agpl-3.0.html.
import uuid
from django.conf import settings
from django.core.cache import cache
from django.urls import reverse
def _mk_key(token):
return "one-time-data-" + token
def set_one_time_data(data):
token = str(uuid.uuid4())
key = _mk_key(token)
cache.set(key, data, 60)
return '{}://{}{}'.format(settings.DEFAULT_PROTOCOL,
settings.HOSTNAME,
reverse("one_time_url", kwargs={"token": token}))
def get_one_time_data(token):
key = _mk_key(token)
data = cache.get(key)
# It seems like Brightcove wants to hit it twice
# cache.delete(key)
return data
| pculture/unisubs | utils/one_time_data.py | Python | agpl-3.0 | 1,410 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
$dashletStrings = array (
'MyTeamModulesUsedChartDashlet' =>
array (
'LBL_TITLE' => 'Moduły używane przez członków mojego zespołu (ostatnie 30 dni)',
'LBL_DESCRIPTION' => 'Moduły używane przez członków mojego zespołu (ostatnie 30 dni)',
'LBL_REFRESH' => 'Odśwież wykres',
),
);
| harish-patel/ecrm | modules/Charts/Dashlets/MyTeamModulesUsedChartDashlet/MyTeamModulesUsedChartDashlet.pl_PL.lang.php | PHP | agpl-3.0 | 2,128 |
<?php
/**
* Skeleton subclass for performing query and update operations on the 'cc_subjs_token' table.
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*/
class CcSubjsTokenQuery extends BaseCcSubjsTokenQuery
{
} // CcSubjsTokenQuery
| LibreTime/libretime | legacy/application/models/airtime/CcSubjsTokenQuery.php | PHP | agpl-3.0 | 384 |
# -*- coding: utf-8 -*-
# Copyright 2018 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import hr_certification
from . import hr_training_participant
| open-synergy/opnsynid-hr | hr_employee_training_experience/models/__init__.py | Python | agpl-3.0 | 197 |
"""Make session:proposal 1:1.
Revision ID: 3a6b2ab00e3e
Revises: 4dbf686f4380
Create Date: 2013-11-09 13:51:58.343243
"""
# revision identifiers, used by Alembic.
revision = '3a6b2ab00e3e'
down_revision = '4dbf686f4380'
from alembic import op
def upgrade():
op.create_unique_constraint('session_proposal_id_key', 'session', ['proposal_id'])
def downgrade():
op.drop_constraint('session_proposal_id_key', 'session', 'unique')
| hasgeek/funnel | migrations/versions/3a6b2ab00e3e_session_proposal_one.py | Python | agpl-3.0 | 441 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2014 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2014. All rights reserved".
********************************************************************************/
abstract class EmailTemplatesBaseDefaultDataMaker extends DefaultDataMaker
{
protected $importedImages = array();
protected function makeBuilderPredefinedEmailTemplate($name, $unserializedData, $subject = null, $modelClassName = null,
$language = null, $type = null, $isDraft = 0, $textContent = null,
$htmlContent = null)
{
$emailTemplate = new EmailTemplate();
$emailTemplate->type = $type;//EmailTemplate::TYPE_WORKFLOW;
$emailTemplate->builtType = EmailTemplate::BUILT_TYPE_BUILDER_TEMPLATE;
$emailTemplate->isDraft = $isDraft;
$emailTemplate->modelClassName = $modelClassName;
$emailTemplate->name = $name;
if (empty($subject))
{
$subject = $name;
}
$emailTemplate->subject = $subject;
if (!isset($language))
{
$language = Yii::app()->languageHelper-> getForCurrentUser();
}
$emailTemplate->language = $language;
$emailTemplate->htmlContent = $htmlContent;
$emailTemplate->textContent = $textContent;
$emailTemplate->serializedData = CJSON::encode($unserializedData);
$emailTemplate->addPermissions(Group::getByName(Group::EVERYONE_GROUP_NAME),
Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER);
$saved = $emailTemplate->save(false);
if (!$saved)
{
throw new FailedToSaveModelException();
}
$emailTemplate = EmailTemplate::getById($emailTemplate->id);
ReadPermissionsOptimizationUtil::
securableItemGivenPermissionsForGroup($emailTemplate, Group::getByName(Group::EVERYONE_GROUP_NAME));
$saved = $emailTemplate->save(false);
assert('$saved');
}
protected function makeImages()
{
$imagesNamesToImport = array(
'200x50' => '200x50.gif',
'200x200' => '200x200.gif',
'580x180' => '580x180.gif',
'googleMaps' => 'staticmap.png'
);
foreach ($imagesNamesToImport as $type => $name)
{
$path = Yii::getPathOfAlias('application.modules.emailTemplates.views.assets.images') . DIRECTORY_SEPARATOR . $name;
$fileUploadData = ImageFileModelUtil::saveImageFromTemporaryFile($path, $type);
$this->importedImages[$type] = $fileUploadData['id'];
}
}
}
?> | maruthisivaprasad/zurmo | app/protected/modules/emailTemplates/data/EmailTemplatesBaseDefaultDataMaker.php | PHP | agpl-3.0 | 4,994 |
/*
Copyright (c) 2013 Matthew Stump
This file is part of libmutton.
libmutton is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
libmutton is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MUTTON_STATUS_H_
#define __MUTTON_STATUS_H_
#include <string>
namespace mtn {
struct status_t
{
bool library;
bool local_storage;
int code;
std::string message;
status_t() :
library(false),
local_storage(false),
code(0)
{}
status_t(int code,
const std::string& message) :
library(true),
local_storage(false),
code(code),
message(message)
{}
status_t(int code,
const std::string& message,
bool library,
bool local_storage) :
library(library),
local_storage(local_storage),
code(code),
message(message)
{}
inline operator
bool() const
{
return ok();
}
inline bool
ok() const
{
return !(library || local_storage);
}
};
} // namespace mtn
#endif // __MUTTON_STATUS_H_
| project-z/mutton | src/status.hpp | C++ | agpl-3.0 | 1,810 |
/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/**
* @brief this file contains the definitions of several constraint
* functions for the detection of subsentences
*
* @file SimplificationConstraints.h
* @author Gael de Chalendar (Gael.de-Chalendar@cea.fr)
* Copyright (c) 2005 by CEA
* @date Created on Tue Mar, 15 2005
*
*
*/
#ifndef LIMA_SYNTACTICANALYSIS_SIMPLIFICATIONCONSTRAINTS_H
#define LIMA_SYNTACTICANALYSIS_SIMPLIFICATIONCONSTRAINTS_H
#include "SyntacticAnalysisExport.h"
#include "HomoSyntagmaticConstraints.h"
#include "linguisticProcessing/core/Automaton/constraintFunction.h"
#include "linguisticProcessing/core/Automaton/recognizerMatch.h"
#include <iostream>
namespace Lima {
namespace LinguisticProcessing {
namespace SyntacticAnalysis {
//**********************************************************************
// ids of constraints defined in this file
#define DefineStringId "DefineString"
#define SameStringId "SameString"
#define DefineModelId "DefineModel"
#define SetInstanceId "SetInstance"
//**********************************************************************
class LIMA_SYNTACTICANALYSIS_EXPORT DefineString : public Automaton::ConstraintFunction
{
public:
explicit DefineString(MediaId language,
const LimaString& complement=LimaString());
~DefineString() {}
bool operator()(const Lima::LinguisticProcessing::LinguisticAnalysisStructure::AnalysisGraph& graph,
const LinguisticGraphVertex& v1,
const LinguisticGraphVertex& v2,
AnalysisContent& analysis) const;
private:
uint64_t m_language;
};
class LIMA_SYNTACTICANALYSIS_EXPORT SameString : public Automaton::ConstraintFunction
{
public:
explicit SameString(MediaId language,
const LimaString& complement=LimaString());
~SameString() {}
bool operator()(const Lima::LinguisticProcessing::LinguisticAnalysisStructure::AnalysisGraph& graph,
const LinguisticGraphVertex& v1,
const LinguisticGraphVertex& v2,
AnalysisContent& analysis) const;
bool actionNeedsRecognizedExpression() { return true; }
private:
uint64_t m_language;
const Common::PropertyCode::PropertyAccessor* m_microAccessor;
};
class LIMA_SYNTACTICANALYSIS_EXPORT DefineModel : public Automaton::ConstraintFunction
{
public:
explicit DefineModel(MediaId language,
const LimaString& complement=LimaString());
~DefineModel() {}
bool operator()(const Lima::LinguisticProcessing::LinguisticAnalysisStructure::AnalysisGraph& graph,
const LinguisticGraphVertex& v1,
const LinguisticGraphVertex& v2,
AnalysisContent& analysis) const;
};
class LIMA_SYNTACTICANALYSIS_EXPORT SetInstance : public Automaton::ConstraintFunction
{
public:
explicit SetInstance(MediaId language,
const LimaString& complement=LimaString());
~SetInstance() {}
bool operator()(
const Lima::LinguisticProcessing::LinguisticAnalysisStructure::AnalysisGraph& graph,
const LinguisticGraphVertex& v1,
const LinguisticGraphVertex& v2,
AnalysisContent& analysis) const;
};
} // end namespace SyntacticAnalysis
} // end namespace LinguisticProcessing
} // end namespace Lima
#endif // LIMA_SYNTACTICANALYSIS_SIMPLIFICATIONCONSTRAINTS_H
| FaizaGara/lima | lima_linguisticprocessing/src/linguisticProcessing/core/SyntacticAnalysis/CoordinationConstraints.h | C | agpl-3.0 | 4,149 |
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2013 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.gl.stress;
import org.jpos.gl.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;
import org.hibernate.Transaction;
public class SummarizeTransactions extends TestBase {
public void testSummarize() throws Exception {
Date POSTDATE = Util.parseDateTime ("20050104120000");
Journal tj = gls.getJournal ("TestJournal");
System.out.println ("Creating summarized Transaction");
Transaction tx = gls.beginTransaction();
gls.summarize (tj, POSTDATE, POSTDATE, "Summarized Stress Txn", new short[] { 0 });
tx.commit();
}
}
| napramirez/jPOS-EE | modules/minigl/src/test/java/org/jpos/gl/stress/SummarizeTransactions.java | Java | agpl-3.0 | 1,379 |
module LibCDB
class CDB
module Version
MAJOR = 0
MINOR = 2
TINY = 1
class << self
# Returns array representation.
def to_a
[MAJOR, MINOR, TINY]
end
# Short-cut for version string.
def to_s
to_a.join('.')
end
end
end
VERSION = Version.to_s
end
end
| blackwinter/libcdb-ruby | lib/libcdb/version.rb | Ruby | agpl-3.0 | 373 |
# -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Noé Rubinstein
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import re
from weboob.capabilities.gallery import ICapGallery, BaseGallery, BaseImage
from weboob.tools.backend import BaseBackend
from weboob.tools.browser import BaseBrowser, BasePage
__all__ = ['GenericComicReaderBackend']
class DisplayPage(BasePage):
def get_page(self, gallery):
src = self.document.xpath(self.browser.params['img_src_xpath'])[0]
return BaseImage(src,
gallery=gallery,
url=src)
def page_list(self):
return self.document.xpath(self.browser.params['page_list_xpath'])
class GenericComicReaderBrowser(BaseBrowser):
def __init__(self, browser_params, *args, **kwargs):
self.params = browser_params
BaseBrowser.__init__(self, *args, **kwargs)
def iter_gallery_images(self, gallery):
self.location(gallery.url)
assert self.is_on_page(DisplayPage)
for p in self.page.page_list():
if 'page_to_location' in self.params:
self.location(self.params['page_to_location'] % p)
else:
self.location(p)
assert self.is_on_page(DisplayPage)
yield self.page.get_page(gallery)
def fill_image(self, image, fields):
if 'data' in fields:
image.data = self.readurl(image.url)
class GenericComicReaderBackend(BaseBackend, ICapGallery):
NAME = 'genericcomicreader'
MAINTAINER = u'Noé Rubinstein'
EMAIL = 'noe.rubinstein@gmail.com'
VERSION = '0.f'
DESCRIPTION = 'Generic comic reader backend; subclasses implement specific sites'
LICENSE = 'AGPLv3+'
BROWSER = GenericComicReaderBrowser
BROWSER_PARAMS = {}
ID_REGEXP = None
URL_REGEXP = None
ID_TO_URL = None
PAGES = {}
def create_default_browser(self):
b = self.create_browser(self.BROWSER_PARAMS)
b.PAGES = self.PAGES
try:
b.DOMAIN = self.DOMAIN
except AttributeError:
pass
return b
def iter_gallery_images(self, gallery):
with self.browser:
return self.browser.iter_gallery_images(gallery)
def get_gallery(self, _id):
match = re.match(r'^%s$' % self.URL_REGEXP, _id)
if match:
_id = match.group(1)
else:
match = re.match(r'^%s$' % self.ID_REGEXP, _id)
if match:
_id = match.group(0)
else:
return None
gallery = BaseGallery(_id, url=(self.ID_TO_URL % _id))
with self.browser:
return gallery
def fill_gallery(self, gallery, fields):
gallery.title = gallery.id
def fill_image(self, image, fields):
with self.browser:
self.browser.fill_image(image, fields)
OBJECTS = {
BaseGallery: fill_gallery,
BaseImage: fill_image}
| franek/weboob | weboob/tools/capabilities/gallery/genericcomicreader.py | Python | agpl-3.0 | 3,614 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/transitional.dtd">
<html><head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="estilos.css" />
<title> Indice de La formación del profesional de la información en Venezuela: una mirada comparativa desde sus diseños curriculares., como contribució en EDUCERE</title>
</head><body>
<div id="container">
<div id="pageHeader">
</div>
<div id="pageContehome">
<center><big><a href="../index.html">Indices EDUCERE</a><br></big></center>
<entry>
<number>
700<br> </number>
<results>
<titulo>
La formación del profesional de la información en Venezuela: una mirada comparativa desde sus diseños curriculares.<br> </titulo>
<subtitulo>
Information professional's education in Venezuela: a comparative look from their curricular designs.<br> </subtitulo>
<autores>
[[Pirela Morillo, Johann],[Peña Vera, Tania]]<br> </autores>
<titulo>
<a href="http://www.saber.ula.ve/handle/123456789/20050">http://www.saber.ula.ve/handle/123456789/20050</a><br> <creado>
2006-01-01<br> </creado>
</titulo>
<results>
<div></div>
<h2 align="center">La frase: La formación del profesional de la información en Venezuela: una mirada comparativa desde sus diseños curriculares.</h2>
<h3 align="center">Produjo 2 resultados</h3>
<table align="center" border="1" width="100%">
<tr><th>Relevancia</th><th>Archivo (URL implicito)</th><th>Tama�o (en Bytes)</th></tr>
<tr><td>1000</td><td><a href=".%2fpdfs%2fv10n32%2farticulo16.pdf">articulo16.pdf</a></td><td><em>327339</em></td></tr>
<tr><td>636</td><td><a href=".%2fpdfs%2fv10n32%2feditorial.pdf">editorial.pdf</a></td><td><em>166024</em></td></tr>
</table>
</results>
</entry>
</div>
<div id="footer"><p>EDUCERE. La Revista Venezolana de Educación Escuela de Educación. <br/>
Facultad de Humanidades y Educación Universidad de Los Andes,<br/>
Mérida - Venezuela<br/>
<br/>
<br/>
</p>
</div>
</div>
</body>
</html>
| jacintodavila/catalogoelectronicoautonomo | ceaWeb/indices/t00700.html | HTML | agpl-3.0 | 2,032 |
<?php $TRANSLATIONS = array(
"Wrong calendar" => "Погрешан календар",
"Timezone changed" => "Временска зона је промењена",
"Invalid request" => "Неисправан захтев",
"Calendar" => "Календар",
"Birthday" => "Рођендан",
"Business" => "Посао",
"Call" => "Позив",
"Clients" => "Клијенти",
"Deliverer" => "Достављач",
"Holidays" => "Празници",
"Ideas" => "Идеје",
"Journey" => "путовање",
"Jubilee" => "јубилеј",
"Meeting" => "Састанак",
"Other" => "Друго",
"Personal" => "Лично",
"Projects" => "Пројекти",
"Questions" => "Питања",
"Work" => "Посао",
"Does not repeat" => "Не понавља се",
"Daily" => "дневно",
"Weekly" => "недељно",
"Every Weekday" => "сваког дана у недељи",
"Bi-Weekly" => "двонедељно",
"Monthly" => "месечно",
"Yearly" => "годишње",
"All day" => "Цео дан",
"New Calendar" => "Нови календар",
"Title" => "Наслов",
"Week" => "Недеља",
"Month" => "Месец",
"List" => "Списак",
"Today" => "Данас",
"Calendars" => "Календари",
"There was a fail, while parsing the file." => "дошло је до грешке при расчлањивању фајла.",
"Choose active calendars" => "Изаберите активне календаре",
"CalDav Link" => "КалДав веза",
"Download" => "Преузми",
"Edit" => "Уреди",
"Delete" => "Обриши",
"New calendar" => "Нови календар",
"Edit calendar" => "Уреди календар",
"Displayname" => "Приказаноиме",
"Active" => "Активан",
"Calendar color" => "Боја календара",
"Save" => "Сними",
"Submit" => "Пошаљи",
"Cancel" => "Откажи",
"Edit an event" => "Уреди догађај",
"Title of the Event" => "Наслов догађаја",
"Category" => "Категорија",
"All Day Event" => "Целодневни догађај",
"From" => "Од",
"To" => "До",
"Location" => "Локација",
"Location of the Event" => "Локација догађаја",
"Description" => "Опис",
"Description of the Event" => "Опис догађаја",
"Repeat" => "Понављај",
"Create a new event" => "Направи нови догађај",
"Select category" => "Изаберите категорију",
"Timezone" => "Временска зона"
);
| KiddoKiddo/WebSecA1Q1 | apps/calendar/l10n/sr.php | PHP | agpl-3.0 | 2,490 |
/*
* Arc MMORPG Server
* Copyright (C) 2005-2010 Arc Team <http://www.arcemulator.net/>
*
* This software is under the terms of the EULA License
* All title, including but not limited to copyrights, in and to the ArcNG Software
* and any copies there of are owned by ZEDCLANS INC. or its suppliers. All title
* and intellectual property rights in and to the content which may be accessed through
* use of the ArcNG is the property of the respective content owner and may be protected
* by applicable copyright or other intellectual property laws and treaties. This EULA grants
* you no rights to use such content. All rights not expressly granted are reserved by ZEDCLANS INC.
*
*/
#include "Common.h"
#include "svn_revision.h"
#include "CrashHandler.h"
#include "Log.h"
void OutputCrashLogLine(const char * format, ...)
{
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE * m_file = fopen(s.c_str(), "a");
if(!m_file) return;
va_list ap;
va_start(ap, format);
vfprintf(m_file, format, ap);
fprintf(m_file, "\n");
fclose(m_file);
va_end(ap);
}
#ifdef WIN32
#include "CircularQueue.h"
Mutex m_crashLock;
/* *
@file CrashHandler.h
Handles crashes/exceptions on a win32 based platform, writes a dump file,
for later bug fixing.
*/
# pragma warning( disable : 4311 )
#include <stdio.h>
#include <time.h>
//#include <windows.h>
#include "Log.h"
#include <tchar.h>
bool ON_CRASH_BREAK_DEBUGGER;
void StartCrashHandler()
{
// Firstly, check if there is a debugger present. There isn't any point in
// handling crashes internally if we have a debugger attached, that would
// just piss us off. :P
// Check for a debugger.
#ifndef X64
DWORD code;
__asm
{
MOV EAX, FS:[0x18]
MOV EAX, DWORD PTR [EAX + 0x30]
MOV ECX, DWORD PTR [EAX]
MOV [DWORD PTR code], ECX
}
if(code & 0x00010000)
{
// We got a debugger. We'll tell it to not exit on a crash but instead break into debugger.
ON_CRASH_BREAK_DEBUGGER = true;
}
else
{
// No debugger. On crash, we'll call OnCrash to save etc.
ON_CRASH_BREAK_DEBUGGER = false;
}
#else
ON_CRASH_BREAK_DEBUGGER = (IsDebuggerPresent() == TRUE) ? true : false;
#endif
}
///////////////////////////////////////////////////////////////////////////////
// GetExceptionDescription
// Translate the exception code into something human readable
static const TCHAR *GetExceptionDescription(DWORD ExceptionCode)
{
struct ExceptionNames
{
DWORD ExceptionCode;
TCHAR * ExceptionName;
};
#if 0 // from winnt.h
#define STATUS_WAIT_0 ((DWORD )0x00000000L)
#define STATUS_ABANDONED_WAIT_0 ((DWORD )0x00000080L)
#define STATUS_USER_APC ((DWORD )0x000000C0L)
#define STATUS_TIMEOUT ((DWORD )0x00000102L)
#define STATUS_PENDING ((DWORD )0x00000103L)
#define STATUS_SEGMENT_NOTIFICATION ((DWORD )0x40000005L)
#define STATUS_GUARD_PAGE_VIOLATION ((DWORD )0x80000001L)
#define STATUS_DATATYPE_MISALIGNMENT ((DWORD )0x80000002L)
#define STATUS_BREAKPOINT ((DWORD )0x80000003L)
#define STATUS_SINGLE_STEP ((DWORD )0x80000004L)
#define STATUS_ACCESS_VIOLATION ((DWORD )0xC0000005L)
#define STATUS_IN_PAGE_ERROR ((DWORD )0xC0000006L)
#define STATUS_INVALID_HANDLE ((DWORD )0xC0000008L)
#define STATUS_NO_MEMORY ((DWORD )0xC0000017L)
#define STATUS_ILLEGAL_INSTRUCTION ((DWORD )0xC000001DL)
#define STATUS_NONCONTINUABLE_EXCEPTION ((DWORD )0xC0000025L)
#define STATUS_INVALID_DISPOSITION ((DWORD )0xC0000026L)
#define STATUS_ARRAY_BOUNDS_EXCEEDED ((DWORD )0xC000008CL)
#define STATUS_FLOAT_DENORMAL_OPERAND ((DWORD )0xC000008DL)
#define STATUS_FLOAT_DIVIDE_BY_ZERO ((DWORD )0xC000008EL)
#define STATUS_FLOAT_INEXACT_RESULT ((DWORD )0xC000008FL)
#define STATUS_FLOAT_INVALID_OPERATION ((DWORD )0xC0000090L)
#define STATUS_FLOAT_OVERFLOW ((DWORD )0xC0000091L)
#define STATUS_FLOAT_STACK_CHECK ((DWORD )0xC0000092L)
#define STATUS_FLOAT_UNDERFLOW ((DWORD )0xC0000093L)
#define STATUS_INTEGER_DIVIDE_BY_ZERO ((DWORD )0xC0000094L)
#define STATUS_INTEGER_OVERFLOW ((DWORD )0xC0000095L)
#define STATUS_PRIVILEGED_INSTRUCTION ((DWORD )0xC0000096L)
#define STATUS_STACK_OVERFLOW ((DWORD )0xC00000FDL)
#define STATUS_CONTROL_C_EXIT ((DWORD )0xC000013AL)
#define STATUS_FLOAT_MULTIPLE_FAULTS ((DWORD )0xC00002B4L)
#define STATUS_FLOAT_MULTIPLE_TRAPS ((DWORD )0xC00002B5L)
#define STATUS_ILLEGAL_VLM_REFERENCE ((DWORD )0xC00002C0L)
#endif
ExceptionNames ExceptionMap[] =
{
{0x40010005, _T("a Control-C")},
{0x40010008, _T("a Control-Break")},
{0x80000002, _T("a Datatype Misalignment")},
{0x80000003, _T("a Breakpoint")},
{0xc0000005, _T("an Access Violation")},
{0xc0000006, _T("an In Page Error")},
{0xc0000017, _T("a No Memory")},
{0xc000001d, _T("an Illegal Instruction")},
{0xc0000025, _T("a Noncontinuable Exception")},
{0xc0000026, _T("an Invalid Disposition")},
{0xc000008c, _T("a Array Bounds Exceeded")},
{0xc000008d, _T("a Float Denormal Operand")},
{0xc000008e, _T("a Float Divide by Zero")},
{0xc000008f, _T("a Float Inexact Result")},
{0xc0000090, _T("a Float Invalid Operation")},
{0xc0000091, _T("a Float Overflow")},
{0xc0000092, _T("a Float Stack Check")},
{0xc0000093, _T("a Float Underflow")},
{0xc0000094, _T("an Integer Divide by Zero")},
{0xc0000095, _T("an Integer Overflow")},
{0xc0000096, _T("a Privileged Instruction")},
{0xc00000fD, _T("a Stack Overflow")},
{0xc0000142, _T("a DLL Initialization Failed")},
{0xe06d7363, _T("a Microsoft C++ Exception")},
};
for (int i = 0; i < sizeof(ExceptionMap) / sizeof(ExceptionMap[0]); i++)
if (ExceptionCode == ExceptionMap[i].ExceptionCode)
return ExceptionMap[i].ExceptionName;
return _T("an Unknown exception type");
}
void echo(const char * format, ...)
{
va_list ap;
va_start(ap, format);
vprintf(format, ap);
std::string s = FormatOutputString("logs", "CrashLog", false);
FILE * m_file = fopen(s.c_str(), "a");
if(!m_file)
{
va_end(ap);
return;
}
vfprintf(m_file, format, ap);
fclose(m_file);
va_end(ap);
}
void PrintCrashInformation(PEXCEPTION_POINTERS except)
{
echo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
echo("Server has crashed. Reason was:\n");
echo(" %s at 0x%08X\n", GetExceptionDescription(except->ExceptionRecord->ExceptionCode),
(unsigned long)except->ExceptionRecord->ExceptionAddress);
#ifdef REPACK
echo("%s repack by %s has crashed. Visit %s for support.", REPACK, REPACK_AUTHOR, REPACK_WEBSITE);
#endif
echo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
echo("Call Stack: \n");
CStackWalker sw;
sw.ShowCallstack();
echo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
}
void CStackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
{
}
void CStackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
{
}
void CStackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
{
}
void CStackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry)
{
CHAR buffer[STACKWALK_MAX_NAMELEN];
if ( (eType != lastEntry) && (entry.offset != 0) )
{
if (entry.name[0] == 0)
strcpy(entry.name, "(function-name not available)");
if (entry.undName[0] != 0)
strcpy(entry.name, entry.undName);
if (entry.undFullName[0] != 0)
strcpy(entry.name, entry.undFullName);
/* if(!stricmp(entry.symTypeString, "-exported-"))
strcpy(entry.symTypeString, "dll");
for(uint32 i = 0; i < strlen(entry.symTypeString); ++i)
entry.symTypeString[i] = tolower(entry.symTypeString);*/
char * p = strrchr(entry.loadedImageName, '\\');
if(!p)
p = entry.loadedImageName;
else
++p;
if (entry.lineFileName[0] == 0)
{
//strcpy(entry.lineFileName, "(filename not available)");
//if (entry.moduleName[0] == 0)
//strcpy(entry.moduleName, "(module-name not available)");
//sprintf(buffer, "%s): %s: %s\n", (LPVOID) entry.offset, entry.moduleName, entry.lineFileName, entry.name);
//sprintf(buffer, "%s.
if(entry.name[0] == 0)
sprintf(entry.name, "%p", entry.offset);
sprintf(buffer, "%s!%s Line %u\n", p, entry.name, entry.lineNumber );
}
else
sprintf(buffer, "%s!%s Line %u\n", p, entry.name, entry.lineNumber);
//OnOutput(buffer);
/*if(p)
OnOutput(p);
else*/
OnOutput(buffer);
}
}
void CStackWalker::OnOutput(LPCSTR szText)
{
std::string s;
if(m_sharedptrlog)
s = FormatOutputString("logs", "SharedPtrLog", false);
else
s = FormatOutputString("logs", "CrashLog", false);
FILE * m_file = fopen(s.c_str(), "a");
if(!m_file) return;
printf(" %s", szText);
fprintf(m_file, " %s", szText);
fclose(m_file);
}
bool died = false;
int __cdecl HandleCrash(PEXCEPTION_POINTERS pExceptPtrs)
{
if(pExceptPtrs == 0)
{
// Raise an exception :P
__try
{
RaiseException(EXCEPTION_BREAKPOINT, 0, 0, 0);
}
__except(HandleCrash(GetExceptionInformation()), EXCEPTION_CONTINUE_EXECUTION)
{
}
}
/* only allow one thread to crash. */
if(!m_crashLock.AttemptAcquire())
{
TerminateThread(GetCurrentThread(),-1);
// not reached
}
if(died)
{
TerminateProcess(GetCurrentProcess(),-1);
// not reached:P
}
died=true;
// Create the date/time string
time_t curtime = time(NULL);
tm * pTime = localtime(&curtime);
char filename[MAX_PATH];
TCHAR modname[MAX_PATH*2];
ZeroMemory(modname, sizeof(modname));
if(GetModuleFileName(0, modname, MAX_PATH*2-2) <= 0)
strcpy(modname, "UNKNOWN");
char * mname = strrchr(modname, '\\');
(void*)mname++; // Remove the last
sprintf(filename, "CrashDumps\\dump-%s-%u-%u-%u-%u-%u-%u-%u.dmp",
mname, pTime->tm_year+1900, pTime->tm_mon, pTime->tm_mday,
pTime->tm_hour, pTime->tm_min, pTime->tm_sec, GetCurrentThreadId());
HANDLE hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
if(hDump == INVALID_HANDLE_VALUE)
{
// Create the directory first
CreateDirectory("CrashDumps", 0);
hDump = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
}
PrintCrashInformation(pExceptPtrs);
// beep
//printf("\x7");
printf("\nCreating crash dump file %s\n", filename);
if(hDump == INVALID_HANDLE_VALUE)
{
MessageBox(0, "Could not open crash dump file.", "Crash dump error.", MB_OK);
}
else
{
MINIDUMP_EXCEPTION_INFORMATION info;
info.ClientPointers = FALSE;
info.ExceptionPointers = pExceptPtrs;
info.ThreadId = GetCurrentThreadId();
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
hDump, MiniDumpWithIndirectlyReferencedMemory, &info, 0, 0);
CloseHandle(hDump);
}
SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
OnCrash(!ON_CRASH_BREAK_DEBUGGER);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
| satanail/ArcTic-d | src/arcemu-shared/CrashHandler.cpp | C++ | agpl-3.0 | 11,056 |
<?php
$thousand =LbGenera::model()->getGeneraSubscription()->lb_thousand_separator;
$decimal= LbGenera::model()->getGeneraSubscription()->lb_decimal_symbol;
$strnum = new LbInvoiceTotal();
$method = LBPayment::model()->method;
$date_from = date('Y-m-d');
$date_to = date('Y-m-d', strtotime("+1 month -1 day"));
$customer_id = false;
if (isset($_REQUEST['search_date_from']) && $_REQUEST['search_date_from'] != "")
$date_from = date('Y-m-d', strtotime($_REQUEST['search_date_from']));
if (isset($_REQUEST['search_date_to']) && $_REQUEST['search_date_to'] != "")
$date_to = date('Y-m-d', strtotime($_REQUEST['search_date_to']));
if(isset($_REQUEST['customer']) && $_REQUEST['customer'] != 0)
$customer_id = $_REQUEST['customer'];
$a = LbInvoice::model()->getInvoiceMonth($customer_id,$date_from,$date_to);
$PDFGst = '<table border="0" style="margin:auto;width:100%;" cellpadding="0" cellspacing="0">'
. '<tr><td>
<table border="0" style="margin:auto;width:100%;" cellpadding="0" cellspacing="0">
<tr><td >
<span style="font-size:20px;font-weight:bold;">GST Report</span>
</td></tr>
</table>
</td></tr>'
. '<tr><td>
<table border="0" style="margin:auto;width:100%;" cellpadding="0" cellspacing="0">
<tr><td >
<span style="margin:10px;padding:10px">From: '.$date_from.'</span>
<span style="margin:10px;">To: '.$date_to.'</span>
</td></tr>
</table>
</td></tr>'
. '<tr><td>
<table border="0" width="100%" class="items table table-bordered">
<thead>
<tr>
<th width="100" class="lb-grid-header">'.Yii::t('lang','Number').'</th>
<th width="100" class="lb-grid-header">'.Yii::t('lang','Date').'</th>
<th width="250" class="lb-grid-header">'.Yii::t('lang','Customer').'</th>
<th width="150" class="lb-grid-header">'.Yii::t('lang','Invoice Value').'</th>
<th width="150" class="lb-grid-header">'.Yii::t('lang','GST Collected').'</th>
</tr>
<tr></tr>
</thead>';
if($customer_id > 0)
{
$PDFGst .= '<tbody>';
$invoiceValue=0;
$gst = 0;
foreach ($a as $data)
{
$customer_id = false;
$invoice_information = LbInvoiceTotal::model()->getInvoiceById($data->lb_record_primary_key);
$invoiceTax = LbInvoiceItem::model()->getInvoiceTaxById($data->lb_record_primary_key,"TAX");
$invoiceValue = $invoiceValue+$invoice_information->lb_invoice_total_after_discounts;
$PDFGst .= '<tr>';
$PDFGst .= '<td>'.$data->lb_invoice_no.'</td>';
$PDFGst .= '<td>'.$data->lb_invoice_date.'</td>';
$PDFGst .= '<td>';
if($data->lb_invoice_customer_id)
{
$customer_id = $data->lb_invoice_customer_id;
$PDFGst .= LbCustomer::model()->customerInformation($customer_id)->attributes['lb_customer_name'];
}
$PDFGst .= '</td>';
$PDFGst .= '<td>$'.$invoice_information->lb_invoice_total_after_discounts.'</td>';
$PDFGst .= '<td>';
$totalTax=0;
if($invoiceTax)
{
$totaltax = $invoice_information->lb_invoice_total_after_taxes-$invoice_information->lb_invoice_total_after_discounts;
$PDFGst .= '$'.$totaltax;
}else
$PDFGst .= '$0.00';
$PDFGst .= '</td>';
$PDFGst .= '</tr>';
$gst = $gst+($invoice_information->lb_invoice_total_after_taxes-$invoice_information->lb_invoice_total_after_discounts);
}
$PDFGst .='</tbody>';
$PDFGst .='<tfoot><tr>
<td colspan="3"><b>Total</b></td>
<td align="right" style="border-top:1px solid #000">
<b>$'.$invoiceValue.'</b>
</td>
<td align="right" style="border-top:1px solid #000">
<b>$'.$gst.'</b>
</td>
</tr>
</tfoot>';
}
else
{
$customer_arr=LbCustomer::model()->getCompanies($sort = 'lb_customer_name ASC',
LbCustomer::LB_QUERY_RETURN_TYPE_MODELS_ARRAY);
$invoiceValue=0;
$gst = 0;
foreach ($customer_arr as $customer)
{
$PDFGst .= '<tbody>';
$a = LbInvoice::model()->getInvoiceMonth($customer['lb_record_primary_key'],$date_from,$date_to);
foreach ($a as $data)
{
$customer_id = false;
$invoice_information = LbInvoiceTotal::model()->getInvoiceById($data->lb_record_primary_key);
$invoiceTax = LbInvoiceItem::model()->getInvoiceTaxById($data->lb_record_primary_key,"TAX");
$invoiceValue = $invoiceValue+$invoice_information->lb_invoice_total_after_discounts;
$PDFGst .= '<tr>';
$PDFGst .= '<td>'.$data->lb_invoice_no.'</td>';
$PDFGst .= '<td>'.$data->lb_invoice_date.'</td>';
$PDFGst .= '<td>';
if($data->lb_invoice_customer_id)
{
$customer_id = $data->lb_invoice_customer_id;
$PDFGst .= LbCustomer::model()->customerInformation($customer_id)->attributes['lb_customer_name'];
}
$PDFGst .= '</td>';
$PDFGst .= '<td>$'.$invoice_information->lb_invoice_total_after_discounts.'</td>';
$PDFGst .= '<td>';
$totalTax=0;
if($invoiceTax)
{
$totaltax = $invoice_information->lb_invoice_total_after_taxes-$invoice_information->lb_invoice_total_after_discounts;
$PDFGst .= '$'.$totaltax;
}else
$PDFGst .= '$0.00';
$PDFGst .= '</td>';
$PDFGst .= '</tr>';
$gst = $gst+($invoice_information->lb_invoice_total_after_taxes-$invoice_information->lb_invoice_total_after_discounts);
}
$PDFGst .= '</tbody>';
}
$PDFGst .='<tfoot><tr>
<td colspan="3"><b>Total</b></td>
<td align="right" style="border-top:1px solid #000">
<b>$'.number_format($invoiceValue,2).'</b>
</td>
<td align="right" style="border-top:1px solid #000">
<b>$'.number_format($gst,2).'</b>
</td>
</tr>
</tfoot>';
}
$PDFGst .='
</table>
</td></tr>'
. '</table>';
echo $PDFGst;
?>
| LinxHQ/LinxCloud | linxbooks/protected/modules/lbReport/views/default/pdf_gstReport.php | PHP | agpl-3.0 | 9,111 |
<?php
class CRM_Api4_Page_AJAX extends CRM_Core_Page {
/**
* Handler for api4 ajax requests
*/
public function run() {
try {
// Call multiple
if (empty($this->urlPath[3])) {
$calls = CRM_Utils_Request::retrieve('calls', 'String', CRM_Core_DAO::$_nullObject, TRUE, NULL, 'POST', TRUE);
$calls = json_decode($calls, TRUE);
$response = [];
foreach ($calls as $index => $call) {
$response[$index] = call_user_func_array([$this, 'execute'], $call);
}
}
// Call single
else {
$entity = $this->urlPath[3];
$action = $this->urlPath[4];
$params = CRM_Utils_Request::retrieve('params', 'String');
$params = $params ? json_decode($params, TRUE) : [];
$index = CRM_Utils_Request::retrieve('index', 'String');
$response = $this->execute($entity, $action, $params, $index);
}
}
catch (Exception $e) {
http_response_code(500);
$response = [
'error_code' => $e->getCode(),
];
if (CRM_Core_Permission::check('view debug output')) {
$response['error_message'] = $e->getMessage();
if (\Civi::settings()->get('backtrace')) {
$response['backtrace'] = $e->getTrace();
}
}
}
CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
echo json_encode($response);
CRM_Utils_System::civiExit();
}
/**
* Run api call & prepare result for json encoding
*
* @param string $entity
* @param string $action
* @param array $params
* @param string $index
* @return array
*/
protected function execute($entity, $action, $params = [], $index = NULL) {
$params['checkPermissions'] = TRUE;
// Handle numeric indexes later so we can get the count
$itemAt = CRM_Utils_Type::validate($index, 'Integer', FALSE);
$result = civicrm_api4($entity, $action, $params, isset($itemAt) ? NULL : $index);
// Convert arrayObject into something more suitable for json
$vals = ['values' => isset($itemAt) ? $result->itemAt($itemAt) : (array) $result];
foreach (get_class_vars(get_class($result)) as $key => $val) {
$vals[$key] = $result->$key;
}
$vals['count'] = $result->count();
return $vals;
}
}
| civicrm/api4 | CRM/Api4/Page/AJAX.php | PHP | agpl-3.0 | 2,284 |
/*
Agora Forum Software
Copyright (C) 2016 Gregory Sartucci
License: AGPL-3.0, Check file LICENSE
*/
Package.describe({
name: 'agoraforum:core',
version: '0.1.3',
summary: 'Graph-based forum',
git: 'https://github.com/Agora-Project/agora-meteor',
documentation: 'README.md'
});
Npm.depends({
step: '1.0.0',
xml2js: '0.4.19',
request: '2.87.0',
'node-rsa': '1.0.0'
});
Package.onUse(function(api) {
both = ['client', 'server'];
api.use([
'mongo',
'accounts-password',
'useraccounts:core',
'agoraforum:activitypub',
'ecmascript',
'iron:router',
'useraccounts:iron-routing',
'matb33:collection-hooks',
'accounts-base',
'alanning:roles',
'utilities:avatar',
'spacebars',
'email',
'http'
], both);
api.use([
'mrest:restivus',
'percolate:migrations'
], 'server');
api.addFiles([
'lib/identity_collections/identity_collections.js',
'lib/grapher/layered_grapher.js',
'lib/collections/actors.js',
'lib/collections/posts.js',
'lib/collections/reports.js',
'lib/collections/users.js',
'lib/collections/orderedCollections.js',
'lib/collections/activities.js',
'routes.js'
], both);
api.addFiles([
'lib/webfinger/lib/webfinger.js',
'server/methods.js',
'server/publish.js',
'server/clientActivity.js',
'server/federation.js',
'lib/collections/keys.js',
'server/migrations.js',
'server/initial-data.js'
], 'server');
api.addFiles([
'client/lib/notifier.js',
'client/lib/requestAnimationFrame.js',
'client/lib/templateParents.js',
'client/lib/seenPosts.js',
'client/subscriptionManager.js'
], 'client');
api.addFiles([
'client/main.html',
'client/main.css',
'client/init.js'
], 'client');
api.addFiles([
'client/userList/userList.html',
'client/userList/userList.js'
], 'client');
api.addFiles([
'client/federation/federation.html',
'client/federation/federation.js',
'client/federation/federation.css'
], 'client');
api.addFiles([
'client/errorPage/errorPage.html'
], 'client');
api.addFiles([
'client/mainView/detailed/detailed.html',
'client/mainView/detailed/detailed.css',
'client/mainView/detailed/detailed.js',
'client/mainView/reply/reply.html',
'client/mainView/reply/reply.css',
'client/mainView/reply/reply.js',
'client/mainView/main.html',
'client/mainView/main.css',
'client/mainView/layout.js',
'client/mainView/partitioner.js',
'client/mainView/camera.js',
'client/mainView/renderer.js',
'client/mainView/main.js'
], 'client');
api.addFiles([
'client/userProfile/userProfile.html',
'client/userProfile/userProfile.css',
'client/userProfile/userProfile.js'
], 'client');
api.addFiles([
'client/adminScreen/adminScreen.html',
'client/adminScreen/adminScreen.css',
'client/adminScreen/adminScreen.js'
], 'client');
api.use([
'ui',
'session',
'templating',
'reactive-var',
'verron:autosize',
'momentjs:moment',
'gwendall:body-events',
'meteorhacks:subs-manager'
], 'client');
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('agoraforum:core', ['client', 'server']);
});
| Agora-Project/agora-meteor | package.js | JavaScript | agpl-3.0 | 3,656 |
const registry = (() => {
if (!process.env.EXTENSION_DATA) {
// console.log("no EXTENSION_DATA found");
return {};
}
const extensions = typeof process.env.EXTENSION_DATA === "string" ?
JSON.parse(process.env.EXTENSION_DATA) : process.env.EXTENSION_DATA;
Object.keys(extensions).forEach((key) => {
if (key.endsWith("Component")) {
// console.log("loading component", key);
/* "@extensions" is a webpack alias */
extensions[key] = require(`@extensions/${extensions[key]}`).default; // eslint-disable-line
}
});
// console.log("extensions", extensions);
return extensions;
})();
export const getExtension = (what) => {
if (registry[what]) {
return registry[what];
}
console.error("Requested non-existing extension", what);
return false;
};
export const hasExtension = (what) => {
return Object.keys(registry).includes(what);
};
| nextstrain/auspice | src/util/extensions.js | JavaScript | agpl-3.0 | 898 |
#!/bin/sh
if [ `uname` = "CYGWIN_NT-5.1" ]; then
EXT=.bat
elif [ `uname` = "Linux" ]; then
EXT=
fi
#Target script
f=test_sch1_uncall.script
i=0
while [ $i -lt 3 ];
do
echo "executing..."$f
time janus$EXT < $f
i=`expr $i + 1`
done | tyoko-dev/Janus-A-sml | tests/test_sch1_uncall_3times.sh | Shell | agpl-3.0 | 249 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Rgaa32017 Test.5.7.3 NMI 02</title>
</head>
<body>
<div>
<h1>Rgaa32017 Test.5.7.3 NMI 02</h1>
<div class="test-detail" lang="fr"> Chaque en-tête (balise
<code>th</code>) ne s'appliquant pas à la totalité de la ligne ou de la colonne vérifie-t-il ces conditions ?
<ul class="ssTests">
<li> L'en-tête ne possède pas d'attribut <code>scope</code></li>
<li> L'en-tête possède un attribut <code>id</code> unique</li>
</ul>
</div>
<div class="testcase">
<table id="table-test">
<tbody>
<tr>
<th>Header 1</th>
<td>Value 1</td>
<th>Header 2</th>
<td>Value 2</td>
</tr>
</tbody>
</table>
</div>
<div class="test-explanation">
NMI : The page contains tables with headers
</div>
</div>
</body>
</html> | Tanaguru/Tanaguru | rules/rgaa3-2017/src/test/resources/testcases/rgaa32017/Rgaa32017Rule050703/Rgaa32017.Test.05.07.03-3NMI-02.html | HTML | agpl-3.0 | 1,472 |
package eu.dzhw.fdz.metadatamanagement.analysispackagemanagement.domain;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Software Packages which can be used in {@link Script}s.
* @author René Reitmann
*/
public class SoftwarePackages {
public static final String STATA = "Stata";
public static final String SPSS = "SPSS";
public static final String R = "R";
public static final String PYTHON = "Python";
public static final String LATENT_GOLD = "Latent GOLD";
public static final String AMOS = "AMOS";
public static final String MAXQDA = "MAXQDA";
public static final String MPLUS = "Mplus";
public static final String MATLAB = "Matlab";
public static final String JULIA = "Julia";
public static final String JASP = "JASP";
public static final String PSPP = "PSPP";
public static final String ALMO = "Almo";
public static final String PRISM = "PRISM";
public static final String SAS = "SAS";
public static final String STATISTICA = "STATISTICA";
public static final String MATHEMATICA = "Mathematica";
public static final String GRETL = "gretl";
public static final String JAMOVI = "Jamovi";
public static final String RAPIDMINER = "RapidMiner";
public static final String GAUSS = "GAUSS";
public static final String SPARQL = "SPARQL";
public static final List<String> ALL = Collections.unmodifiableList(Arrays.asList(STATA, SPSS, R,
PYTHON, LATENT_GOLD, AMOS, MAXQDA, MPLUS, MATLAB, JULIA, JASP, PSPP, ALMO, PRISM, SAS,
STATISTICA, MATHEMATICA, GRETL, JAMOVI, RAPIDMINER, GAUSS, SPARQL));
}
| dzhw/metadatamanagement | src/main/java/eu/dzhw/fdz/metadatamanagement/analysispackagemanagement/domain/SoftwarePackages.java | Java | agpl-3.0 | 1,593 |
/*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.headsupdev.agile.storage.hibernate;
import org.hibernate.search.bridge.TwoWayStringBridge;
import org.headsupdev.agile.api.Manager;
/**
* TODO Document me!
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class NameProjectBridge
implements TwoWayStringBridge
{
public String objectToString( Object o )
{
if ( !( o instanceof NameProjectId ) )
{
return null;
}
NameProjectId id = (NameProjectId) o;
return id.getName() + "#" + id.getProject().getId();
}
public Object stringToObject( String s )
{
if ( s == null )
{
return null;
}
int pos = s.indexOf( '#' );
String name = s.substring( 0, pos );
String project = s.substring( pos + 1 );
return new NameProjectId( name, Manager.getStorageInstance().getProject( project ) );
}
}
| headsupdev/agile | agile-storage/src/main/java/org/headsupdev/agile/storage/hibernate/NameProjectBridge.java | Java | agpl-3.0 | 1,655 |
<?php
/* Template Name: Holiday Home Page Template */
?>
<?php get_header( 'home' ); ?>
<?php if( get_post_meta( $post->ID, 'mast_ad_left_img_url', TRUE) &&
get_post_meta( $post->ID, 'mast_ad_right_img_url', TRUE) ): ?>
<div class="row" data-equalizer="mast_ad_blocks">
<div class="large-6 columns">
<div class="panel" data-equalizer-watch="mast_ad_blocks">
<div class="home_quad_blocks">
<a href="<?php echo get_post_meta( $post->ID, 'mast_ad_left_link', TRUE); ?>" target="_blank"></a>
<img src="<?php echo get_post_meta( $post->ID, 'mast_ad_left_img_url', TRUE); ?>">
</div>
</div>
</div>
<div class="large-6 columns">
<div class="panel" data-equalizer-watch="mast_ad_blocks">
<div class="home_quad_blocks">
<a href="<?php echo get_post_meta( $post->ID, 'mast_ad_right_link', TRUE); ?>" target="_blank"></a>
<img src="<?php echo get_post_meta( $post->ID, 'mast_ad_right_img_url', TRUE); ?>">
</div>
</div>
</div>
</div>
<?php endif; ?>
<div class="row">
<div class="large-6 columns">
<div class="row">
<div class="large-12 large-offset-0 medium-10 medium-offset-1 small-10 small-offset-1 columns">
<div class="home_slider">
<?php foreach ( get_post_meta( $post->ID, 'slider_image_url' ) as $image_url): ?>
<div>
<img src="<?php echo $image_url; ?>">
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<br>
</div>
<div class="large-6 columns">
<div class="panel">
<h4><?php echo get_post_meta( $post->ID, 'main_block_header', TRUE ); ?></h4><hr />
<h5 class="subheader"><?php echo get_post_meta( $post->ID, 'main_block_body', TRUE); ?></h5>
</div>
<div class="row">
<div class="large-12 columns">
<div class="panel">
<div class="home_quad_blocks">
<a href="<?php echo get_post_meta( $post->ID, 'sub_block_link', TRUE); ?>" target="_blank"></a>
<img src="<?php echo get_post_meta( $post->ID, 'sub_block_img', TRUE); ?>">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div class="radius panel">
<div id="success_message" style="display:none;" data-alert class="alert-box hidden radius">
Thanks for signing up!
<a href="#" class="close">×</a>
</div>
<form data-id="embedded_signup:form" class="ctct-custom-form Form" name="embedded_signup" method="POST" action="https://visitor2.constantcontact.com/api/signup">
<h5>Sign-up for our E-Newsletter</h5>
<!-- The following code must be included to ensure your sign-up form works properly. -->
<input data-id="ca:input" type="hidden" name="ca" value="238ed0d9-e683-4a81-ac8a-d503bcc2b4b6">
<input data-id="list:input" type="hidden" name="list" value="1561268378">
<input data-id="source:input" type="hidden" name="source" value="EFD">
<input data-id="required:input" type="hidden" name="required" value="email">
<input data-id="url:input" type="hidden" name="url" value="">
<div class="row collapse">
<div class="large-10 small-8 columns">
<p data-id="Email Address:p" >
<input data-id="Email Address:input" type="text" name="email" value="" maxlength="80">
</p>
</div>
<div class="large-2 small-4 columns">
<!--<a href="#" class="postfix button expand">Subscribe</a>-->
<button type="submit" class="postfix button expand Button ctct-button Button--block Button-secondary" data-enabled="enabled">Subscribe</button>
</div>
</div>
</form>
<script type='text/javascript'>
var localizedErrMap = {};
localizedErrMap['required'] = 'This field is required.';
localizedErrMap['ca'] = 'An unexpected error occurred while attempting to send email.';
localizedErrMap['email'] = 'Please enter your email address in name@email.com format.';
localizedErrMap['birthday'] = 'Please enter birthday in MM/DD format.';
localizedErrMap['anniversary'] = 'Please enter anniversary in MM/DD/YYYY format.';
localizedErrMap['custom_date'] = 'Please enter this date in MM/DD/YYYY format.';
localizedErrMap['list'] = 'Please select at least one email list.';
localizedErrMap['generic'] = 'This field is invalid.';
localizedErrMap['shared'] = 'Sorry, we could not complete your sign-up. Please contact us to resolve this.';
localizedErrMap['state_mismatch'] = 'Mismatched State/Province and Country.';
localizedErrMap['state_province'] = 'Select a state/province';
localizedErrMap['selectcountry'] = 'Select a country';
var postURL = 'https://visitor2.constantcontact.com/api/signup';
</script>
<script type='text/javascript' src='https://static.ctctcdn.com/h/contacts-embedded-signup-assets/1.0.0/js/signup-form.js'></script>
<!--End CTCT Sign-Up Form-->
</div>
</div>
</div>
<div class="row">
<div class="large-3 small-6 columns home_quad_blocks">
<a href="<?php echo get_post_meta( $post->ID, 'base_widget_one_link', TRUE); ?>"></a>
<img src="<?php echo get_post_meta( $post->ID, 'base_widget_one_img_url', TRUE); ?>">
<div class="panel">
<p><?php echo get_post_meta( $post->ID, 'base_widget_one_text', TRUE); ?></p>
</div>
</div>
<div class="large-3 small-6 columns home_quad_blocks">
<a href="<?php echo get_post_meta( $post->ID, 'base_widget_two_link', TRUE); ?>"></a>
<img src="<?php echo get_post_meta( $post->ID, 'base_widget_two_img_url', TRUE); ?>">
<div class="panel">
<p><?php echo get_post_meta( $post->ID, 'base_widget_two_text', TRUE); ?></p>
</div>
</div>
<div class="large-3 small-6 columns home_quad_blocks">
<a href="<?php echo get_post_meta( $post->ID, 'base_widget_three_link', TRUE); ?>"></a>
<img src="<?php echo get_post_meta( $post->ID, 'base_widget_three_img_url', TRUE); ?>">
<div class="panel">
<p><?php echo get_post_meta( $post->ID, 'base_widget_three_text', TRUE); ?></p>
</div>
</div>
<div class="large-3 small-6 columns home_quad_blocks">
<a href="<?php echo get_post_meta( $post->ID, 'base_widget_four_link', TRUE); ?>"></a>
<img src="<?php echo get_post_meta( $post->ID, 'base_widget_four_img_url', TRUE); ?>">
<div class="panel">
<p><?php echo get_post_meta( $post->ID, 'base_widget_four_text', TRUE); ?></p>
</div>
</div>
</div>
<div class="row" data-equalizer="news_blocks">
<div class="large-6 medium-6 columns">
<div class="panel collapse" data-equalizer-watch="news_blocks">
<?php
$query = new WP_Query( array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'order_by' => 'date',
'order' => 'DESC',
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ):
$query->the_post(); ?>
<?php if ( has_post_thumbnail() ) : ?>
<div class="left recent_thumb">
<?php the_post_thumbnail( 'small' ); ?>
</div>
<?php endif; ?>
<h5><?php the_title(); ?></h5>
<?php html5wp_excerpt('home_recent_post'); ?>
<?php endwhile; ?>
<?php
} else {
// no posts found
}
wp_reset_postdata();
?>
</div>
</div>
<div class="large-6 medium-6 columns">
<div class="panel" data-equalizer-watch="news_blocks">
<?php
$query = new WP_Query( array(
'post_type' => 'chesterfield_news',
'post_status' => 'publish',
'posts_per_page' => 1,
'order_by' => 'date',
'order' => 'DESC',
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_content();
}
} else {
// no posts found
}
wp_reset_postdata();
?>
</div>
</div>
</div>
<?php get_footer(); ?>
| zmetcalf/rtmd_wordpress_theme | page-templates/holiday_home_page.php | PHP | agpl-3.0 | 8,256 |
@charset "UTF-8";
/*=== GENERAL */
/*============*/
html, body {
background: #fafafa;
height: 100%;
font-family: "OpenSans", "Cantarell", "Helvetica", "Arial", "PingFang SC", "Microsoft YaHei", sans-serif;
font-size: 92%;
}
/*=== Links */
a, button.as-link {
color: #d18114;
outline: none;
}
legend {
margin: 20px 0 5px;
padding: 5px 0;
font-size: 1.4em;
border-bottom: 1px solid #ddd;
}
label {
min-height: 25px;
padding: 5px 0;
cursor: pointer;
}
textarea {
width: 360px;
height: 100px;
}
input, select, textarea {
padding: 5px;
background: #fff;
color: #222;
border: 1px solid #ccc;
border-radius: 3px;
box-shadow: 0 1px 2px #ccc inset, 0 1px #fff;
min-height: 25px;
line-height: 25px;
vertical-align: middle;
}
option {
padding: 0 .5em;
}
input:focus, select:focus, textarea:focus {
color: #0f0f0f;
border: solid 1px #e7ab34;
box-shadow: 0 0 3px #e7ab34;
}
input:invalid, select:invalid {
border-color: #f00;
box-shadow: 0 0 2px 2px #fdd inset;
}
input:disabled, select:disabled {
background: #eee;
}
input.extend {
transition: width 200ms linear;
}
/*=== Tables */
table {
border-collapse: collapse;
}
tr, th, td {
padding: 0.5em;
border: 1px solid #ddd;
}
th {
background: #f6f6f6;
}
form td,
form th {
font-weight: normal;
text-align: center;
}
/*=== COMPONENTS */
/*===============*/
/*=== Forms */
.form-group.form-actions {
padding: 5px 0;
background: #f4f4f4;
border-top: 1px solid #ddd;
}
.form-group.form-actions .btn {
margin: 0 10px;
border-radius: 4px;
box-shadow: 0 1px rgba(255,255,255,0.08) inset;
}
.form-group .group-name {
padding: 10px 0;
text-align: right;
}
.form-group .group-controls {
min-height: 25px;
padding: 5px 0;
}
.form-group table {
margin: 10px 0 0 220px;
}
/*=== Buttons */
button.as-link[disabled] {
color: #555 !important;
}
.dropdown-menu .input select, .dropdown-menu .input input {
margin: 0 auto 5px;
padding: 2px 5px;
background: #444;
color: #fff;
border: solid 1px #171717;
border-radius: 3px;
box-shadow: 0 2px 2px #222 inset, 0px 1px rgba(255, 255, 255, 0.08);
}
.stick {
vertical-align: middle;
font-size: 0;
}
.stick input,
.stick .btn {
border-radius: 0;
}
.stick .btn:first-child,.stick input:first-child {
border-radius: 6px 0 0 6px;
}
.stick .btn:last-child, .stick input:last-child {
border-radius: 0 6px 6px 0;
}
.stick .btn + .btn,
.stick .btn + input,
.stick .btn + .dropdown > .btn,
.stick input + .btn,
.stick input + input,
.stick input + .dropdown > .btn,
.stick .dropdown + .btn,
.stick .dropdown + input,
.stick .dropdown + .dropdown > .btn {
border-left: none;
}
.stick .btn + .dropdown > .btn {
border-left: none;
border-radius: 0 3px 3px 0;
}
.btn {
margin: 0;
padding: 5px 10px;
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
display: inline-block;
color: #222;
font-size: 0.9rem;
border: solid 1px #ccc;
border-radius: 4px;
min-height: 37px;
min-width: 15px;
text-shadow: 0px -1px rgba(255,255,255,0.08);
vertical-align: middle;
cursor: pointer;
overflow: hidden;
}
a.btn {
min-height: 25px;
line-height: 25px;
}
.btn:hover {
text-shadow: 0 0 2px #fff;
text-decoration: none;
}
.btn.active,.btn:active,.dropdown-target:target ~ .btn.dropdown-toggle {
background: linear-gradient(180deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(top, #ede7de 0%, #fff 100%);
}
.nav_menu .btn.active, .nav_menu .btn:active, .nav_menu .dropdown-target:target ~ .btn.dropdown-toggle {
background: linear-gradient(180deg, #ede7de 0%, #f6f6f6 100%) #ede7de;
background: -webkit-linear-gradient(top, #ede7de 0%, #f6f6f6 100%);
border: solid 1px #ccc;
border-radius: 4px;
box-shadow: 0 1px #fff;
}
.nav_menu .btn {
background: transparent;
border: 0;
}
.read_all {
color: #222;
}
.btn.dropdown-toggle[href="#dropdown-configure"] {
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
border: solid 1px #ccc;
border-radius: 4px;
box-shadow: 0 1px #fff;
}
.btn.dropdown-toggle:active {
background: transparent;
}
.btn-important {
background: linear-gradient(180deg, #e4992c 0%, #d18114 100%) #e4992c;
background: -webkit-linear-gradient(top, #e4992c 0%, #d18114 100%);
color: #fff;
border-radius: 4px;
box-shadow: 0 1px rgba(255,255,255,0.08) inset;
text-shadow: 0px -1px rgba(255,255,255,0.08);
font-weight: normal;
}
.btn-important:active {
background: linear-gradient(0deg, #e4992c 0%, #d18114 100%) #e4992c;
background: -webkit-linear-gradient(bottom, #e4992c 0%, #d18114 100%);
}
.btn-attention {
background: #e95b57;
background: linear-gradient(to bottom, #e95b57, #bd362f);
background: -webkit-linear-gradient(top, #e95b57 0%, #bd362f 100%);
color: #fff;
border: 1px solid #c44742;
text-shadow: 0px -1px 0px #666;
}
.btn-attention:hover {
background: linear-gradient(to bottom, #d14641, #bd362f);
background: -webkit-linear-gradient(top, #d14641 0%, #bd362f 100%);
}
.btn-attention:active {
background: #bd362f;
box-shadow: none;
}
.btn[type="reset"] {
background: linear-gradient(180deg, #222 0%, #171717 100%) #171717;
background: -webkit-linear-gradient(top, #222 0%, #171717 100%);
color: #fff;
box-shadow: 0 -1px rgba(255,255,255,0.08) inset;
}
/*=== Navigation */
.nav-list .nav-header,
.nav-list .item {
height: 2.5em;
line-height: 2.5em;
font-size: 0.9rem;
}
.nav-list .item:hover {
text-shadow: 0 0 2px rgba(255,255,255,0.28);
color: #fff;
}
.nav-list .item.active {
margin: 0;
background: linear-gradient(180deg, #222 0%, #171717 100%) repeat scroll 0% 0% #171717;
background: -webkit-linear-gradient(180deg, #222 0%, #171717 100%);
box-shadow: -1px 2px 2px #171717, 0px 1px rgba(255, 255, 255, 0.08) inset;
border-width: medium medium 1px;
border-style: none none solid;
border-color: -moz-use-text-color -moz-use-text-color #171717;
}
.nav-list .item.active a {
color: #d18114;
}
.nav-list .disable {
background: #fafafa;
color: #aaa;
text-align: center;
}
.nav-list .item > a {
padding: 0 10px;
color: #ccc;
}
.nav-list a:hover {
text-decoration: none;
}
.nav-list .item.empty a {
color: #f39c12;
}
.nav-list .item.active.empty a {
background: linear-gradient(180deg, #e4992c 0%, #d18114 100%) #e4992c;
background: -webkit-linear-gradient(180deg, #e4992c 0%, #d18114 100%);
color: #fff;
}
.nav-list .item.error a {
color: #bd362f;
}
.nav-list .item.active.error a {
background: #bd362f;
color: #fff;
}
.nav-list .nav-header {
padding: 0 10px;
background: transparent;
color: #222;
}
.nav-list .nav-form {
padding: 3px;
text-align: center;
}
.nav-head {
margin: 0;
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
text-align: right;
}
.nav-head .item {
padding: 5px 10px;
font-size: 0.9rem;
line-height: 1.5rem;
}
/*=== Horizontal-list */
.horizontal-list {
margin: 0;
padding: 0;
}
.horizontal-list .item {
vertical-align: middle;
}
/*=== Dropdown */
.dropdown-menu {
margin: 5px 0 0;
padding: 5px 0;
background: #222;
font-size: 0.8rem;
border: 1px solid #171717;
border-radius: 4px;
box-shadow: 0 0 3px #000;
text-align: left;
}
.dropdown-menu::after {
background: #222;
width: 10px;
height: 10px;
border-top: 1px solid #171717;
border-left: 1px solid #171717;
content: "";
position: absolute;
top: -6px;
right: 13px;
z-index: -10;
transform: rotate(45deg);
}
.dropdown-header {
display: none;
}
.dropdown-menu > .item > a,
.dropdown-menu > .item > span,
.dropdown-menu > .item > .as-link {
padding: 0 22px;
line-height: 2.5em;
color: #ccc;
font-size: 0.8rem;
}
.dropdown-menu > .item > label {
color: #ccc;
}
.dropdown-menu > .item:hover {
background: #171717;
color: #fff;
}
.dropdown-menu > .item[aria-checked="true"] > a::before {
font-weight: bold;
margin: 0 0 0 -14px;
}
.dropdown-menu > .item:hover > a {
color: #fff;
text-decoration: none;
}
.separator {
margin: 5px 0;
border-bottom: 1px solid #171717;
box-shadow: 0 1px rgba(255,255,255,0.08);
}
/*=== Alerts */
.alert {
margin: 15px auto;
padding: 10px 15px;
background: #f4f4f4;
color: #aaa;
font-size: 0.9em;
border: 1px solid #ccc;
border-right: 1px solid #aaa;
border-bottom: 1px solid #aaa;
border-radius: 5px;
text-shadow: 0 0 1px #eee;
}
.alert-head {
font-size: 1.15em;
}
.alert > a {
color: inherit;
text-decoration: underline;
}
.alert-warn {
background: #ffe;
color: #c95;
border: 1px solid #eeb;
}
.alert-success {
background: #dfd;
color: #484;
border: 1px solid #cec;
}
.alert-error {
background: #fdd;
color: #844;
border: 1px solid #ecc;
}
/*=== Pagination */
.pagination {
background: #fafafa;
text-align: center;
color: #333;
font-size: 0.8em;
}
.content .pagination {
margin: 0;
padding: 0;
}
.pagination .item.pager-current {
font-weight: bold;
font-size: 1.5em;
}
.pagination .item a {
display: block;
color: #333;
font-style: italic;
line-height: 3em;
text-decoration: none;
}
.pagination .item a:hover {
background: #ddd;
}
.pagination:first-child .item {
border-bottom: 1px solid #aaa;
}
.pagination:last-child .item {
border-top: 1px solid #ddd;
}
.pagination .loading,
.pagination a:hover.loading {
background: url("loader.gif") center center no-repeat #fff;
font-size: 0;
}
/*=== Boxes */
.box {
background: #ede7de;
border-radius: 4px;
box-shadow: 0 1px #fff;
}
.box .box-title {
margin: 0;
padding: 5px 10px;
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #171717;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
color: #888;
font-size: 1.1rem;
border-radius: 4px 4px 0 0;
box-shadow: 0px -1px #fff inset,0 -2px #ccc inset;
text-shadow: 0 1px #ccc;
font-weight: normal;
}
.box .box-content {
max-height: 260px;
}
.box .box-content .item {
padding: 0 10px;
font-size: 0.9rem;
line-height: 2.5em;
}
.box .box-title .configure,
.box .box-content .item .configure {
visibility: hidden;
}
.box .box-title:hover .configure,
.box .box-content .item:hover .configure {
visibility: visible;
}
/*=== Tree */
.tree {
margin: 10px 0;
}
.tree-folder-title {
position: relative;
padding: 0 10px;
line-height: 2.5rem;
font-size: 0.9rem;
}
.tree-folder-title .title {
background: inherit;
color: #fff;
}
.tree-folder-title .title:hover {
text-decoration: none;
}
.tree-folder.active .tree-folder-title {
background: linear-gradient(180deg, #222 0%, #171717 100%) #171717;
background: -webkit-linear-gradient(top, #222 0%, #171717 100%);
color: #fff;
box-shadow: 0px 1px #171717, 0px 1px rgba(255, 255, 255, 0.08) inset;
text-shadow: 0 0 2px rgba(255,255,255,0.28);
}
.tree-folder-items {
padding: 8px 0;
background: #171717;
box-shadow: 0 4px 4px #171717 inset, 0 1px rgba(255,255,255,0.08),0 -1px rgba(255,255,255,0.08);
}
.tree-folder-items > .item {
padding: 0 10px;
line-height: 2.5rem;
font-size: 0.8rem;
}
.tree-folder-items > .item.active {
margin: 0px 8px;
background: linear-gradient(180deg, #222 0%, #171717 100%) #171717;
background: -webkit-linear-gradient(top, #222 0%, #171717 100%);
border-radius: 4px;
box-shadow: 0px 1px #171717, 0px 1px rgba(255, 255, 255, 0.08) inset, 0 2px 2px #111;
}
.tree-folder-items > .item > a {
text-decoration: none;
color: #fff;
font-size: 0.92em;
}
/*=== Scrollbar */
@supports (scrollbar-width: thin) {
#sidebar {
scrollbar-color: rgba(255, 255, 255, 0.05) rgba(0, 0, 0, 0.0);
}
#sidebar:hover {
scrollbar-color: rgba(255, 255, 255, 0.3) rgba(0, 0, 0, 0.0);
}
}
@supports not (scrollbar-width: thin) {
#sidebar::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.1);
}
#sidebar:hover::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
}
}
/*=== STRUCTURE */
/*===============*/
/*=== Header */
.header {
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
height: 55px;
}
.header > .item {
padding: 0;
vertical-align: middle;
text-align: center;
}
.header > .item.title .logo {
width: 60px;
height: 60px;
}
.header > .item.title {
width: 250px;
}
.header > .item.title h1 {
margin: 0.5em 0;
}
.header > .item.title h1 a {
color: #222;
font-size: 28px;
text-decoration: none;
text-shadow: 0 1px #fff;
}
.header > .item.search input {
width: 230px;
}
.header .item.search input:focus {
width: 350px;
}
/*=== Body */
#global {
background: #ede7de;
height: calc(100% - 60px);
}
.aside {
background: #222;
width: 235px;
border-top: 1px solid #ccc;
border-radius: 0px 12px 0px 0px;
box-shadow: 0px -1px #fff, 0 2px 2px #171717 inset;
}
.aside.aside_feed {
padding: 10px 0;
text-align: center;
}
.aside.aside_feed .tree {
margin: 10px 0 50px;
}
/*=== Aside main page (categories) */
.aside_feed .tree-folder-title > .title:not([data-unread="0"])::after {
position: absolute;
right: 3px;
padding: 1px 5px;
color: #fff;
text-shadow: 0 1px rgba(255,255,255,0.08);
}
.aside_feed .btn-important {
border: none;
}
/*=== Aside main page (feeds) */
.feed.item.empty,
.feed.item.empty > a {
color: #e67e22;
}
.feed.item.error,
.feed.item.error > a {
color: #bd362f;
}
.aside_feed .tree-folder-items .dropdown-menu::after {
left: 2px;
}
.aside_feed .tree-folder-items .item .dropdown-target:target ~ .dropdown-toggle > .icon,
.aside_feed .tree-folder-items .item:hover .dropdown-toggle > .icon,
.aside_feed .tree-folder-items .item.active .dropdown-toggle > .icon {
border-radius: 3px;
}
/*=== Configuration pages */
.post {
padding: 10px 50px;
font-size: 0.9em;
}
.post form {
margin: 10px 0;
}
.post.content {
max-width: 550px;
}
/*=== Prompt (centered) */
.prompt {
text-align: center;
padding: 14px 0px;
text-shadow: 0 1px rgba(255,255,255,0.08);
}
.prompt label {
text-align: left;
}
.prompt form {
margin: 10px auto 20px auto;
width: 180px;
}
.prompt input {
margin: 5px auto;
width: 100%;
}
.prompt p {
margin: 20px 0;
}
.prompt input#username,.prompt input#passwordPlain {
background: #fff;
border: solid 1px #ccc;
box-shadow: 0 4px -4px #ccc inset,0px 1px rgba(255, 255, 255, 0.08);
}
.prompt input#username:focus,.prompt input#passwordPlain:focus {
border: solid 1px #e7ab34;
box-shadow: 0 0 3px #e7ab34;
}
/*=== New article notification */
#new-article {
background: #0084cc;
text-align: center;
font-size: 0.9em;
}
#new-article:hover {
background: #06c;
}
#new-article > a {
line-height: 3em;
color: #fff;
font-weight: bold;
}
#new-article > a:hover {
text-decoration: none;
}
/*=== Day indication */
.day {
padding: 0 10px;
background: linear-gradient(0deg, #ede7de 0%, #c2bcb3 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #c2bcb3 0%, #fff 100%);
color: #666;
box-shadow: 0 1px #bdb7ae inset, 0 -1px rgba(255,255,255,0.28) inset;
font-style: italic;
line-height: 3em;
text-shadow: 0 1px rgba(255,255,255,0.28);
text-align: center;
}
#new-article + .day {
border-top: none;
}
.day .name {
display: none;
}
/*=== Index menu */
.nav_menu {
padding: 5px 0;
background: #ede7de;
border-bottom: 1px solid #ccc;
box-shadow: 0 -1px rgba(255, 255, 255, 0.28) inset;
text-align: center;
}
#panel >.nav_menu {
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
}
#panel > .nav_menu > #nav_menu_read_all {
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0px 1px #fff;
}
#panel > .nav_menu > #nav_menu_read_all .dropdown > .btn.dropdown-toggle {
border: none;
border-left: solid 1px #ccc;
border-radius: 0 4px 4px 0;
}
/*=== Feed articles */
.flux_content {
background: #fff;
border-radius: 10px;
}
.flux {
background: #ede7de;
}
.flux:hover {
background: #f9f7f4;
}
.flux:not(.current):hover .item.title {
background: #f9f7f4;
}
.flux.current .flux .item.title a {
text-shadow: 0 0 2px #ccc;
}
.flux.favorite {
background: #fff6da;
}
.flux.favorite:not(.current):hover {
background: #f9f7f4;
}
.flux.favorite:not(.current):hover .item.title {
background: #f9f7f4;
}
.flux.current {
margin: 3px 6px;
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #ede7de;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
border-radius: 10px;
box-shadow: 0 -1px #fff inset, 0 2px #ccc;
}
.flux .item.title a {
color: #aca8a3;
}
.flux.not_read .item.title a,
.flux.favorite .item.title a {
color: #333;
}
.flux.not_read:not(.current):hover .item.title a {
color: #50504f;
}
.flux.current .item.title a {
color: #0f0f0f;
}
.flux_header {
font-size: 0.8rem;
border-top: 1px solid #ddd;
box-shadow: 0 -1px rgba(255,255,255,0.28) inset;
cursor: pointer;
}
.flux_header .title {
font-size: 0.9rem;
}
.flux .website .favicon {
padding: 5px;
}
.flux .date {
color: #666;
font-size: 0.7rem;
}
.flux .bottom {
font-size: 0.8rem;
text-align: center;
}
/*=== Content of feed articles */
.content {
padding: 20px 10px;
}
.content > h1.title > a {
color: #000;
}
.content hr {
margin: 30px 10px;
background: #ddd;
height: 1px;
border: 0;
box-shadow: 0 2px 5px #ccc;
}
.content pre {
margin: 10px auto;
padding: 10px 20px;
overflow: auto;
background: #222;
color: #fff;
font-size: 0.9rem;
border-radius: 3px;
}
.content code {
padding: 2px 5px;
background: #fafafa;
color: #d14;
border: 1px solid #eee;
border-radius: 3px;
}
.content pre code {
background: transparent;
color: #fff;
border: none;
}
.content blockquote {
margin: 0;
padding: 5px 20px;
background: #fafafa;
display: block;
color: #333;
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
.content blockquote p {
margin: 0;
}
/*=== Notification and actualize notification */
.notification {
padding: 0 0 0 5px;
background: #222;
color: #fff;
font-size: 0.9em;
border: none;
border-radius: 0 0 12px 12px;
box-shadow: 0px 0px 4px rgba(0,0,0,0.45), 0 -1px rgba(255,255,255,0.08) inset, 0 2px 2px #171717 inset;
text-align: center;
font-weight: bold;
line-height: 3em;
position: absolute;
top: 0;
z-index: 10;
vertical-align: middle;
}
.notification.good {
color: #c95;
}
.notification.bad {
background: #fdd;
color: #844;
}
.notification a.close {
padding: 0 15px;
line-height: 3em;
}
.notification#actualizeProgress {
line-height: 2em;
}
/*=== "Load more" part */
#bigMarkAsRead {
background: #ede7de;
color: #666;
box-shadow: 0 1px rgba(255,255,255,0.28)inset;
text-align: center;
text-decoration: none;
text-shadow: 0 -1px 0 #aaa;
}
#bigMarkAsRead:hover {
background: #ede7de;
background: radial-gradient(circle at 50% -25% , #ccc 0%, #ede7de 50%);
color: #000;
}
#bigMarkAsRead:hover .bigTick {
text-shadow: 0 0 10px #666;
}
/*=== Navigation menu (for articles) */
#nav_entries {
background: linear-gradient(180deg, #222 0%, #171717 100%) #222;
background: -webkit-linear-gradient(top, #222 0%, #171717 100%);
width: 235px;
border-top: 1px solid #171717;
box-shadow: 0 1px rgba(255,255,255,0.08) inset, 0 -2px 2px #171717;
text-align: center;
line-height: 3em;
table-layout: fixed;
}
/*=== READER VIEW */
/*================*/
#stream.reader .flux {
padding: 0 0 50px;
background: #f0f0f0;
color: #333;
border: none;
}
#stream.reader .flux .author {
margin: 0 0 10px;
color: #666;
font-size: 90%;
}
/*=== GLOBAL VIEW */
/*================*/
#stream.global {
padding: 24px 0;
box-shadow: 0px 8px 8px #c2bcb3 inset;
}
.box.category .box-title {
background: linear-gradient(0deg, #ede7de 0%, #fff 100%) #171717;
background: -webkit-linear-gradient(bottom, #ede7de 0%, #fff 100%);
font-size: 1.2rem;
border-radius: none;
box-shadow: 0px -1px #fff inset,0 -2px #ccc inset;
line-height: 2em;
text-shadow: 0 1px #ccc;
}
.box.category .box-title .title {
font-weight: normal;
text-decoration: none;
text-align: left;
color: #888;
}
.box.category:not([data-unread="0"]) .box-title .title {
color: #222;
font-weight: bold;
}
.box.category .title:not([data-unread="0"])::after {
background: none;
border: 0;
position: absolute;
top: 5px; right: 10px;
font-weight: bold;
}
.box.category .item.feed {
padding: 2px 10px;
font-size: 0.8rem;
}
.box.category .item.feed:not(.empty):not(.error) .item-title {
color: #222;
}
/*=== PANEL */
/*===========*/
#panel {
background: #ede7de;
border-radius: 8px;
box-shadow: 0px 0px 4px #000;
}
/*=== DIVERS */
/*===========*/
.aside.aside_feed .nav-form input,.aside.aside_feed .nav-form select {
width: 130px;
}
.aside.aside_feed .nav-form .dropdown .dropdown-menu {
right: -20px;
}
.aside.aside_feed .nav-form .dropdown .dropdown-menu::after {
right: 33px;
}
/*=== STATISTICS */
/*===============*/
.stat {
margin: 10px 0 20px;
}
.stat th,
.stat td,
.stat tr {
border: none;
}
.stat > table td,
.stat > table th {
background: rgba(255,255,255,0.38);
border-bottom: 1px solid #ccc;
box-shadow: 0 1px #fff;
}
.stat > .horizontal-list {
margin: 0 0 5px;
}
.stat > .horizontal-list .item {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.stat > .horizontal-list .item:first-child {
width: 250px;
}
/*=== LOGS */
/*=========*/
.loglist {
border: 1px solid #aaa;
border-radius: 5px;
overflow: hidden;
}
.log {
padding: 5px 10px;
background: #fafafa;
color: #333;
font-size: 0.8rem;
}
.log+.log {
border-top: 1px solid #aaa;
}
.log .date {
display: block;
font-weight: bold;
}
.log.error {
background: #fdd;
color: #844;
}
.log.warning {
background: #ffe;
color: #c95;
}
.log.notice {
background: #f4f4f4;
color: #aaa;
}
.log.debug {
background: #333;
color: #eee;
}
#slider.active {
background: #f8f8f8;
box-shadow: -4px 0 4px rgba(15, 15, 15, 0.55);
}
#close-slider.active {
background: rgba(15, 15, 15, 0.35);
}
/*=== MOBILE */
/*===========*/
@media screen and (max-width: 840px) {
.form-group .group-name {
padding-bottom: 0;
text-align: left;
}
.box .box-title .configure,
.box .box-content .item .configure {
visibility: visible;
}
.header {
display: table;
}
.nav-login {
display: none;
}
.aside {
width: 0;
border-top: none;
box-shadow: 3px 0 3px #000;
transition: width 200ms linear;
}
.aside:target {
width: 235px;
}
.aside .toggle_aside,
#panel .close {
background: #171717;
display: block;
width: 100%;
height: 40px;
border-radius: 0 8px 0 8px;
box-shadow: 0 1px rgba(255,255,255,0.08);
line-height: 40px;
text-align: center;
}
.aside.aside_feed {
padding: 0;
}
.nav_menu .btn {
margin: 5px 10px;
}
.nav_menu .stick {
margin: 0 10px;
}
.nav_menu .stick .btn {
margin: 5px 0;
}
.nav_menu .search {
display: none;
}
.nav_menu .search input {
max-width: 97%;
width: 90px;
}
.nav_menu .search input:focus {
width: 400px;
}
.day .name {
display: none;
}
.pagination {
margin: 0 0 3.5em;
}
.notification a.close {
background: transparent;
display: block;
left: 0;
}
.notification a.close:hover {
opacity: 0.5;
}
.notification a.close .icon {
display: none;
}
#nav_entries {
width: 100%;
}
.post {
padding-left: 15px;
padding-right: 15px;
}
#close-slider.active {
background: #171717;
box-shadow: 0 1px rgba(255,255,255,0.08)
}
}
@media (max-width: 700px) {
.header {
display: none;
}
.nav-login {
display: inline-block;
width: 100%;
}
.nav_menu .search {
display: inline-block;
}
}
| romibi/FreshRSS | p/themes/Screwdriver/screwdriver.css | CSS | agpl-3.0 | 23,639 |
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "conf.h"
#include <iostream>
#include "ed/connectors/synonym_parser.h"
#include "utils/timer.h"
#include "utils/init.h"
#include <fstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include "utils/exception.h"
#include "ed_persistor.h"
namespace po = boost::program_options;
namespace pt = boost::posix_time;
int main(int argc, char* argv[]) {
std::string input, connection_string;
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("help,h", "Show this message")
("input,i", po::value<std::string>(&input), "Synonyms file name")
("version,v", "Show version")
("config-file", po::value<std::string>(), "Path to config file")
("connection-string", po::value<std::string>(&connection_string)->required(),
"Database connection parameters: host=localhost user=navitia"
" dbname=navitia password=navitia")
("local_syslog", "activate log redirection within local syslog")
("log_comment", po::value<std::string>(), "optional field to add extra information like coverage name");
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("version")) {
std::cout << argv[0] << " " << navitia::config::project_version << " " << navitia::config::navitia_build_type
<< std::endl;
return 0;
}
// Construct logger and signal handling
std::string log_comment = "";
if (vm.count("log_comment")) {
log_comment = vm["log_comment"].as<std::string>();
}
navitia::init_app("synonym2ed", "DEBUG", vm.count("local_syslog"), log_comment);
auto logger = log4cplus::Logger::getInstance("log");
if (vm.count("config-file")) {
std::ifstream stream;
stream.open(vm["config-file"].as<std::string>());
if (!stream.is_open()) {
throw navitia::exception("loading config file failed");
} else {
po::store(po::parse_config_file(stream, desc), vm);
}
}
if (vm.count("help") || !vm.count("input")) {
std::cout << "Reads and inserts a synonym file into an ed database" << std::endl;
std::cout << desc << std::endl;
return 1;
}
po::notify(vm);
pt::ptime start;
start = pt::microsec_clock::local_time();
ed::connectors::SynonymParser synonym_parser(input);
try {
synonym_parser.fill();
} catch (const ed::connectors::SynonymParserException& e) {
LOG4CPLUS_FATAL(logger, "Erreur :" + std::string(e.what()) + " backtrace :" + e.backtrace());
return -1;
}
ed::EdPersistor p(connection_string);
p.persist_synonym(synonym_parser.synonym_map);
LOG4CPLUS_FATAL(logger, "temps :" << to_simple_string(pt::microsec_clock::local_time() - start));
return 0;
}
| pbougue/navitia | source/ed/synonym2ed.cpp | C++ | agpl-3.0 | 4,075 |
DELETE FROM `weenie` WHERE `class_Id` = 53484;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (53484, 'ace53484-viridiankeyofthesixthportal', 51, '2019-02-10 00:00:00') /* Stackable */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (53484, 1, 128) /* ItemType - Misc */
, (53484, 5, 1) /* EncumbranceVal */
, (53484, 11, 100) /* MaxStackSize */
, (53484, 12, 1) /* StackSize */
, (53484, 13, 1) /* StackUnitEncumbrance */
, (53484, 15, 1) /* StackUnitValue */
, (53484, 16, 1) /* ItemUseable - No */
, (53484, 19, 1) /* Value */
, (53484, 33, 1) /* Bonded - Bonded */
, (53484, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (53484, 98, 1485849095) /* CreationTimestamp */
, (53484, 114, 1) /* Attuned - Attuned */
, (53484, 267, 15000) /* Lifespan */
, (53484, 268, 14998) /* RemainingLifespan */
, (53484, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (53484, 69, False) /* IsSellable */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (53484, 1, 'Viridian Key of the Sixth Portal') /* Name */
, (53484, 15, 'Hand this to the entrance statue of the Viridian Rise to enter the sixth area of the Viridian Rise. ') /* ShortDesc */
, (53484, 20, 'Viridian Keys of the Sixth Portal') /* PluralName */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (53484, 1, 33554784) /* Setup */
, (53484, 3, 536870932) /* SoundTable */
, (53484, 8, 100667486) /* Icon */
, (53484, 22, 872415275) /* PhysicsEffectTable */
, (53484, 52, 100689826) /* IconUnderlay */
, (53484, 8001, 2125849) /* PCAPRecordedWeenieHeader - PluralName, Value, Usable, StackSize, MaxStackSize, Container, Burden */
, (53484, 8002, 1) /* PCAPRecordedWeenieHeader2 - IconUnderlay */
, (53484, 8003, 67108880) /* PCAPRecordedObjectDesc - Attackable, IncludesSecondHeader */
, (53484, 8005, 137217) /* PCAPRecordedPhysicsDesc - CSetup, STable, PeTable, AnimationFrame */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (53484, 8000, 2885546634) /* PCAPRecordedObjectIID */;
| LtRipley36706/ACE-World | Database/3-Core/9 WeenieDefaults/SQL/Stackable/Misc/53484 Viridian Key of the Sixth Portal.sql | SQL | agpl-3.0 | 2,467 |
import os
test_dir = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(test_dir, 'db.sqlite3'),
}
}
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.staticfiles',
'imperavi',
'tinymce',
'newsletter'
]
# Imperavi is not compatible with Django 1.9+
import django
if django.VERSION > (1, 8):
INSTALLED_APPS.remove('imperavi')
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
ROOT_URLCONF = 'test_project.urls'
FIXTURE_DIRS = [os.path.join(test_dir, 'fixtures'), ]
SITE_ID = 1
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [os.path.join(test_dir, 'templates')],
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# Enable time-zone support
USE_TZ = True
TIME_ZONE = 'UTC'
# Required for django-webtest to work
STATIC_URL = '/static/'
# Random secret key
import random
key_chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = ''.join([
random.SystemRandom().choice(key_chars) for i in range(50)
])
# Logs all newsletter app messages to the console
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'newsletter': {
'handlers': ['console'],
'propagate': True,
},
},
}
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
| dsanders11/django-newsletter | test_project/test_project/settings.py | Python | agpl-3.0 | 2,081 |
class AddDescriptionToSiteSettings < ActiveRecord::Migration[5.2]
def change
add_column :site_settings, :description, :text
end
end
| ArtOfCode-/qpixel | db/migrate/20191125135227_add_description_to_site_settings.rb | Ruby | agpl-3.0 | 140 |
<div id="host_list_table" {{ host_list.count }}>
{% if host_list %}
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="select_all" /></th>
<th> eth1 </th>
<th> 状态 </th>
<th> 操作 </th>
</tr>
</thead>
{% for i in host_list %}
<tbody>
<tr >
<td width="40">
<input type="checkbox" name="node_name" value="{{i.node_name}}"/>
</td>
<td width="200">
<a class="fancybox fancybox.ajax" href="/assets/server/node_id/{{ i.id }}/" title="{{ i.eth1 }}" >{{ i.eth1 }}</a>
</td>
<td width="50">
<div class="btn-group tooltip-demo" data-toggle="buttons">
{% if i.status == 0 %}
<span class="glyphicon glyphicon-remove" data-toggle="tooltip" data-placement="bottom" title="未安装系统" aria-hidden="true" style="color: #ff6846"></span>
{% elif i.status == 1 %}
<span class="glyphicon glyphicon-ok" aria-hidden="true" data-toggle="tooltip" data-placement="bottom" title="已安装系统" style="color:#2ad49e"></span>
{% else %}
<span class="glyphicon glyphicon-saved" aria-hidden="true" data-toggle="tooltip" data-placement="bottom" title="安装系统中..." style="color:#2d98d4"></span>
{% endif %}
</div></td>
<td width="160" >
<a href="" class="btn node_cmd" value="{{i.node_name}}" onclick="return false" >执行命令</a>
</td>
</tr>
</tbody>
{% endfor %}
</table>
<pre>推送配置文件</pre>
<button type="button" class="btn btn-primary" id="node_list_cmd">批量执行命令</button>
{# {% if env not in "all" %}#}
<button type="button" class="btn btn-info" id="state_highstate">自动化部署</button>
{# {% endif %}#}
<script type="text/javascript">
$(function(){
$("#select_all").change(function(){
var selected = $("#select_all").prop("checked");
if(selected){
$("input[name='node_name']").prop('checked',true);
}else{
$("input[name='node_name']").prop("checked",false);
}
});
});
</script>
{% else %}
<pre style="margin-top:8px">该环境木有机器</pre>
{% endif %}
</div>
<style>
#node_name_list{
width: 150px;
height: auto;
max-height: 400px;
min-height: 80px;
overflow-y: auto;
overflow-x: hidden;
margin: 0px;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
color: #555;
display: block;
font-size: 14px;
line-height: 1.42857;
padding: 6px 12px;
transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
vertical-align: middle;
}
#host_list, #swan_host_list{
width: 190px;
height: auto;
max-height: 400px;
min-height: 80px;
overflow-y: auto;
overflow-x: hidden;
margin: 0px;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
color: #555;
display: block;
font-size: 14px;
line-height: 1.42857;
padding: 6px 12px;
transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
vertical-align: middle;
}
.salt-cmd{
display:none;
}
.highstate{
display:none;
}
.swan_project{display: none}
</style>
<div class="row salt-cmd">
<form method = "post" action="{% url 'cmd_run' %}" id="run_form">
{% csrf_token %}
<div class="col-lg-9">
<h3>请输入执行命令</h3>
<div class="input-group">
<span class="input-group-addon ">
<select id="id_brand" name="comm_shell">
<option value="cmd" selected="selected">cmd.run</option>
{# <option value="grains">grains.item</option>#}
</select>
</span>
<input type="text" class="form-control" name="salt_cmd" id="salt_cmd" placeholder="如:ifconfig 命令可连输哦,如ls;pwd;uname -a中间以;做分割" maxlength="100" size="60">
<span class="input-group-btn">
<button class="btn btn-success" id="button" type="submit">执行</button>
</span>
</div>
<br>
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
磁盘 <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=disk_blkid">blkid</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=disk_inodeusage">inode使用情况</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=disk_percent">百分比</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=disk_usage">总使用情况</a></li>
</ul>
</div>
<div class="btn-group">
<button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" type="button">
nginx <span class="caret"></span>
</button>
<ul role="menu" class="dropdown-menu">
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=nginx_configtest">配置文件检查</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=nginx_status">状态</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=nginx_version">版本</a></li>
</ul>
</div>
<div class="btn-group">
<button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" type="button">
网络 <span class="caret"></span>
</button>
<ul role="menu" class="dropdown-menu">
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=network_active_tcp">活动TCP连接</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=network_arp">arp</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=network_netstat">netstat</a></li>
<li class="divider"></li>
<li><a class="btn_cmd_run" data-id="network_connect" data="{% url 'button_cmd_run' %}?cmd=network_connect">测试connect</a></li>
<li><a class="btn_cmd_run" data-id="network_dig" data="{% url 'button_cmd_run' %}?cmd=network_dig">dig</a></li>
</ul>
</div>
<div class="btn-group">
<button data-toggle="dropdown" class="btn btn-primary dropdown-toggle" type="button">
进程 <span class="caret"></span>
</button>
<ul role="menu" class="dropdown-menu">
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=ps_top">top</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=ps_get_users">get_users</a></li>
<li><a class="btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=ps_cpu_times">cpu时间</a></li>
<li><a class="btn_cmd_run" data-id="ps_pgrep" data="{% url 'button_cmd_run' %}?cmd=ps_pgrep">进程grep</a></li>
<li class="divider"></li>
</ul>
</div>
<a class="btn btn-primary btn_cmd_run" data-id="cmd_tail" data="{% url 'button_cmd_run' %}?cmd=cmd_tail">查看文件</a>
<a class="btn btn-primary btn_cmd_run" data="{% url 'button_cmd_run' %}?cmd=list_log">Log文件</a>
<br>
<br>
<div style="display:none" id='ps_pgrep'>
<div class="form-group col-md-3">
<label class="sr-only" for="pattern">pattern</label>
<input type="text" class="form-control" id="pattern" placeholder="pattern">
</div>
<a id="ps_pgrep_btn" data="{% url 'button_cmd_run' %}?cmd=ps_pgrep" class="btn btn-success">提交</a>
</div>
<div style="display:none" id='network_dig'>
<div class="form-group col-md-3">
<label class="sr-only" for="host">host</label>
<input type="text" class="form-control" id="host" placeholder="host">
</div>
<a id="network_dig_btn" data="{% url 'button_cmd_run' %}?cmd=network_dig" class="btn btn-success">提交</a>
</div>
<div style="display:none" id='network_connect'>
<div class="form-group col-md-3">
<label class="sr-only" for="pattern">host</label>
<input type="text" class="form-control" id="host" placeholder="host">
</div>
<div class="form-group col-md-2">
<label class="sr-only" for="pattern">port</label>
<input type="text" class="form-control" id="port" placeholder="port">
</div>
<a id="network_connect_btn" data="{% url 'button_cmd_run' %}?cmd=network_connect" class="btn btn-success">提交</a>
</div>
<div style="display:none" id='cmd_tail'>
<div class="form-group col-md-3">
<label class="sr-only" for="pattern">文件路径</label>
<input type="text" class="form-control" id="tail_path" placeholder="文件路径">
</div>
<div class="form-group col-md-2">
<label class="sr-only" for="pattern"></label>
<input type="text" class="form-control" id="tail_num" placeholder="行数">
</div>
<a id="cmd_tail_btn" data="{% url 'button_cmd_run' %}?cmd=cmd_tail" class="btn btn-success">提交</a>
</div>
<br>
<div id="return_block"></div>
</div>
<div class="col-lg-3">
<h3>选中的机器</h3>
<div class="input-group">
<ul id="node_name_list" class="list-unstyled"></ul>
</div>
</div>
</form>
</div>
<div class="row highstate">
<form method = "post" action="{% url 'highstate' %}" id="highstate_form">
<div class="col-lg-8">
<h3>自动化部署</h3>
{# <div class="col-md-12 column">#}
<pre class="col-md-10 column"></pre>
<div class="col-md-10 column">
<button type="button" class="btn btn-success" id="highstate_butten">开始执行</button>
</div>
{# </div>#}
<div id="return_highstate"></div>
</div>
<div class="col-lg-2">
<h3>选中的机器</h3>
<div class="input-group">
{% csrf_token %}
<ul id="host_list" class="list-unstyled"></ul>
{# <input hidden="hidden" name="{{ env }}" />#}
<input hidden="hidden" name="project" value="{{ item.aliases_name }}"/>
</div>
</div>
</form>
</div>
<script type="text/javascript">
function get_node(){
var arg = '';
$("[name='node_name']").each(function(){
arg+='&project={{ business_item }}&node_name=' + $(this).attr('value');
});
return arg;
}
function input_hide(){
$('#network_dig_btn').parent().hide();
$('#network_connect_btn').parent().hide();
$('#ps_pgrep_btn').parent().hide();
$('#cmd_tail_btn').parent().hide();
}
$(function(){
$('.btn_cmd_run').unbind('click').bind('click',function(e){
e.preventDefault();
var data_id = $(this).attr('data-id');
input_hide();
if (data_id == 'ps_pgrep'){
$("#ps_pgrep").show();
}else if (data_id == 'network_connect'){
$("#network_connect").show();
}else if (data_id == 'network_dig'){
$("#network_dig").show();
}else if (data_id == 'cmd_tail'){
$("#cmd_tail").show();
}else{
var url = $(this).attr('data');
var arg = get_node();
$.get(url+arg,{},function(data){
$("#return_block").html(data);
});
}
});
$('#ps_pgrep_btn').click(function(e){
e.preventDefault();
var arg = get_node();
arg += "&pattern=" + $("#pattern").val();
var url = $(this).attr('data');
$.get(url+arg,{},function(data){
$("#return_block").html(data);
});
});
$('#network_dig_btn').click(function(e){
e.preventDefault();
var arg = get_node();
arg += "&host=" + $("#host").val();
var url = $(this).attr('data');
$.get(url+arg,{},function(data){
$("#return_block").html(data);
});
});
$('#cmd_tail_btn').click(function(e){
e.preventDefault();
var arg = get_node();
arg += "&path=" + $("#tail_path").val()+"&num=" + $("#tail_num").val();
var url = $(this).attr('data');
$.get(url+arg,{},function(data){
$("#return_block").html(data);
});
});
$('#network_connect_btn').click(function(e){
e.preventDefault();
var arg = get_node();
arg += "&host=" + $("#host").val()+"&port=" + $("#port").val();
var url = $(this).attr('data');
$.get(url+arg,{},function(data){
$("#return_block").html(data);
});
});
$('.node_cmd').click(function(){
var node_name = $(this).attr('value');
var li_html = "<li>"+node_name+"</li>";
li_html += "<li><input type='hidden' name='node_name' value="+node_name+"></li>";
$('#node_name_list').html(li_html);
$('#host_list_table').remove();
$('.salt-cmd').show()
});
$('#node_list_cmd').click(function(){
$("table :checked").each(function(){
node_name = $(this).attr('value');
if (node_name != undefined) {
var li_html = "<li>"+node_name+"</li>";
li_html += "<li><input type='hidden' name='node_name' value="+node_name+"></li>";
li_html += "<li><input hidden='hidden' name='project' value='{{ business_item }}'></li>";
$('#node_name_list').append(li_html);
$('#host_list_table').remove();
$('.salt-cmd').show();
};
});
});
$('#button').click(function(e){
e.preventDefault();
$.post($('#run_form').attr('action'),$('#run_form').serialize(),function(data){
$("#return_block").html(data);
});
});
// 自动部署
$('#state_highstate').click(function(){
$("table :checked").each(function(){
node_name = $(this).attr('value');
if (node_name != undefined) {
var li_html = "<li>"+node_name+"</li>";
li_html += "<li><input type='hidden' name='node_name' value="+node_name+"></li>";
$('#host_list').append(li_html);
$('#host_list_table').remove();
$('.highstate').show();
};
});
});
// 自动部署提交
// $('#highstate_butten').unbind('click').bind('click',function(){
//
// $.post($('#highstate_form').attr('action'), $('#highstate_form').serialize(),function(data){
// //console.log(data);
// var jid=JSON.parse(data.data);
// console.log(jid);
// //$("#return_highstate").html(data);
// //var height = $(window).height(), index = $.layer({
// // type: 2,
// // shade: [0.5, '#000', true],
// // shadeClose: true,
// // maxmin: true,
// // // border : [!0],
// // moveOut: true,
// // shift: 'top',
// // border: [10, 0.3, '#000'],
// // title: "服务器详细信息",
// // area: ['800px', (height - 50) + 'px'],
// // //area : ['80%', (height - 50)+'px'],
// // //iframe: {src: $(this).attr('href')}
// // iframe: {src: 'http://127.0.0.1:8000/assets/host_detail/?uuid=0547b11f26014b41be9e4bc0c89f3db6'}
// //});
// });
// });
$('#highstate_butten').unbind('click').bind('click',function(event){
$.ajax({
type: "POST",
url: '/auto/highstate/', // 提交的页面
data: $('#highstate_form').serialize(), // 从表单中获取数据
dataType:'json',
success: function(data){
if (data.status == 200){
var height = $(window).height(), index = $.layer({
type: 2,
shade: [0.5, '#000', true],
shadeClose: true,
maxmin: true,
// border : [!0],
moveOut: true,
shift: 'top',
border: [10, 0.3, '#000'],
title: "服务器详细信息",
area: ['800px', (height - 50) + 'px'],
//area : ['80%', (height - 50)+'px'],
//iframe: {src: 'http://127.0.0.1:8000/assets/host_detail/?uuid=0547b11f26014b41be9e4bc0c89f3db6'}
iframe: {src: '/salt/jobs/?jid=' + data.jid + '&token=' + data.token + '&name=' + data.name}
});
event.preventDefault();
}
}
});
});
//$(function(){
$('.project').unbind('click').bind('click',function(){
$.ajax({
type: "POST",
url: $(this).attr("href"), // 提交的页面
data: $('#swan_form').serialize(), // 从表单中获取数据
dataType:'text',
success: function(data){
$("#return_block_push").html(data);
}
});
});
//})
});
</script>
| voilet/cmdb | templates/server_idc/host_list_widget.html | HTML | agpl-3.0 | 17,500 |
// (C) Copyright Jeremy Siek 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ITERATOR_CONCEPTS_HPP
#define BOOST_ITERATOR_CONCEPTS_HPP
#include <boost/concept_check.hpp>
#include <boost/iterator/iterator_categories.hpp>
// Use abt_boost::detail::iterator_traits to work around some MSVC/Dinkumware problems.
#include <boost/detail/iterator.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>
#include <boost/static_assert.hpp>
// Use boost/limits to work around missing limits headers on some compilers
#include <boost/limits.hpp>
#include <boost/config.hpp>
#include <algorithm>
#include <boost/concept/detail/concept_def.hpp>
namespace abt_boost_concepts
{
// Used a different namespace here (instead of "boost") so that the
// concept descriptions do not take for granted the names in
// namespace abt_boost.
//===========================================================================
// Iterator Access Concepts
BOOST_concept(ReadableIterator,(Iterator))
: abt_boost::Assignable<Iterator>
, abt_boost::CopyConstructible<Iterator>
{
typedef BOOST_DEDUCED_TYPENAME abt_boost::detail::iterator_traits<Iterator>::value_type value_type;
typedef BOOST_DEDUCED_TYPENAME abt_boost::detail::iterator_traits<Iterator>::reference reference;
BOOST_CONCEPT_USAGE(ReadableIterator)
{
value_type v = *i;
abt_boost::ignore_unused_variable_warning(v);
}
private:
Iterator i;
};
template <
typename Iterator
, typename ValueType = BOOST_DEDUCED_TYPENAME abt_boost::detail::iterator_traits<Iterator>::value_type
>
struct WritableIterator
: abt_boost::CopyConstructible<Iterator>
{
BOOST_CONCEPT_USAGE(WritableIterator)
{
*i = v;
}
private:
ValueType v;
Iterator i;
};
template <
typename Iterator
, typename ValueType = BOOST_DEDUCED_TYPENAME abt_boost::detail::iterator_traits<Iterator>::value_type
>
struct WritableIteratorConcept : WritableIterator<Iterator,ValueType> {};
BOOST_concept(SwappableIterator,(Iterator))
{
BOOST_CONCEPT_USAGE(SwappableIterator)
{
std::iter_swap(i1, i2);
}
private:
Iterator i1;
Iterator i2;
};
BOOST_concept(LvalueIterator,(Iterator))
{
typedef typename abt_boost::detail::iterator_traits<Iterator>::value_type value_type;
BOOST_CONCEPT_USAGE(LvalueIterator)
{
value_type& r = const_cast<value_type&>(*i);
abt_boost::ignore_unused_variable_warning(r);
}
private:
Iterator i;
};
//===========================================================================
// Iterator Traversal Concepts
BOOST_concept(IncrementableIterator,(Iterator))
: abt_boost::Assignable<Iterator>
, abt_boost::CopyConstructible<Iterator>
{
typedef typename abt_boost::iterator_traversal<Iterator>::type traversal_category;
BOOST_CONCEPT_ASSERT((
abt_boost::Convertible<
traversal_category
, abt_boost::incrementable_traversal_tag
>));
BOOST_CONCEPT_USAGE(IncrementableIterator)
{
++i;
(void)i++;
}
private:
Iterator i;
};
BOOST_concept(SinglePassIterator,(Iterator))
: IncrementableIterator<Iterator>
, abt_boost::EqualityComparable<Iterator>
{
BOOST_CONCEPT_ASSERT((
abt_boost::Convertible<
BOOST_DEDUCED_TYPENAME SinglePassIterator::traversal_category
, abt_boost::single_pass_traversal_tag
> ));
};
BOOST_concept(ForwardTraversal,(Iterator))
: SinglePassIterator<Iterator>
, abt_boost::DefaultConstructible<Iterator>
{
typedef typename abt_boost::detail::iterator_traits<Iterator>::difference_type difference_type;
BOOST_MPL_ASSERT((abt_boost::is_integral<difference_type>));
BOOST_MPL_ASSERT_RELATION(std::numeric_limits<difference_type>::is_signed, ==, true);
BOOST_CONCEPT_ASSERT((
abt_boost::Convertible<
BOOST_DEDUCED_TYPENAME ForwardTraversal::traversal_category
, abt_boost::forward_traversal_tag
> ));
};
BOOST_concept(BidirectionalTraversal,(Iterator))
: ForwardTraversal<Iterator>
{
BOOST_CONCEPT_ASSERT((
abt_boost::Convertible<
BOOST_DEDUCED_TYPENAME BidirectionalTraversal::traversal_category
, abt_boost::bidirectional_traversal_tag
> ));
BOOST_CONCEPT_USAGE(BidirectionalTraversal)
{
--i;
(void)i--;
}
private:
Iterator i;
};
BOOST_concept(RandomAccessTraversal,(Iterator))
: BidirectionalTraversal<Iterator>
{
BOOST_CONCEPT_ASSERT((
abt_boost::Convertible<
BOOST_DEDUCED_TYPENAME RandomAccessTraversal::traversal_category
, abt_boost::random_access_traversal_tag
> ));
BOOST_CONCEPT_USAGE(RandomAccessTraversal)
{
i += n;
i = i + n;
i = n + i;
i -= n;
i = i - n;
n = i - j;
}
private:
typename BidirectionalTraversal<Iterator>::difference_type n;
Iterator i, j;
};
//===========================================================================
// Iterator Interoperability
namespace detail
{
template <typename Iterator1, typename Iterator2>
void interop_single_pass_constraints(Iterator1 const& i1, Iterator2 const& i2)
{
bool b;
b = i1 == i2;
b = i1 != i2;
b = i2 == i1;
b = i2 != i1;
abt_boost::ignore_unused_variable_warning(b);
}
template <typename Iterator1, typename Iterator2>
void interop_rand_access_constraints(
Iterator1 const& i1, Iterator2 const& i2,
abt_boost::random_access_traversal_tag, abt_boost::random_access_traversal_tag)
{
bool b;
typename abt_boost::detail::iterator_traits<Iterator2>::difference_type n;
b = i1 < i2;
b = i1 <= i2;
b = i1 > i2;
b = i1 >= i2;
n = i1 - i2;
b = i2 < i1;
b = i2 <= i1;
b = i2 > i1;
b = i2 >= i1;
n = i2 - i1;
abt_boost::ignore_unused_variable_warning(b);
abt_boost::ignore_unused_variable_warning(n);
}
template <typename Iterator1, typename Iterator2>
void interop_rand_access_constraints(
Iterator1 const&, Iterator2 const&,
abt_boost::single_pass_traversal_tag, abt_boost::single_pass_traversal_tag)
{ }
} // namespace detail
BOOST_concept(InteroperableIterator,(Iterator)(ConstIterator))
{
private:
typedef typename abt_boost::detail::pure_traversal_tag<
typename abt_boost::iterator_traversal<
Iterator
>::type
>::type traversal_category;
typedef typename abt_boost::detail::pure_traversal_tag<
typename abt_boost::iterator_traversal<
ConstIterator
>::type
>::type const_traversal_category;
public:
BOOST_CONCEPT_ASSERT((SinglePassIterator<Iterator>));
BOOST_CONCEPT_ASSERT((SinglePassIterator<ConstIterator>));
BOOST_CONCEPT_USAGE(InteroperableIterator)
{
detail::interop_single_pass_constraints(i, ci);
detail::interop_rand_access_constraints(i, ci, traversal_category(), const_traversal_category());
ci = i;
}
private:
Iterator i;
ConstIterator ci;
};
} // namespace abt_boost_concepts
#include <boost/concept/detail/concept_undef.hpp>
#endif // BOOST_ITERATOR_CONCEPTS_HPP
| jbruestle/aggregate_btree | tiny_boost/boost/iterator/iterator_concepts.hpp | C++ | agpl-3.0 | 7,940 |
class FieldRegistry(object):
_registry = {}
def add_field(self, model, field):
reg = self.__class__._registry.setdefault(model, [])
reg.append(field)
def get_fields(self, model):
return self.__class__._registry.get(model, [])
def __contains__(self, model):
return model in self.__class__._registry
| feroda/django-pro-history | current_user/registration.py | Python | agpl-3.0 | 349 |
/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Definition of the RegisteredRegionImplPy
* This provides the plugin interface for the Python implemented Regions.
* This is a subclass of RegisteredRegionImpl; the base class of an object that can instantiate
* a plugin (a subclass of RegionImpl) and get its spec.
*
* the subclasses of RegistedRegionImpl must perform the following:
* 1) Be Registered with the CPP engine using
* Network::registerRegion( nodeType, module, classname);
* It only needs to be registed once even if multiple Regions will use
* an instance of the same plugin type. The 'nodeType' used in this registration
* is the 'nodeType' when calling Network::addRegion() to create a
* region. It is like declaring the type of the plugin.
* As a convention, the nodeType used by C++ plugins will be the class name.
* The name for Python plugins should start with 'py_'. Those for CSharp
* will start with 'cs_'.
*
* 2) Override the destructor if needed to cleanup your RegisteredRegionImpl subclass
*
* 3) Instantiate the plugin and return its pointer when createRegionImpl()
* is called.
*
* 4) Instantiate and deserialize the plugin when deserializeRegionImpl() is called,
* returning its pointer. This gets called when Network::Network(path) is called
* to initialize an entire network from a previous serialization file.
*
* 5) Get and return a pointer to the spec from the plugin when createSpec() is called.
* During this call the class should be loaded.
* The pointer to the spec returned from the plugin should be dynamically allocated
* and the caller takes ownership.
*
* 6) Before doing anything with a python region, we must initialize the python interpreter.
*
* 7) After the last python region has been deleted, we must finalize the python interpreter.
*
* An instance of a RegisteredRegionImplPy class represents a Python Region implementation type registration.
* An instance of a PyBindRegion class represents an instance of a Python Region implentation.
*
*/
#ifndef NTA_REGISTERED_REGION_IMPL_CPP_HPP
#define NTA_REGISTERED_REGION_IMPL_CPP_HPP
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
#include <plugin/PyBindRegion.hpp>
#include <nupic/engine/RegisteredRegionImpl.hpp>
#include <nupic/engine/RegionImplFactory.hpp>
#include <string>
namespace py = pybind11;
// A global variable to hold the number of python classes currently registered.
// If this is 0 then python library has not been initialized.
static int python_node_count = 0;
namespace nupic
{
class Spec;
class BundleIO;
class PyRegionImpl;
class Region;
class ValueMap;
class RegisteredRegionImplPy: public RegisteredRegionImpl {
public:
RegisteredRegionImplPy(const std::string& classname, const std::string& module="")
: RegisteredRegionImpl(classname, module) {
// NOTE: If this is called by .py code (and probably is) then the python interpreter is already running
// so we don't need to start it up.
}
~RegisteredRegionImplPy() override {
}
RegionImpl* createRegionImpl( ValueMap& params, Region *region) override
{
try {
// use PyBindRegion class to instantiate the python class in the specified module.
return new PyBindRegion(module_.c_str(), params, region, classname_.c_str());
}
catch (const py::error_already_set& e)
{
throw Exception(__FILE__, __LINE__, e.what());
}
catch (nupic::Exception & e)
{
throw nupic::Exception(e);
}
catch (...)
{
NTA_THROW << "Something bad happed while creating a .py region";
}
}
// use PyBindRegion class to instantiate and deserialize the python class in the specified module.
RegionImpl* deserializeRegionImpl(BundleIO& bundle, Region *region) override
{
try {
return new PyBindRegion(module_.c_str(), bundle, region, classname_.c_str());
}
catch (const py::error_already_set& e)
{
throw Exception(__FILE__, __LINE__, e.what());
}
catch (nupic::Exception & e)
{
throw nupic::Exception(e);
}
catch (...)
{
NTA_THROW << "Something bad happed while deserializing a .py region";
}
}
Spec* createSpec() override
{
Spec* sp = new Spec();
try {
PyBindRegion::createSpec(module_.c_str(), *sp, classname_.c_str());
}
catch (nupic::Exception & e) {
UNUSED(e);
delete sp;
throw;
}
catch (...) {
delete sp;
NTA_THROW << "PyBindRegion::createSpec failed: unknown exception.";
}
return sp;
}
/**
* Registers a python region implementation class so that it can be instantiated
* when its name is used in a Network::addRegion() call.
*
* @param className -- the name of the Python class that implements the region.
* @param module -- the module (shared library) in which the class resides.
*/
inline static void registerPyRegion(const std::string& module, const std::string& className) {
std::string nodeType = "py." + className;
RegisteredRegionImplPy *reg = new RegisteredRegionImplPy(className, module);
RegionImplFactory::registerRegion(nodeType, reg);
}
/*
* Removes a region from RegionImplFactory's packages
*/
inline static void unregisterPyRegion(const std::string& className) {
std::string nodeType = "py." + className;
RegionImplFactory::unregisterRegion(nodeType);
}
};
}
#endif // NTA_REGISTERED_REGION_IMPL_CPP_HPP
| breznak/nupic.core | bindings/py/cpp_src/plugin/RegisteredRegionImplPy.hpp | C++ | agpl-3.0 | 6,767 |
import {
REQUEST_COMPLETED, WEB_SOCKET_CONNECT,
WEB_SOCKET_SEND
} from '../connectionConstants';
import * as ReconnectingWebsocket from 'reconnecting-websocket';
import {Dispatch, Middleware} from 'redux';
import {authConnected, error} from "../connectionActions";
import {Item} from "../../graph/interfaces/item";
import {
liveReceive,
searchReceive,
setSearchTotal
} from "../../search/searchActions";
import {requestCompleted} from "../connectionActions";
import { receiveFieldMapping } from "../../fields/fieldsActions";
import {LIVE_RECEIVE, SEARCH_RECEIVE} from "../../search/searchConstants";
import {INITIAL_STATE_RECEIVE} from "../../datasources/datasourcesConstants";
import {receiveInitialState} from "../../datasources/datasourcesActions";
import Timer = NodeJS.Timer;
import { getResponses } from './mockServer';
import { FieldMapping } from '../../fields/interfaces/fieldMapping';
import { receiveWorkspaceDescriptions } from '../../ui/uiActions';
let opened: Promise<ReconnectingWebsocket>;
export const webSocketMiddleware: Middleware = ({dispatch}) => next => action => {
switch (action.type) {
case WEB_SOCKET_CONNECT: {
const backendUri: string = action.payload.backendUri;
console.log('Connecting to backend on ', backendUri);
opened = new Promise(resolve => {
const socket = new ReconnectingWebsocket(backendUri);
socket.onopen = event => {onOpen(dispatch); resolve(socket)};
socket.onmessage = event => onMessage(event, dispatch);
socket.onclose = event => onClose(event, dispatch);
socket.onerror = event => onClose(event, dispatch);
});
break;
}
case WEB_SOCKET_SEND: {
const payload: string = JSON.stringify(action.payload);
console.log('Send', action.payload);
let mockedResponses;
if (process.env.MOCK_SERVER) {
mockedResponses = getResponses(action.payload) as MessageEvent[];
}
if (mockedResponses) {
mockedResponses.forEach(response => {
console.log('Mocking server response', response);
onMessage(response, dispatch);
});
} else {
opened.then(socket => socket.send(payload));
}
break;
}
}
return next(action);
};
function onOpen(dispatch: Dispatch<any>) {
dispatch(authConnected(true, null));
dispatch(receiveWorkspaceDescriptions([
{
id: '1',
title: 'Research',
version: 7
},
{
id: '2',
title: 'Malware',
version: 7
}
]));
}
function onMessage(event: MessageEvent, dispatch: Dispatch<any>) {
const data = JSON.parse(event.data);
console.log('Receive', data.type);
switch (data.type) {
case SEARCH_RECEIVE: {
if (typeof data.total_count === 'number') {
dispatch(setSearchTotal(data['request-id'], data.total_count));
}
debounceItems(
data.results,
data.mapping,
data['request-id'],
dispatch,
false,
data.datasource
);
break;
}
case LIVE_RECEIVE: {
debounceItems(
data.graphs,
data.mapping,
data.datasource,
dispatch,
true,
data.datasource
);
break;
}
case INITIAL_STATE_RECEIVE:
dispatch(receiveInitialState({
datasources: data.datasources,
enrichers: data.enrichers,
version: data.version
}));
break;
case REQUEST_COMPLETED:
dispatch(requestCompleted(data['request-id']));
break;
case 'ERROR':
console.error(data);
dispatch(error(data.message, data['request-id']));
}
}
function onClose(event: CloseEvent, dispatch: Dispatch<any>) {
let reason = getCloseMessage(event);
dispatch(authConnected(false, reason));
}
function getCloseMessage(event: CloseEvent): string {
switch (event.code) {
case 1000:
return 'Normal closure, meaning that the purpose for which the connection was established has been fulfilled.';
case 1001:
return 'An endpoint is \'going away\', such as a server going down or a browser having navigated away from a page.';
case 1002:
return 'An endpoint is terminating the connection due to a protocol error';
case 1003:
return 'An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).';
case 1004:
return 'Reserved. The specific meaning might be defined in the future.';
case 1005:
return 'No status code was actually present.';
case 1006:
return 'The connection was closed abnormally, e.g., without sending or receiving a Close control frame';
case 1007:
return 'An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).';
case 1008:
return 'An endpoint is terminating the connection because it has received a message that \'violates its policy\'. This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.';
case 1009:
return 'An endpoint is terminating the connection because it has received a message that is too big for it to process.';
case 1010: // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead:
return 'An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn\'t return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: ' + event.reason;
case 1011:
return 'A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.';
case 1015:
return 'The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can\'t be verified).';
default:
return 'Unknown reason';
}
}
interface ItemsTimeout {
/**
* Resets every time we receive new results, so that we bundle results that
* are received in quick succession of each other.
*
* When the timeout completes, results are dispatched.
*
*/
bundleTimeout: Timer;
/**
* Does not reset when we receive new results. Used for solving the problem
* of the above timeout: imagine that we keep on getting results quickly
* forever -> the above timeout would never complete.
*
* When the timeout completes, results are dispatched.
*
*/
maxTimeout: Timer;
}
const debouncedItems: {
[requestId: string]: Item[]
} = {};
let debouncedFields: FieldMapping = {};
const debounceTimeouts: {
[requestId: string]: ItemsTimeout
} = {};
const timeoutMs = 500;
const maxTimeoutMs = 2000;
/**
* Sometimes we receive many items from the server in quick succession of
* each other. This is not good, because then we would need to calculate the
* graph for each time we receive it (so multiple times per second).
*
* Instead, we wait for 500ms and bundle all of the items together.
*
* @param newItems
* @param fields
* @param requestId
* @param dispatch
* @param isLive
* @param datasourceId
*/
function debounceItems(newItems: Item[], fields: FieldMapping, requestId: string, dispatch: Dispatch<any>, isLive: boolean, datasourceId: string) {
if (fields) {
Object.keys(fields).forEach(datasource => {
if (!debouncedFields[datasource]) {
debouncedFields[datasource] = {};
}
Object.keys(fields[datasource]).forEach(field => {
const type: string = fields[datasource][field];
debouncedFields[datasource][field] = type;
});
});
}
if (newItems === null) {
return;
}
newItems.forEach(item => {
item.datasourceId = datasourceId
});
let results = debouncedItems[requestId] || [];
for (let i = 0; i < newItems.length; i++ ) {
let result = newItems[i];
let index = results.findIndex((item) => item.id === result.id);
if (index === -1) {
results.push(result);
continue;
}
// already exists, update count
results[index].count = result.count;
}
debouncedItems[requestId] = results;
const searchTimeout: any = debounceTimeouts[requestId] || {};
const timeoutFinished = () => {
clearTimeout(searchTimeout.bundleTimeout);
clearTimeout(searchTimeout.maxTimeout);
dispatch(receiveFieldMapping(debouncedFields));
debouncedFields = {};
if (isLive) {
dispatch(liveReceive(debouncedItems[requestId], datasourceId));
} else {
dispatch(searchReceive(debouncedItems[requestId], requestId));
}
delete debouncedItems[requestId];
};
// Dispatch when we haven't received any new items for 500 ms.
clearTimeout(searchTimeout.bundleTimeout);
searchTimeout.bundleTimeout = setTimeout(timeoutFinished, timeoutMs);
// Only set the max timeout if it wasn't set already. It does not get
// cleared when new items are received.
if (!searchTimeout.maxTimeout) {
// Dispatch also when the max timeout is finished
searchTimeout.maxTimeout = setTimeout(timeoutFinished, maxTimeoutMs);
}
debounceTimeouts[requestId] = searchTimeout;
} | dutchcoders/marija-web | src/app/connection/helpers/webSocketMiddleware.ts | TypeScript | agpl-3.0 | 10,080 |
# Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
from zope.component import (
ComponentLookupError,
getMultiAdapter,
)
from zope.configuration import xmlconfig
from zope.interface import (
implements,
Interface,
)
from zope.publisher.interfaces.browser import (
IBrowserPublisher,
IDefaultBrowserLayer,
)
from zope.testing.cleanup import cleanUp
from lp.services.webapp import Navigation
from lp.testing import TestCase
class TestNavigationDirective(TestCase):
def test_default_layer(self):
# By default all navigation classes are registered for
# IDefaultBrowserLayer.
directive = """
<browser:navigation
module="%(this)s" classes="ThingNavigation"/>
""" % dict(this=this)
xmlconfig.string(zcml_configure % directive)
navigation = getMultiAdapter(
(Thing(), DefaultBrowserLayer()), IBrowserPublisher, name='')
self.assertIsInstance(navigation, ThingNavigation)
def test_specific_layer(self):
# If we specify a layer when registering a navigation class, it will
# only be available on that layer.
directive = """
<browser:navigation
module="%(this)s" classes="OtherThingNavigation"
layer="%(this)s.IOtherLayer" />
""" % dict(this=this)
xmlconfig.string(zcml_configure % directive)
self.assertRaises(
ComponentLookupError,
getMultiAdapter,
(Thing(), DefaultBrowserLayer()), IBrowserPublisher, name='')
navigation = getMultiAdapter(
(Thing(), OtherLayer()), IBrowserPublisher, name='')
self.assertIsInstance(navigation, OtherThingNavigation)
def test_multiple_navigations_for_single_context(self):
# It is possible to have multiple navigation classes for a given
# context class as long as they are registered for different layers.
directive = """
<browser:navigation
module="%(this)s" classes="ThingNavigation"/>
<browser:navigation
module="%(this)s" classes="OtherThingNavigation"
layer="%(this)s.IOtherLayer" />
""" % dict(this=this)
xmlconfig.string(zcml_configure % directive)
navigation = getMultiAdapter(
(Thing(), DefaultBrowserLayer()), IBrowserPublisher, name='')
other_navigation = getMultiAdapter(
(Thing(), OtherLayer()), IBrowserPublisher, name='')
self.assertNotEqual(navigation, other_navigation)
def tearDown(self):
TestCase.tearDown(self)
cleanUp()
class DefaultBrowserLayer:
implements(IDefaultBrowserLayer)
class IThing(Interface):
pass
class Thing(object):
implements(IThing)
class ThingNavigation(Navigation):
usedfor = IThing
class OtherThingNavigation(Navigation):
usedfor = IThing
class IOtherLayer(Interface):
pass
class OtherLayer:
implements(IOtherLayer)
this = "lp.services.webapp.tests.test_navigation"
zcml_configure = """
<configure xmlns:browser="http://namespaces.zope.org/browser">
<include package="lp.services.webapp" file="meta.zcml" />
%s
</configure>
"""
| abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/services/webapp/tests/test_navigation.py | Python | agpl-3.0 | 3,377 |
# mixml Selection
This document demonstrates the different methods to select XML nodes when using mixml.
## Select nodes using XPath expressions
You can use standard XPath expressions to select the nodes to process.
Let's use the following XML in file `test.xml`:
<list>
<philosopher name="Hobbes"/>
<philosopher name="Rawls"/>
</list>
Now execute the following command to rename some nodes:
# mixml rename --xpath '//philosopher[@name="Hobbes"]' --string 'tiger' test.xml
This produces the following XML output:
<list>
<tiger name="Hobbes"/>
<philosopher name="Rawls"/>
</list>
## Select nodes using CSS rules
You can also use CSS rules instead of XPath expressions to select the nodes to process.
Let's use the following XML in file `test.xml`:
<list>
<philosopher name="Hobbes"/>
<philosopher name="Rawls"/>
</list>
Now execute the following command to rename some nodes:
# mixml rename --css 'philosopher:first-child' --string 'tiger' test.xml
This produces the following XML output:
<list>
<tiger name="Hobbes"/>
<philosopher name="Rawls"/>
</list>
| jochenseeber/mixml | demo/application_selection.md | Markdown | agpl-3.0 | 1,175 |
<?php
require_once 'suppressblankaddress.civix.php';
/**
* Implementation of hook_civicrm_config
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
*/
function suppressblankaddress_civicrm_config(&$config) {
_suppressblankaddress_civix_civicrm_config($config);
}
/**
* Implementation of hook_civicrm_xmlMenu
*
* @param $files array(string)
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu
*/
function suppressblankaddress_civicrm_xmlMenu(&$files) {
_suppressblankaddress_civix_civicrm_xmlMenu($files);
}
/**
* Implementation of hook_civicrm_install
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
*/
function suppressblankaddress_civicrm_install() {
return _suppressblankaddress_civix_civicrm_install();
}
/**
* Implementation of hook_civicrm_uninstall
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_uninstall
*/
function suppressblankaddress_civicrm_uninstall() {
return _suppressblankaddress_civix_civicrm_uninstall();
}
/**
* Implementation of hook_civicrm_enable
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
*/
function suppressblankaddress_civicrm_enable() {
return _suppressblankaddress_civix_civicrm_enable();
}
/**
* Implementation of hook_civicrm_disable
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_disable
*/
function suppressblankaddress_civicrm_disable() {
return _suppressblankaddress_civix_civicrm_disable();
}
/**
* Implementation of hook_civicrm_upgrade
*
* @param $op string, the type of operation being performed; 'check' or 'enqueue'
* @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks
*
* @return mixed based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending)
* for 'enqueue', returns void
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_upgrade
*/
function suppressblankaddress_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
return _suppressblankaddress_civix_civicrm_upgrade($op, $queue);
}
/**
* Implementation of hook_civicrm_managed
*
* Generate a list of entities to create/deactivate/delete when this module
* is installed, disabled, uninstalled.
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_managed
*/
function suppressblankaddress_civicrm_managed(&$entities) {
return _suppressblankaddress_civix_civicrm_managed($entities);
}
/**
* Implementation of hook_civicrm_caseTypes
*
* Generate a list of case-types
*
* Note: This hook only runs in CiviCRM 4.4+.
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_caseTypes
*/
function suppressblankaddress_civicrm_caseTypes(&$caseTypes) {
_suppressblankaddress_civix_civicrm_caseTypes($caseTypes);
}
/**
* Implementation of hook_civicrm_alterSettingsFolders
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_alterSettingsFolders
*/
function suppressblankaddress_civicrm_alterSettingsFolders(&$metaDataFolders = NULL) {
_suppressblankaddress_civix_civicrm_alterSettingsFolders($metaDataFolders);
}
function suppressblankaddress_civicrm_tokens(&$tokens) {
$tokens['contact']['contact.address_block'] = 'Address block';
$tokens['contact']['contact.today_date'] = "Today's Date";
$tokens['contact']['contact.billing_block'] = 'Billing block';
}
function suppressblankaddress_civicrm_tokenValues( &$values, $cids, $job = null, $tokens = array(), $context = null ) {
foreach($cids as $id){
$params = array('contact_id' => $id);
try {
$contact = civicrm_api3( 'Contact' , 'get' , $params );
$originalContact = $contact['values'][$id];
$billingAddressQuery = "SELECT * FROM `civicrm_address` WHERE `contact_id` = %1 and `is_billing` = %2";
$billingParams = array(1 => array($contact['id'], 'Int'), 2 => array(1, 'Int'));
$billingDao = CRM_Core_DAO::executeQuery($billingAddressQuery, $billingParams);
if($billingDao->fetch()) {
$billingAddressFields = array(
'street_address' => $billingDao->street_address,
'supplemental_address_1' => $billingDao->supplemental_address_1,
'supplemental_address_2' => $billingDao->supplemental_address_2,
'city' => $billingDao->city,
'postal_code' => $billingDao->postal_code,
'state_province_id' => $billingDao->state_province_id,
);
}
if(!empty($contact['values'][$id]['state_province_id'])) {
$contact['values'][$id]['state_province_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $contact['values'][$id]['state_province_id'], 'name', 'id');
}
$values[$id]['contact.address_block'] = nl2br(CRM_Utils_Address::format($contact['values'][$id]), FALSE);
}
catch (CiviCRM_API3_Exception $e) {
$values[$id]['contact.address_block'] = $e->getMessage;
}
$values[$id]['contact.today_date'] = CRM_Utils_Date::customFormat(date('Ymd'));
if($billingAddressFields) {
$billingContact = array_merge($originalContact, $billingAddressFields);
if(!empty($billingContact['state_province_id'])) {
$billingContact['state_province_name'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $billingContact['state_province_id'], 'name', 'id');
}
$values[$id]['contact.billing_block'] = nl2br(CRM_Utils_Address::format($billingContact, FALSE));
}
}
} | veda-consulting/uk.co.vedaconsulting.surpressblankaddress | suppressblankaddress.php | PHP | agpl-3.0 | 5,629 |
import os
import sys
import glob
import json
import subprocess
from collections import defaultdict
from utils import UnicodeReader, slugify, count_pages, combine_pdfs, parser
import addresscleaner
from click2mail import Click2MailBatch
parser.add_argument("directory", help="Path to downloaded mail batch")
parser.add_argument("--skip-letters", action='store_true', default=False)
parser.add_argument("--skip-postcards", action='store_true', default=False)
def fix_lines(address):
"""
Click2Mail screws up addresses with 3 lines. If we have only one address
line, put it in "address1". If we have more, put the first in
"organization", and subsequent ones in "addressN".
"""
lines = [a for a in [
address.get('organization', None),
address.get('address1', None),
address.get('address2', None),
address.get('address3', None)] if a]
if len(lines) == 1:
address['organization'] = ''
address['address1'] = lines[0]
address['address2'] = ''
address['address3'] = ''
if len(lines) >= 2:
address['organization'] = lines[0]
address['address1'] = lines[1]
address['address2'] = ''
address['address3'] = ''
if len(lines) >= 3:
address['address2'] = lines[2]
address['address3'] = ''
if len(lines) >= 4:
address['address3'] = lines[3]
return address
def collate_letters(mailing_dir, letters, page=1):
# Sort by recipient.
recipient_letters = defaultdict(list)
for letter in letters:
recipient_letters[(letter['recipient'], letter['sender'])].append(letter)
# Assemble list of files and jobs.
files = []
jobs = {}
for (recipient, sender), letters in recipient_letters.iteritems():
count = 0
for letter in letters:
filename = os.path.join(mailing_dir, letter["file"])
files.append(filename)
count += count_pages(filename)
end = page + count
jobs[recipient] = {
"startingPage": page,
"endingPage": end - 1,
"recipients": [fix_lines(addresscleaner.parse_address(recipient))],
"sender": addresscleaner.parse_address(sender),
"type": "letter"
}
page = end
vals = jobs.values()
vals.sort(key=lambda j: j['startingPage'])
return files, vals, page
def collate_postcards(postcards, page=1):
# Collate postcards into a list per type and sender.
type_sender_postcards = defaultdict(list)
for letter in postcards:
key = (letter['type'], letter['sender'])
type_sender_postcards[key].append(letter)
files = []
jobs = []
for (postcard_type, sender), letters in type_sender_postcards.iteritems():
files.append(os.path.join(
os.path.dirname(__file__),
"postcards",
"{}.pdf".format(postcard_type)
))
jobs.append({
"startingPage": page + len(files) - 1,
"endingPage": page + len(files) - 1,
"recipients": [
fix_lines(addresscleaner.parse_address(letter['recipient'])) for letter in letters
],
"sender": addresscleaner.parse_address(sender),
"type": "postcard",
})
return files, jobs, page + len(files)
def run_batch(args, files, jobs):
filename = combine_pdfs(files)
print "Building job with", filename
batch = Click2MailBatch(
username=args.username,
password=args.password,
filename=filename,
jobs=jobs,
staging=args.staging)
if batch.run(args.dry_run):
os.remove(filename)
def main():
args = parser.parse_args()
if args.directory.endswith(".zip"):
directory = os.path.abspath(args.directory[0:-len(".zip")])
if not os.path.exists(directory):
subprocess.check_call([
"unzip", args.directory, "-d", os.path.dirname(args.directory)
])
else:
directory = args.directory
with open(os.path.join(directory, "manifest.json")) as fh:
manifest = json.load(fh)
if manifest["letters"] and not args.skip_letters:
lfiles, ljobs, lpage = collate_letters(directory, manifest["letters"], 1)
print "Found", len(ljobs), "letter jobs"
if ljobs:
run_batch(args, lfiles, ljobs)
if manifest["postcards"] and not args.skip_postcards:
pfiles, pjobs, ppage = collate_postcards(manifest["postcards"], 1)
print "Found", len(pjobs), "postcard jobs"
if pjobs:
run_batch(args, pfiles, pjobs)
if __name__ == "__main__":
main()
| yourcelf/btb | printing/print_mail.py | Python | agpl-3.0 | 4,703 |
# Managed via ansible.
export NICKNAME={{ nickname }}
| joyxu/kernelci-backend | ansible/roles/common/templates/host-nickname.sh | Shell | agpl-3.0 | 54 |
---
title: THE ELECTRONIC WINDOW
layout: default
---
# What is it?
# Ewindow is a TECHNOLOGICAL DEVICE
for a NEW REVOLUTIONARY __Social Network__
### 1. __OPEN SOURCE__
// the code is here [ewindow Code](https://github.com/strfry/ewindow) enjoy it //
### 1. __DECENTRALISED__
// no central control owned by some big corporation using for other purposes your data //
### 1. __FREE__
// It can be set up with low-cost technologies (Raspberry Pi, a speakers,a flat monitor, a webcam with microphone) and is a dedicated single-app device, not a desktop computer or a smartphone.
# Why we started this project based on free software?
--> WE BELIEVE it is time to do a STEP BACK and RETHINK on how to use technologies for comunication purposes:
### The E-window is based on a free Open Source software and accessible to everybody as we strongly believe that a free software communication platform is necessary to protect freedom of speech and e-democracy.
#### And it’s easy and cheap to build it by yourself of an estimated cost around 300 euros.
#### It can be replicated anywhere in the world with no hardware problems.
#### We would like to spread it in the South of the World to have direct and non-mediated communication with startups and local entrepreneurs, build partnerships between peers, build a decentralised communication system, non depending on top down policies.
It is a tunnel for comunication you find is physical spaces.
## it is like a window in a wall:

##### We think this tool can break down physical, political and mnemonic walls.
# THE STORY
After some years of trials and experiments on instant communication we decided it was time to do something bigger and we involved the Verbund Offener Werkstaetten (D) which decided to join us in the long process of making the community and spreading awarness around this theme.
Then, to maintain the software development we created a small company TEILWERK.

## How does it work?
Many different EWindows, all togheter, can make their own social network. Imagine you want to connect 3 different spaces.
Every space has its own window in a common area, like in the coffebreak, a corridor, the kitchen.
With the press of a button, the EWindow will connect to another EWindow in the same network.
Once the Window is opened, there is a # 1:1 encrypted connection.
### And why don't just use skype or slack or any other existing video chat software?
To make a skype call, you have to ALREADY know who you're calling and their contact information. With the electronic window, you can easily interact with people you've never met before. But you might have seen their video tutorial online...
Of course for this end, we had to develop a user-friendly interface that requires no mediators such as a keyboard or a mouse.
The E-windows are based on a software which runs on affordable technologies ( such as Raspberry Pi *raspberryPi is a open-source hardware computer. is like a small computer that you can use for prototyping.*, a flat monitor, a webcam, Linux ).
The OS is Raspbian which is a free operating system, optimized for the Raspberry Pi hardware, that coincides with the open standards as in public, transparent and accessible to everyone . It provides an encrypted and secure connection as we strongly believe in freedom of speech.
It is also optimized to be efficiently used on most hardware from single board computers such as the raspberry pi to high end pc’s. And it facilitates further experimentation with new hardware of software features.
To build the e-window , you need a monitor , a small computer such raspberry pie 2, a webcam and a pair of speakers. All the E–window need to operate after is a Stable video and audio connection and Small band usage (short bandwidth). The appearance is customizable and could easily be altered and adjusted .
DESIGN DEVELOPMENT
========================================
*FRAME
There is no one frame, every space build his own.
# Have a look to some existing frames:

done by Fabrizio

done by Felix
The HEI MUNICH

done by HEI Team
*ELECTRONICS
- A Raspberry Pi //3 (2 is ok too)//
- 2 GiB SD Card
- Monitor (with Cable)
- Speakers //CONNECTED VIA JACK, AND NO VIA USB//
- USB Webcam with microphones
- A button and a bit of jumpwire
---
If you would like to improve the audio/video quality:
- Raspberry PiCam //wide-angle version recommended//
- USB Speakerphone //will replace speakers and microphone//
SOFTWARE DEVELOPMENT
===========
## How is it implemented?
Development of the EWindow is focused on three parts:
1) Enhancing a lightweight SIP Video Phone with Raspberry Pi support
git clone https://github.com/alfredh/baresip
2) A Qt/QML-based user interface
git clone https://github.com/strfry/ewindowui
3) Configuration details for a specific platform
git clone https://github.com/strfry/ewindowui
To Download the Image
========
[https://ewindow.org/download/ewindow-v0.3.zip]: https://ewindow.org/download/ewindow-v0.3.zip "Get the Image for Raspberry Pi here"
[https://ewindow.org/download/ewindow-v0.3.zip]
Unpack the archive, and write the .img to the SD card.
If you don't know how to do that, use [etcher.io](http://etcher.io)
## Button
To use the ewindow, you will need to connect a button between GPIO 3 and Ground. Refer to [https://pinout.xyz] to find it.
## After Installation
Login with SSH. If you are on Linux or Mac, chances are high you can connect to the device with
ssh ewindow@ewindow.local
# Password: ewindow
If that doesn't work, please ask your local network admin to find the device.
Login and change your hostname:
echo NAMEOFYOURPLACE | sudo tee /etc/hostname
And change the password for the ewindow user
passwd
I left acces for my SSH key, just in case ;)
If you don't like that, remove the backdoor like this:
sudo rm /root/.ssh/authorized_keys
# BUILD YOUR OWN EWINDOW NETWORK:
The "electronic window" is a direct way to establish informal and unplanned connections.
They can be useful for different situations.
# JOIN THE EXISTING EWINDOW NETWORK:
[THE MULTIFACTOY NETWORK](MultiFactory.md)
## THE MULTIFACTORY NETWORK
Is it for me?
--> If you're a member of a collaborative, shared workspace, if you believe the world can change through a new economy based on sharing of knowledge, ressurces and machines, trust between entrepreneurs, orizontal business relationships and no exploitation of anything. You can think to join us!
The e-window is a prototype that was developed to facilitate the exchange and the flow of ideas between shared working spaces known as the Multifactory network. THe goal of the Multifactory Network was to permanently connect open work/hack/make/share spaces with a similar attitude in different cities around the world.
The multifactory is a network of shared workspace across Europe and the e-window is a tool that ensures the constant circulation of ideas in sharing knowledge and in exchanging skills and professional services between the spaces involved.
A community of real people, who make a living within the collaborative economy new paradigm.
“Electronic Window” solves two current problems: first it let team members working in different buildings, cities or countries to share daily life and common values which is crucial team building. Second it lowers the email communication that in the last years increased so much that it loses power on communication.
HOW TO ENTER THE MULTIFACTORY NETWORK:
If a shared workspace wants to join the network, a member needs to:
1. visit another space already inside the network
2. agree with the FREE EXCHANGE PROGRAM rules
3. invite a member of a space already into the network to attend to an event to his space
For now, you just download and install the image to a Raspberry Pi (3).
In the future, passwords and secure connectivity are planned and this will change the way you become part of the network.
# How it can be used in the Future?
This Technology offers new ways to work: we can connect each other from everywhere in the world, we can share skills and experiences.
It is the solution to real problem faced by many different communities of interest and is an answer to a real need, it can become a new practical and common way of communicating by moving ideas, not people. This would result in a faster, better, cheaper way to work.
The e-window can be adapted to local or personal needs in emerging communities in Africa or other developing communities and could be used to form possibly and unconventional partnerships between enterprises, startups, actors of international cooperation ,NGOs, Universities and Research Centers and Countries from Global South.
Subscribe to our newsletter
## Contacts
Community development --> Lorenza Salati - lorenza@teilwerk.com
Business Development --> Maik Jähne - maik@teilwek.com
Strategy Development --> Giulio Focardi - giulio@teilwerk.com
Software development --> Jonathan Sieber - jonathan@teilwerk.com
| eleKtronicwindow/eleKtronicwindow.github.io | index.md | Markdown | agpl-3.0 | 9,487 |
#include <iostream>
using std::istream;
using std::ostream;
#include <stdexcept>
using std::invalid_argument;
#include "ISO-8583/DTT/AlphaNumericSpecial.h"
#include "ISO-8583/DTT/InputStream.h"
#include "ISO-8583/DTT/OutputStream.h"
namespace ISO_8583 {
namespace DTT {
bool isAlphaNumericSpecial(byte value) {
return isprint(value) != 0;
}
bool isAlphaNumericSpecial(char value) {
return isprint(value) != 0;
}
bool isAlphaNumericSpecial(const char* value) {
if (value) {
int no = 0;
while (value[no]) {
if (!isAlphaNumericSpecial(value[no++]))
return false;
}
}
return true;
}
IsAnAlphaNumericSpecial isAnAlphaNumericSpecial;
NotAnAlphaNumericSpecial notAnAlphaNumericSpecial;
bool IsAnAlphaNumericSpecial::operator()(byte b) {
return isAlphaNumericSpecial(b);
}
void NotAnAlphaNumericSpecial::operator()(byte b) {
invalidByte = b;
throw *this;
}
void NotAnAlphaNumericSpecial::operator()(char b) {
invalidByte = b;
throw *this;
}
void NotAnAlphaNumericSpecial::operator()(char b, const char* value) {
invalidByte = b;
invalidString = value;
throw *this;
}
template<int sizeb>
AlphaNumericSpecial<sizeb>::AlphaNumericSpecial(const char* value) {
DataType::fill(&isAnAlphaNumericSpecial, ¬AnAlphaNumericSpecial, value);
}
template<int sizeb>
AlphaNumericSpecial<sizeb>::~AlphaNumericSpecial() {
}
template<int sizeb>
AlphaNumericSpecial<sizeb>& AlphaNumericSpecial<sizeb>::operator= (const string& value) {
DataType::fill(&isAnAlphaNumericSpecial, ¬AnAlphaNumericSpecial, value);
return *this;
}
template<int sizeb>
AlphaNumericSpecial<sizeb>& AlphaNumericSpecial<sizeb>::operator= (const char* value) {
DataType::fill(&isAnAlphaNumericSpecial, ¬AnAlphaNumericSpecial, value);
return *this;
}
template<int sizeb>
AlphaNumericSpecial<sizeb>& AlphaNumericSpecial<sizeb>::operator= (nat8 value) {
DataType::fill(&isAnAlphaNumericSpecial, ¬AnAlphaNumericSpecial, value);
return *this;
}
template<int size>
DTT_API_SCOPE InputStream& operator>>(InputStream& is, AlphaNumericSpecial<size>& ans) {
ans.fill(&isAnAlphaNumericSpecial, ¬AnAlphaNumericSpecial, is);
return is;
}
template<int size>
DTT_API_SCOPE OutputStream& operator<<(OutputStream& os, const AlphaNumericSpecial<size>& ans) {
os << static_cast<const typename AlphaNumericSpecial<size>::DataType&>(ans);
return os;
}
INOUT(AlphaNumericSpecial, 2);
INOUT(AlphaNumericSpecial, 3);
INOUT(AlphaNumericSpecial, 4);
INOUT(AlphaNumericSpecial, 8);
INOUT(AlphaNumericSpecial, 12);
INOUT(AlphaNumericSpecial, 15);
INOUT(AlphaNumericSpecial, 16);
INOUT(AlphaNumericSpecial, 22);
INOUT(AlphaNumericSpecial, 25);
INOUT(AlphaNumericSpecial, 35);
INOUT(AlphaNumericSpecial, 40);
INOUT(AlphaNumericSpecial, 76);
INOUT(AlphaNumericSpecial, 99);
INOUT(AlphaNumericSpecial, 120);
INOUT(AlphaNumericSpecial, 126);
INOUT(AlphaNumericSpecial, 140);
INOUT(AlphaNumericSpecial, 216);
INOUT(AlphaNumericSpecial, 255);
INOUT(AlphaNumericSpecial, 256);
INOUT(AlphaNumericSpecial, 999);
INOUT(AlphaNumericSpecial, 9999);
template class AlphaNumericSpecial < 2 > ;
template class AlphaNumericSpecial < 3 > ;
template class AlphaNumericSpecial < 4 > ;
template class AlphaNumericSpecial < 8 > ;
template class AlphaNumericSpecial < 12 > ;
template class AlphaNumericSpecial < 15 > ;
template class AlphaNumericSpecial < 16 > ;
template class AlphaNumericSpecial < 22 > ;
template class AlphaNumericSpecial < 25 > ;
template class AlphaNumericSpecial < 35 > ;
template class AlphaNumericSpecial < 40 > ;
template class AlphaNumericSpecial < 76 > ;
template class AlphaNumericSpecial < 99 > ;
template class AlphaNumericSpecial < 120 > ;
template class AlphaNumericSpecial < 126 > ;
template class AlphaNumericSpecial < 140 > ;
template class AlphaNumericSpecial < 216 > ;
template class AlphaNumericSpecial < 255 > ;
template class AlphaNumericSpecial < 256 > ;
template class AlphaNumericSpecial < 999 > ;
template class AlphaNumericSpecial < 9999 > ;
}
}
| Kampbell/ISO-8583 | cpp/code/ISO-8583/DTT/AlphaNumericSpecial.cpp | C++ | agpl-3.0 | 4,171 |
<?php
class CRM_Streetimport_Update_Controller extends CRM_Core_Controller {
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
$stateMachine = new CRM_Core_StateMachine($this);
$this->setStateMachine($stateMachine);
$pages = array(
'CRM_Streetimport_Update_Form_Define' => NULL,
'CRM_Streetimport_Update_Form_Confirm' => NULL,
'CRM_Streetimport_Update_Form_Result' => NULL,
// 'CRM_Streetimport_Update_Form_PartThree' => NULL,
);
$stateMachine->addSequentialPages($pages, $action);
$this->addPages($stateMachine, $action);
$this->addActions();
}
}
| CiviCooP/be.aivl.streetimport | CRM/Streetimport/Update/Controller.php | PHP | agpl-3.0 | 695 |
/**
* @file libcomp/src/MessageTimeout.h
* @ingroup libcomp
*
* @author COMP Omega <compomega@tutanota.com>
*
* @brief Indicates that a timeout has occurred.
*
* This file is part of the COMP_hack Library (libcomp).
*
* Copyright (C) 2012-2016 COMP_hack Team <compomega@tutanota.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBCOMP_SRC_MESSAGETIMEOUT_H
#define LIBCOMP_SRC_MESSAGETIMEOUT_H
// libcomp Includes
#include "CString.h"
#include "Message.h"
// Standard C++11 Includes
#include <memory>
namespace libcomp
{
namespace Message
{
/**
* Message that signifies a connection has timed out.
*/
class Timeout : public Message
{
public:
/**
* Create the message.
*/
Timeout();
/**
* Cleanup the message.
*/
virtual ~Timeout();
virtual MessageType GetType() const;
};
} // namespace Message
} // namespace libcomp
#endif // LIBCOMP_SRC_MESSAGETIMEOUT_H
| aswiftproduction/comp_hack | libcomp/src/MessageTimeout.h | C | agpl-3.0 | 1,558 |
<?php
define('DefaultPage', 'Flerp');
define('Database', 'joypeak');
define('DatabaseUserName', 'root');
define('DatabasePassword', 'underbar');
?>
| Rovanion/Yaws | lib/settings.php | PHP | agpl-3.0 | 149 |
/*
Copyright (C) 2014 Omega software d.o.o.
This file is part of Rhetos.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Rhetos.Compiler;
using Rhetos.Extensibility;
using Rhetos.Logging;
using Rhetos.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace Rhetos.MvcModelGenerator
{
[Export(typeof(IGenerator))]
public class CaptionsResourceGenerator : IGenerator
{
private readonly IPluginsContainer<ICaptionsResourceGeneratorPlugin> _plugins;
private readonly CaptionsInitialCodePlugin _initialCodePlugin;
private readonly ICodeGenerator _codeGenerator;
private readonly ILogger _logger;
private readonly ILogger _performanceLogger;
private readonly RhetosBuildEnvironment _rhetosBuildEnvironment;
private readonly MvcModelGeneratorOptions _options;
private readonly CacheUtility _cacheUtility;
public IEnumerable<string> Dependencies => null;
public CaptionsResourceGenerator(
IPluginsContainer<ICaptionsResourceGeneratorPlugin> plugins,
CaptionsInitialCodePlugin initialCodePlugin,
ICodeGenerator codeGenerator,
ILogProvider logProvider,
RhetosBuildEnvironment rhetosBuildEnvironment,
FilesUtility filesUtility,
MvcModelGeneratorOptions options)
{
_plugins = plugins;
_initialCodePlugin = initialCodePlugin;
_codeGenerator = codeGenerator;
_logger = logProvider.GetLogger("CaptionsResourceGenerator");
_performanceLogger = logProvider.GetLogger($"Performance.{nameof(CaptionsResourceGenerator)}");
_rhetosBuildEnvironment = rhetosBuildEnvironment;
_options = options;
_cacheUtility = new CacheUtility(typeof(CaptionsResourceGenerator), rhetosBuildEnvironment, filesUtility);
}
public static string ResourcesAssemblyName => "Captions";
public static string ResourcesFileName => "Captions.resx";
public string ResourcesFilePath => Path.Combine(_rhetosBuildEnvironment.GeneratedAssetsFolder, ResourcesFileName);
public string CompiledResourcesFilePath => Path.ChangeExtension(ResourcesFilePath, "resources");
public string SourceFromCompiledResources => $"{CompiledResourcesFilePath}.cs";
public string CsGeneratorVersionFile => $"{Path.GetFileName(SourceFromCompiledResources)}.version";
public void Generate()
{
// Generate ResourcesFilePath:
bool resxModified = GenerateNewResourcesResx();
var resxKeyValuePairs = new Lazy<IEnumerable<KeyValuePair<string, string>>>(
() => GetKeyValuePairsFromResxFile(ResourcesFilePath));
// Generate CompiledResourcesFilePath:
if (resxModified)
CompileResourceFile(resxKeyValuePairs.Value);
else
_cacheUtility.CopyFromCache(CompiledResourcesFilePath);
// Generate SourceFromCompiledResources:
string sourceFromResources;
if (resxModified || IsCodeGeneratorModified())
{
sourceFromResources = GenerateSourceFromCompiledResources(resxKeyValuePairs.Value);
}
else
{
_cacheUtility.CopyFromCache(SourceFromCompiledResources);
sourceFromResources = File.ReadAllText(SourceFromCompiledResources);
}
// Write source to ResourcesAssemblyName cs:
File.WriteAllText(Path.Combine(_rhetosBuildEnvironment.GeneratedAssetsFolder, ResourcesAssemblyName + ".cs"), sourceFromResources, Encoding.UTF8);
}
private bool GenerateNewResourcesResx()
{
var sw = Stopwatch.StartNew();
// NOTE: There is no need for ICaptionsResourceGeneratorPlugin plugins, they are not used.
// CaptionsInitialCodePlugin _initialCodePlugin is this only implementation and all the work
// is done there by calling ICaptionsProvider and its ICaptionsValuePlugin plugins.
// The ICaptionsResourceGeneratorPlugin interface can be deleted, and the code from CaptionsInitialCodePlugin called directly.
// We could leave ICaptionsResourceGeneratorPlugin just in case we need to add
// to the resx file something other then simple "data" elements for captions.
var resxContext = _codeGenerator.ExecutePlugins(_plugins, "<!--", "-->", _initialCodePlugin);
resxContext = CleanupXml(resxContext);
_performanceLogger.Write(sw, "GenerateNewResourcesResx: ExecutePlugins and cleanup.");
var resxHash = _cacheUtility.ComputeHash(resxContext);
var cachedHash = _cacheUtility.LoadHash(ResourcesFilePath);
_performanceLogger.Write(sw, "GenerateNewResourcesResx: Hash.");
if (resxHash.SequenceEqual(cachedHash))
{
_logger.Trace(() => $"'{ResourcesFilePath}' hash not changed, using cache.");
if (_cacheUtility.FileIsCached(CompiledResourcesFilePath) && _cacheUtility.FileIsCached(SourceFromCompiledResources))
{
_cacheUtility.CopyFromCache(ResourcesFilePath);
return false;
}
_logger.Trace(() => $"'{CompiledResourcesFilePath}' and '{SourceFromCompiledResources}' expected in cache, but some are missing.");
}
else
{
_logger.Trace(() => $"'{ResourcesFilePath}' hash changed, invalidating cache.");
}
_cacheUtility.RemoveFromCache(CompiledResourcesFilePath);
_cacheUtility.RemoveFromCache(SourceFromCompiledResources);
File.WriteAllText(ResourcesFilePath, resxContext, Encoding.UTF8);
_cacheUtility.SaveHash(ResourcesFilePath, resxHash);
_cacheUtility.CopyToCache(ResourcesFilePath);
_performanceLogger.Write(sw, "GenerateNewResourcesResx: Save.");
return true;
}
const string detectLineTag = @"\n\s*<!--.*?-->\s*\r?\n";
const string detectTag = @"<!--.*?-->";
private static string CleanupXml(string resourcesXml)
{
resourcesXml = Regex.Replace(resourcesXml, detectLineTag, "\n");
resourcesXml = Regex.Replace(resourcesXml, detectTag, "");
resourcesXml = resourcesXml.Trim();
return resourcesXml;
}
private IEnumerable<KeyValuePair<string, string>> GetKeyValuePairsFromResxFile(string path)
{
return XDocument.Load(path).Root.Descendants("data").Select(x => KeyValuePair.Create(x.Attribute("name").Value, x.Element("value").Value));
}
private void CompileResourceFile(IEnumerable<KeyValuePair<string, string>> resxKeyValuePairs)
{
var sw = Stopwatch.StartNew();
using (IResourceWriter writer = new ResourceWriter(CompiledResourcesFilePath))
{
foreach (var resxKeyValue in resxKeyValuePairs)
{
try
{
writer.AddResource(resxKeyValue.Key.ToString(), resxKeyValue.Value);
}
catch (Exception ex)
{
throw new FrameworkException(string.Format("Error while compiling resource file \"{0}\" on key \"{1}\".", ResourcesFileName, resxKeyValue.Key.ToString()), ex);
}
}
writer.Generate();
writer.Close();
}
_cacheUtility.CopyToCache(CompiledResourcesFilePath);
_performanceLogger.Write(sw, nameof(CompileResourceFile));
}
//The StronglyTypedResourceBuilder was generating the Captions.cs file with the value split in this way
//so we are keeping the same functionality
private IEnumerable<string> SplitStringForCaptionsValue(string str)
{
var firstChunkSize = 81;
var otherChunkSizes = 80;
yield return str.Substring(0, Math.Min(firstChunkSize, str.Length));
for (int i = 81; i < str.Length; i += otherChunkSizes)
yield return str.Substring(i, Math.Min(otherChunkSizes, str.Length - i));
}
private bool IsCodeGeneratorModified()
{
bool currentCsGeneratorMatchesCache =
_cacheUtility.FileIsCached(CsGeneratorVersionFile)
&& _cacheUtility.ReadFromCache(CsGeneratorVersionFile) == GetCurrentCsGeneratorVersion();
return !currentCsGeneratorMatchesCache;
}
private string GetCurrentCsGeneratorVersion()
{
string csGeneratorVersion = "1"; // Increase this when modifying code in GenerateSourceFromCompiledResources() method.
string versionAndOptions = Newtonsoft.Json.JsonConvert.SerializeObject(
new
{
CodeGeneratorVersion = csGeneratorVersion,
Options = _options
});
return versionAndOptions;
}
/// <summary>
/// Generates "resources.cs" file. In standard projects, it is generated automatically by Visual Studio.
/// </summary>
private string GenerateSourceFromCompiledResources(IEnumerable<KeyValuePair<string, string>> resxKeyValuePairs)
{
// NOTE: When modifying the generated code below, increase the csGeneratorVersion in GetCurrentCsGeneratorVersion() method below.
var sw = Stopwatch.StartNew();
var sb = new StringBuilder();
sb.Append($@"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace {_options.CaptionsClassNamespace} {{
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""System.Resources.Tools.StronglyTypedResourceBuilder"", ""4.0.0.0"")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class {_options.CaptionsClassName} {{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""Microsoft.Performance"", ""CA1811:AvoidUncalledPrivateCode"")]
internal {_options.CaptionsClassName}() {{
}}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {{
get {{
if (object.ReferenceEquals(resourceMan, null)) {{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(""{_options.ResourceFullName}"", typeof({_options.CaptionsClassName}).Assembly);
resourceMan = temp;
}}
return resourceMan;
}}
}}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {{
get {{
return resourceCulture;
}}
set {{
resourceCulture = value;
}}
}}
");
foreach (var resxKeyValue in resxKeyValuePairs)
{
var formatedKey = string.Join($" +{Environment.NewLine} ", SplitStringForCaptionsValue(resxKeyValue.Key).Select(k => $"\"{k}\""));
sb.Append($@"
/// <summary>
/// Looks up a localized string similar to {resxKeyValue.Value}.
/// </summary>
public static string {resxKeyValue.Key} {{
get {{
return ResourceManager.GetString({formatedKey}, resourceCulture);
}}
}}
");
}
sb.Append(@" }
}
");
var sourceCode = sb.ToString();
File.WriteAllText(SourceFromCompiledResources, sourceCode);
_cacheUtility.CopyToCache(SourceFromCompiledResources);
_cacheUtility.WriteToCache(CsGeneratorVersionFile, GetCurrentCsGeneratorVersion());
_performanceLogger.Write(sw, nameof(GenerateSourceFromCompiledResources));
return sourceCode;
}
}
}
| Rhetos/MvcModelGenerator | Plugins/Rhetos.MvcModelGenerator/CaptionsResourceGenerator.cs | C# | agpl-3.0 | 14,878 |
<?php
class KalturaAuditTrailContext extends KalturaEnum
{
const CLIENT = -1;
const SCRIPT = 0;
const PS2 = 1;
const API_V3 = 2;
}
| MimocomMedia/kaltura | package/app/app/plugins/audit/lib/api/KalturaAuditTrailContext.php | PHP | agpl-3.0 | 145 |
package io.evercam.androidapp;
import android.os.Bundle;
import android.webkit.WebView;
import io.evercam.androidapp.utils.Constants;
public class AboutWebActivity extends WebActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
if(bundle != null)
{
loadPage();
}
else
{
finish();
}
}
@Override
protected void loadPage()
{
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(getWebViewClient());
String url = bundle.getString(Constants.BUNDLE_KEY_URL);
webView.loadUrl(url);
}
}
| GNUDimarik/evercam-play-android2 | evercamPlay/src/main/java/io/evercam/androidapp/AboutWebActivity.java | Java | agpl-3.0 | 820 |
/*
* get_iframes_content.js
*
* -> returns as a string all innerHTML from current document
* as well as from all iframes present in the document
*/
var phantom_iframes = document.getElementsByTagName('frame'),
iframes_content = '',
iframe_content,
ph_i, ph_j;
if (!phantom_iframes.length) {
phantom_iframes = [];
}
phantom_iframes.push(document);
for (ph_i=0; ph_i<phantom_iframes.length; ph_i++) {
if ("contentDocument" in phantom_iframes[ph_i]) {
iframe_content = phantom_iframes[ph_i].contentDocument.childNodes;
} else {
iframe_content = phantom_iframes[ph_i].childNodes;
}
if (iframe_content) {
for (ph_j=0; ph_j<iframe_content.length; ph_j++) {
if (iframe_content[ph_j] && "innerHTML" in iframe_content[ph_j]) {
iframes_content += iframe_content[ph_j].innerHTML;
}
}
}
}
return iframes_content;
| medialab/hyphe | hyphe_backend/crawler/hcicrawler/spiders/js/get_iframes_content.js | JavaScript | agpl-3.0 | 870 |
<?php declare(strict_types=1);
namespace SmrTest\lib\DefaultGame;
use Smr\UserRanking;
/**
* @covers Smr\UserRanking
*/
class UserRankingTest extends \PHPUnit\Framework\TestCase {
public function test_getName() : void {
$this->assertSame('Expert', UserRanking::getName(6));
}
public function test_getAllNames() : void {
$this->assertSame('Expert', UserRanking::getAllNames()[6]);
}
public function test_rank_limits() : void {
$ranks = array_keys(UserRanking::getAllNames());
$this->assertSame(UserRanking::MIN_RANK, min($ranks));
$this->assertSame(UserRanking::MAX_RANK, max($ranks));
}
public function test_score_limits() : void {
// test the lowest possible score
$rank = UserRanking::getRankFromScore(0);
$this->assertSame(UserRanking::MIN_RANK, $rank);
// test an absurdly high score
$rank = UserRanking::getRankFromScore(PHP_INT_MAX);
$this->assertSame(UserRanking::MAX_RANK, $rank);
}
public function test_getMinScoreForRank() : void {
// test all ranks
foreach (UserRanking::getAllNames() as $rank => $name) {
$minScore = UserRanking::getMinScoreForRank($rank);
// make sure the given min score is still the same rank
$rankFromScore = UserRanking::getRankFromScore($minScore);
$this->assertSame($rank, $rankFromScore);
}
}
}
| smrealms/smr | test/SmrTest/lib/DefaultGame/UserRankingTest.php | PHP | agpl-3.0 | 1,293 |
{% extends "base.html" %}
{% block content %}
<style>
.form-actions{
margin-bottom:0px;
}
</style>
{% if request.POST %}
<div class="alert alert-error">Your passwords did not match.</div>
{% endif %}
<p>
<form method="POST" class="well form-inline">
{% csrf_token %}
<legend>Confirm your new password</legend>
<input placeholder="New password" type="password" name="new_password1" id="id_new_password1">
<input placeholder="Confirm new password" type="password" name="new_password2" id="id_new_password2">
<div class="form-actions">
<input type="submit" value="Confirm new password" class="btn btn-primary" />
<a href="{% url "accounts-login" %}" class="btn">Cancel</a>
</div>
</form>
</p>
{% endblock %}
| amcat/amcat | accounts/templates/accounts/recover_confirm.html | HTML | agpl-3.0 | 754 |
## DEPRECATION NOTICE: Do not add new tests to this file!
##
## View and controller tests are deprecated in the Growstuff project
## We no longer write new view and controller tests, but instead write
## feature tests (in spec/features) using Capybara (https://github.com/jnicklas/capybara).
## These test the full stack, behaving as a browser, and require less complicated setup
## to run. Please feel free to delete old view/controller tests as they are reimplemented
## in feature tests.
##
## If you submit a pull request containing new view or controller tests, it will not be
## merged.
require 'rails_helper'
describe "accounts/new" do
before(:each) do
@member = FactoryGirl.create(:member)
assign(:account, @member.account)
end
it "renders new account form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", action: accounts_path, method: "post" do
assert_select "input#account_member_id", name: "account[member_id]"
assert_select "input#account_account_type", name: "account[account_type]"
end
end
end
| maco/growstuff | spec/views/accounts/new.html.haml_spec.rb | Ruby | agpl-3.0 | 1,125 |
Roast Coins
============
A universal cryptocurrency wallet backend by Roast Beef Sandwich Company.
##Progress
A partial rewrite and significant enhancement set over [Ripple-Coins](https://github.com/RoastBeefSandwichCo/ripple-coins), full functionality is expected by Feb 29, 2016
*update*: get-new-address is complete and released. This module can be invoked from the command line to generate a new cryptocurrency address on-demand and automatically associate it with a provided external address. For more information go to the lib directory and (after installation) run ``node get-new-address.js``
## Dependencies
1. [Nodejs 4.x] (https://github.com/nodesource/distributions)
2. [node-bitcoin](https://www.npmjs.org/package/bitcoin)
- Node module providing *coin connection objects
- Moving to [node-dogecoin](https://www.npmjs.org/package/node-dogecoin)!
3. [Almost any cryptocurrency daemon](https://github.com/dogecoin/dogecoin)(local or remote)
- These modules aim to be crypto-agnostic, so any daemon with (the de facto standard) bitcoin-compatible RPC calls (sendtoaddress, sendfromaccount...) should do.
4. [Gatewayd](https://github.com/ripple/gatewayd) - OPTIONAL and atm BROKEN
- Provides easy deposit and withdrawal management (and endpoints in Ripple REST)
- Provides [Node.js](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager), [Ripple REST API](https://github.com/ripple/ripple-rest.git)
5. [node-rest-client](https://www.npmjs.org/package/node-rest-client) - for gatewayd only
- Easy interfacing with gatewayd api
## Installation
- Development: clone the repo, fumble around, good luck!
- Production: Run setup.sh in the scripts directory. This will install mysql on Debian 8 or LAMP on Ubuntu 12.04+. *Comment/Uncomment the appropriate lines*. It will create the required database and user, install the Roast Coins package with npm, and then call it to initialize its table. *If you already have mysql installed*, replace occurrences of $MYSQL_ROOT_PW with your msql root pw. Don't forget to clean up afterward.
## Tests
Testing with mocha are to be re-implemented.
Run this tests with mocha
npm install -g mocha
mocha -R spec test/
## Usage
- `npm start`. Not yet implemented. #TODO
##Processes:
1. Withdrawals:
- Read database for pending withdrawals, initiate blockchain transactions via RPC, store TXID and relevant infos for use by gateway/exchange
- [RPC](https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list) to coin daemon via node-bitcoin
- add database deps/infos here #TODO
2. Deposits:
- Monitor blockchain for incoming transactions, record relevant deposits for gateway/exchange use.
## TODO:
- List unsupported coins, extend to crypto 2.0 apis.
- Addresses should really [only be used once](https://en.bitcoin.it/wiki/Address). Let's find a way to do that.
##CAVEAT:
- Ninobrooks is a javascript noob and makes no pretense that his code is elegant or purdy. He in fact welcomes (begs) others to clean it up and improve it. The only reason he's doing this in the first place is because far more talented people have had more pressing matters to attend to. Also, he's going to stop talking about himself in the third person.
##Thanks!
- To everyone who donates, contributes code, or has developed a module I'm using. In particular everyone who's worked on nodejs and @freewil et al for node-bitcoin.
- [The Rock Trading Ltd](https://www.therocktrading.com) for financial support. The Rock is a UK-based *ripple-integrated* exchange and gateway (XRPGA Gateway ftw!) with crypto-fiat trading for EUR, USD, BTC, LTC, DOGE and more, *and* derivatives. Check them out, sign up, use my promoter code :D therocktrading.com/referral/79
Thanks, Rock. Your donations came at a critical time for us. Your private encouragement via correspondence and promotion of our efforts on Twitter are appreciated, too!
##Donate
Help us with development costs (pretty please)! Ways to contribute:
- Ripples!(XRP) rPyBms1XZtNbF4UFGgM1dDWTmtfDmsfGNs
- PayPal: darthcookient@gmail.com
- Bitcoin 1K2BZ3XxpRNiNissEHoVcrCv3tEqEsHP28
- Litecoin LgaoNgSNxJwyno61edyRUz2ZKFkgPQYV5t
- Dogecoin D7U9VyJsStZ23MPgTr2TxGLj4bdfs69b8e
- Stellar (STR): ninobrooks
- If you would like to donate hardware, remote servers or in any other way, please contact me directly!
| RoastBeefSandwichCo/Roast-Coins | README.md | Markdown | agpl-3.0 | 4,375 |
// Copyright 2016 David Li, Michael Mauer, Andy Jiang
// This file is part of Tell Me to Survive.
// Tell Me to Survive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tell Me to Survive is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with Tell Me to Survive. If not, see <http://www.gnu.org/licenses/>.
import PubSub = require("pubsub");
import {EditorContext, MAIN} from "model/editorcontext";
interface ControlsController extends _mithril.MithrilController {
}
export const Component: _mithril.MithrilComponent<ControlsController> = <any> {
controller: function(): ControlsController {
return {};
},
view: function(controller: ControlsController, args: {
executing: _mithril.MithrilProperty<boolean>,
doneExecuting: _mithril.MithrilProperty<boolean>,
paused: _mithril.MithrilProperty<boolean>,
speed: _mithril.MithrilProperty<number>,
valid: boolean,
memoryUsage: EditorContext,
onrun?: () => void,
onruninvalid?: () => void,
onrunmemory?: () => void,
onreset?: () => void,
onabort?: () => void,
onpause?: () => void,
onstep?: () => void,
}): _mithril.MithrilVirtualElement<ControlsController> {
let buttons: _mithril.MithrilVirtualElement<ControlsController>[] = [];
if (args.doneExecuting()) {
buttons.push(m(<any> "button.reset", {
onclick: function() {
if (args.onreset) {
args.onreset();
}
},
}, "Reset"));
}
else if (!args.executing()) {
let cssClass = args.valid ? ".run" : ".runInvalid";
let text = args.valid ? "Run" : "Invalid Code";
if (args.memoryUsage !== null) {
cssClass = ".runMemory";
let overLimit = args.memoryUsage.className + "." + args.memoryUsage.method;
if (args.memoryUsage.className === MAIN) {
overLimit = "main";
}
text = "Over Memory Limit: " + overLimit;
}
buttons.push(m(<any> ("button" + cssClass), {
onclick: function() {
if (!args.valid) {
if (args.onruninvalid) {
args.onruninvalid();
}
}
else if (args.memoryUsage !== null) {
if (args.onrunmemory) {
args.onrunmemory();
}
}
else if (args.onrun) {
args.onrun();
}
},
}, text));
}
else {
buttons.push(m(<any> "button.abort", {
onclick: function() {
if (args.onabort) {
args.onabort();
}
},
}, "Abort"));
buttons.push(m(".speed-control", [
"Slow",
m("input[type=range][min=0.5][max=2.0][step=0.1]", {
value: args.speed(),
onchange: function(event: any) {
let value = parseFloat(event.target.value);
args.speed(value);
},
}),
"Fast"
]));
}
return m("nav#gameControls", buttons);
}
}
| lidavidm/cs6360 | server_prototype/static/app/views/controls.ts | TypeScript | agpl-3.0 | 3,982 |
Monitoring for [Rotter](https://www.aelius.com/njh/rotter/).
| radiorabe/rabe-zabbix | app/Rotter/doc/README.head.md | Markdown | agpl-3.0 | 61 |
# -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import test_employee_display_own_info
| VitalPet/addons-onestein | hr_employee_display_own_info/tests/__init__.py | Python | agpl-3.0 | 192 |
{% extends "plain.html" %} | mitar/django-mongo-auth | mongo_auth/contrib/templates/mongo_auth/base.html | HTML | agpl-3.0 | 26 |
{% extends "custom/base-mini.html" %}
{% block content %}
<div class="contentbg">
<div class="post">
<h2 class="title">highlights</h2>
</div>
<div style="clear: both;"> </div>
</div>
{% endblock %}
| cristilav/FLEQ | template/custom/home.html | HTML | agpl-3.0 | 235 |
/*
Classe gerada automaticamente pelo MSTech Code Creator
*/
namespace MSTech.GestaoEscolar.BLL
{
using MSTech.Business.Common;
using MSTech.GestaoEscolar.Entities;
using MSTech.GestaoEscolar.DAL;
using System.Collections.Generic;
using System.Data;
/// <summary>
/// Description: ACA_TipoEventoGrupo Business Object.
/// </summary>
public class ACA_TipoEventoGrupoBO : BusinessBase<ACA_TipoEventoGrupoDAO, ACA_TipoEventoGrupo>
{
public static void DeleteByTipoEvento(int tev_id)
{
ACA_TipoEventoGrupoDAO dao = new ACA_TipoEventoGrupoDAO();
dao.DeleteByTipoEvento(tev_id);
}
public static List<ACA_TipoEventoGrupo> SelectByTipoEvento(int tev_id)
{
ACA_TipoEventoGrupoDAO dao = new ACA_TipoEventoGrupoDAO();
return dao.SelectByTipoEvento(tev_id);
}
}
} | prefeiturasp/SME-SGP | Src/MSTech.GestaoEscolar.BLL/ACA_TipoEventoGrupoBO.cs | C# | agpl-3.0 | 863 |
<?php
use YesWiki\Core\YesWikiAction;
class CalendrierAction extends YesWikiAction
{
public function formatArguments($arg)
{
if (!empty($arg['class'])) {
$classes = explode(' ', $arg['class']);
$classes = array_combine($classes, $classes);
}
$minical = (isset($arg['minical']) && $arg['minical'] == "true") || (isset($classes) && in_array('minical', $classes)) ;
if ($minical) {
$classes['minical'] = 'minical';
}
$class = (isset($classes) && count($classes)>0) ? implode(' ', $classes) :null;
return([
'minical' => $minical ?? null,
'class' => $class,
//template - default value calendar
'template' => $arg['template'] ?? 'calendar.tpl.html',
]);
}
public function run()
{
return $this->callAction('bazarliste', $this->arguments);
}
}
| YesWiki/yeswiki | tools/bazar/actions/CalendrierAction.php | PHP | agpl-3.0 | 920 |
from django.conf.urls import patterns, url
from application import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<application_id>\d+)/$', views.detail, name='detail'),
url(r'^klogin/(?P<username>\w+)/(?P<password>\w+)/$', views.klogin, name='klogin'),
)
| davidegalletti/koa-proof-of-concept | kag/application/urls.py | Python | agpl-3.0 | 305 |
class FileModel {
readonly fileMetadataId: string;
readonly width: number;
readonly height: number;
readonly takenAt: Date | null;
readonly uploadedAt: Date;
readonly originalFilename: string;
readonly userName: KnockoutObservable<string>;
readonly category: KnockoutObservable<string>;
readonly size: number;
readonly contentType: string;
readonly url: string;
readonly thumbnailUrl: string;
readonly newFilename: string;
checked: KnockoutObservable<boolean>;
readonly takenOrUploadedAt: Date;
readonly sizeStr: string;
readonly takenAtStr: KnockoutComputed<string | null>;
readonly uploadedAtStr: KnockoutComputed<string>;
constructor(readonly parent: ListViewModel, m: IFileMetadata) {
this.fileMetadataId = m.fileMetadataId;
this.width = m.width;
this.height = m.height;
this.takenAt = m.takenAt instanceof Date ? m.takenAt
: m.takenAt != null ? new Date(m.takenAt)
: null;
this.uploadedAt = m.uploadedAt instanceof Date
? m.uploadedAt
: new Date(m.uploadedAt);
this.takenOrUploadedAt = this.takenAt || this.uploadedAt;
this.originalFilename = m.originalFilename;
this.userName = ko.observable(m.userName || "");
this.category = ko.observable(m.category || "");
this.size = m.size;
this.sizeStr = this.size >= 1048576 ? `${(this.size / 1048576).toFixed(2)} MiB`
: this.size >= 1024 ? `${(this.size / 1024).toFixed(2)} KiB`
: `${this.size} bytes`;
this.contentType = m.contentType;
this.newFilename = m.newFilename;
this.url = m.url;
this.thumbnailUrl = m.thumbnailUrl;
this.checked = ko.observable(false);
this.takenAtStr = ko.pureComputed(() => this.takenAt && this.takenAt.toLocaleString());
this.uploadedAtStr = ko.pureComputed(() => this.uploadedAt && this.uploadedAt.toLocaleString());
}
toggle(x: FileModel, e: JQuery.Event) {
if (e.shiftKey) {
let index1 = Math.max(0, this.parent.files.indexOf(this.parent.lastClicked));
let index2 = Math.max(0, this.parent.files.indexOf(this));
let min = Math.min(index1, index2);
let max = Math.max(index1, index2);
this.parent.files().forEach((f, i) => {
f.checked(i >= min && i <= max);
});
} else if (e.ctrlKey) {
this.checked(!this.checked());
this.parent.lastClicked = this;
} else {
this.parent.files().forEach(f => {
f.checked(f === this);
});
this.parent.lastClicked = this;
}
}
defaultAction(f: FileModel, e: Event) {
return true;
}
}
interface KnockoutObservableArray<T> {
orderField: KnockoutObservable<string>;
orderDirection: KnockoutObservable<"asc" | "desc">;
}
class ListViewModel {
readonly files: KnockoutObservableArray<FileModel>;
readonly myTimeZone: string;
readonly startDate: KnockoutObservable<string>;
readonly endDate: KnockoutObservable<string>;
readonly userName: KnockoutObservable<string>;
readonly category: KnockoutObservable<string>;
readonly viewStyle: KnockoutObservable<string>;
readonly selectAllChecked: KnockoutObservable<boolean>;
readonly selectedFiles: KnockoutComputed<FileModel[]>;
readonly userNames: KnockoutObservable<string[]>;
readonly categories: KnockoutObservable<string[]>;
readonly displayedFiles: KnockoutComputed<FileModel[]>;
readonly undisplayedSelectedFiles: KnockoutComputed<FileModel[]>;
public lastClicked: FileModel;
private password: string | null;
constructor() {
this.files = ko.observableArray();
this.lastClicked = this.files()[0];
try {
this.myTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch (e) {
this.myTimeZone = `UTC + ${new Date().getTimezoneOffset()} minutes`;
}
this.startDate = ko.observable("");
this.endDate = ko.observable("");
this.userName = ko.observable("");
this.category = ko.observable("");
this.resetFilters();
this.viewStyle = ko.observable("table");
this.selectAllChecked = ko.observable(false);
this.selectAllChecked.subscribe(newValue => {
for (const f of this.displayedFiles()) {
f.checked(newValue);
}
});
this.selectedFiles = ko.pureComputed(() => this.files().filter(f => f.checked()));
this.userNames = ko.pureComputed(() => [""].concat(this.files().map(f => f.userName()))
.filter((v, i, a) => a.indexOf(v) === i)
.sort());
this.categories = ko.pureComputed(() => [""].concat(this.files().map(f => f.category()))
.filter((v, i, a) => a.indexOf(v) === i)
.sort());
this.displayedFiles = ko.pureComputed(() => this.files().filter(f => {
if (this.startDate() && new Date(this.startDate()) > (f.takenAt || f.uploadedAt)) return false;
if (this.endDate() && new Date(this.endDate()) < (f.takenAt || f.uploadedAt)) return false;
if (this.userName() && f.userName() != this.userName()) return false;
if (this.category() && f.category() != this.category()) return false;
return true;
}));
this.undisplayedSelectedFiles = ko.pureComputed(() => {
const displayedFiles = this.displayedFiles();
return this.selectedFiles().filter(f => displayedFiles.indexOf(f) < 0);
});
this.password = null;
}
async loadFiles() {
let resp = await this.fetchOrError("/api/files");
let files: IFileMetadata[] = await resp.json();
this.files(files.map(f => new FileModel(this, f)));
this.resetFilters();
}
private async getPassword() {
if (this.password == null) {
const p = await promptAsync("Enter the file management password to make changes.");
if (p != null) {
const response = await fetch("/api/password/check", {
headers: { "X-FileManagementPassword": p },
method: "GET"
});
if (Math.floor(response.status / 100) == 2) {
this.password = p;
} else {
console.error(`${response.status} ${response.statusText}: ${await response.text()}`);
await alertAsync(response.status == 400 ? "The password is not valid." : "An unknown error occurred.");
}
}
}
return this.password;
}
resetFilters() {
let dates = this.files().map(f => f.takenOrUploadedAt).sort((a, b) => +a - +b);
if (dates.length == 0) {
this.startDate("2000-01-01T00:00");
this.endDate("2025-01-01T00:00");
} else {
this.startDate(`${dates[0].getFullYear()}-01-01T00:00`);
this.endDate(`${dates[dates.length - 1].getFullYear() + 1}-01-01T00:00`);
}
this.userName("");
this.category("");
}
private async fetchOrError(input: RequestInfo, init?: RequestInit) {
const response = await fetch(input, {
...init,
headers: {
'X-FileManagementPassword': await this.getPassword() || "",
...(init ? init.headers : {})
}
});
if (Math.floor(response.status / 100) != 2) {
throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);
}
return response;
}
download() {
const f = $("<form></form>")
.attr("method", "post")
.attr("action", "/api/files/zip")
.appendTo(document.body);
$("<textarea></textarea>")
.attr("name", "ids")
.text(this.selectedFiles().map(f => f.fileMetadataId).join(","))
.appendTo(f);
f.submit().remove();
}
async changeUserName() {
if (await this.getPassword() == null) return;
const newName = await promptAsync("What \"taken by\" name should be listed for these files?", this.selectedFiles()[0].userName());
if (newName != null) {
try {
for (const f of this.selectedFiles()) {
const response = await this.fetchOrError(f.url, {
headers: {
'Content-Type': 'application/json'
},
method: "PATCH",
body: JSON.stringify({ userName: newName })
});
f.userName(newName);
f.checked(false);
}
} catch (e) {
console.error(e);
await alertAsync("An unknown error occurred.");
}
}
}
async changeCategory() {
if (await this.getPassword() == null) return;
const newCategory = await promptAsync("What category should these files be part of?", this.selectedFiles()[0].category());
if (newCategory != null) {
try {
for (const f of this.selectedFiles()) {
const response = await this.fetchOrError(f.url, {
headers: {
'Content-Type': 'application/json',
},
method: "PATCH",
body: JSON.stringify({ category: newCategory })
});
f.category(newCategory);
f.checked(false);
}
} catch (e) {
console.error(e);
await alertAsync("An unknown error occurred.");
}
}
}
async del() {
if (await this.getPassword() == null) return;
if (await confirmAsync(`Are you sure you want to permanently delete ${this.selectedFiles().length} file(s) from the server?`)) {
try {
for (const f of this.selectedFiles()) {
const response = await this.fetchOrError(f.url, {
method: "DELETE"
});
this.files.remove(f);
}
} catch (e) {
console.error(e);
await alertAsync("An unknown error occurred.");
}
}
}
}
var vm: ListViewModel;
document.addEventListener("DOMContentLoaded", async () => {
ko.applyBindings(vm = new ListViewModel(), document.getElementById("ko-area"));
$(document.body).applyDateTimeLocalPolyfill();
vm.files.orderField("takenOrUploadedAt");
vm.loadFiles();
}, false);
| IsaacSchemm/AnonymousPhotoBin | AnonymousPhotoBin/wwwroot/scripts/list.ts | TypeScript | agpl-3.0 | 10,918 |
/*
* This program is part of the OpenLMIS logistics management information
* system platform software.
*
* Copyright © 2015 ThoughtWorks, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (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 Affero General Public License for more details. You should
* have received a copy of the GNU Affero General Public License along with
* this program. If not, see http://www.gnu.org/licenses. For additional
* information contact info@OpenLMIS.org
*/
package org.openlmis.core.persistence.migrations;
import com.j256.ormlite.dao.Dao;
import org.openlmis.core.LMISApp;
import org.openlmis.core.exceptions.LMISException;
import org.openlmis.core.manager.MovementReasonManager;
import org.openlmis.core.model.StockMovementItem;
import org.openlmis.core.persistence.DbUtil;
import org.openlmis.core.persistence.GenericDao;
import org.openlmis.core.persistence.Migration;
import java.sql.SQLException;
import java.util.List;
public class AddCreatedTimeToStockMovement extends Migration {
GenericDao<StockMovementItem> stockItemGenericDao;
MovementReasonManager reasonManager;
DbUtil dbUtil;
public AddCreatedTimeToStockMovement() {
stockItemGenericDao = new GenericDao<>(StockMovementItem.class, LMISApp.getContext());
reasonManager = MovementReasonManager.getInstance();
dbUtil = new DbUtil();
}
@Override
public void up() {
execSQL("ALTER TABLE 'stock_items' ADD COLUMN createdTime VARCHAR");
execSQL("CREATE INDEX `stock_items_created_time_idx` ON `stock_items` ( `createdTime` )");
try {
initCreatedTime();
}catch (LMISException e){
e.reportToFabric();
}
}
private void initCreatedTime() throws LMISException {
List<StockMovementItem> itemList = stockItemGenericDao.queryForAll();
if (itemList == null || itemList.size() == 0) {
return;
}
for (StockMovementItem item : itemList) {
item.setCreatedTime(item.getCreatedAt());
}
updateStockMovementItems(itemList);
}
private void updateStockMovementItems(final List<StockMovementItem> stockMovementItems) throws LMISException {
dbUtil.withDaoAsBatch(LMISApp.getContext(), StockMovementItem.class, new DbUtil.Operation<StockMovementItem, Void>() {
@Override
public Void operate(Dao<StockMovementItem, String> dao) throws SQLException {
for (StockMovementItem stockMovementItem : stockMovementItems) {
dao.update(stockMovementItem);
}
return null;
}
});
}
}
| clintonhealthaccess/lmis-moz-mobile | app/src/main/java/org/openlmis/core/persistence/migrations/AddCreatedTimeToStockMovement.java | Java | agpl-3.0 | 3,056 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.