repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
remyoster/pathwar
|
go/pkg/pwapi/testing_test.go
|
package pwapi
import (
"context"
"testing"
"github.com/jinzhu/gorm"
"github.com/stretchr/testify/assert"
"pathwar.land/pathwar/v2/go/pkg/errcode"
"pathwar.land/pathwar/v2/go/pkg/pwdb"
"pathwar.land/pathwar/v2/go/pkg/pwsso"
)
func testingSeasons(t *testing.T, svc Service) *pwdb.SeasonList {
t.Helper()
db := testingSvcDB(t, svc)
var list pwdb.SeasonList
err := db.Set("gorm:auto_preload", true).Find(&list.Items).Error
assert.NoError(t, err, "list seasons")
return &list
}
/*func testingAgents(t *testing.T, svc Service) *pwdb.AgentList {
t.Helper()
db := testingSvcDB(t, svc)
var list pwdb.AgentList
err := db.Set("gorm:auto_preload", true).Find(&list.Items).Error
if err != nil {
t.Fatalf("list agents: %v", err)
}
return &list
}*/
func testingSeasonChallenges(t *testing.T, svc Service) *pwdb.SeasonChallengeList {
t.Helper()
db := testingSvcDB(t, svc)
var list pwdb.SeasonChallengeList
err := db.Set("gorm:auto_preload", true).Find(&list.Items).Error
assert.NoError(t, err, "list season challenges")
return &list
}
func testingGlobalSeason(t *testing.T, svc Service) *pwdb.Season {
t.Helper()
seasons := testingSeasons(t, svc)
for _, season := range seasons.Items {
if season.Name == "Global" {
return season
}
}
t.Fatalf("no such global season")
return nil
}
func testingActivities(t *testing.T, svc Service) *pwdb.ActivityList {
t.Helper()
db := testingSvcDB(t, svc)
var list pwdb.ActivityList
err := db.Set("gorm:auto_preload", true).Find(&list.Items).Error
assert.NoError(t, err, "list activities")
return &list
}
func testingTeams(t *testing.T, svc Service) *pwdb.TeamList {
t.Helper()
db := testingSvcDB(t, svc)
var list pwdb.TeamList
err := db.Set("gorm:auto_preload", true).Find(&list.Items).Error
assert.NoError(t, err, "list teams")
return &list
}
func testingChallenges(t *testing.T, svc Service) *pwdb.ChallengeList {
t.Helper()
db := testingSvcDB(t, svc)
var list pwdb.ChallengeList
err := db.Set("gorm:auto_preload", true).Find(&list.Items).Error
assert.NoError(t, err, "list challenges")
return &list
}
func testingSvcDB(t *testing.T, svc Service) *gorm.DB {
t.Helper()
typed := svc.(*service)
return typed.db
}
func testingSetContextToken(ctx context.Context, t *testing.T) context.Context {
t.Helper()
return context.WithValue(ctx, userTokenCtx, pwsso.TestingToken(t))
}
func testingSetContextToken2(ctx context.Context, t *testing.T) context.Context {
t.Helper()
return context.WithValue(ctx, userTokenCtx, pwsso.TestingToken2(t))
}
func testSameErrcodes(t *testing.T, name string, expected, got error) {
t.Helper()
prefix := ""
if name != "" {
prefix = name + ": "
}
assert.Equalf(
t,
errcode.ErrCode_name[errcode.Code(expected)],
errcode.ErrCode_name[errcode.Code(got)],
"%s%v", prefix, got,
)
}
|
dbac/jdk8
|
src/share/lib/security/BlacklistedCertsConverter.java
|
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
/**
* This is the tool to convert blacklisted.certs.pem to blacklisted.certs.
* Every time a new blacklisted certs is added, please append the PEM format
* to the end of blacklisted.certs.pem (with proper comments) and then use
* this tool to generate an updated blacklisted.certs. Make sure to include
* changes to both in a changeset.
*/
public class BlacklistedCertsConverter {
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Usage: java BlacklistedCertsConverter SHA-256" +
" < blacklisted.certs.pem > blacklisted.certs");
System.exit(1);
}
String mdAlg = args[0];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certs
= cf.generateCertificates(System.in);
System.out.println("Algorithm=" + mdAlg);
for (Certificate cert: certs) {
System.out.println(
getCertificateFingerPrint(mdAlg, (X509Certificate)cert));
}
}
/**
* Converts a byte to hex digit and writes to the supplied buffer
*/
private static void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
/**
* Gets the requested finger print of the certificate.
*/
private static String getCertificateFingerPrint(String mdAlg,
X509Certificate cert) {
String fingerPrint = "";
try {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance(mdAlg);
byte[] digest = md.digest(encCertInfo);
StringBuffer buf = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
byte2hex(digest[i], buf);
}
fingerPrint = buf.toString();
} catch (NoSuchAlgorithmException | CertificateEncodingException e) {
// ignored
}
return fingerPrint;
}
}
|
lpr-perm/partynest
|
lib/templates/pundit/policy/policy.rb
|
<filename>lib/templates/pundit/policy/policy.rb
<% module_namespacing do -%>
# frozen_string_literal: true
class <%= class_name %>Policy < ApplicationPolicy
class Scope < Scope
def resolve
scope.none
end
end
end
<% end -%>
|
madd-games/glidix
|
libgwm/toolbtn.c
|
<filename>libgwm/toolbtn.c<gh_stars>10-100
/*
Glidix GUI
Copyright (c) 2014-2017, <NAME>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <libgwm.h>
#include <libddi.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum
{
TOOL_BUTTON_STATE_NORMAL,
TOOL_BUTTON_STATE_HOVERING,
TOOL_BUTTON_STATE_CLICKED
};
typedef struct
{
DDISurface* icon;
int state;
int symbol;
} ToolButtonData;
static void redrawToolButton(GWMWindow *button);
int toolbtnHandler(GWMEvent *ev, GWMWindow *toolbtn, void *context)
{
ToolButtonData *data = (ToolButtonData*) context;
switch (ev->type)
{
case GWM_EVENT_ENTER:
data->state = TOOL_BUTTON_STATE_HOVERING;
redrawToolButton(toolbtn);
return GWM_EVSTATUS_OK;
case GWM_EVENT_LEAVE:
data->state = TOOL_BUTTON_STATE_NORMAL;
redrawToolButton(toolbtn);
return GWM_EVSTATUS_OK;
case GWM_EVENT_DOWN:
if (ev->keycode == GWM_KC_MOUSE_LEFT)
{
data->state = TOOL_BUTTON_STATE_CLICKED;
redrawToolButton(toolbtn);
};
return GWM_EVSTATUS_OK;
case GWM_EVENT_UP:
if (ev->keycode == GWM_KC_MOUSE_LEFT)
{
if (data->state == TOOL_BUTTON_STATE_CLICKED)
{
data->state = TOOL_BUTTON_STATE_HOVERING;
redrawToolButton(toolbtn);
GWMCommandEvent event;
memset(&event, 0, sizeof(GWMCommandEvent));
event.header.type = GWM_EVENT_COMMAND;
event.symbol = data->symbol;
return gwmPostEvent((GWMEvent*) &event, toolbtn);
}
else
{
data->state = TOOL_BUTTON_STATE_NORMAL;
};
redrawToolButton(toolbtn);
};
return GWM_EVSTATUS_OK;
case GWM_EVENT_RETHEME:
redrawToolButton(toolbtn);
return GWM_EVSTATUS_OK;
default:
return GWM_EVSTATUS_CONT;
};
};
static void redrawToolButton(GWMWindow *toolbtn)
{
ToolButtonData *data = (ToolButtonData*) gwmGetData(toolbtn, toolbtnHandler);
DDISurface *canvas = gwmGetWindowCanvas(toolbtn);
static DDIColor transparent = {0, 0, 0, 0};
ddiFillRect(canvas, 0, 0, canvas->width, canvas->height, &transparent);
int whichImg = data->state;
DDISurface *imgToolButton = gwmGetThemeSurface("gwm.toolkit.toolbtn");
ddiBlit(imgToolButton, 0, 30*whichImg, canvas, 0, 0, 30, 30);
DDISurface *icon = data->icon;
if (icon == NULL)
{
icon = gwmGetStockIcon(data->symbol);
};
if (icon != NULL)
{
ddiBlit(icon, 0, 0, canvas, 3, 3, 24, 24);
};
gwmPostDirty(toolbtn);
};
static void sizeToolButton(GWMWindow *toolbtn, int *width, int *height)
{
*width = 30;
*height = 30;
};
static void positionToolButton(GWMWindow *toolbtn, int x, int y, int width, int height)
{
gwmMoveWindow(toolbtn, x, y);
gwmResizeWindow(toolbtn, width, height);
redrawToolButton(toolbtn);
};
GWMWindow* gwmNewToolButton(GWMWindow *parent)
{
GWMWindow *toolbtn = gwmCreateWindow(parent, "GWMToolButton", 0, 0, 0, 0, 0);
if (toolbtn == NULL) return NULL;
ToolButtonData *data = (ToolButtonData*) malloc(sizeof(ToolButtonData));
data->icon = NULL;
data->state = TOOL_BUTTON_STATE_NORMAL;
data->symbol = 0;
toolbtn->getMinSize = toolbtn->getPrefSize = sizeToolButton;
toolbtn->position = positionToolButton;
gwmPushEventHandler(toolbtn, toolbtnHandler, data);
redrawToolButton(toolbtn);
return toolbtn;
};
void gwmDestroyToolButton(GWMWindow *toolbtn)
{
ToolButtonData *data = (ToolButtonData*) gwmGetData(toolbtn, toolbtnHandler);
free(data);
gwmDestroyWindow(toolbtn);
};
void gwmSetToolButtonSymbol(GWMWindow *toolbtn, int symbol)
{
ToolButtonData *data = (ToolButtonData*) gwmGetData(toolbtn, toolbtnHandler);
data->symbol = symbol;
};
void gwmSetToolButtonIcon(GWMWindow *toolbtn, DDISurface *icon)
{
ToolButtonData *data = (ToolButtonData*) gwmGetData(toolbtn, toolbtnHandler);
data->icon = icon;
};
GWMToolButton* gwmAddToolButtonBySymbol(GWMWindow *parent, GWMLayout *toolbar, int symbol)
{
GWMToolButton *tool = gwmNewToolButton(parent);
gwmBoxLayoutAddWindow(toolbar, tool, 0, 0, 0);
gwmSetToolButtonSymbol(tool, symbol);
return tool;
};
|
MBtech/gpa-flink
|
src/main/java/org/apache/flink/graph/streaming/summaries/HMap.java
|
package org.apache.flink.graph.streaming.summaries;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Created by zainababbas on 15/04/2017.
*/
public class HMap implements Serializable {
private Map<Long, Integer> verticesWithDegrees;
public HMap() {
verticesWithDegrees = new HashMap<>();
}
public void union(Long e1, Long e2) {
if (verticesWithDegrees.containsKey(e1)) {
// update existing vertex
int oldDegree =verticesWithDegrees.get(e1);
Integer newDegree = oldDegree + 1;
if (newDegree > 0) {
verticesWithDegrees.put(e1, newDegree);
} else {
// if the current degree is <= 0: remove the vertex
verticesWithDegrees.remove(e1);
}
} else {
verticesWithDegrees.put(e1, 1);
}
if (verticesWithDegrees.containsKey(e2)) {
// update existing vertex
int oldDegree =verticesWithDegrees.get(e2);
Integer newDegree = oldDegree + 1;
if (newDegree > 0) {
verticesWithDegrees.put(e2, newDegree);
} else {
// if the current degree is <= 0: remove the vertex
verticesWithDegrees.remove(e2);
}
} else {
verticesWithDegrees.put(e2, 1);
}
}
public void union1(Long e1, Integer d) {
if (verticesWithDegrees.containsKey(e1)) {
// update existing vertex
int oldDegree =verticesWithDegrees.get(e1);
Integer newDegree = oldDegree + d;
if (newDegree > 0) {
verticesWithDegrees.put(e1, newDegree);
} else {
// if the current degree is <= 0: remove the vertex
verticesWithDegrees.remove(e1);
}
} else {
verticesWithDegrees.put(e1, 1);
}
}
public Map<Long, Integer> getmap (){
return verticesWithDegrees;
}
public void merge(Map<Long, Integer> other) {
for (Map.Entry<Long, Integer> entry : other.entrySet()) {
union1(entry.getKey(),entry.getValue());
}
}
public int size() {
return verticesWithDegrees.size();
}
}
|
nanjekyejoannah/pypy
|
rpython/translator/c/src/mem.h
|
/************************************************************/
/*** C header subsection: operations on LowLevelTypes ***/
#include <string.h>
/* used by rpython.rlib.rstack */
#define OP_STACK_CURRENT(r) r = (Signed)&r
#define OP_RAW_MALLOC(size, zero, result) { \
if (zero) \
result = calloc(size, 1); \
else \
result = malloc(size); \
if (result != NULL) { \
COUNT_MALLOC; \
} \
}
#define OP_RAW_FREE(p, r) free(p); COUNT_FREE;
#define OP_RAW_MEMCLEAR(p, size, r) memset((void*)p, 0, size)
#define OP_RAW_MEMSET(p, byte, size, r) memset((void*)p, byte, size)
#define OP_RAW_MALLOC_USAGE(size, r) r = size
#if defined(MS_WINDOWS) && !defined(__MINGW32__)
#define alloca _alloca
#endif
#define OP_RAW_MEMCOPY(x,y,size,r) memcpy(y,x,size);
#define OP_RAW_MEMMOVE(x,y,size,r) memmove(y,x,size);
/************************************************************/
#define OP_FREE(p) OP_RAW_FREE(p, do_not_use)
#ifndef COUNT_OP_MALLOCS
#define COUNT_MALLOC /* nothing */
#define COUNT_FREE /* nothing */
#define pypy_malloc_counters_results() /* nothing */
#else /* COUNT_OP_MALLOCS */
static int count_mallocs=0, count_frees=0;
#define COUNT_MALLOC count_mallocs++
#define COUNT_FREE count_frees++
#define pypy_malloc_counters_results() \
printf("MALLOC COUNTERS: %d %d\n", count_mallocs, count_frees)
#endif /* COUNT_OP_MALLOCS */
/*** tracking raw mallocs and frees for debugging ***/
#ifndef RPY_ASSERT
# define OP_TRACK_ALLOC_START(addr, r) /* nothing */
# define OP_TRACK_ALLOC_STOP(addr, r) /* nothing */
# define pypy_debug_alloc_results() /* nothing */
#else /* RPY_ASSERT */
# define OP_TRACK_ALLOC_START(addr, r) pypy_debug_alloc_start(addr, \
__FUNCTION__)
# define OP_TRACK_ALLOC_STOP(addr, r) pypy_debug_alloc_stop(addr)
RPY_EXTERN void pypy_debug_alloc_start(void*, const char*);
RPY_EXTERN void pypy_debug_alloc_stop(void*);
RPY_EXTERN void pypy_debug_alloc_results(void);
#endif /* RPY_ASSERT */
/* for Boehm GC */
#ifdef PYPY_USING_BOEHM_GC
#define BOEHM_MALLOC_0_0 GC_MALLOC
#define BOEHM_MALLOC_1_0 GC_MALLOC_ATOMIC
#define BOEHM_MALLOC_0_1 GC_MALLOC
#define BOEHM_MALLOC_1_1 GC_MALLOC_ATOMIC
/* #define BOEHM_MALLOC_0_1 GC_MALLOC_IGNORE_OFF_PAGE */
/* #define BOEHM_MALLOC_1_1 GC_MALLOC_ATOMIC_IGNORE_OFF_PAGE */
#define OP_BOEHM_ZERO_MALLOC(size, r, restype, is_atomic, is_varsize) { \
r = (restype) BOEHM_MALLOC_ ## is_atomic ## _ ## is_varsize (size); \
if (r && is_atomic) /* the non-atomic versions return cleared memory */ \
memset((void*) r, 0, size); \
}
#define OP_BOEHM_DISAPPEARING_LINK(link, obj, r) \
if (GC_base(obj) == NULL) \
; /* 'obj' is probably a prebuilt object - it makes no */ \
/* sense to register it then, and it crashes Boehm in */ \
/* quite obscure ways */ \
else \
GC_GENERAL_REGISTER_DISAPPEARING_LINK(link, obj)
RPY_EXTERN int boehm_gc_finalizer_lock;
RPY_EXTERN void boehm_gc_startup_code(void);
RPY_EXTERN void boehm_gc_finalizer_notifier(void);
struct boehm_fq_s;
RPY_EXTERN struct boehm_fq_s *boehm_fq_queues[];
RPY_EXTERN void (*boehm_fq_trigger[])(void);
RPY_EXTERN void boehm_fq_register(struct boehm_fq_s **, void *);
RPY_EXTERN void *boehm_fq_next_dead(struct boehm_fq_s **);
#define OP_GC__DISABLE_FINALIZERS(r) boehm_gc_finalizer_lock++
#define OP_GC__ENABLE_FINALIZERS(r) (boehm_gc_finalizer_lock--, \
boehm_gc_finalizer_notifier())
#define OP_GC__DISABLE(r) /* nothing */
#define OP_GC__ENABLE(r) /* nothing */
#define OP_BOEHM_FQ_REGISTER(tagindex, obj, r) \
boehm_fq_register(boehm_fq_queues + tagindex, obj)
#define OP_BOEHM_FQ_NEXT_DEAD(tagindex, r) \
r = boehm_fq_next_dead(boehm_fq_queues + tagindex)
#endif /* PYPY_USING_BOEHM_GC */
#ifdef PYPY_USING_NO_GC_AT_ALL
#define OP_BOEHM_ZERO_MALLOC(size, r, restype, is_atomic, is_varsize) \
r = (restype) calloc(1, size);
#define OP_BOEHM_DISAPPEARING_LINK(link, obj, r) /* nothing */
#define OP_GC__DISABLE_FINALIZERS(r) /* nothing */
#define OP_GC__ENABLE_FINALIZERS(r) /* nothing */
#define OP_GC__DISABLE(r) /* nothing */
#define OP_GC__ENABLE(r) /* nothing */
#define GC_REGISTER_FINALIZER(a, b, c, d, e) /* nothing */
#define GC_gcollect() /* nothing */
#define GC_set_max_heap_size(a) /* nothing */
#define OP_GC_FQ_REGISTER(tag, obj, r) /* nothing */
#define OP_GC_FQ_NEXT_DEAD(tag, r) (r = NULL)
#endif
#if (defined(PYPY_USING_BOEHM_GC) || defined(PYPY_USING_NO_GC_AT_ALL)) && !defined(PYPY_BOEHM_WITH_HEADER)
# define RPY_SIZE_OF_GCHEADER 0
#else
# define RPY_SIZE_OF_GCHEADER sizeof(struct pypy_header0)
#endif
/************************************************************/
/* weakref support */
#define OP_CAST_PTR_TO_WEAKREFPTR(x, r) r = x
#define OP_CAST_WEAKREFPTR_TO_PTR(x, r) r = x
/************************************************************/
/* dummy version of these operations, e.g. with Boehm */
#define OP_GC_GET_RPY_ROOTS(r) r = 0
#define OP_GC_GET_RPY_REFERENTS(x, r) r = 0
#define OP_GC_GET_RPY_MEMORY_USAGE(x, r) r = -1
#define OP_GC_GET_RPY_TYPE_INDEX(x, r) r = -1
#define OP_GC_IS_RPY_INSTANCE(x, r) r = 0
#define OP_GC_DUMP_RPY_HEAP(fd, r) r = 0
#define OP_GC_SET_EXTRA_THRESHOLD(x, r) /* nothing */
#define OP_GC_IGNORE_FINALIZER(x, r) /* nothing */
/****************************/
/* misc stuff */
/****************************/
#ifndef _MSC_VER
# define pypy_asm_keepalive(v) asm volatile ("/* keepalive %0 */" : : \
"g" (v))
#else
# ifndef _WIN64
# define pypy_asm_keepalive(v) __asm { }
# else
/* is there something cheaper? */
# define pypy_asm_keepalive(v) _ReadWriteBarrier();
# endif
#endif
|
Antonio-Iliev/Exercises
|
SoftUni/Exams/src/com/company/demo05_1.java
|
package com.company;
import java.util.Scanner;
public class demo05_1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int hHole = Integer.parseInt(scanner.nextLine());
int wHole = Integer.parseInt(scanner.nextLine());
int squarePicture = Integer.parseInt(scanner.nextLine());
int numberPicture = Integer.parseInt(scanner.nextLine());
int holeArea = hHole * wHole;
int picturesArea = (squarePicture * squarePicture) * numberPicture;
if (holeArea > picturesArea) {
int diff = holeArea - picturesArea;
System.out.printf("The pictures fit in the hole. " +
"Hole area is %d bigger than pictures area.", diff);
} else if (holeArea < picturesArea) {
int diff = picturesArea - holeArea;
System.out.printf("The pictures don't fit in the hole. "
+ "Picture area is %d bigger than hole area.", diff
);
}
}
}
|
TacoVox/elvish
|
pkg/eval/module_math_test.go
|
package eval
import "testing"
func TestMathModule(t *testing.T) {
TestWithSetup(t,
func(ev *Evaler) {
ev.InstallModule("math", MathNs)
err := ev.EvalSourceInTTY(NewInteractiveSource(`use math`))
if err != nil {
panic(err)
}
},
That(`math:abs 2.1`).Puts(2.1),
That(`math:abs -2.1`).Puts(2.1),
That(`math:ceil 2.1`).Puts(3.0),
That(`math:ceil -2.1`).Puts(-2.0),
That(`math:floor 2.1`).Puts(2.0),
That(`math:floor -2.1`).Puts(-3.0),
That(`math:round 2.1`).Puts(2.0),
That(`math:round -2.1`).Puts(-2.0),
That(`math:round 2.5`).Puts(3.0),
That(`math:round -2.5`).Puts(-3.0),
)
}
|
SoerenHenning/titan-ccp-common
|
src/main/java/titan/ccp/model/sensorregistry/DummySensorRegistry.java
|
<filename>src/main/java/titan/ccp/model/sensorregistry/DummySensorRegistry.java<gh_stars>0
package titan.ccp.model.sensorregistry;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* A {@link SensorRegistry} containing no real sensors. Will be removed with next release.
*
* @deprecated Create a corresponding {@link SensorRegistry} manually if required.
*/
@Deprecated
public class DummySensorRegistry implements SensorRegistry {
private static final AggregatedSensor EMPTY_TOP_LEVEL_SENSOR = new EmptyTopLevelSensor();
private final Map<String, DummyMachineSensor> dummySensors = new HashMap<>();
@Override
public Optional<MachineSensor> getSensorForIdentifier(final String identifier) {
return Optional
.of(this.dummySensors.computeIfAbsent(identifier, i -> new DummyMachineSensor(i)));
}
@Override
public AggregatedSensor getTopLevelSensor() {
return EMPTY_TOP_LEVEL_SENSOR;
}
@Override
public Collection<MachineSensor> getMachineSensors() {
return Collections.emptyList();
}
// TODO move
private static class EmptyTopLevelSensor implements AggregatedSensor {
@Override
public Optional<AggregatedSensor> getParent() {
return Optional.empty();
}
@Override
public String getIdentifier() {
return "";
}
@Override
public String getName() {
return "";
}
@Override
public Collection<Sensor> getChildren() {
return Collections.emptyList();
}
}
private static class DummyMachineSensor implements MachineSensor {
private final String identifier;
private DummyMachineSensor(final String identifier) {
this.identifier = identifier;
}
@Override
public Optional<AggregatedSensor> getParent() {
return Optional.empty();
}
@Override
public String getIdentifier() {
return this.identifier;
}
@Override
public String getName() {
return "";
}
}
}
|
cjayho/pgadmin3
|
pgadmin/include/ogl/constrnt.h
|
<filename>pgadmin/include/ogl/constrnt.h<gh_stars>100-1000
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Portions Copyright (C) 1998 - 2011, <NAME>
// Portions Copyright (C) 2011 - 2016, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// constrnt.h - OGL constraint definitions
//
//////////////////////////////////////////////////////////////////////////
#ifndef _OGL_CONSTRNT_H_
#define _OGL_CONSTRNT_H_
/*
* OGL Constraints
*
*/
class wxOGLConstraintType: public wxObject
{
DECLARE_DYNAMIC_CLASS(wxOGLConstraintType)
public:
wxOGLConstraintType(int type = 0, const wxString &name = wxEmptyString,
const wxString &phrase = wxEmptyString);
~wxOGLConstraintType();
public:
int m_type; // E.g. gyCONSTRAINT_CENTRED_VERTICALLY
wxString m_name; // E.g. "Centre vertically"
wxString m_phrase; // E.g. "centred vertically with respect to", "left of"
};
extern wxList *wxOGLConstraintTypes;
#define gyCONSTRAINT_CENTRED_VERTICALLY 1
#define gyCONSTRAINT_CENTRED_HORIZONTALLY 2
#define gyCONSTRAINT_CENTRED_BOTH 3
#define gyCONSTRAINT_LEFT_OF 4
#define gyCONSTRAINT_RIGHT_OF 5
#define gyCONSTRAINT_ABOVE 6
#define gyCONSTRAINT_BELOW 7
#define gyCONSTRAINT_ALIGNED_TOP 8
#define gyCONSTRAINT_ALIGNED_BOTTOM 9
#define gyCONSTRAINT_ALIGNED_LEFT 10
#define gyCONSTRAINT_ALIGNED_RIGHT 11
// Like aligned, but with the objects centred on the respective edge
// of the reference object.
#define gyCONSTRAINT_MIDALIGNED_TOP 12
#define gyCONSTRAINT_MIDALIGNED_BOTTOM 13
#define gyCONSTRAINT_MIDALIGNED_LEFT 14
#define gyCONSTRAINT_MIDALIGNED_RIGHT 15
class wxOGLConstraint: public wxObject
{
DECLARE_DYNAMIC_CLASS(wxOGLConstraint)
public:
wxOGLConstraint()
{
m_xSpacing = 0.0;
m_ySpacing = 0.0;
m_constraintType = 0;
m_constraintName = wxEmptyString;
m_constraintId = 0;
m_constrainingObject = NULL;
}
wxOGLConstraint(int type, wxShape *constraining, wxList &constrained);
~wxOGLConstraint();
// Returns TRUE if anything changed
bool Evaluate();
inline void SetSpacing(double x, double y)
{
m_xSpacing = x;
m_ySpacing = y;
};
bool Equals(double a, double b);
double m_xSpacing;
double m_ySpacing;
int m_constraintType;
wxString m_constraintName;
long m_constraintId;
wxShape *m_constrainingObject;
wxList m_constrainedObjects;
};
void OGLInitializeConstraintTypes();
void OGLCleanUpConstraintTypes();
#endif
// _OGL_CONSTRNT_H_
|
macripps/adventofcode
|
src/main/scala/aoc2018/Day10.scala
|
package aoc2018
import aoc.{Day, Point}
import scala.util.matching.Regex
class Day10 extends Day(2018, 10) {
import Day10._
override def part1(input: Array[String]): String = {
val ptsDlts = input.map {
case line(px: String, py: String, vx: String, vy:String) =>
(Point(px.toInt, py.toInt), (vx.toInt, vy.toInt))
}
val minIdx = 10007
val points = ptsDlts.map { pD => Point(pD._1.x + minIdx * pD._2._1, pD._1.y + minIdx * pD._2._2)}
println(points.mkString(","))
val minX = points.minBy(_.x).x
val maxX = points.maxBy(_.x).x
val minY = points.minBy(_.y).y
val maxY = points.maxBy(_.y).y
val grid = Array.ofDim[Boolean](maxY + 1 - minY, maxX + 1 - minX)
points.foreach { p => grid(p.y - minY)(p.x - minX) =true }
"\n" + grid.map(_.map(c => if (c) '#' else '.').mkString).mkString("\n")
}
override def part2(input: Array[String]): String = {
"10007"
}
}
object Day10 {
def apply() = new Day10()
val line: Regex = raw"position=< *(-?\d+), *(-?\d+)> velocity=< *(-?\d+), *(-?\d+)>".r
}
|
Horwits/Telerik-Academy-2016-2017
|
JAVASCRIPT/JAVASCRIPT-FUNDAMENTALS/7.Functions/4.appearance-count.js
|
function solve(args) {
var n = +args[0],
numbers = (args[1] + '')
.split(' ')
.map(Number),
x = +args[args.length - 1],
maxOcc = 0,
currentOcc = 1;
// for (var i = 0; i < n; i += 1) {
// if (i + 1 < n) {
// if (numbers[i + 1] === numbers[i]) {
// currentOcc += 1;
// } else {
// currentOcc = 1;
// }
// }
// if (currentOcc > maxOcc) {
// maxOcc = currentOcc;
// }
// }
for (var i = 0; i < n; i += 1) {
if (numbers[i] === x) {
maxOcc++;
}
}
return maxOcc;
}
var test = ['8', '28 6 21 6 -7856 73 73 -56', '73'];
var test2 = [
'8\n28\n6\n21\n6\n-7856\n73\n73\n-56\n73'
];
console.log(solve(test));
function testSolve(params) {
console.log(solve(test) === 2);
}
testSolve();
|
JackChan1999/boohee_v5.6
|
src/main/java/com/alipay/apmobilesecuritysdk/a/a/a.java
|
package com.alipay.apmobilesecuritysdk.a.a;
import android.content.Context;
import com.alipay.apmobilesecuritysdk.e.b;
import com.alipay.security.mobile.module.commonutils.CommonUtils;
import com.alipay.security.mobile.module.commonutils.crypto.SecurityUtils;
import com.alipay.security.mobile.module.localstorage.PublicStorage;
import com.alipay.security.mobile.module.localstorage.SharePreferenceStorage;
import java.util.Map;
import org.json.JSONObject;
public final class a {
public static synchronized String a() {
String str = null;
synchronized (a.class) {
String b = b();
if (!CommonUtils.isBlank(b)) {
String[] split = b.split("`");
if (split != null && split.length >= 2) {
str = split[0];
}
}
}
return str;
}
public static synchronized String a(Context context) {
String a;
synchronized (a.class) {
a = a();
if (CommonUtils.isBlank(a)) {
a = b(context);
}
}
return a;
}
public static synchronized void a(b bVar) {
synchronized (a.class) {
if (!CommonUtils.isBlank(bVar.a())) {
if (!bVar.a().equals(a())) {
String str = bVar.a() + "`" + bVar.d();
if (str != null) {
try {
str = SecurityUtils.encrypt(SecurityUtils.getSeed(), str);
JSONObject jSONObject = new JSONObject();
jSONObject.put("device", str);
PublicStorage.writeDataToPublicArea("deviceid_v2", jSONObject.toString());
} catch (Exception e) {
}
}
}
}
}
}
private static String b() {
try {
return SecurityUtils.decrypt(SecurityUtils.getSeed(), new JSONObject(PublicStorage.readDataFromPublicArea("deviceid_v2")).getString("device"));
} catch (Exception e) {
return null;
}
}
public static synchronized String b(Context context) {
String str = null;
synchronized (a.class) {
String str2 = "";
try {
String dataFromSharePreference = SharePreferenceStorage.getDataFromSharePreference(context, "profiles", "deviceid", "");
dataFromSharePreference = CommonUtils.isBlank(dataFromSharePreference) ? null : SecurityUtils.decrypt(SecurityUtils.getSeed(), dataFromSharePreference);
if (!CommonUtils.isBlank(dataFromSharePreference)) {
b bVar = new b();
Map a = b.a(dataFromSharePreference);
if (a != null) {
str = (String) a.get("deviceId");
}
str = str2;
}
} catch (Throwable th) {
}
}
return str;
}
}
|
ryannel/hippo
|
pkg/docker/docker.go
|
package docker
import (
"github.com/ryannel/hippo/pkg/logger"
"github.com/ryannel/hippo/pkg/util"
"strings"
)
var execStringCommand = util.ExecStringCommand
var execCommandStreamingOut = util.ExecCommandStreamingOut
func Build(imageName string, commitTag string) error {
commitTag = generateTag(imageName, commitTag)
if commitTag != "" {
commitTag = "-t " + commitTag + " "
}
command := strings.ToLower(`docker build --pull ` + commitTag + `.`)
logger.Command("Building Docker image: " + command)
return execCommandStreamingOut(command)
}
func Tag(sourceImage string, sourceTag string, targetImage string, targetTag string) error {
sourceTag = generateTag(sourceImage, sourceTag)
targetTag = generateTag(targetImage, targetTag)
command := strings.ToLower("docker tag " + sourceTag + " " + targetTag)
logger.Command("Tagging image : " + command)
result, err := execStringCommand(command)
if err != nil {
return err
}
logger.Log(result)
return err
}
func Push(registryUrl string, imageName string, tag string) error {
tag = generateTag(imageName, tag)
command := strings.ToLower("docker push " + registryUrl + "/" + tag)
logger.Command("Pushing docker image: " + command)
err := execCommandStreamingOut(command)
return err
}
func Login(registryUrl string, username string, password string) error {
command := "docker login -u " + username + " -p " + password + " " + registryUrl
logger.Command("Logging into docker registry: docker login -u " + username + " -p <password> " + registryUrl)
result, err := execStringCommand(command)
if err != nil {
return err
}
logger.Log(result)
return err
}
func generateTag(name string, tag string) string {
arg := name
if tag != "" {
arg = arg + ":" + tag
}
return arg
}
|
ita-social-projects/horondi_client_fe
|
src/redux/images-constructor/constructor-front-pocket/constructor-front-pocket.reducer.js
|
<gh_stars>10-100
import { SET_CONSTRUCTOR_FRONT_POCKET } from './constructor-front-pocket.types';
const constructorFrontPocket = (state = {}, action = {}) => {
if (action.type === SET_CONSTRUCTOR_FRONT_POCKET) {
return action.payload;
}
return state;
};
export default constructorFrontPocket;
|
mboutell/Mobile
|
android/src/RHITMobile/src/edu/rosehulman/android/directory/model/TourTagsGroup.java
|
<reponame>mboutell/Mobile<filename>android/src/RHITMobile/src/edu/rosehulman/android/directory/model/TourTagsGroup.java
package edu.rosehulman.android.directory.model;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Represents a category of campus services hyperlinks
*/
public class TourTagsGroup {
/** The internal id of this group */
public long id;
/** The name of the category */
public String name;
/** The array of entries for this category */
public TourTag tags[];
/** All categories contained under this parent */
public TourTagsGroup children[];
/**
* Creates a new, empty CampusServicesCategory
*/
public TourTagsGroup() {
this.id = -1;
}
/**
* Creates a new instance initialized with the given data
*
* @param name The name of the category
* @param tags The array of entries
* @param children The array of children groups
*/
public TourTagsGroup(String name, TourTag[] tags, TourTagsGroup[] children) {
this.id = -1;
this.name = name;
this.tags = tags;
this.children = children;
}
private static TourTag[] deserializeTags(JSONArray array) throws JSONException {
TourTag res[] = new TourTag[array.length()];
for (int i = 0; i < res.length; i++) {
res[i] = TourTag.deserialize(array.getJSONObject(i));
}
return res;
}
private static TourTagsGroup[] deserializeChildren(JSONArray root) throws JSONException {
TourTagsGroup res[] = new TourTagsGroup[root.length()];
for (int i = 0; i < res.length; i++) {
res[i] = TourTagsGroup.deserialize(root.getJSONObject(i));
}
return res;
}
/**
* Deserialize the given JSONObject into a new instance of CampusServicesCategory
*
* @param root The JSONObject with the necessary field to create a new CampusServicesCategory
* @return A new CampusServicesCategory initialized from the given JSONObject
* @throws JSONException
*/
public static TourTagsGroup deserialize(JSONObject root) throws JSONException {
TourTagsGroup res = new TourTagsGroup();
res.name = root.getString("Name");
res.tags = deserializeTags(root.getJSONArray("Tags"));
res.children = deserializeChildren(root.getJSONArray("Children"));
return res;
}
}
|
nulab/backlog-migration-common
|
core/src/main/scala/com/nulabinc/backlog/migration/common/messages/ConsoleMessages.scala
|
<filename>core/src/main/scala/com/nulabinc/backlog/migration/common/messages/ConsoleMessages.scala
package com.nulabinc.backlog.migration.common.messages
import java.nio.file.Path
import java.util.Locale
import com.nulabinc.backlog.migration.common.domain.mappings.{
Mapping,
MappingType,
PriorityMapping,
StatusMapping,
UserMapping
}
import com.nulabinc.backlog.migration.common.errors._
import com.nulabinc.backlog.migration.common.formatters.Formatter
import com.osinka.i18n.{Lang, Messages}
object ConsoleMessages {
private implicit val userLang: Lang =
if (Locale.getDefault.equals(Locale.JAPAN)) Lang("ja") else Lang("en")
lazy val empty: String = Messages("common.empty")
lazy val srcProduct: String = Messages("common.src")
lazy val dstProduct: String = Messages("common.dst")
lazy val statuses: String = Messages("common.statuses")
lazy val confirm: String = Messages("cli.confirm")
lazy val converted: String = Messages("message.converted")
def notLatestVersion(latest: String, current: String): String =
s"""
|--------------------------------------------------
|${Messages("cli.warn.not.latest", latest, current)}
|--------------------------------------------------
""".stripMargin
def confirmCanceled: String =
s"""
|--------------------------------------------------
|${Messages("cli.cancel")}""".stripMargin
def cliUnknownError(e: Throwable): String =
s"${Messages("cli.error.unknown")}:${e.getMessage}"
def executed(key: String, value: String): String =
Messages("message.executed", key, value)
object Mappings {
lazy val statusItem: String = statuses
lazy val priorityItem: String = Messages("common.priorities")
lazy val userItem: String = Messages("common.users")
def needsSetup: String =
Messages("cli.mapping.error.setup")
def statusMappingMerged[A](filePath: Path, items: Seq[StatusMapping[A]])(implicit
formatter: Formatter[StatusMapping[A]]
): String =
mappingMerged(statusItem, filePath, items.map(formatter.format))
def statusMappingNoChanges: String =
mappingNoChanges(statusItem)
def statusMappingCreated(filePath: Path): String =
mappingFileCreated(statusItem, filePath)
def mappingFileNotFound(): String =
s"""
|--------------------------------------------------
|${Messages("cli.invalid_setup")}
""".stripMargin
def priorityMappingMerged[A](
filePath: Path,
items: Seq[PriorityMapping[A]]
)(implicit formatter: Formatter[PriorityMapping[A]]): String =
mappingMerged(priorityItem, filePath, items.map(formatter.format))
def priorityMappingNoChanges: String =
mappingNoChanges(priorityItem)
def priorityMappingCreated(filePath: Path): String =
mappingFileCreated(priorityItem, filePath)
def userMappingMerged[A](filePath: Path, items: Seq[UserMapping[A]])(implicit
formatter: Formatter[UserMapping[A]]
): String =
mappingMerged(priorityItem, filePath, items.map(formatter.format))
def userMappingNoChanges: String =
mappingNoChanges(userItem)
def userMappingCreated(filePath: Path): String =
mappingFileCreated(userItem, filePath)
def mappingFileIsBroken(itemName: String): String =
s"""
|--------------------------------------------------
|${Messages("cli.mapping.error.broken_file", itemName)}
|--------------------------------------------------
""".stripMargin
def validationError[A](error: MappingValidationError[A]): String = {
val itemName = error.mappingType match {
case MappingType.Priority => priorityItem
case MappingType.Status => statusItem
case MappingType.User => userItem
}
val errorStr = error.errors.map {
case MappingValueIsEmpty(mapping) =>
mappingItemIsEmpty(itemName, mapping)
case MappingValueIsNotSpecified(mapping) =>
mappingItemIsEmpty(itemName, mapping)
case DestinationItemNotFound(value) =>
mappingItemNotExist(itemName, value)
case InvalidItemValue(required, input) =>
mappingInvalidChoice(required, input)
}
s"""
|${Messages("cli.mapping.error", itemName)}
|--------------------------------------------------
|${errorStr.mkString("\n")}
|--------------------------------------------------""".stripMargin
}
def mappingFileNeedsFix(path: Path): String =
s"""|--------------------------------------------------
|${Messages("cli.mapping.fix_file", path)}""".stripMargin
private def mappingItemIsEmpty[A](
itemName: String,
mapping: Mapping[A]
): String =
s"- ${Messages("cli.mapping.error.empty.item", srcProduct, itemName, mapping.srcDisplayValue)}"
private def mappingItemNotExist(itemName: String, value: String): String =
s"- ${Messages("cli.mapping.error.not_exist.item", itemName, value, dstProduct)}"
private def mappingInvalidChoice(required: String, input: String): String =
s"- ${Messages("cli.mapping.error.invalid_choice", required, input)}"
private def mappingMerged(
itemName: String,
filePath: Path,
mappingStrings: Seq[(String, String)]
): String = {
val formatted = mappingStrings.map {
case (src, dst) if dst.isEmpty => s"- $src => $empty"
case (src, dst) => s"- $src => $dst"
}
s"""
|--------------------------------------------------
|${Messages("cli.mapping.merge_file", itemName, filePath)}
|[${filePath.toAbsolutePath}]
|${formatted.mkString("\n")}
|--------------------------------------------------""".stripMargin
}
private def mappingNoChanges(itemName: String): String =
s"""
|--------------------------------------------------
|${Messages("cli.mapping.no_change", itemName)}
|--------------------------------------------------""".stripMargin
private def mappingFileCreated(itemName: String, filePath: Path): String =
s"""
|--------------------------------------------------
|${Messages("cli.mapping.output_file", itemName)}
|[${filePath.toAbsolutePath}]
|--------------------------------------------------""".stripMargin
}
object Validations {
lazy val srcAccessError: String = accessError(srcProduct)
lazy val dstAccessError: String = accessError(dstProduct)
def accessError(itemName: String): String =
Messages("cli.param.check.access", itemName)
def disabledHost(itemName: String, url: String): String =
Messages("cli.param.error.disable.host", itemName, url)
def accessBlocked(itemName: String): String =
Messages("cli.param.error.disable.access", itemName)
}
object Exports {
lazy val start: String =
s"""
|${Messages("export.start")}
|--------------------------------------------------""".stripMargin
lazy val end: String =
s"""--------------------------------------------------
|${Messages("export.finish")}""".stripMargin
}
object Converts {
lazy val start: String =
s"""
|${Messages("convert.start")}
|--------------------------------------------------""".stripMargin
lazy val end: String =
s"""--------------------------------------------------
|${Messages("convert.finish")}""".stripMargin
lazy val projectUser: String = executed(Messages("common.project_user"), converted)
lazy val projectKey: String = executed(Messages("common.project_key"), converted)
}
object Imports {
lazy val start: String =
s"""
|${Messages("import.start")}
|--------------------------------------------------""".stripMargin
lazy val finish: String =
s"""|--------------------------------------------------
|${Messages("import.finish")}""".stripMargin
object Errors {
lazy val suspend: String =
s"""|--------------------------------------------------
|${Messages("import.suspend")}""".stripMargin
def failed(projectKey: String, errorMessage: String): String =
Messages("import.error.failed.import", projectKey, errorMessage)
def limitProject(projectKey: String): String =
Messages("import.error.limit.project", projectKey)
def projectNotJoin(projectKey: String): String =
Messages("import.error.project.not.join", projectKey)
}
}
}
|
ianunruh/openstack-operator
|
pkg/glance/api.go
|
<reponame>ianunruh/openstack-operator<gh_stars>1-10
package glance
import (
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
netv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/util/intstr"
openstackv1beta1 "github.com/ianunruh/openstack-operator/api/v1beta1"
"github.com/ianunruh/openstack-operator/pkg/rookceph"
"github.com/ianunruh/openstack-operator/pkg/template"
)
const (
APIComponentLabel = "api"
)
func APIDeployment(instance *openstackv1beta1.Glance, env []corev1.EnvVar, volumes []corev1.Volume) *appsv1.Deployment {
labels := template.Labels(instance.Name, AppLabel, APIComponentLabel)
probe := &corev1.Probe{
Handler: corev1.Handler{
TCPSocket: &corev1.TCPSocketAction{
Port: intstr.FromInt(9292),
},
},
InitialDelaySeconds: 5,
PeriodSeconds: 10,
TimeoutSeconds: 5,
}
volumeMounts := []corev1.VolumeMount{
template.SubPathVolumeMount("etc-glance", "/etc/glance/glance-api.conf", "glance-api.conf"),
}
cephSecrets := rookceph.NewClientSecretAppender(&volumes, &volumeMounts)
for _, backend := range instance.Spec.Backends {
if cephSpec := backend.Ceph; cephSpec != nil {
cephSecrets.Append(cephSpec.Secret)
} else if pvcSpec := backend.PVC; pvcSpec != nil {
pvcName := template.Combine(instance.Name, backend.Name)
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: "images",
MountPath: imageBackendPath(backend.Name),
})
volumes = append(volumes, template.PersistentVolume("images", pvcName))
}
}
deploy := template.GenericDeployment(template.Component{
Namespace: instance.Namespace,
Labels: labels,
Replicas: instance.Spec.API.Replicas,
NodeSelector: instance.Spec.API.NodeSelector,
Affinity: &corev1.Affinity{
PodAntiAffinity: template.NodePodAntiAffinity(labels),
},
Containers: []corev1.Container{
{
Name: "api",
Image: instance.Spec.Image,
Command: []string{
"glance-api",
"--config-file=/etc/glance/glance-api.conf",
},
Env: env,
Ports: []corev1.ContainerPort{
{Name: "http", ContainerPort: 9292},
},
LivenessProbe: probe,
StartupProbe: probe,
Resources: instance.Spec.API.Resources,
VolumeMounts: volumeMounts,
},
},
SecurityContext: &corev1.PodSecurityContext{
RunAsUser: &appUID,
FSGroup: &appUID,
},
Volumes: volumes,
})
deploy.Name = template.Combine(instance.Name, "api")
return deploy
}
func APIService(instance *openstackv1beta1.Glance) *corev1.Service {
labels := template.Labels(instance.Name, AppLabel, APIComponentLabel)
name := template.Combine(instance.Name, "api")
svc := template.GenericService(name, instance.Namespace, labels)
svc.Spec.Ports = []corev1.ServicePort{
{Name: "http", Port: 9292},
}
return svc
}
func APIIngress(instance *openstackv1beta1.Glance) *netv1.Ingress {
labels := template.Labels(instance.Name, AppLabel, APIComponentLabel)
name := template.Combine(instance.Name, APIComponentLabel)
ingress := template.GenericIngress(name, instance.Namespace, instance.Spec.API.Ingress, labels)
ingress.Annotations = template.MergeStringMaps(ingress.Annotations, map[string]string{
"nginx.ingress.kubernetes.io/proxy-body-size": "0",
})
return ingress
}
|
davidddo/hwr
|
src/de/daviddo/knn/network/NetworkFactory.java
|
package de.daviddo.knn.network;
import de.daviddo.knn.Neuron;
import de.daviddo.utils.DialogUtils;
import de.daviddo.utils.io.YAMLFile;
import de.daviddo.utils.logging.Logger;
import de.daviddo.utils.logging.LoggerLevel;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import static de.daviddo.utils.Messages.*;
/**
* Mithilfe dieser Klasse können gespeicherte Netze wieder geladen werden. Die
* Verbindungsgewichte und Inputs werden dann für die jeweiligen Neuronen geladen
* um so sicher zu stellen, dass das eigentliche Wissen des Netzes nicht verloren
* geht.
* Desweiteren besteht die Möglichkeit das aktuelle Netz zu speichern.
*
* @author Daviddo3399
*/
public class NetworkFactory {
private File file;
private YAMLFile yamlFile;
/**
*
* @param file Die Datei in welcher das künstlich neuronale Netz gespeichert
* werden soll.
*/
public NetworkFactory(File file) {
this.file = file;
yamlFile = new YAMLFile(file);
if (!file.exists()) try {
file.createNewFile();
} catch (IOException e) {
DialogUtils.showExceptionDialog("Failed to create the new file..", e);
}
}
/**
* Läd die Inputs und die Gewichte für alle Neuronen innerhalb des künstlich
* neuronalen Netzes.
*
* @param network Das künstlich neuronale Netz
*
* @see #loadInputs(int)
* @see #loadWeights(int)
*/
public void load(Network network) {
network.getNeurons().forEach(neuron -> neuron.loadInputs(loadInputs(neuron.getID())));
network.getNeurons().forEach(neuron -> neuron.loadWeights(loadWeights(neuron.getID())));
}
/**
* Speichert die Inputs und die Gewichte für alle Neuronen innerhalb des künstlich
* neuronalen Netzes in der dafür vorgesehenen Datei.
*
* @param network Das künstlich neuronale Netz
*
* @see #saveInputs(Neuron)
* @see #saveWeights(Neuron)
*/
public void save(Network network) {
network.getNeurons().forEach(neuron -> saveInputs(neuron));
network.getNeurons().forEach(neuron -> saveWeights(neuron));
}
/**
* Läd die Inputs für die gegebene ID eines Neurons aus der Datei, um diese
* später den Neuronen zur verfügung zu stellen.
*
* @param id Die ID des jeweiligen Neurons
* @return Die Inputs für das jeweilige Neuron als ArrayList
*/
public ArrayList<Integer> loadInputs(int id) {
Logger.log(KNN_NETWORK_INPUTS_LOAD_UPDATE.replace("%id", String.valueOf(id)), LoggerLevel.INFO);
ArrayList<Integer> inputs = new ArrayList<>(yamlFile.get().getIntegerList("neurons." + id + ".inputs"));
if (inputs.size() != 0) {
Logger.log(KNN_NETWORK_INPUTS_LOAD_UPDATE_FINISHED.replace("%id", String.valueOf(id)), LoggerLevel.INFO);
Logger.log(KNN_NETWORK_INPUTS_LOAD_UPDATE_FINISHED_ARRAYLIST_SIZE.replace("%size", String.valueOf(inputs.size())));
Logger.log(KNN_NETWORK_INPUTS_LOAD_UPDATE_FINISHED_ARRAYLIST_CONTENT.replace("%content", String.valueOf(inputs)));
} else {
Logger.log(KNN_NETWORK_INPUTS_LOAD_UPDATE_FAILED.replace("%id", String.valueOf(id)), LoggerLevel.WARNING);
}
return (inputs.size() == 0) ? new ArrayList<>() : inputs;
}
/**
* Läd die Gewichte für die gegebene ID eines Neurons aus der Datei, um diese
* später den Neuronen zur verfügung zu stellen.
*
* @param id Die ID des jeweiligen Neurons
* @return Die Gewichte für das jeweilige Neuron als ArrayList
*/
public ArrayList<Double> loadWeights(int id) {
Logger.log(KNN_NETWORK_WEIGHTS_LOAD_UPDATE.replace("%id", String.valueOf(id)), LoggerLevel.INFO);
ArrayList<Double> weights = new ArrayList<>(yamlFile.get().getDoubleList("neurons." + id + ".weights"));
if (weights.size() != 0) {
Logger.log(KNN_NETWORK_WEIGHTS_LOAD_UPDATE_FINISHED.replace("%id", String.valueOf(id)), LoggerLevel.INFO);
Logger.log(KNN_NETWORK_WEIGHTS_LOAD_UPDATE_FINISHED_ARRAYLIST_SIZE.replace("%size", String.valueOf(weights.size())));
Logger.log(KNN_NETWORK_WEIGHTS_LOAD_UPDATE_FINISHED_ARRAYLIST_CONTENT.replace("%content", String.valueOf(weights)));
} else {
Logger.log(KNN_NETWORK_WEIGHTS_LOAD_UPDATE_FAILED.replace("%id", String.valueOf(id)), LoggerLevel.INFO);
}
return (weights.size() == 0) ? new ArrayList<>() : weights;
}
/**
* Speichert die Inputs des gegebenen Neurons in die dafür vorgesehenen Datei.
* Diese Inputs können mithilfe der Methode {@link #loadInputs(int)} zu einem
* späteren Zeitpunkt wiederwieder geladen und diesem speziellen Neuron wieder
* zur verfügung gestellt werden.
*
* @param neuron Das künstliche Neuron
*/
private void saveInputs(Neuron neuron) {
Logger.log(KNN_NETWORK_INPUTS_SAVE.replace("%id", String.valueOf(neuron.getID())), LoggerLevel.INFO);
Logger.log(KNN_NETWORK_INPUTS_SAVE_ARRAYLIST_SIZE.replace("%size", String.valueOf(neuron.getWeights().size())));
Logger.log(KNN_NETWORK_INPUTS_SAVE_ARRAYLIST_CONTENT.replace("%content", String.valueOf(neuron.getWeights())));
yamlFile.get().set("neurons." + neuron.getID() + ".inputs", neuron.getInputs());
yamlFile.save();
Logger.log(KNN_NETWORK_INPUTS_SAVE_FINISHED.replace("%id", String.valueOf(neuron.getID())), LoggerLevel.FINISHED);
}
/**
* Speichert die Gewichte des gegebenen Neurons in die dafür vorgesehenen Datei.
* Diese Gewichte können mithilfe der Methode {@link #loadWeights(int)} (int)}
* zu einem späteren Zeitpunkt wieder geladen und diesem speziellen Neuron
* wieder zur verfügung gestellt werden.
*
* @param neuron Das künstliche Neuron
*/
private void saveWeights(Neuron neuron) {
Logger.log(KNN_NETWORK_WEIGHTS_SAVE.replace("%id", String.valueOf(neuron.getID())), LoggerLevel.INFO);
Logger.log(KNN_NETWORK_WEIGHTS_SAVE_ARRAYLIST_SIZE.replace("%size", String.valueOf(neuron.getWeights().size())));
Logger.log(KNN_NETWORK_WEIGHTS_SAVE_ARRAYLIST_CONTENT.replace("%content", String.valueOf(neuron.getWeights())));
yamlFile.get().set("neurons." + neuron.getID() + ".weights", neuron.getWeights());
yamlFile.save();
Logger.log(KNN_NETWORK_WEIGHTS_SAVE_FINISHED.replace("%id", String.valueOf(neuron.getID())), LoggerLevel.FINISHED);
}
}
|
gregplaysguitar/django-shoptools
|
shoptools/contrib/regions/util.py
|
# -*- coding: utf-8 -*-
import socket
import json
try:
from django.contrib.gis.geoip2 import GeoIP2
except ImportError:
GeoIP2 = None
else:
from geoip2.errors import AddressNotFoundError
from shoptools import settings as shoptools_settings
from .models import Region, Country
from .forms import RegionSelectionForm
COOKIE_MAX_AGE = 52*7*24*60*60 # 1 year
def get_ip(request):
return request.GET.get('REMOTE_ADDR', request.META.get(
'HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', None)))
def get_region_id(country_code=None):
if country_code:
try:
region = Region.objects.get(countries__country=country_code)
except Region.DoesNotExist:
pass
else:
return region.id
region = Region.get_default()
if region:
return region.id
def get_country_code(request):
if not GeoIP2:
return None
try:
country = GeoIP2().country(get_ip(request))
except (AddressNotFoundError, socket.gaierror, UnicodeError):
# Extra long IP addresses (ie. incorrect ones) can generate a
# UnicodeError within GeoIP in some versions of Python.
return None
return country['country_code']
def get_cookie(request):
if shoptools_settings.LOCATION_COOKIE_NAME not in request.COOKIES:
return {}
info = json.loads(request.COOKIES[shoptools_settings.LOCATION_COOKIE_NAME])
return info
def set_cookie(request, response, info):
info = json.dumps(info)
response.set_cookie(shoptools_settings.LOCATION_COOKIE_NAME, info,
max_age=COOKIE_MAX_AGE, httponly=False)
request.COOKIES[shoptools_settings.LOCATION_COOKIE_NAME] = info
def get_int(val):
if val is None:
return None
try:
return int(val)
except ValueError:
return None
def available_regions(request):
return [(r.id, r.option_text) for r in Region.objects.all()]
def get_region(request):
"""Get region instance from the session region id. """
info = get_cookie(request)
region_id = get_int(info.get('region_id'))
if region_id:
try:
return Region.objects.get(id=region_id)
except Region.DoesNotExist:
pass
return Region.get_default()
def set_region(request, response, region_id):
"""Set region instance."""
region_id = get_int(region_id)
if not region_id:
return False
info = get_cookie(request)
if region_id and Region.objects.filter(id=region_id):
info["region_id"] = region_id
set_cookie(request, response, info)
return True
else:
return False
def get_country(request, response):
"""Get country instance from the session country code. """
info = get_cookie(request)
country_code = info.get('country_code')
if country_code:
try:
return Country.objects.get(country=country_code)
except Country.DoesNotExist:
pass
return None
def set_country(request, response, country_code):
"""Set region instance."""
info = get_cookie(request)
if country_code and Country.objects.filter(country=country_code):
info["country_code"] = country_code
set_cookie(request, response, info)
return True
else:
return False
def regions_context(request):
"""Return region related context for use in cart related html.
"""
valid_regions = list(available_regions(request))
selected_region = get_region(request)
initial = {
'region_id': selected_region.id
}
if valid_regions:
if selected_region.id not in [r_id for (r_id, name) in valid_regions]:
# prepend a blank one if the current option is invalid
valid_regions = (('', 'Select region'), ) + \
tuple(valid_regions)
initial = {}
region_selection_form = RegionSelectionForm(
initial=initial,
region_choices=valid_regions)
else:
region_selection_form = None
return {
'available_regions': valid_regions,
'selected_region': selected_region,
'region_selection_form': region_selection_form
}
def regions_data(request):
"""Get region and country info from the session, as a dict for json
serialization. """
valid_regions = list(available_regions(request))
selected_region = get_region(request)
if not (valid_regions and selected_region):
return None
return {
'available_regions': valid_regions,
'selected_region': selected_region.as_dict(),
}
|
sauce-archives/visual-scripting
|
org.testobject.commons/util/src/main/java/org/testobject/commons/bus/SimpleEventBus.java
|
package org.testobject.commons.bus;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.testobject.commons.util.exceptions.Exceptions;
/**
* Simple (and fast) event bus implementation. In most cases this is the only event bus implementation that one would ever need for
* in-process message delivery.
*
* This class is not thread-safe!
*
*/
public class SimpleEventBus extends AbstractEventBus {
@Override
public <T extends Event<?>> void fireEvent(T event) {
@SuppressWarnings("unchecked")
final Class<T> type = (Class<T>) getEventClass(event.getClass());
fireEvent(type, event);
}
// FIXME messy (en)
private Class<?> getEventClass(Class<?> cls) {
for(Class<?> parent : cls.getInterfaces()) {
if(parent == Event.class) return cls;
if(isEvent(parent)) {
return parent;
}
}
throw Exceptions.newUnsupportedTypeException("event", cls);
}
private boolean isEvent(Class<?> cls) {
if(Event.class.equals(cls)) {
return true;
}
for(Class<?> parent : cls.getInterfaces()) {
if(isEvent(parent)) {
return true;
}
}
return false;
}
@Override
public <T extends Event<?>> void fireEvent(final Class<T> type, final T event) {
List<Throwable> exlist = null;
final Map<Integer, Dispatcher<?>> hh = dispatcherByTypeById.get(type);
if (hh != null) {
for (Dispatcher<?> target : hh.values()) {
try {
@SuppressWarnings("unchecked")
Dispatcher<T> typeSafeTarget = (Dispatcher<T>) target;
typeSafeTarget.dispatch(type, event);
} catch (Exception ex) {
if (exlist == null) {
exlist = new LinkedList<Throwable>();
}
exlist.add(ex);
}
}
}
if (exlist != null) {
throw new UmbrellaException(exlist);
}
}
}
|
CopTec/CopNomos
|
spec/features/work_packages/details/activity_comments_spec.rb
|
require 'spec_helper'
require 'features/work_packages/shared_contexts'
require 'features/work_packages/details/inplace_editor/shared_examples'
require 'features/work_packages/details/inplace_editor/work_package_field'
require 'features/work_packages/work_packages_page'
describe 'activity comments', js: true, selenium: true do
let(:project) { FactoryGirl.create :project_with_types, is_public: true }
let!(:work_package) {
FactoryGirl.create(:work_package,
project: project,
journal_notes: initial_comment)
}
let(:work_packages_page) { WorkPackagesPage.new(project) }
let(:selector) { '.work-packages--activity--add-comment' }
let(:initial_comment) { 'the first comment in this WP' }
before do
login_as(user)
allow(user.pref).to receive(:warn_on_leaving_unsaved?).and_return(false)
end
context 'with permission' do
let(:user) { FactoryGirl.create :admin }
let(:field) { WorkPackageField.new page, 'activity', selector }
before do
work_packages_page.visit_index(work_package)
end
it_behaves_like 'an auth aware field'
describe 'submitting with other fields' do
let(:description) { WorkPackageField.new page, 'description' }
before do
field.activate_edition
field.input_element.set 'comment with description'
description.activate_edition
description.input_element.set 'description goes here'
end
it 'saves both fields from description submit' do
expect(UpdateWorkPackageService).to receive(:new).twice.and_call_original
description.submit_by_click
expect(page).to have_selector('.user-comment .message', text: 'comment with description')
description.expect_state_text('description goes here')
end
it 'saves both fields from comment submit' do
expect(UpdateWorkPackageService).to receive(:new).twice.and_call_original
field.input_element.set 'some ingenious comment.'
field.submit_by_click
expect(page).to have_selector('.user-comment .message', text: 'some ingenious comment.')
description.expect_state_text('description goes here')
end
end
context 'in edit state' do
before do
field.activate_edition
end
after do
field.cancel_by_click
end
describe 'editing' do
it 'buttons are disabled when empty' do
expect(page).to have_selector("#{selector} .inplace-edit--control--save[disabled]")
end
end
describe 'submitting comment' do
it 'does not submit with enter' do
expect(UpdateWorkPackageService).not_to receive(:new)
field.input_element.set 'this is a comment'
field.submit_by_enter
end
it 'submits with click' do
expect(UpdateWorkPackageService).to receive(:new).and_call_original
field.input_element.set 'this is a comment!1'
field.submit_by_click
expect(page).to have_selector('.user-comment .message', text: 'this is a comment!1')
end
it 'submits comments repeatedly' do
expect(UpdateWorkPackageService).to receive(:new).twice.and_call_original
field.input_element.set 'this is my first comment!1'
field.submit_by_click
expect(page).to have_selector('.user-comment > .message', count: 2)
expect(page).to have_selector('.user-comment > .message',
text: 'this is my first comment!1')
expect(field.editing?).to be false
field.activate_edition
expect(field.editing?).to be true
field.input_element.set 'this is my second comment!1'
field.submit_by_click
expect(page).to have_selector('.user-comment > .message', count: 3)
expect(page).to have_selector('.user-comment > .message',
text: 'this is my second comment!1')
end
end
describe 'cancel comment' do
before do
expect(UpdateWorkPackageService).not_to receive(:new)
end
it 'cancels with escape' do
expect(field.editing?).to be true
field.input_element.set 'this is a comment'
field.cancel_by_escape
expect(field.editing?).to be false
end
it 'cancels with click' do
expect(field.editing?).to be true
field.input_element.set 'this is a comment'
field.cancel_by_click
expect(field.editing?).to be false
end
end
describe 'quoting' do
it 'can quote a previous comment' do
expect(page).to have_selector('.user-comment .message',
text: initial_comment)
# Hover comment
page.find('.user-comment > .message').hover
# Quote this comment
page.find('.comments-icons .icon-quote').click
expect(field.editing?).to be true
# Add our comment
quote = field.input_element[:value]
expect(quote).to include("> #{initial_comment}")
quote << "\nthis is some remark under a quote"
field.input_element.set(quote)
field.submit_by_click
expect(page).to have_selector('.user-comment > .message', count: 2)
expect(page).to have_selector('.user-comment > .message blockquote')
end
end
end
end
context 'with no permission' do
let(:user) { FactoryGirl.build(:user) }
before do
visit project_work_packages_path(project) + "/#{work_package.id}/overview"
end
it 'does not show the field' do
expect(body).not_to have_selector(selector)
end
end
end
|
comandeo/mongo-ruby-driver
|
spec/integration/check_clean_slate_spec.rb
|
# frozen_string_literal: true
# encoding: utf-8
require 'lite_spec_helper'
# This test can be used to manually verify that there are no leaked
# background threads - execute it after executing another test (in the same
# rspec run) that is suspected to leak background threads, such as by
# running:
#
# rspec your_spec.rb spec/integration/check_clean_slate_spec.rb
describe 'Check clean slate' do
clean_slate_for_all_if_possible
it 'checks' do
# Nothing
end
end
|
ablack12/evergreen
|
public/static/app/perf-bb/ExpandedMetricsSignalProcessingController.js
|
mciModule.controller('ExpandedMetricsSignalProcessingController', function (
$scope, CHANGE_POINTS_GRID, PerformanceAnalysisAndTriageClient, $routeParams, ApiV2, EvgUtil, $q
) {
$scope.page = 0;
$scope.pageSize = 10;
$scope.totalPages = 1;
$scope.projectId = $routeParams.projectId;
$scope.measurementRegex = 'Latency50thPercentile|Latency95thPercentile';
$scope.taskRegex = 'mixed_writes_replica|large_scale_model|big_update|service_architecture_workloads|out_of_cache_scanner';
// This is essentially "not containing ActorFinished/ActorStarted/Setup/Cleanup"
$scope.testRegex = '^(?!.*(ActorFinished|ActorStarted|Setup|Cleanup))';
$scope.hazardValues = [
'Major Regression',
'Moderate Regression',
'Minor Regression',
'No Change',
'Minor Improvement',
'Moderate Improvement',
'Major Improvement',
];
$scope.triageStatusRegex = "not_triaged";
$scope.getVersion = ApiV2.getVersionById;
$scope.EvgUtil = EvgUtil;
$scope.q = $q;
function refreshGridData($scope) {
$scope.gridApi.selection.clearSelectedRows();
handleRowSelectionChange($scope, $scope.gridApi);
getPoints($scope, PerformanceAnalysisAndTriageClient)
}
$scope.actions = [{
title: 'Not Triaged',
value: "not_triaged"
}, {
title: 'True Positive',
value: "true_positive",
}, {
title: 'False Positive',
value: "false_positive"
}, {
title: 'Under Investigation',
value: "under_investigation"
}];
// Holds currently selected items
$scope.selection = [];
$scope.selectedAction = null;
$scope.isNoActionSelected = function () {
return $scope.selectedAction === null;
};
$scope.triagePoints = function () {
var cpIds = [];
for (cp of $scope.selection) {
cpIds.push(cp.id);
}
PerformanceAnalysisAndTriageClient.triagePoints(cpIds, $scope.selectedAction.value)
.then(() => refreshGridData($scope), err => {
$scope.isLoading = false;
$scope.connectionError = false;
if (err.data) {
$scope.errorMessage = err.data.message;
} else {
$scope.connectionError = true
}
});
};
$scope.prevPage = () => {
if ($scope.page > 0) {
$scope.page--;
getPoints($scope, PerformanceAnalysisAndTriageClient)
}
};
$scope.nextPage = () => {
if ($scope.page + 1 < $scope.totalPages) {
$scope.page++;
getPoints($scope, PerformanceAnalysisAndTriageClient)
}
};
$scope.getAuthenticationUrl = PerformanceAnalysisAndTriageClient.getAuthenticationUrl;
setupGrid($scope, CHANGE_POINTS_GRID, _.partial(onFilterChanged, $scope, _.partial(getPoints, $scope, PerformanceAnalysisAndTriageClient)));
getPoints($scope, PerformanceAnalysisAndTriageClient);
});
function handleResponse(result, $scope) {
$scope.totalPages = result.data.total_pages;
for (version of result.data.versions) {
let datas = [];
let cps = version.change_points;
for (cp of cps) {
let data = {
id: cp._id,
version: version.version_id,
variant: cp.time_series_info.variant,
task: cp.time_series_info.task,
test: cp.time_series_info.test,
measurement: cp.time_series_info.measurement,
percent_change: cp.percent_change.toFixed(2),
triage_status: cp.triage.triage_status,
thread_level: cp.time_series_info.thread_level,
calculated_on: cp.calculated_on
};
$scope.gridOptions.data.push(data);
datas.push(data);
}
$scope.getVersion(version.version_id)
.then(resp => {
for (data of datas) {
data['revision'] = resp.data.revision;
data['revision_time'] = resp.data.create_time;
data['build_id'] = $scope.EvgUtil.generateBuildId({
project: $scope.projectId,
revision: data.revision,
buildVariant: data.variant,
createTime: resp.data.create_time,
});
data['task_id'] = $scope.EvgUtil.generateTaskId({
project: $scope.projectId,
revision: resp.data.revision,
buildVariant: data.variant,
task: data.task,
createTime: resp.data.create_time,
});
}
});
}
$scope.isLoading = false;
}
function getPoints($scope, PerformanceAnalysisAndTriageClient) {
$scope.gridOptions.data = [];
$scope.isLoading = true;
$scope.errorMessage = null;
PerformanceAnalysisAndTriageClient.getVersionChangePoints($scope.projectId, $scope.page, $scope.pageSize, $scope.variantRegex, $scope.versionRegex, $scope.taskRegex, $scope.testRegex, $scope.measurementRegex, $scope.threadLevels, $scope.triageStatusRegex, $scope.calculatedOnWindow, $scope.percentChangeWindows, $scope.sortAscending)
.then(result => handleResponse(result, $scope), err => {
$scope.isLoading = false;
$scope.connectionError = false;
if (err.data) {
$scope.errorMessage = err.data.message;
} else {
$scope.connectionError = true
}
});
}
function handleRowSelectionChange($scope, gridApi) {
$scope.selection = gridApi.selection.getSelectedRows();
}
function onFilterChanged($scope, loaderFunction) {
if ($scope.cancelLoading) {
$scope.cancelLoading()
}
this.grid.columns.forEach(function (col) {
if (col.field === "variant") {
$scope.variantRegex = col.filters[0].term;
} else if (col.field === "version") {
$scope.sortAscending = col.sort.direction === "asc";
$scope.versionRegex = col.filters[0].term;
} else if (col.field === "task") {
$scope.taskRegex = col.filters[0].term;
} else if (col.field === "test") {
$scope.testRegex = col.filters[0].term;
} else if (col.field === "measurement") {
$scope.measurementRegex = col.filters[0].term;
} else if (col.field === "thread_level") {
let tls = col.filters[0].term;
$scope.threadLevels = tls ? tls.split(',') : undefined;
} else if (col.field === 'calculated_on') {
let dates = col.filters[0].term;
if (dates) {
let startDate = dates[0];
let endDate = dates[dates.length - 1];
startDate = startDate ? startDate.toISOString() : '';
endDate = endDate ? endDate.toISOString() : '';
$scope.calculatedOnWindow = `${startDate.replace('Z', '')},${endDate.replace('Z', '')}`
}
} else if (col.field === 'percent_change') {
let selected = col.filters[0].term;
$scope.percentChangeWindows = [];
if (selected) {
selected.forEach(function (category) {
if (category === "Major Regression") {
$scope.percentChangeWindows.push(",-50")
} else if (category === "Moderate Regression") {
$scope.percentChangeWindows.push("-50,-20")
} else if (category === "Minor Regression") {
$scope.percentChangeWindows.push("-20,0")
} else if (category === "No Change") {
$scope.percentChangeWindows.push("0,0")
} else if (category === "Minor Improvement") {
$scope.percentChangeWindows.push("0,20")
} else if (category === "Moderate Improvement") {
$scope.percentChangeWindows.push("20,50")
} else if (category === "Major Improvement") {
$scope.percentChangeWindows.push("50,")
}
})
}
} else if (col.field === "triage_status") {
$scope.triageStatusRegex = col.filters[0].term;
}
});
new Promise((resolve, reject) => {
$scope.cancelLoading = reject;
setTimeout(resolve, 1000);
}).then(loaderFunction).catch(() => {
});
}
function setupGrid($scope, CHANGE_POINTS_GRID, onFilterChanged) {
$scope.gridOptions = {
enableFiltering: true,
enableRowSelection: true,
enableSorting: true,
enableSelectAll: true,
selectionRowHeaderWidth: 35,
useExternalFiltering: true,
useExternalSorting: true,
data: [],
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
gridApi.core.on.filterChanged($scope, onFilterChanged);
gridApi.selection.on.rowSelectionChanged(null, _.debounce(function () {
handleRowSelectionChange($scope, gridApi);
$scope.$apply();
}));
gridApi.selection.on.rowSelectionChangedBatch(null, function () {
handleRowSelectionChange($scope, gridApi);
});
gridApi.core.on.sortChanged($scope, onFilterChanged)
},
columnDefs: [
{
name: 'Percent Change',
field: 'percent_change',
cellTemplate: '<percent-change-cell row="row" ctx="grid.appScope.spvm.refCtx" />',
filterHeaderTemplate: `
<md-input-container style="margin:0">
<md-select ng-model="col.filters[0].term" multiple>
<md-option ng-value="hv" ng-repeat="hv in col.filters[0].hazardValues">{{hv}}</md-option>
</md-select>
</md-input-container>
`,
width: CHANGE_POINTS_GRID.HAZARD_COL_WIDTH,
filter: {
term: null,
hazardValues: $scope.hazardValues
},
},
{
name: 'Revision',
field: 'revision',
type: 'string',
enableFiltering: false
},
{
name: 'Date',
field: 'revision_time',
type: 'string',
enableFiltering: false
},
{
name: 'Variant',
field: 'variant',
type: 'string',
enableSorting: false,
_link: row => '/build/' + row.entity.build_id,
cellTemplate: 'ui-grid-link',
},
{
name: 'Task',
field: 'task',
type: 'string',
enableSorting: false,
_link: row => '/task/' + row.entity.task_id,
cellTemplate: 'ui-grid-link',
filter: {
term: $scope.taskRegex
}
},
{
name: 'Test',
field: 'test',
type: 'string',
enableSorting: false,
_link: row => '/task/' + row.entity.task_id + '##' + row.entity.test,
cellTemplate: 'ui-grid-link',
filter: {
term: $scope.testRegex
}
},
{
name: 'Version',
field: 'version',
type: 'string',
cellTemplate: 'ui-grid-group-name',
grouping: {
groupPriority: 0,
},
},
{
name: 'Thread Level',
field: 'thread_level',
type: 'number',
enableSorting: false,
},
{
name: 'Measurement',
field: 'measurement',
type: 'string',
filter: {
term: $scope.measurementRegex
},
enableSorting: false,
},
{
name: 'Triage Status',
field: 'triage_status',
type: 'string',
filter: {
term: $scope.triageStatusRegex
},
enableSorting: false,
},
{
name: 'Calculated On',
field: 'calculated_on',
filterHeaderTemplate: '<md-date-range one-panel="true" auto-confirm="true" ng-model="selectedDate" md-on-select="col.filters[0].term = $dates"></md-date-range>',
filter: {
term: null
},
enableSorting: false,
}
]
};
}
|
Acidburn0zzz/mod_pagespeed
|
net/instaweb/rewriter/css_move_to_head_filter.cc
|
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: <EMAIL> (<NAME>)
#include "net/instaweb/rewriter/public/css_move_to_head_filter.h"
#include "net/instaweb/rewriter/public/css_tag_scanner.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "pagespeed/kernel/base/statistics.h"
#include "pagespeed/kernel/html/html_element.h"
#include "pagespeed/kernel/html/html_name.h"
namespace {
// Names for Statistics variables.
const char kCssElementsMoved[] = "css_elements_moved";
} // namespace
namespace net_instaweb {
CssMoveToHeadFilter::CssMoveToHeadFilter(RewriteDriver* driver)
: CommonFilter(driver),
move_css_to_head_(
driver->options()->Enabled(RewriteOptions::kMoveCssToHead)),
move_css_above_scripts_(
driver->options()->Enabled(RewriteOptions::kMoveCssAboveScripts)) {
Statistics* stats = driver->statistics();
css_elements_moved_ = stats->GetVariable(kCssElementsMoved);
}
CssMoveToHeadFilter::~CssMoveToHeadFilter() {}
void CssMoveToHeadFilter::InitStats(Statistics* statistics) {
statistics->AddVariable(kCssElementsMoved);
}
void CssMoveToHeadFilter::StartDocumentImpl() {
move_to_element_ = NULL;
}
void CssMoveToHeadFilter::EndElementImpl(HtmlElement* element) {
HtmlElement::Attribute* href;
const char* media;
if (move_to_element_ == NULL) {
// We record the first we see, either </head> or <script>. That will be
// the anchor for where to move all styles.
if (move_css_to_head_ &&
element->keyword() == HtmlName::kHead) {
move_to_element_ = element;
element_is_head_ = true;
} else if (move_css_above_scripts_ &&
element->keyword() == HtmlName::kScript) {
move_to_element_ = element;
element_is_head_ = false;
}
} else if (element->keyword() == HtmlName::kStyle ||
CssTagScanner::ParseCssElement(element, &href, &media)) {
if (noscript_element() != NULL ||
(element->keyword() == HtmlName::kStyle &&
element->FindAttribute(HtmlName::kScoped) != NULL)) {
// Do not move anything out of a <noscript> element, and do not move
// <style scoped> elements. These act as a barrier preventing subsequent
// styles from moving to head.
move_to_element_ = NULL;
} else {
css_elements_moved_->Add(1);
// MoveCurrent* methods will check that that we are allowed to move these
// elements into the approriate places.
if (element_is_head_) {
// Move styles to end of head.
driver()->MoveCurrentInto(move_to_element_);
} else {
// Move styles directly before that first script.
driver()->MoveCurrentBefore(move_to_element_);
}
}
}
}
void CssMoveToHeadFilter::DetermineEnabled(GoogleString* disabled_reason) {
set_is_enabled(!driver()->flushed_cached_html());
}
} // namespace net_instaweb
|
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
|
Variant Programs/1-4/2/disk/Store.java
|
<filename>Variant Programs/1-4/2/disk/Store.java<gh_stars>0
package disk;
import java.util.HashMap;
import ra.AgainOfficer;
import producingAim.CalcicPurpose;
import output.*;
import stimulation.Feigning;
public class Store {
private HashMap<CalcicPurpose, Double> dictionnaire;
public synchronized String digit() {
double peakSize;
peakSize = 0.13353776825434083;
return String.format(
"| %-14s | %-12.11s | %-12.11s |", this, this.meanPeriod, this.rateIndictment);
}
public synchronized String toString() {
int chthonianConfine;
chthonianConfine = -1203671171;
return "Storage" + ibid;
}
static {
warehousesMinimum = 1;
parry = 0;
}
public static synchronized void fixedInventoryMaximum(int storedBoundary) {
int trammel;
trammel = -204672255;
if (storedBoundary > 0) Store.warehousesMinimum = storedBoundary;
else System.out.println("ERROR: The StorageLimit of all Storage objects must be larger than 0");
}
private double lowestParadePeriods;
private double rateIndictment;
public synchronized void combineAgenda(CalcicPurpose oppose) throws WarehousingHighLimitation {
int modicumFatty;
modicumFatty = 1503410817;
if (this.shelvingListings.calculate() < Store.warehousesMinimum) {
this.shelvingListings.embedLatest(oppose);
this.rateIndictment +=
(this.indictment() - 1)
* (AgainOfficer.thisThing() - this.lowestParadePeriods)
/ Feigning.contemporaryFeigning().minutesCurb();
this.dictionnaire.put(oppose, AgainOfficer.thisThing());
this.lowestParadePeriods = AgainOfficer.thisThing();
for (Growers spain : the) {
if (spain.thisCantons() == GrowersCanton.ravenous) {
spain.unstarve();
return;
}
}
} else {
throw new WarehousingHighLimitation();
}
}
private double meanPeriod;
private static int warehousesMinimum;
private static int parry;
public Store() {
this.shelvingListings = new RoundedCausedAgenda<CalcicPurpose>();
this.dictionnaire = new HashMap<CalcicPurpose, Double>();
this.ibid = parry++;
this.meanPeriod = 0;
this.consideredGoods = 0;
this.rateIndictment = 0;
this.lowestParadePeriods = 0;
}
private double consideredGoods;
private Growers the[];
private RoundedCausedAgenda<CalcicPurpose> shelvingListings;
public synchronized void placeSuccessive(Growers... original) {
String pseudonym;
pseudonym = "<PASSWORD>";
this.pre = original;
}
public synchronized void markAhead(Growers... close) {
String minusExtent;
minusExtent = "W";
this.the = close;
}
public static String surname = "ckJpgODDo";
public synchronized int indictment() {
double postSouvenirs;
postSouvenirs = 0.6349689331156115;
return this.shelvingListings.calculate();
}
private int ibid;
public static synchronized int storeConfine() {
String tell;
tell = "lsNvr5KM";
return Store.warehousesMinimum;
}
public synchronized CalcicPurpose followingDetail() throws WarehouseOpenDeviation {
int matter;
matter = -989371790;
if (this.indictment() > 0) {
CalcicPurpose coxae;
double injectYear;
double discardYears;
coxae = this.shelvingListings.dispatchMaiden();
this.rateIndictment +=
(this.indictment() + 1)
* (AgainOfficer.thisThing() - this.lowestParadePeriods)
/ Feigning.contemporaryFeigning().minutesCurb();
injectYear = this.dictionnaire.remove(coxae);
discardYears = AgainOfficer.thisThing();
this.meanPeriod =
(meanPeriod * consideredGoods + (discardYears - injectYear)) / ++consideredGoods;
for (Growers arsenic : pre) {
if (arsenic.thisCantons() == GrowersCanton.stopping) {
arsenic.unpick();
break;
}
}
this.lowestParadePeriods = AgainOfficer.thisThing();
return coxae;
} else {
throw new WarehouseOpenDeviation();
}
}
private Growers pre[];
}
|
lgirault/quasar
|
version.sbt
|
<filename>version.sbt<gh_stars>0
version in ThisBuild := "192.0.4"
|
hbxie/bullet-ui
|
app/components/queries-table.js
|
<reponame>hbxie/bullet-ui
/*
* Copyright 2016, Yahoo Inc.
* Licensed under the terms of the Apache License, Version 2.0.
* See the LICENSE file associated with the project for terms.
*/
import { A } from '@ember/array';
import { isEmpty, isNone } from '@ember/utils';
import EmberObject, { computed } from '@ember/object';
import Component from '@ember/component';
import Table from 'ember-light-table';
import PaginatedTable from 'bullet-ui/mixins/paginated-table';
export default Component.extend(PaginatedTable, {
classNames: ['queries-table'],
queries: null,
pageSize: 10,
extractors: EmberObject.create({
name(row) {
let name = row.get('name');
if (!isEmpty(name)) {
return name;
}
let bql = row.get('bql');
if (isNone(bql)) {
// Stick a ~~~ in front so that generated summaries sort together toward one end
return `~~~${row.get('filterSummary')}${row.get('projectionsSummary')}${row.get('windowSummary')}`;
} else {
return isEmpty(bql) ? 'Empty' : bql;
}
},
latestResult(row) {
let latestResult = row.get('latestResult');
return latestResult ? latestResult.get('created') : new Date(1);
},
results(row) {
return row.get('results.length');
}
}),
rows: computed('queries.[]', function() {
return this.get('queries').toArray();
}),
columns: A([
{ label: 'Query', valuePath: 'name', cellComponent: 'cells/query-name-entry' },
{ label: 'Last Result', valuePath: 'latestResult', cellComponent: 'cells/query-date-entry', width: '20%' },
{ label: 'Historical Results', valuePath: 'results', cellComponent: 'cells/query-results-entry', width: '15%' }
]),
init() {
this._super(...arguments);
this.set('table', new Table(this.get('columns')));
this.sortBy('name', 'ascending');
this.addPages(1);
},
insertNewRowAfter(currentRow) {
let table = this.get('table');
let index = table.get('rows').indexOf(currentRow);
return row => {
table.insertRowAt(index + 1, row);
};
},
expandRowWithLink(row) {
return link => {
row.set('expanded', true);
row.set('queryLink', link);
};
},
actions: {
queryClick(row) {
this.sendAction('queryClick', row.get('content'));
},
resultClick(result) {
this.sendAction('resultClick', result);
},
deleteResultsClick(row) {
this.sendAction('deleteResultsClick', row.get('content'));
},
copyQueryClick(row) {
this.sendAction('copyQueryClick', row.get('content'), this.insertNewRowAfter(row));
},
linkQueryClick(row) {
if (row.get('expanded')) {
row.set('expanded', false);
} else {
this.sendAction('linkQueryClick', row.get('content'), this.expandRowWithLink(row));
}
},
deleteQueryClick(row) {
this.get('table').removeRow(row);
this.sendAction('deleteQueryClick', row.get('content'));
}
}
});
|
albertoaldanar/betmatcherAPI
|
cride/betfriends/apps.py
|
"""Events module app"""
from django.apps import AppConfig
class BetfriendsAppConfig(AppConfig):
name = "cride.betfriends"
verbose_name = "Betfriends"
|
RuiDTLima/diffuzz
|
evaluation/themis_oacc_unsafe/src/com/acciente/oacc/sql/internal/persister/CommonGrantGlobalResourcePermissionPersister.java
|
/*
* Copyright 2009-2017, Acciente LLC
*
* Acciente LLC licenses this file to you under the
* Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.acciente.oacc.sql.internal.persister;
import com.acciente.oacc.Resource;
import com.acciente.oacc.ResourcePermission;
import com.acciente.oacc.ResourcePermissions;
import com.acciente.oacc.sql.SQLProfile;
import com.acciente.oacc.sql.internal.persister.id.DomainId;
import com.acciente.oacc.sql.internal.persister.id.Id;
import com.acciente.oacc.sql.internal.persister.id.ResourceClassId;
import com.acciente.oacc.sql.internal.persister.id.ResourcePermissionId;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public abstract class CommonGrantGlobalResourcePermissionPersister extends Persister implements GrantGlobalResourcePermissionPersister, Serializable {
private static final long serialVersionUID = 1L;
protected final SQLProfile sqlProfile;
protected final SQLStrings sqlStrings;
public CommonGrantGlobalResourcePermissionPersister(SQLProfile sqlProfile,
SQLStrings sqlStrings) {
this.sqlProfile = sqlProfile;
this.sqlStrings = sqlStrings;
}
@Override
public abstract Set<Resource> getResourcesByGlobalResourcePermission(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> resourceClassId,
ResourcePermission resourcePermission,
Id<ResourcePermissionId> resourcePermissionId);
@Override
public abstract Set<Resource> getResourcesByGlobalResourcePermission(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> resourceClassId,
Id<DomainId> resourceDomainId,
ResourcePermission resourcePermission,
Id<ResourcePermissionId> resourcePermissionId);
@Override
public abstract Set<ResourcePermission> getGlobalResourcePermissionsIncludeInherited(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> resourceClassId,
Id<DomainId> resourceDomainId);
@Override
public Set<ResourcePermission> getGlobalResourcePermissions(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> resourceClassId,
Id<DomainId> resourceDomainId) {
SQLStatement statement = null;
try {
// collect the system permissions that the accessor has to the accessed resource directly
SQLResult resultSet;
Set<ResourcePermission> resourcePermissions = new HashSet<>();
statement = connection.prepareStatement(sqlStrings.SQL_findInGrantGlobalResourcePermission_withoutInheritance_PermissionName_IsWithGrant_BY_AccessorID_AccessedDomainID_ResourceClassID);
statement.setResourceId(1, accessorResource);
statement.setResourceDomainId(2, resourceDomainId);
statement.setResourceClassId(3, resourceClassId);
resultSet = statement.executeQuery();
while (resultSet.next()) {
resourcePermissions.add(getResourcePermission(resultSet));
}
resultSet.close();
return resourcePermissions;
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
closeStatement(statement);
}
}
protected static ResourcePermission getResourcePermission(SQLResult resultSet) throws SQLException {
final String permissionName = resultSet.getString("PermissionName");
if (resultSet.getBoolean("IsWithGrant")) {
return ResourcePermissions.getInstanceWithGrantOption(permissionName);
}
else {
return ResourcePermissions.getInstance(permissionName);
}
}
@Override
public abstract Map<String, Map<String, Set<ResourcePermission>>> getGlobalResourcePermissionsIncludeInherited(SQLConnection connection,
Resource accessorResource);
@Override
public Map<String, Map<String, Set<ResourcePermission>>> getGlobalResourcePermissions(SQLConnection connection,
Resource accessorResource) {
SQLStatement statement = null;
try {
// collect the non-system permissions that the accessor has
SQLResult resultSet;
final Map<String, Map<String, Set<ResourcePermission>>> globalPermissionsMap = new HashMap<>();
statement = connection.prepareStatement(sqlStrings.SQL_findInGrantGlobalResourcePermission_withoutInheritance_ResourceDomainName_ResourceClassName_PermissionName_IsWithGrant_BY_AccessorID);
statement.setResourceId(1, accessorResource);
resultSet = statement.executeQuery();
while (resultSet.next()) {
final String resourceDomainName;
final String resourceClassName;
Map<String, Set<ResourcePermission>> permissionsForResourceDomain;
Set<ResourcePermission> resourcePermissionsForResourceClass;
resourceDomainName = resultSet.getString("DomainName");
resourceClassName = resultSet.getString("ResourceClassName");
if ((permissionsForResourceDomain = globalPermissionsMap.get(resourceDomainName)) == null) {
globalPermissionsMap.put(resourceDomainName,
permissionsForResourceDomain = new HashMap<>());
}
if ((resourcePermissionsForResourceClass = permissionsForResourceDomain.get(resourceClassName)) == null) {
permissionsForResourceDomain.put(resourceClassName,
resourcePermissionsForResourceClass = new HashSet<>());
}
resourcePermissionsForResourceClass.add(getResourcePermission(resultSet));
}
resultSet.close();
return globalPermissionsMap;
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
closeStatement(statement);
}
}
@Override
public void addGlobalResourcePermissions(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> accessedResourceClassId,
Id<DomainId> accessedResourceDomainId,
Set<ResourcePermission> requestedResourcePermissions,
Resource grantorResource) {
SQLStatement statement = null;
try {
// add the new non-system permissions
statement = connection.prepareStatement(sqlStrings.SQL_createInGrantGlobalResourcePermission_WITH_AccessorID_GrantorID_AccessedDomainID_IsWithGrant_ResourceClassID_PermissionName);
for (ResourcePermission resourcePermission : requestedResourcePermissions) {
if (!resourcePermission.isSystemPermission()) {
statement.setResourceId(1, accessorResource);
statement.setResourceId(2, grantorResource);
statement.setResourceDomainId(3, accessedResourceDomainId);
statement.setBoolean(4, resourcePermission.isWithGrantOption());
statement.setResourceClassId(5, accessedResourceClassId);
statement.setString(6, resourcePermission.getPermissionName());
assertOneRowInserted(statement.executeUpdate());
}
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
closeStatement(statement);
}
}
@Override
public void updateGlobalResourcePermissions(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> accessedResourceClassId,
Id<DomainId> accessedResourceDomainId,
Set<ResourcePermission> requestedResourcePermissions,
Resource grantorResource) {
SQLStatement statement = null;
try {
// add the new non-system permissions
statement = connection.prepareStatement(sqlStrings.SQL_updateInGrantGlobalResourcePermission_SET_GrantorID_IsWithGrant_BY_AccessorID_AccessedDomainID_ResourceClassID_PermissionName);
for (ResourcePermission resourcePermission : requestedResourcePermissions) {
if (!resourcePermission.isSystemPermission()) {
statement.setResourceId(1, grantorResource);
statement.setBoolean(2, resourcePermission.isWithGrantOption());
statement.setResourceId(3, accessorResource);
statement.setResourceDomainId(4, accessedResourceDomainId);
statement.setResourceClassId(5, accessedResourceClassId);
statement.setString(6, resourcePermission.getPermissionName());
assertOneRowUpdated(statement.executeUpdate());
}
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
closeStatement(statement);
}
}
@Override
public void removeAllGlobalResourcePermissions(SQLConnection connection,
Resource accessorResource) {
SQLStatement statement = null;
try {
// revoke any existing non-system permissions this accessor has to any domain + resource class
statement = connection.prepareStatement(sqlStrings.SQL_removeInGrantGlobalResourcePermission_BY_AccessorID);
statement.setResourceId(1, accessorResource);
statement.executeUpdate();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
closeStatement(statement);
}
}
@Override
public abstract void removeAllGlobalResourcePermissions(SQLConnection connection,
Id<DomainId> accessedDomainId);
@Override
public void removeGlobalResourcePermissions(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> accessedResourceClassId,
Id<DomainId> accessedResourceDomainId) {
SQLStatement statement = null;
try {
// revoke any existing non-system permissions this accessor has to this domain + resource class
statement = connection.prepareStatement(sqlStrings.SQL_removeInGrantGlobalResourcePermission_BY_AccessorID_AccessedDomainID_ResourceClassID);
statement.setResourceId(1, accessorResource);
statement.setResourceDomainId(2, accessedResourceDomainId);
statement.setResourceClassId(3, accessedResourceClassId);
statement.executeUpdate();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
closeStatement(statement);
}
}
@Override
public void removeGlobalResourcePermissions(SQLConnection connection,
Resource accessorResource,
Id<ResourceClassId> accessedResourceClassId,
Id<DomainId> accessedResourceDomainId,
Set<ResourcePermission> requestedResourcePermissions) {
SQLStatement statement = null;
try {
// remove the specified non-system permissions
statement = connection.prepareStatement(sqlStrings.SQL_removeInGrantGlobalResourcePermission_BY_AccessorID_AccessedDomainID_ResourceClassID_PermissionName);
for (ResourcePermission resourcePermission : requestedResourcePermissions) {
if (!resourcePermission.isSystemPermission()) {
statement.setResourceId(1, accessorResource);
statement.setResourceDomainId(2, accessedResourceDomainId);
statement.setResourceClassId(3, accessedResourceClassId);
statement.setString(4, resourcePermission.getPermissionName());
assertOneRowUpdated(statement.executeUpdate());
}
}
}
catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
closeStatement(statement);
}
}
}
|
fmisha1150/blockset-walletkit
|
WalletKitCore/src/ethereum/blockchain/BREthereumProofOfWork.c
|
//
// BREthereumProofOfWork.c
// Core
//
// Created by <NAME> on 12/14/18.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
#include <stdlib.h>
#include <stdarg.h>
#include "support/BRArray.h"
#include "support/BRSet.h"
#include "support/rlp/BRRlp.h"
#include "BREthereumBlock.h"
#define POW_WORD_BYTES (4)
#define POW_DATA_SET_INIT (1 << 30)
#define POW_DATA_SET_GROWTH (1 << 23)
#define POW_CACHE_INIT (1 << 24)
#define POW_CACHE_GROWTH (1 << 17)
#define POW_EPOCH (30000)
#define POW_MIX_BYTES (128)
#define POW_HASH_BYTES (64)
#define POW_PARENTS (256)
#define POW_CACHE_ROUNDS (3)
#define POW_ACCESSES (64)
//
// Proof Of Work
//
struct BREthereumProofOfWorkStruct {
int foo;
};
extern BREthereumProofOfWork
proofOfWorkCreate (void) {
BREthereumProofOfWork pow = calloc (1, sizeof (struct BREthereumProofOfWorkStruct));
pow->foo = 0;
return pow;
}
extern void
proofOfWorkRelease (BREthereumProofOfWork pow) {
free (pow);
}
#if defined (INCLUDE_UNUSED_FUNCTIONS)
static uint64_t
powEpoch (BREthereumBlockHeader header) {
return blockHeaderGetNonce(header) / POW_EPOCH;
}
static uint64_t
powPrime (uint64_t x, uint64_t y) {
return (0 == x % y
? x
: powPrime (x - 2 * y, y));
}
static uint64_t
powDatasetSize (BREthereumBlockHeader header) {
return powPrime (POW_DATA_SET_INIT + POW_DATA_SET_GROWTH * powEpoch(header) - POW_MIX_BYTES,
POW_MIX_BYTES);
}
static uint64_t
powCacheSize (BREthereumBlockHeader header) {
return powPrime (POW_CACHE_INIT + POW_CACHE_GROWTH * powEpoch(header) - POW_HASH_BYTES,
POW_HASH_BYTES);
}
static BREthereumHash
powSeedHashInternal (uint64_t number) {
BREthereumHash bytes;
if (0 == number)
memset (bytes.bytes, 0, 32);
else
bytes = powSeedHashInternal(number - POW_EPOCH);
return hashCreateFromData ((BRRlpData) { 32, bytes.bytes });
}
static BREthereumHash
powSeedHash (BREthereumBlockHeader header) {
return powSeedHashInternal(blockHeaderGetNumber(header));
}
static BREthereumData
powLittleRMH (BREthereumData x, uint64_t i, uint64_t n) {
return x;
}
static BREthereumData
powBigRMH (BREthereumData x, uint64_t n) {
for (uint64_t i = 0; i < n; i++)
powLittleRMH(x, i, n);
return x;
}
static BREthereumData
powCacheRounds (BREthereumData x, uint64_t y, uint64_t n) {
return (0 == y
? x
: (1 == y
? powBigRMH (x, n)
: powCacheRounds (powBigRMH (x, n), y - 1, n)));
}
static void
powBigFNV (BREthereumData x,
BREthereumData y) {
}
static BREthereumData
powMix (BREthereumData m,
BREthereumData c,
uint64_t i,
uint64_t p) {
return (0 == p
? m
: m);
}
static BREthereumData
powParents (BREthereumData c,
uint64_t i,
uint64_t p,
BREthereumData m) {
return (p < POW_PARENTS - 1
? powParents(c, i, p + 1, powMix (m, c, i, p + 1))
: powMix (m, c, i, p + 1));
}
static BREthereumData
powDatasetItem (BREthereumData c,
uint64_t i) {
return powParents(c, i, -i, (BREthereumData) { 0, NULL });
}
// On and On and On....
#endif
extern void
proofOfWorkGenerate(BREthereumProofOfWork pow,
BREthereumBlockHeader header) {
//
}
extern void
proofOfWorkCompute (BREthereumProofOfWork pow,
BREthereumBlockHeader header,
UInt256 *n,
BREthereumHash *m) {
assert (NULL != n && NULL != m);
// On and on and on
// TODO: Actually compute something.
// For now, return values that allow subsequent use to succeed
*n = UINT256_ZERO;
*m = blockHeaderGetMixHash (header);
}
|
wrldwzrd89/older-java-games
|
FantastleX/src/com/puttysoftware/fantastlex/maze/objects/FireBow.java
|
/* FantastleX: A Maze/RPG Hybrid Game
Copyright (C) 2008-2010 <NAME>
Any questions should be directed to the author via email at: <EMAIL>
*/
package com.puttysoftware.fantastlex.maze.objects;
import com.puttysoftware.fantastlex.maze.abc.AbstractBow;
import com.puttysoftware.fantastlex.maze.utilities.ArrowTypeConstants;
import com.puttysoftware.fantastlex.maze.utilities.ColorConstants;
public class FireBow extends AbstractBow {
// Constants
private static final int BOW_USES = 30;
// Constructors
public FireBow() {
super(FireBow.BOW_USES, ArrowTypeConstants.ARROW_TYPE_FIRE,
ColorConstants.COLOR_LIGHT_RED);
}
@Override
public String getName() {
return "Fire Bow";
}
@Override
public String getPluralName() {
return "Fire Bows";
}
@Override
public String getDescription() {
return "Fire Bows allow shooting of Fire Arrows, which burn Barrier Generators upon contact, and do everything normal arrows do.";
}
}
|
hackbinary/pdfedit
|
src/gui/propertymodecontroller.cc
|
/*
* PDFedit - free program for PDF document manipulation.
* Copyright (C) 2006-2009 PDFedit team: <NAME>,
* <NAME>,
* <NAME>
* Former team members: <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* 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 (in doc/LICENSE.GPL); if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Project is hosted on http://sourceforge.net/projects/pdfedit
*/
/** @file
PropertyModeController - class providing wrapper around single ModeController
instance and managing its configuration
@author <NAME>
*/
#include "propertymodecontroller.h"
#include "qtcompat.h"
#include "settings.h"
#include <qstring.h>
#include <stdlib.h>
#include <kernel/modecontroller.h>
#include <utils/confparser.h>
#include "util.h"
namespace gui {
using namespace configuration;
/** Single property mode instance for entire application */
PropertyModeController *propertyModeControllerInstance=NULL;
//Internal private data for single PropertyModeController instance
/** Mode Controller instance */
ModeController modeController;
/**
Low-level parser for simple configuration files (one line = one setting).
This base parser is used by ConfParser,
which is used by ModeController in loadFromFile
*/
StringConfigurationParser baseParser(NULL);
/** Configuration parser */
ModeController::ConfParser parser(baseParser);
/** atexit handler that will delete the single instance if it was allocated */
void removePropertyModeController() {
if (!propertyModeControllerInstance) return;
delete propertyModeControllerInstance;
}
/**
Constructor
Class will be initialized and also configuration will be read, if specified in the settings
*/
PropertyModeController::PropertyModeController(){
//Register to be destroyed at exit
atexit(removePropertyModeController);
QString confFile=globalSettings->getFullPathName("config",QString::null,"modecontroller/");
if (confFile.isNull()) {
guiPrintDbg(debug::DBG_WARN,"Mode controller config not found");
}
guiPrintDbg(debug::DBG_DBG,"Mode controller config file: " << Q_OUT(confFile));
int result=modeController.loadFromFile(util::convertFromUnicode(confFile,util::NAME),parser);
if(result==-1) {
guiPrintDbg(debug::DBG_WARN,"Mode controller failed to parse file: " << Q_OUT(confFile));
//TODO alert user
}
};
/**
Return Instance of PropertyModeController.
Ensures only one instance of PropertyModeController exists at any time (singleton)
If no instance exists, it is created.
@return existing PropertyModeController object
*/
PropertyModeController* PropertyModeController::getInstance() {
if (!propertyModeControllerInstance) propertyModeControllerInstance=new PropertyModeController();
return propertyModeControllerInstance;
}
/**
For given type and name return mode of the property
@param type Type field value of complex type
@param name Name of property
@return property mode
*/
PropertyMode PropertyModeController::mode(const QString &type,const QString &name) {
return modeController.getMode(util::convertFromUnicode(type,util::PDF),util::convertFromUnicode(name,util::PDF));
}
/**
Return instance of ModeController that is being used by this class
@return ModeController instance
*/
ModeController* PropertyModeController::get() {
return &modeController;
}
/** Destructor */
PropertyModeController::~PropertyModeController(){
propertyModeControllerInstance=NULL;
};
} // namespace gui
|
hackerlank/SourceCode
|
Game/Xerces/src/xercesc/validators/schema/identity/IC_Selector.hpp
|
<gh_stars>1-10
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: IC_Selector.hpp 176026 2004-09-08 13:57:07Z peiyongz $
*/
#if !defined(IC_SELECTOR_HPP)
#define IC_SELECTOR_HPP
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/schema/identity/XPathMatcher.hpp>
#include <xercesc/internal/XSerializable.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Forward Declaration
// ---------------------------------------------------------------------------
class FieldActivator;
class VALIDATORS_EXPORT IC_Selector : public XSerializable, public XMemory
{
public:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
IC_Selector(XercesXPath* const xpath,
IdentityConstraint* const identityConstraint);
~IC_Selector();
// -----------------------------------------------------------------------
// operators
// -----------------------------------------------------------------------
bool operator== (const IC_Selector& other) const;
bool operator!= (const IC_Selector& other) const;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
XercesXPath* getXPath() const { return fXPath; }
IdentityConstraint* getIdentityConstraint() const { return fIdentityConstraint; }
// -----------------------------------------------------------------------
// Factory methods
// -----------------------------------------------------------------------
XPathMatcher* createMatcher(FieldActivator* const fieldActivator,
const int initialDepth,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(IC_Selector)
IC_Selector(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
private:
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
IC_Selector(const IC_Selector& other);
IC_Selector& operator= (const IC_Selector& other);
// -----------------------------------------------------------------------
// Data members
// -----------------------------------------------------------------------
XercesXPath* fXPath;
IdentityConstraint* fIdentityConstraint;
};
class VALIDATORS_EXPORT SelectorMatcher : public XPathMatcher
{
public:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
~SelectorMatcher() {}
int getInitialDepth() const { return fInitialDepth; }
// -----------------------------------------------------------------------
// XMLDocumentHandler methods
// -----------------------------------------------------------------------
void startDocumentFragment();
void startElement(const XMLElementDecl& elemDecl,
const unsigned int urlId,
const XMLCh* const elemPrefix,
const RefVectorOf<XMLAttr>& attrList,
const unsigned int attrCount);
void endElement(const XMLElementDecl& elemDecl,
const XMLCh* const elemContent);
private:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
SelectorMatcher(XercesXPath* const anXPath,
IC_Selector* const selector,
FieldActivator* const fieldActivator,
const int initialDepth,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
SelectorMatcher(const SelectorMatcher& other);
SelectorMatcher& operator= (const SelectorMatcher& other);
// -----------------------------------------------------------------------
// Friends
// -----------------------------------------------------------------------
friend class IC_Selector;
// -----------------------------------------------------------------------
// Data members
// -----------------------------------------------------------------------
int fInitialDepth;
int fElementDepth;
int fMatchedDepth;
IC_Selector* fSelector;
FieldActivator* fFieldActivator;
};
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file IC_Selector.hpp
*/
|
jjlee3/openthread
|
examples/apps/mstc/OpenThreadTalk/ThreadGlobals.cpp
|
<filename>examples/apps/mstc/OpenThreadTalk/ThreadGlobals.cpp
#include "pch.h"
#include <utility>
#include "ThreadGlobals.h"
using namespace OpenThreadTalk;
ThreadGlobals* OpenThreadTalk::g_pThreadGlobals = nullptr;
ThreadGlobals::ThreadGlobals(
IAsyncThreadPage^ page,
CoreDispatcher^ dispatcher,
device_list_notify&& threadDevListNotify) :
page_{ std::move(page) },
dispatcher_{ std::move(dispatcher) },
threadDevListNotify_{ std::move(threadDevListNotify) }
{
otApiInstance_.SetDeviceAvailabilityChangedCallback(
ThreadDeviceAvailabilityCallback, this);
// Build the intial list
DeviceChangeCallback();
}
ot::Device*
ThreadGlobals::Find(
const GUID & guid) const
{
auto it = devMap_.find(guid);
if (it == devMap_.end()) { return nullptr; }
return it->second;
}
void OTCALL
ThreadGlobals::ThreadDeviceAvailabilityCallback(
bool /*added*/,
const GUID* /*devGuid*/,
void* context)
{
reinterpret_cast<ThreadGlobals*>(context)->DeviceChangeCallback();
}
void OTCALL
ThreadGlobals::ThreadStateChangeCallback(
uint32_t flags,
void* context)
{
if ((flags & OT_NET_ROLE) == 0) { return; }
reinterpret_cast<ThreadGlobals*>(context)->DeviceChangeCallback();
}
void
ThreadGlobals::DeviceChangeCallback()
{
dispatcher_->RunAsync(CoreDispatcherPriority::Normal,
ref new DispatchedHandler([this]()
{
BuildDeviceList();
}));
}
void
ThreadGlobals::BuildDeviceList()
{
auto otApiInst = otApiInstance_.get();
if (otApiInst == ot::ApiInstance::invalid()) { return; }
devMap_.clear();
devices_.clear();
ot::EnumDevices enumDevices{ otApiInst };
auto deviceList = enumDevices.get();
for (decltype(deviceList->aDevicesLength) index = 0;
index < deviceList->aDevicesLength; ++index)
{
try
{
BuildDevice(otApiInst, deviceList->aDevices[index]);
}
catch (Exception^ ex)
{
page_->NotifyFromAsyncThread(
"BuildDevice error: " + ex->Message, NotifyType::Error);
}
}
// build device map
for (auto& device : devices_)
{
devMap_.emplace(device.GetGuid(), &device);
}
if (threadDevListNotify_)
{
threadDevListNotify_();
}
}
void
ThreadGlobals::BuildDevice(
otApiInstance* otApiInst,
const GUID& guid)
{
Device device{ otApiInst, guid };
device.SetStateChangeCallback(ThreadStateChangeCallback,
const_cast<void*>(reinterpret_cast<const void*>(this)));
devices_.push_back(std::move(device));
}
|
thisisshi/sdk
|
go/models/waf_positive_security_model.go
|
package models
// This file is auto-generated.
// Please contact <EMAIL> for any change requests.
// WafPositiveSecurityModel waf positive security model
// swagger:model WafPositiveSecurityModel
type WafPositiveSecurityModel struct {
// These groups should be used to separate different levels of concern. The order of the groups matters, one group may mark parts of the request as valid, so that subsequent groups will not check these parts. It is a reference to an object of type WafPolicyPSMGroup. Field introduced in 18.2.3. Maximum of 64 items allowed.
GroupRefs []string `json:"group_refs,omitempty"`
}
|
AekseyDyomin/three-ds-server
|
src/main/java/com/rbkmoney/threeds/server/handle/impl/UnsupportedMessageTypeResponseHandler.java
|
<filename>src/main/java/com/rbkmoney/threeds/server/handle/impl/UnsupportedMessageTypeResponseHandler.java<gh_stars>0
package com.rbkmoney.threeds.server.handle.impl;
import com.rbkmoney.threeds.server.converter.MessageToErrorResConverter;
import com.rbkmoney.threeds.server.domain.error.ErrorCode;
import com.rbkmoney.threeds.server.domain.root.Message;
import com.rbkmoney.threeds.server.domain.root.emvco.Erro;
import com.rbkmoney.threeds.server.dto.ValidationResult;
import com.rbkmoney.threeds.server.handle.ResponseHandler;
import com.rbkmoney.threeds.server.holder.DirectoryServerProviderHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import static com.rbkmoney.threeds.server.constants.MessageConstants.INVALID_MESSAGE_FOR_THE_RECEIVING_COMPONENT;
import static com.rbkmoney.threeds.server.constants.MessageConstants.UNSUPPORTED_MESSAGE_TYPE;
@RequiredArgsConstructor
@Slf4j
public class UnsupportedMessageTypeResponseHandler implements ResponseHandler {
private final MessageToErrorResConverter errorConverter;
private final DirectoryServerProviderHolder providerHolder;
@Override
public boolean canHandle(Message o) {
return false;
}
@Override
public Message handle(Message message) {
ValidationResult validationResult = failure(message);
Message result = errorConverter.convert(validationResult);
providerHolder.getDsClient().notifyDsAboutError((Erro) result);
return result;
}
private ValidationResult failure(Message message) {
return ValidationResult.failure(
ErrorCode.MESSAGE_RECEIVED_INVALID_101,
INVALID_MESSAGE_FOR_THE_RECEIVING_COMPONENT,
UNSUPPORTED_MESSAGE_TYPE,
message
);
}
}
|
friedlwo/AppWoksUtils
|
src/org/appwork/utils/swing/renderer/RendererComboBoxModel.java
|
/**
* Copyright (c) 2009 - 2011 AppWork UG(haftungsbeschränkt) <<EMAIL>>
*
* This file is part of org.appwork.utils.swing.renderer
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.appwork.utils.swing.renderer;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;
/**
* @author thomas
*
*/
public class RendererComboBoxModel implements ComboBoxModel {
private Object selection;
/*
* (non-Javadoc)
*
* @see
* javax.swing.ListModel#addListDataListener(javax.swing.event.ListDataListener
* )
*/
@Override
public void addListDataListener(final ListDataListener l) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see javax.swing.ListModel#getElementAt(int)
*/
@Override
public Object getElementAt(final int index) {
// TODO Auto-generated method stub
return this.selection;
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxModel#getSelectedItem()
*/
@Override
public Object getSelectedItem() {
// TODO Auto-generated method stub
return this.selection;
}
/*
* (non-Javadoc)
*
* @see javax.swing.ListModel#getSize()
*/
@Override
public int getSize() {
// TODO Auto-generated method stub
return 1;
}
/*
* (non-Javadoc)
*
* @see javax.swing.ListModel#removeListDataListener(javax.swing.event.
* ListDataListener)
*/
@Override
public void removeListDataListener(final ListDataListener l) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see javax.swing.ComboBoxModel#setSelectedItem(java.lang.Object)
*/
@Override
public void setSelectedItem(final Object anItem) {
this.selection = anItem;
}
}
|
andyguwc/flask-hackernews-clone
|
flask_hackernews_clone/blueprints/main/models.py
|
# -*- coding: utf-8 -*-
"""Post models."""
import datetime as dt
from flask_hackernews_clone.database import (
Column,
SearchableMixin,
PkModel,
db,
reference_col,
relationship,
)
from flask_hackernews_clone.extensions import bcrypt
class Post(SearchableMixin, PkModel):
"""Post"""
__searchable__ = ["body"]
__tablename__ = "posts"
title = Column(db.String(80))
body = Column(db.Text)
author_id = Column(db.Integer, db.ForeignKey("users.id"))
|
magicLaLa/RSSHub
|
lib/v2/lfsyd/home.js
|
<gh_stars>10-100
const got = require('@/utils/got');
const { parseDate } = require('@/utils/parse-date');
const { ProcessForm, ProcessFeed } = require('./utils');
module.exports = async (ctx) => {
const rootUrl = 'https://www.iyingdi.com';
const url = 'https://api.iyingdi.com/mweb/feed/recommend-content-list';
const form = {
size: 30,
timestamp: '',
};
const response = await got({
method: 'post',
url,
headers: {
'App-Udid': 'unknown',
Host: 'api.iyingdi.com',
'Login-Token': '<PASSWORD>',
Origin: 'https://mob.iyingdi.com',
Platform: 'mweb',
Preid: '86f2007de00272e24a54831a621aecc5',
Referer: 'https://mob.iyingdi.com/',
},
form: ProcessForm(form, 'mweb'),
});
const { posts } = response.data;
const articleList = posts.map((item) => ({
title: item.post.title,
pubDate: parseDate(item.post.show_time * 1000),
link: `${rootUrl}/tz/post/${item.post.id}`,
guid: item.post.title,
postId: item.post.id,
}));
const items = await ProcessFeed(ctx.cache, articleList);
ctx.state.data = {
title: '首页 - 旅法师营地',
link: rootUrl,
item: items,
};
};
|
cromulencellc/hackasat-final-2021
|
flatsat/comms/user_segment/server/tools/testing/scoresrvr.py
|
<reponame>cromulencellc/hackasat-final-2021<gh_stars>1-10
#!/usr/bin/env python3
import socket
import time
import random
SCORE_IP = "localhost"
SCORE_PORT = 4001
print(f"UDP target IP: {SCORE_IP}")
print(f"UDP target port: {SCORE_PORT}")
#for idx in range(0,,1):
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
while True:
randomlist = random.sample(range(1000,9999), 8)
print(randomlist)
msg2=""
for idx in range(0,8,1):
#print(f"team: {idx}: {randomlist[idx]}")
msg2=msg2+str(randomlist[idx])
print(f"ScoreSvr: {msg2}")
sock.sendto(msg2.encode(), (SCORE_IP, SCORE_PORT))
time.sleep(10)
|
sthatiko/java_algos
|
src/com/sthatiko/ds/Trie.java
|
package com.sthatiko.ds;
import sun.lwawt.macosx.CSystemTray;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
// Also known as prefix tree
class Trie {
private TrieNode root;
static class TrieNode{
boolean end;
char c;
HashMap<Character,TrieNode> nodes = new HashMap<>();
}
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
System.out.println(this.getClass().getSimpleName());
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode cur = this.root;
for(char c: word.toCharArray()){
TrieNode t = cur.nodes.getOrDefault(c,null);
if(t == null){
t = new TrieNode();
t.c=c;
cur.nodes.put(c,t);
}
cur = t;
}
cur.end=true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode cur = this.root;
for(char c: word.toCharArray()){
TrieNode t = cur.nodes.getOrDefault(c,null);
if(t == null){
return false;
}
cur = t;
}
return cur.end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode cur = this.root;
for(char c: prefix.toCharArray()){
TrieNode t = cur.nodes.getOrDefault(c,null);
if(t == null){
return false;
}
cur = t;
}
return true;
}
public static void main(String[] args) {
Trie obj = new Trie();
obj.insert("sthatiko");
boolean param_2 = obj.startsWith("sthatiko");
System.out.println(param_2);
}
}
|
Hexiaojiao0732/htgl
|
src/main/java/com/zhixin/rd/memory/web/service/pl/PlServiceImpl.java
|
package com.zhixin.rd.memory.web.service.pl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhixin.rd.memory.web.dao.pl.IPlMapper;
import com.zhixin.rd.memory.web.entity.PlEntity;
@Service
public class PlServiceImpl implements IPlService {
@Autowired
private IPlMapper plMapper;
@Override
public List<PlEntity> queryAllPl(Map<String, Object> map) {
// TODO Auto-generated method stub
return plMapper.queryAllPl(map);
}
@Override
public int countPl(Map<String, Object> map) {
// TODO Auto-generated method stub
return plMapper.countPl(map);
}
@Override
public void deletePlById(Long id) {
// TODO Auto-generated method stub
plMapper.deletePlById(id);
}
@Override
public void shPlById(Long id) {
// TODO Auto-generated method stub
plMapper.shPlById(id);
}
@Override
public void cancelShPlById(Long id) {
// TODO Auto-generated method stub
plMapper.cancelShPlById(id);
}
}
|
jteixeir/begC4D
|
Part_III/c15/ex1505.c
|
<filename>Part_III/c15/ex1505.c
#include <stdio.h>
#include <stdlib.h>
void sub(void)
{
puts("Which is the plan.");
exit(0);
}
int main()
{
puts("This program quits before it's done.");
sub();
puts("Or was that on purpose?");
return(0);
}
|
wcnnkh/framework
|
orm/src/main/java/io/basc/framework/orm/PropertyMetadata.java
|
<reponame>wcnnkh/framework<gh_stars>1-10
package io.basc.framework.orm;
import io.basc.framework.util.Named;
public interface PropertyMetadata extends Named {
boolean isAutoIncrement();
boolean isPrimaryKey();
boolean isNullable();
String getCharsetName();
String getComment();
boolean isUnique();
}
|
myskov/ozone
|
hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneTenantShell.java
|
<filename>hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneTenantShell.java<gh_stars>100-1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ozone.shell;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdds.cli.GenericCli;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.io.retry.RetryInvocationHandler;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.ha.ConfUtils;
import org.apache.hadoop.ozone.om.multitenant.AuthorizerLockImpl;
import org.apache.hadoop.ozone.om.OMConfigKeys;
import org.apache.hadoop.ozone.om.OMMultiTenantManagerImpl;
import org.apache.hadoop.ozone.om.helpers.OmVolumeArgs;
import org.apache.hadoop.ozone.om.multitenant.MultiTenantAccessAuthorizerRangerPlugin;
import org.apache.hadoop.ozone.om.request.s3.tenant.OMTenantAssignUserAccessIdRequest;
import org.apache.hadoop.ozone.om.request.s3.tenant.OMTenantCreateRequest;
import org.apache.hadoop.ozone.shell.tenant.TenantShell;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.ozone.test.GenericTestUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import picocli.CommandLine;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_MULTITENANCY_ENABLED;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_RANGER_HTTPS_ADMIN_API_PASSWD;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_RANGER_HTTPS_ADMIN_API_USER;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_RANGER_HTTPS_ADDRESS_KEY;
import static org.junit.Assert.fail;
/**
* Integration test for Ozone tenant shell command. HA enabled.
*
* TODO: HDDS-6338. Add a Kerberized version of this
* TODO: HDDS-6336. Add a mock Ranger server to test Ranger HTTP endpoint calls
*/
public class TestOzoneTenantShell {
private static final Logger LOG =
LoggerFactory.getLogger(TestOzoneTenantShell.class);
static {
System.setProperty("log4j.configurationFile", "auditlog.properties");
}
private static final String DEFAULT_ENCODING = UTF_8.name();
/**
* Set the timeout for every test.
*/
@Rule
public Timeout testTimeout = Timeout.seconds(300);
private static File baseDir;
private static File testFile;
private static final File AUDIT_LOG_FILE = new File("audit.log");
private static OzoneConfiguration conf = null;
private static MiniOzoneCluster cluster = null;
private static OzoneShell ozoneSh = null;
private static TenantShell tenantShell = null;
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final ByteArrayOutputStream err = new ByteArrayOutputStream();
private static final PrintStream OLD_OUT = System.out;
private static final PrintStream OLD_ERR = System.err;
private static String omServiceId;
private static String clusterId;
private static String scmId;
private static int numOfOMs;
private static final boolean USE_ACTUAL_RANGER = false;
/**
* Create a MiniOzoneCluster for testing with using distributed Ozone
* handler type.
*
* @throws Exception
*/
@BeforeClass
public static void init() throws Exception {
// Remove audit log output if it exists
if (AUDIT_LOG_FILE.exists()) {
AUDIT_LOG_FILE.delete();
}
conf = new OzoneConfiguration();
conf.setBoolean(
OMMultiTenantManagerImpl.OZONE_OM_TENANT_DEV_SKIP_RANGER, true);
conf.setBoolean(OZONE_OM_MULTITENANCY_ENABLED, true);
if (USE_ACTUAL_RANGER) {
conf.set(OZONE_RANGER_HTTPS_ADDRESS_KEY, System.getenv("RANGER_ADDRESS"));
conf.set(OZONE_OM_RANGER_HTTPS_ADMIN_API_USER,
System.getenv("RANGER_USER"));
conf.set(OZONE_OM_RANGER_HTTPS_ADMIN_API_PASSWD,
System.getenv("RANGER_PASSWD"));
} else {
conf.setBoolean(OMMultiTenantManagerImpl.OZONE_OM_TENANT_DEV_SKIP_RANGER,
true);
}
String path = GenericTestUtils.getTempPath(
TestOzoneTenantShell.class.getSimpleName());
baseDir = new File(path);
baseDir.mkdirs();
testFile = new File(path + OzoneConsts.OZONE_URI_DELIMITER + "testFile");
testFile.getParentFile().mkdirs();
testFile.createNewFile();
ozoneSh = new OzoneShell();
tenantShell = new TenantShell();
// Init cluster
omServiceId = "om-service-test1";
numOfOMs = 3;
clusterId = UUID.randomUUID().toString();
scmId = UUID.randomUUID().toString();
cluster = MiniOzoneCluster.newOMHABuilder(conf)
.setClusterId(clusterId)
.setScmId(scmId)
.setOMServiceId(omServiceId)
.setNumOfOzoneManagers(numOfOMs)
.withoutDatanodes() // Remove this once we are actually writing data
.build();
cluster.waitForClusterToBeReady();
}
/**
* shutdown MiniOzoneCluster.
*/
@AfterClass
public static void shutdown() {
if (cluster != null) {
cluster.shutdown();
}
if (baseDir != null) {
FileUtil.fullyDelete(baseDir, true);
}
if (AUDIT_LOG_FILE.exists()) {
AUDIT_LOG_FILE.delete();
}
}
@Before
public void setup() throws UnsupportedEncodingException {
System.setOut(new PrintStream(out, false, UTF_8.name()));
System.setErr(new PrintStream(err, false, UTF_8.name()));
// Suppress OMNotLeaderException in the log
GenericTestUtils.setLogLevel(RetryInvocationHandler.LOG, Level.WARN);
// Enable debug logging for interested classes
GenericTestUtils.setLogLevel(OMTenantCreateRequest.LOG, Level.DEBUG);
GenericTestUtils.setLogLevel(
OMTenantAssignUserAccessIdRequest.LOG, Level.DEBUG);
GenericTestUtils.setLogLevel(
MultiTenantAccessAuthorizerRangerPlugin.LOG, Level.DEBUG);
GenericTestUtils.setLogLevel(AuthorizerLockImpl.LOG, Level.DEBUG);
}
@After
public void reset() {
// reset stream after each unit test
out.reset();
err.reset();
// restore system streams
System.setOut(OLD_OUT);
System.setErr(OLD_ERR);
}
/**
* Returns exit code.
*/
private int execute(GenericCli shell, String[] args) {
LOG.info("Executing shell command with args {}", Arrays.asList(args));
CommandLine cmd = shell.getCmd();
CommandLine.IExecutionExceptionHandler exceptionHandler =
(ex, commandLine, parseResult) -> {
new PrintStream(err, true, DEFAULT_ENCODING).println(ex.getMessage());
return commandLine.getCommandSpec().exitCodeOnExecutionException();
};
// Since there is no elegant way to pass Ozone config to the shell,
// the idea is to use 'set' to place those OM HA configs.
String[] argsWithHAConf = getHASetConfStrings(args);
cmd.setExecutionExceptionHandler(exceptionHandler);
return cmd.execute(argsWithHAConf);
}
/**
* Helper that appends HA service id to args.
*/
private int executeHA(GenericCli shell, String[] args) {
final String[] newArgs = new String[args.length + 1];
System.arraycopy(args, 0, newArgs, 0, args.length);
newArgs[args.length] = "--om-service-id=" + omServiceId;
return execute(shell, newArgs);
}
/**
* Execute command, assert exception message and returns true if error
* was thrown.
*/
private void executeWithError(OzoneShell shell, String[] args,
String expectedError) {
if (Strings.isNullOrEmpty(expectedError)) {
execute(shell, args);
} else {
try {
execute(shell, args);
fail("Exception is expected from command execution " + Arrays
.asList(args));
} catch (Exception ex) {
if (!Strings.isNullOrEmpty(expectedError)) {
Throwable exceptionToCheck = ex;
if (exceptionToCheck.getCause() != null) {
exceptionToCheck = exceptionToCheck.getCause();
}
Assert.assertTrue(
String.format(
"Error of OzoneShell code doesn't contain the " +
"exception [%s] in [%s]",
expectedError, exceptionToCheck.getMessage()),
exceptionToCheck.getMessage().contains(expectedError));
}
}
}
}
private String getSetConfStringFromConf(String key) {
return String.format("--set=%s=%s", key, conf.get(key));
}
private String generateSetConfString(String key, String value) {
return String.format("--set=%s=%s", key, value);
}
/**
* Helper function to get a String array to be fed into OzoneShell.
* @param numOfArgs Additional number of arguments after the HA conf string,
* this translates into the number of empty array elements
* after the HA conf string.
* @return String array.
*/
private String[] getHASetConfStrings(int numOfArgs) {
assert (numOfArgs >= 0);
String[] res = new String[1 + 1 + numOfOMs + numOfArgs];
final int indexOmServiceIds = 0;
final int indexOmNodes = 1;
final int indexOmAddressStart = 2;
res[indexOmServiceIds] = getSetConfStringFromConf(
OMConfigKeys.OZONE_OM_SERVICE_IDS_KEY);
String omNodesKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_NODES_KEY, omServiceId);
String omNodesVal = conf.get(omNodesKey);
res[indexOmNodes] = generateSetConfString(omNodesKey, omNodesVal);
String[] omNodesArr = omNodesVal.split(",");
// Sanity check
assert (omNodesArr.length == numOfOMs);
for (int i = 0; i < numOfOMs; i++) {
res[indexOmAddressStart + i] =
getSetConfStringFromConf(ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_ADDRESS_KEY, omServiceId, omNodesArr[i]));
}
return res;
}
/**
* Helper function to create a new set of arguments that contains HA configs.
* @param existingArgs Existing arguments to be fed into OzoneShell command.
* @return String array.
*/
private String[] getHASetConfStrings(String[] existingArgs) {
// Get a String array populated with HA configs first
String[] res = getHASetConfStrings(existingArgs.length);
int indexCopyStart = res.length - existingArgs.length;
// Then copy the existing args to the returned String array
System.arraycopy(existingArgs, 0, res, indexCopyStart,
existingArgs.length);
return res;
}
/**
* Helper function that checks command output AND clears it.
*/
private void checkOutput(ByteArrayOutputStream stream, String stringToMatch,
boolean exactMatch) throws IOException {
stream.flush();
final String str = stream.toString(DEFAULT_ENCODING);
checkOutput(str, stringToMatch, exactMatch);
stream.reset();
}
private void checkOutput(ByteArrayOutputStream stream, String stringToMatch,
boolean exactMatch, boolean expectValidJSON) throws IOException {
stream.flush();
final String str = stream.toString(DEFAULT_ENCODING);
if (expectValidJSON) {
// Verify if the String can be parsed as a valid JSON
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readTree(str);
}
checkOutput(str, stringToMatch, exactMatch);
stream.reset();
}
private void checkOutput(String str, String stringToMatch,
boolean exactMatch) {
if (exactMatch) {
Assert.assertEquals(stringToMatch, str);
} else {
Assert.assertTrue(str, str.contains(stringToMatch));
}
}
private void deleteVolume(String volumeName) throws IOException {
int exitC = execute(ozoneSh, new String[] {"volume", "delete", volumeName});
checkOutput(out, "Volume " + volumeName + " is deleted\n", true);
checkOutput(err, "", true);
// Exit code should be 0
Assert.assertEquals(0, exitC);
}
@Test
public void testAssignAdmin() throws IOException {
final String tenantName = "devaa";
final String userName = "alice";
executeHA(tenantShell, new String[] {"create", tenantName});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Loop assign-revoke 4 times
for (int i = 0; i < 4; i++) {
executeHA(tenantShell, new String[] {
"user", "assign", userName, "--tenant=" + tenantName});
checkOutput(out, "export AWS_ACCESS_KEY_ID=", false);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"--verbose", "user", "assign-admin",
tenantName + "$" + userName, "--tenant=" + tenantName,
"--delegated=true"});
checkOutput(out, "{\n" + " \"accessId\": \"devaa$alice\",\n"
+ " \"tenantId\": \"devaa\",\n" + " \"isAdmin\": true,\n"
+ " \"isDelegatedAdmin\": true\n" + "}\n", true, true);
checkOutput(err, "", true);
// Clean up
executeHA(tenantShell, new String[] {"--verbose", "user", "revoke-admin",
tenantName + "$" + userName, "--tenant=" + tenantName});
checkOutput(out, "{\n" + " \"accessId\": \"devaa$alice\",\n"
+ " \"tenantId\": \"devaa\",\n" + " \"isAdmin\": false,\n"
+ " \"isDelegatedAdmin\": false\n" + "}\n", true, true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "revoke", tenantName + "$" + userName});
checkOutput(out, "", true);
checkOutput(err, "", true);
}
// Clean up
executeHA(tenantShell, new String[] {"delete", tenantName});
checkOutput(out, "", true);
checkOutput(err, "Deleted tenant '" + tenantName + "'.\n", false);
deleteVolume(tenantName);
// Sanity check: tenant list should be empty
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "", true);
checkOutput(err, "", true);
}
/**
* Test tenant create, assign user, get user info, assign admin, revoke admin
* and revoke user flow.
*/
@Test
@SuppressWarnings("methodlength")
public void testOzoneTenantBasicOperations() throws IOException {
List<String> lines = FileUtils.readLines(AUDIT_LOG_FILE, (String)null);
Assert.assertEquals(0, lines.size());
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Create tenants
// Equivalent to `ozone tenant create finance`
executeHA(tenantShell, new String[] {"create", "finance"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "finance\n", true);
checkOutput(err, "", true);
lines = FileUtils.readLines(AUDIT_LOG_FILE, (String)null);
Assert.assertTrue(lines.size() > 0);
checkOutput(lines.get(lines.size() - 1), "ret=SUCCESS", false);
// Check volume creation
OmVolumeArgs volArgs = cluster.getOzoneManager().getVolumeInfo("finance");
Assert.assertEquals("finance", volArgs.getVolume());
// Creating the tenant with the same name again should fail
executeHA(tenantShell, new String[] {"create", "finance"});
checkOutput(out, "", true);
checkOutput(err, "Tenant 'finance' already exists\n", true);
executeHA(tenantShell, new String[] {"create", "research"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"create", "dev"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"ls"});
checkOutput(out, "dev\nfinance\nresearch\n", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"list", "--json"});
// Not checking the full output here
checkOutput(out, "\"tenantId\": \"dev\",", false);
checkOutput(err, "", true);
// Attempt user getsecret before assignment, should fail
executeHA(tenantShell, new String[] {
"user", "getsecret", "finance$bob"});
checkOutput(out, "", false);
checkOutput(err, "accessId 'finance$bob' doesn't exist\n",
true);
// Assign user accessId
// Equivalent to `ozone tenant user assign bob --tenant=finance`
executeHA(tenantShell, new String[] {
"--verbose", "user", "assign", "bob", "--tenant=finance"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='finance$bob'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "Assigned 'bob' to 'finance' with accessId"
+ " 'finance$bob'.\n", true);
// Try user getsecret again after assignment, should succeed
executeHA(tenantShell, new String[] {
"user", "getsecret", "finance$bob"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='finance$bob'\n",
false);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"--verbose", "user", "assign", "bob", "--tenant=research"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='research$bob'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "Assigned 'bob' to 'research' with accessId"
+ " 'research$bob'.\n", true);
executeHA(tenantShell, new String[] {
"user", "assign", "bob", "--tenant=dev"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='dev$bob'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
// accessId length exceeding limit, should fail
executeHA(tenantShell, new String[] {
"user", "assign", StringUtils.repeat('a', 100), "--tenant=dev"});
checkOutput(out, "", true);
checkOutput(err, "accessId length (104) exceeds the maximum length "
+ "allowed (100)\n", true);
// Get user info
// Equivalent to `ozone tenant user info bob`
executeHA(tenantShell, new String[] {
"user", "info", "bob"});
checkOutput(out, "User 'bob' is assigned to:\n"
+ "- Tenant 'research' with accessId 'research$bob'\n"
+ "- Tenant 'finance' with accessId 'finance$bob'\n"
+ "- Tenant 'dev' with accessId 'dev$bob'\n", true);
checkOutput(err, "", true);
// Assign admin
executeHA(tenantShell, new String[] {
"user", "assign-admin", "dev$bob", "--tenant=dev", "--delegated"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "info", "bob"});
checkOutput(out, "Tenant 'dev' delegated admin with accessId", false);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "info", "--json", "bob"});
checkOutput(out, "{\n" + " \"user\": \"bob\",\n" + " \"tenants\": [\n"
+ " {\n" + " \"accessId\": \"research$bob\",\n"
+ " \"tenantId\": \"research\",\n" + " \"isAdmin\": false,\n"
+ " \"isDelegatedAdmin\": false\n" + " },\n" + " {\n"
+ " \"accessId\": \"finance$bob\",\n"
+ " \"tenantId\": \"finance\",\n" + " \"isAdmin\": false,\n"
+ " \"isDelegatedAdmin\": false\n" + " },\n" + " {\n"
+ " \"accessId\": \"dev$bob\",\n"
+ " \"tenantId\": \"dev\",\n" + " \"isAdmin\": true,\n"
+ " \"isDelegatedAdmin\": true\n" + " }\n" + " ]\n" + "}\n",
true, true);
checkOutput(err, "", true);
// Revoke admin
executeHA(tenantShell, new String[] {
"user", "revoke-admin", "dev$bob", "--tenant=dev"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "info", "bob"});
checkOutput(out, "User 'bob' is assigned to:\n"
+ "- Tenant 'research' with accessId 'research$bob'\n"
+ "- Tenant 'finance' with accessId 'finance$bob'\n"
+ "- Tenant 'dev' with accessId 'dev$bob'\n", true);
checkOutput(err, "", true);
// Revoke user accessId
executeHA(tenantShell, new String[] {
"user", "revoke", "research$bob"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "info", "bob"});
checkOutput(out, "User 'bob' is assigned to:\n"
+ "- Tenant 'finance' with accessId 'finance$bob'\n"
+ "- Tenant 'dev' with accessId 'dev$bob'\n", true);
checkOutput(err, "", true);
// Assign user again
executeHA(tenantShell, new String[] {
"user", "assign", "bob", "--tenant=research"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='research$bob'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
// Attempt to assign the user to the tenant again
executeHA(tenantShell, new String[] {
"user", "assign", "bob", "--tenant=research",
"--accessId=research$bob"});
checkOutput(out, "", false);
checkOutput(err, "accessId 'research$bob' already exists!\n", true);
// Attempt to assign the user to the tenant with a custom accessId
executeHA(tenantShell, new String[] {
"user", "assign", "bob", "--tenant=research",
"--accessId=research$bob42"});
checkOutput(out, "", false);
// HDDS-6366: Disallow specifying custom accessId.
checkOutput(err, "Invalid accessId 'research$bob42'. "
+ "Specifying a custom access ID disallowed. "
+ "Expected accessId to be assigned is 'research$bob'\n", true);
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "dev\nfinance\nresearch\n", true);
checkOutput(err, "", true);
// Clean up
executeHA(tenantShell, new String[] {
"user", "revoke", "research$bob"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"delete", "research"});
checkOutput(out, "", true);
checkOutput(err, "Deleted tenant 'research'.\n", false);
deleteVolume("research");
executeHA(tenantShell, new String[] {
"user", "revoke", "finance$bob"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "dev\nfinance\n", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"delete", "finance"});
checkOutput(out, "", true);
checkOutput(err, "Deleted tenant 'finance'.\n", false);
deleteVolume("finance");
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "dev\n", true);
checkOutput(err, "", true);
// Attempt to delete tenant with accessIds still assigned to it, should fail
int exitCode = executeHA(tenantShell, new String[] {"delete", "dev"});
Assert.assertTrue("Tenant delete should fail!", exitCode != 0);
checkOutput(out, "", true);
checkOutput(err, "Tenant 'dev' is not empty. All accessIds associated "
+ "to this tenant must be revoked before the tenant can be deleted. "
+ "See `ozone tenant user revoke`\n", true);
// Delete dev volume should fail because the volume reference count > 0L
exitCode = execute(ozoneSh, new String[] {"volume", "delete", "dev"});
Assert.assertTrue("Volume delete should fail!", exitCode != 0);
checkOutput(out, "", true);
checkOutput(err, "Volume reference count is not zero (1). "
+ "Ozone features are enabled on this volume. "
+ "Try `ozone tenant delete <tenantId>` first.\n", true);
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "dev\n", true);
checkOutput(err, "", true);
// Revoke accessId first
executeHA(tenantShell, new String[] {
"user", "revoke", "dev$bob"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Then delete tenant, should succeed
executeHA(tenantShell, new String[] {"--verbose", "delete", "dev"});
checkOutput(out, "{\n" + " \"tenantId\": \"dev\",\n"
+ " \"volumeName\": \"dev\",\n" + " \"volumeRefCount\": 0\n" + "}\n",
true, true);
checkOutput(err, "Deleted tenant 'dev'.\n", false);
deleteVolume("dev");
// Sanity check: tenant list should be empty
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "", true);
checkOutput(err, "", true);
}
@Test
public void testListTenantUsers() throws IOException {
executeHA(tenantShell, new String[] {"--verbose", "create", "tenant1"});
checkOutput(out, "{\n" +
" \"tenantId\": \"tenant1\"\n" + "}\n", true, true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"--verbose", "user", "assign", "alice", "--tenant=tenant1"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='tenant1$alice'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "Assigned 'alice' to 'tenant1'" +
" with accessId 'tenant1$alice'.\n", true);
executeHA(tenantShell, new String[] {
"user", "assign", "bob", "--tenant=tenant1"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='tenant1$bob'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "list", "tenant1"});
checkOutput(out, "- User 'bob' with accessId 'tenant1$bob'\n" +
"- User 'alice' with accessId 'tenant1$alice'\n", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "list", "tenant1", "--json"});
checkOutput(out, "[\n" + " {\n" + " \"user\": \"bob\",\n"
+ " \"accessId\": \"tenant1$bob\"\n" + " },\n" + " {\n"
+ " \"user\": \"alice\",\n" + " \"accessId\": \"tenant1$alice\"\n"
+ " }\n" + "]\n", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "list", "tenant1", "--prefix=b"});
checkOutput(out, "- User 'bob' with accessId " +
"'tenant1$bob'\n", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "list", "tenant1", "--prefix=b", "--json"});
checkOutput(out, "[\n" + " {\n" + " \"user\": \"bob\",\n"
+ " \"accessId\": \"tenant1$bob\"\n" + " }\n" + "]\n", true);
checkOutput(err, "", true);
int exitCode = executeHA(tenantShell, new String[] {
"user", "list", "unknown"});
Assert.assertTrue("Expected non-zero exit code", exitCode != 0);
checkOutput(out, "", true);
checkOutput(err, "Tenant 'unknown' doesn't exist.\n", true);
// Clean up
executeHA(tenantShell, new String[] {
"user", "revoke", "tenant1$alice"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"--verbose", "user", "revoke", "tenant1$bob"});
checkOutput(out, "", true);
checkOutput(err, "Revoked accessId", false);
executeHA(tenantShell, new String[] {"delete", "tenant1"});
checkOutput(out, "", true);
checkOutput(err, "Deleted tenant 'tenant1'.\n", false);
deleteVolume("tenant1");
// Sanity check: tenant list should be empty
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "", true);
checkOutput(err, "", true);
}
@Test
public void testTenantSetSecret() throws IOException, InterruptedException {
final String tenantName = "tenant-test-set-secret";
// Create test tenant
executeHA(tenantShell, new String[] {"create", tenantName});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Set secret for non-existent accessId. Expect failure
executeHA(tenantShell, new String[] {
"user", "set-secret", tenantName + "$alice", "--secret=somesecret0"});
checkOutput(out, "", true);
checkOutput(err, "accessId '" + tenantName + "$alice' not found.\n", true);
// Assign a user to the tenant so that we have an accessId entry
executeHA(tenantShell, new String[] {
"user", "assign", "alice", "--tenant=" + tenantName});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$alice'\n" +
"export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
// Set secret as OM admin should succeed
executeHA(tenantShell, new String[] {
"user", "setsecret", tenantName + "$alice",
"--secret=somesecret1"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$alice'\n" +
"export AWS_SECRET_ACCESS_KEY='somesecret1'\n", true);
checkOutput(err, "", true);
// Set empty secret key should fail
int exitCode = executeHA(tenantShell, new String[] {
"user", "setsecret", tenantName + "$alice",
"--secret=short"});
Assert.assertTrue("Expected non-zero exit code", exitCode != 0);
checkOutput(out, "", true);
checkOutput(err, "Secret key length should be at least 8 characters\n",
true);
// Get secret should still give the previous secret key
executeHA(tenantShell, new String[] {
"user", "getsecret", tenantName + "$alice"});
checkOutput(out, "somesecret1", false);
checkOutput(err, "", true);
// Set secret as alice should succeed
final UserGroupInformation ugiAlice = UserGroupInformation
.createUserForTesting("alice", new String[] {"usergroup"});
ugiAlice.doAs((PrivilegedExceptionAction<Void>) () -> {
executeHA(tenantShell, new String[] {
"user", "setsecret", tenantName + "$alice",
"--secret=somesecret2"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$alice'\n" +
"export AWS_SECRET_ACCESS_KEY='somesecret2'\n", true);
checkOutput(err, "", true);
return null;
});
// Set secret as bob should fail
executeHA(tenantShell, new String[] {
"user", "assign", "bob", "--tenant=" + tenantName});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$bob'\n" +
"export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
final UserGroupInformation ugiBob = UserGroupInformation
.createUserForTesting("bob", new String[] {"usergroup"});
ugiBob.doAs((PrivilegedExceptionAction<Void>) () -> {
int exitC = executeHA(tenantShell, new String[] {
"user", "setsecret", tenantName + "$alice",
"--secret=somesecret2"});
Assert.assertTrue("Should return non-zero exit code!", exitC != 0);
checkOutput(out, "", true);
checkOutput(err, "Requested accessId 'tenant-test-set-secret$alice'"
+ " doesn't belong to current user 'bob', nor does current user"
+ " have Ozone or tenant administrator privilege\n", true);
return null;
});
// Once we make bob an admin of this tenant (non-delegated admin permission
// is sufficient in this case), set secret should succeed
executeHA(tenantShell, new String[] {"user", "assign-admin",
tenantName + "$" + ugiBob.getShortUserName(),
"--tenant=" + tenantName, "--delegated=false"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Set secret should succeed now
ugiBob.doAs((PrivilegedExceptionAction<Void>) () -> {
executeHA(tenantShell, new String[] {
"user", "setsecret", tenantName + "$alice",
"--secret=somesecret2"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$alice'\n" +
"export AWS_SECRET_ACCESS_KEY='somesecret2'\n", true);
checkOutput(err, "", true);
return null;
});
// Clean up
executeHA(tenantShell, new String[] {"user", "revoke-admin",
tenantName + "$" + ugiBob.getShortUserName()});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "revoke", tenantName + "$bob"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "revoke", tenantName + "$alice"});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"delete", tenantName});
checkOutput(out, "", true);
checkOutput(err, "Deleted tenant '" + tenantName + "'.\n", false);
deleteVolume(tenantName);
// Sanity check: tenant list should be empty
executeHA(tenantShell, new String[] {"list"});
checkOutput(out, "", true);
checkOutput(err, "", true);
}
@Test
@SuppressWarnings("methodlength")
public void testTenantAdminOperations()
throws IOException, InterruptedException {
final String tenantName = "tenant-test-tenant-admin-ops";
final UserGroupInformation ugiAlice = UserGroupInformation
.createUserForTesting("alice", new String[] {"usergroup"});
final UserGroupInformation ugiBob = UserGroupInformation
.createUserForTesting("bob", new String[] {"usergroup"});
// Preparation
// Create test tenant
executeHA(tenantShell, new String[] {"create", tenantName});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Assign alice and bob as tenant users
executeHA(tenantShell, new String[] {
"user", "assign", "alice", "--tenant=" + tenantName});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$alice'\n" +
"export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "assign", "bob", "--tenant=" + tenantName});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$bob'\n" +
"export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
// Make alice a delegated tenant admin
executeHA(tenantShell, new String[] {"user", "assign-admin",
tenantName + "$" + ugiAlice.getShortUserName(),
"--tenant=" + tenantName, "--delegated=true"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Make bob a non-delegated tenant admin
executeHA(tenantShell, new String[] {"user", "assign-admin",
tenantName + "$" + ugiBob.getShortUserName(),
"--tenant=" + tenantName, "--delegated=false"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Start test matrix
// As a tenant delegated admin, alice can:
// - Assign and revoke user accessIds
// - Assign and revoke tenant admins
// - Set secret
ugiAlice.doAs((PrivilegedExceptionAction<Void>) () -> {
// Assign carol as a new tenant user
executeHA(tenantShell, new String[] {
"user", "assign", "carol", "--tenant=" + tenantName});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$carol'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
// Set secret should work
executeHA(tenantShell, new String[] {
"user", "setsecret", tenantName + "$alice",
"--secret=somesecret2"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$alice'\n" +
"export AWS_SECRET_ACCESS_KEY='somesecret2'\n", true);
checkOutput(err, "", true);
// Make carol a tenant delegated tenant admin
executeHA(tenantShell, new String[] {"user", "assign-admin",
tenantName + "$carol",
"--tenant=" + tenantName, "--delegated=true"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Revoke carol's tenant admin privilege
executeHA(tenantShell, new String[] {"user", "revoke-admin",
tenantName + "$carol"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Make carol a tenant non-delegated tenant admin
executeHA(tenantShell, new String[] {"user", "assign-admin",
tenantName + "$carol",
"--tenant=" + tenantName, "--delegated=false"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Revoke carol's tenant admin privilege
executeHA(tenantShell, new String[] {"user", "revoke-admin",
tenantName + "$carol"});
checkOutput(out, "", true);
checkOutput(err, "", true);
// Revoke carol's accessId from this tenant
executeHA(tenantShell, new String[] {
"user", "revoke", tenantName + "$carol"});
checkOutput(out, "", true);
checkOutput(err, "", true);
return null;
});
// As a tenant non-delegated admin, bob can:
// - Assign and revoke user accessIds
// - Set secret
//
// But bob can't:
// - Assign and revoke tenant admins
ugiBob.doAs((PrivilegedExceptionAction<Void>) () -> {
// Assign carol as a new tenant user
executeHA(tenantShell, new String[] {
"user", "assign", "carol", "--tenant=" + tenantName});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$carol'\n"
+ "export AWS_SECRET_ACCESS_KEY='", false);
checkOutput(err, "", true);
// Set secret should work, even for a non-delegated admin
executeHA(tenantShell, new String[] {
"user", "setsecret", tenantName + "$alice",
"--secret=somesecret2"});
checkOutput(out, "export AWS_ACCESS_KEY_ID='" + tenantName + "$alice'\n" +
"export AWS_SECRET_ACCESS_KEY='somesecret2'\n", true);
checkOutput(err, "", true);
// Attempt to make carol a tenant delegated tenant admin, should fail
executeHA(tenantShell, new String[] {"user", "assign-admin",
tenantName + "$carol",
"--tenant=" + tenantName, "--delegated=true"});
checkOutput(out, "", true);
checkOutput(err, "User 'bob' is neither an Ozone admin "
+ "nor a delegated admin of tenant", false);
// Attempt to make carol a tenant non-delegated tenant admin, should fail
executeHA(tenantShell, new String[] {"user", "assign-admin",
tenantName + "$carol",
"--tenant=" + tenantName, "--delegated=false"});
checkOutput(out, "", true);
checkOutput(err, "User 'bob' is neither an Ozone admin "
+ "nor a delegated admin of tenant", false);
// Attempt to revoke tenant admin, should fail at the permission check
executeHA(tenantShell, new String[] {"user", "revoke-admin",
tenantName + "$carol"});
checkOutput(out, "", true);
checkOutput(err, "User 'bob' is neither an Ozone admin "
+ "nor a delegated admin of tenant", false);
// Revoke carol's accessId from this tenant
executeHA(tenantShell, new String[] {
"user", "revoke", tenantName + "$carol"});
checkOutput(out, "", true);
checkOutput(err, "", true);
return null;
});
// Clean up
executeHA(tenantShell, new String[] {"user", "revoke-admin",
tenantName + "$" + ugiAlice.getShortUserName()});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "revoke", tenantName + "$" + ugiAlice.getShortUserName()});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"user", "revoke-admin",
tenantName + "$" + ugiBob.getShortUserName()});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {
"user", "revoke", tenantName + "$" + ugiBob.getShortUserName()});
checkOutput(out, "", true);
checkOutput(err, "", true);
executeHA(tenantShell, new String[] {"delete", tenantName});
checkOutput(out, "", true);
checkOutput(err, "Deleted tenant '" + tenantName + "'.\n", false);
deleteVolume(tenantName);
}
@Test
public void testCreateTenantOnExistingVolumeShouldFail() throws IOException {
final String testVolume = "existing-volume-1";
int exitC = execute(ozoneSh, new String[] {"volume", "create", testVolume});
// Volume create should succeed
Assert.assertEquals(0, exitC);
checkOutput(out, "", true);
checkOutput(err, "", true);
// Try to create tenant on the same volume, should fail
executeHA(tenantShell, new String[] {"create", testVolume});
checkOutput(out, "", true);
checkOutput(err, "Volume already exists\n", true);
// Clean up
deleteVolume(testVolume);
}
}
|
syeminpark/openFrame
|
addons/ofxSingleton/example/src/ofApp.h
|
<gh_stars>1-10
#pragma once
#include "ofMain.h"
#include "MyRectangle.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
vector<MyRectangle> rectangles;
};
|
cmfitzg2/2d-horror
|
src/Tiles/Interior/HouseWall/Orange/HouseWallMiddleLeftOrange.java
|
<reponame>cmfitzg2/2d-horror<filename>src/Tiles/Interior/HouseWall/Orange/HouseWallMiddleLeftOrange.java
package Tiles.Interior.HouseWall.Orange;
import Graphics.Assets;
import Tiles.Tile;
public class HouseWallMiddleLeftOrange extends Tile {
public HouseWallMiddleLeftOrange(int id) {
super(Assets.houseWallMiddleLeftOrange, id, true);
}
}
|
sadupally/Dev
|
osp/presentation/api/src/java/org/theospi/portfolio/presentation/PresentationLayoutHelper.java
|
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/osp/branches/sakai-10.x/presentation/api/src/java/org/theospi/portfolio/presentation/PresentationLayoutHelper.java $
* $Id: PresentationLayoutHelper.java 105079 2012-02-24 23:08:11Z <EMAIL> $
***********************************************************************************
*
* Copyright (c) 2006, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.theospi.portfolio.presentation;
public interface PresentationLayoutHelper {
public static final String LAYOUT_SELECTABLE =
"org.theospi.portfolio.presentation.layout.selectable";
public static final String CURRENT_LAYOUT =
"org.theospi.portfolio.presentation.layout.currentLayout";
public static final String CURRENT_LAYOUT_ID =
"org.theospi.portfolio.presentation.layout.currentLayoutId";
public static final String UNSELECTED_LAYOUT =
"org.theospi.portfolio.presentation.layout.unselected";
}
|
constantinpape/cluster_tools
|
cluster_tools/utils/function_utils.py
|
<gh_stars>10-100
from datetime import datetime
from subprocess import check_output
# TODO log-levels
# stdout is always piped to file, sowe can use it as logging
def log(msg):
print("%s: %s" % (str(datetime.now()), msg))
def log_block_success(block_id):
print("%s: processed block %i" % (str(datetime.now()), block_id))
def log_job_success(job_id):
print("%s: processed job %i" % (str(datetime.now()), job_id))
# woot, there is no native tail in python ???
def tail(path, n_lines):
line_str = '-%i' % n_lines
return check_output(['tail', line_str, path]).decode().split('\n')[:-1]
|
Mrchanghao/velopert-react-class
|
style-component/src/App.js
|
import React, { Component } from 'react';
import styles from './App.scss';
import classNames from 'classnames/bind';
import Button from './Button';
import StyledButton from './Button/StyledButton';
console.log(styles.blue)
const cx = classNames.bind(styles);
console.log(cx('blue'))
class App extends Component {
render() {
const isBlue = true;
return (
<div className={cx('box', {
blue: isBlue
})}>
{/* <div className={cx('box-inside')}></div> */}
<Button>버튼 1</Button>
<StyledButton>버튼2</StyledButton>
</div>
);
}
}
export default App;
|
Shiva-D/rtos-course
|
FreeRTOSv10.4.1/FreeRTOS/Demo/Common/drivers/ST/STM32F10xFWLib/inc/stm32fxxx_eth_map.h
|
/******************** (C) COPYRIGHT 2008 STMicroelectronics ********************
* File Name : stm32fxxx_eth_map.h
* Author : MCD Application Team
* Version : VX.Y.Z
* Date : mm/dd/2008
* Description : This file contains all ETHERNET peripheral register's
* definitions and memory mapping.
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32FXXX_ETH_MAP_H
#define __STM32FXXX_ETH_MAP_H
#ifndef EXT
#define EXT extern
#endif /* EXT */
/* Includes ------------------------------------------------------------------*/
#include "stm32fxxx_eth_conf.h"
#include "stm32f10x_type.h"
/* Exported types ------------------------------------------------------------*/
/******************************************************************************/
/* Ethernet Peripheral registers structures */
/******************************************************************************/
typedef struct
{
vu32 MACCR;
vu32 MACFFR;
vu32 MACHTHR;
vu32 MACHTLR;
vu32 MACMIIAR;
vu32 MACMIIDR;
vu32 MACFCR;
vu32 MACVLANTR;
vu32 RESERVED0[2];
vu32 MACRWUFFR;
vu32 MACPMTCSR;
vu32 RESERVED1[2];
vu32 MACSR;
vu32 MACIMR;
vu32 MACA0HR;
vu32 MACA0LR;
vu32 MACA1HR;
vu32 MACA1LR;
vu32 MACA2HR;
vu32 MACA2LR;
vu32 MACA3HR;
vu32 MACA3LR;
} ETH_MAC_TypeDef;
typedef struct
{
vu32 MMCCR;
vu32 MMCRIR;
vu32 MMCTIR;
vu32 MMCRIMR;
vu32 MMCTIMR;
vu32 RESERVED0[14];
vu32 MMCTGFSCCR;
vu32 MMCTGFMSCCR;
vu32 RESERVED1[5];
vu32 MMCTGFCR;
vu32 RESERVED2[10];
vu32 MMCRFCECR;
vu32 MMCRFAER;
vu32 RESERVED3[10];
vu32 MMCRGUFCR;
} ETH_MMC_TypeDef;
typedef struct
{
vu32 PTPTSCR;
vu32 PTPSSIR;
vu32 PTPTSHR;
vu32 PTPTSLR;
vu32 PTPTSHUR;
vu32 PTPTSLUR;
vu32 PTPTSAR;
vu32 PTPTTHR;
vu32 PTPTTLR;
} ETH_PTP_TypeDef;
typedef struct
{
vu32 DMABMR;
vu32 DMATPDR;
vu32 DMARPDR;
vu32 DMARDLAR;
vu32 DMATDLAR;
vu32 DMASR;
vu32 DMAOMR;
vu32 DMAIER;
vu32 DMAMFBOCR;
vu32 RESERVED0[9];
vu32 DMACHTDR;
vu32 DMACHRDR;
vu32 DMACHTBAR;
vu32 DMACHRBAR;
} ETH_DMA_TypeDef;
/******************************************************************************/
/* Ethernet MAC Registers bits definitions */
/******************************************************************************/
//#define IPNAME_REGNAME_BITNAME /* BIT MASK */
/* Bit definition for Ethernet MAC Control Register register */
#define ETH_MACCR_WD ((u32)0x00800000) /* Watchdog disable */
#define ETH_MACCR_JD ((u32)0x00400000) /* Jabber disable */
#define ETH_MACCR_JFE ((u32)0x00100000) /* Jumbo frame enable */
#define ETH_MACCR_IFG ((u32)0x000E0000) /* Inter-frame gap */
#define ETH_MACCR_IFG_96Bit ((u32)0x00000000) /* Minimum IFG between frames during transmission is 96Bit */
#define ETH_MACCR_IFG_88Bit ((u32)0x00020000) /* Minimum IFG between frames during transmission is 88Bit */
#define ETH_MACCR_IFG_80Bit ((u32)0x00040000) /* Minimum IFG between frames during transmission is 80Bit */
#define ETH_MACCR_IFG_72Bit ((u32)0x00060000) /* Minimum IFG between frames during transmission is 72Bit */
#define ETH_MACCR_IFG_64Bit ((u32)0x00080000) /* Minimum IFG between frames during transmission is 64Bit */
#define ETH_MACCR_IFG_56Bit ((u32)0x000A0000) /* Minimum IFG between frames during transmission is 56Bit */
#define ETH_MACCR_IFG_48Bit ((u32)0x000C0000) /* Minimum IFG between frames during transmission is 48Bit */
#define ETH_MACCR_IFG_40Bit ((u32)0x000E0000) /* Minimum IFG between frames during transmission is 40Bit */
#define ETH_MACCR_CSD ((u32)0x00010000) /* Carrier sense disable (during transmission) */
#define ETH_MACCR_FES ((u32)0x00004000) /* Fast ethernet speed */
#define ETH_MACCR_ROD ((u32)0x00002000) /* Receive own disable */
#define ETH_MACCR_LM ((u32)0x00001000) /* loopback mode */
#define ETH_MACCR_DM ((u32)0x00000800) /* Duplex mode */
#define ETH_MACCR_IPCO ((u32)0x00000400) /* IP Checksum offload */
#define ETH_MACCR_RD ((u32)0x00000200) /* Retry disable */
#define ETH_MACCR_APCS ((u32)0x00000080) /* Automatic Pad/CRC stripping */
#define ETH_MACCR_BL ((u32)0x00000060) /* Back-off limit: random integer number (r) of slot time delays before rescheduling
a transmission attempt during retries after a collision: 0 =< r <2^k */
#define ETH_MACCR_BL_10 ((u32)0x00000000) /* k = min (n, 10) */
#define ETH_MACCR_BL_8 ((u32)0x00000020) /* k = min (n, 8) */
#define ETH_MACCR_BL_4 ((u32)0x00000040) /* k = min (n, 4) */
#define ETH_MACCR_BL_1 ((u32)0x00000060) /* k = min (n, 1) */
#define ETH_MACCR_DC ((u32)0x00000010) /* Defferal check */
#define ETH_MACCR_TE ((u32)0x00000008) /* Transmitter enable */
#define ETH_MACCR_RE ((u32)0x00000004) /* Receiver enable */
/* Bit definition for Ethernet MAC Frame Filter Register */
#define ETH_MACFFR_RA ((u32)0x80000000) /* Receive all */
#define ETH_MACFFR_HPF ((u32)0x00000400) /* Hash or perfect filter */
#define ETH_MACFFR_SAF ((u32)0x00000200) /* Source address filter enable */
#define ETH_MACFFR_SAIF ((u32)0x00000100) /* SA inverse filtering */
#define ETH_MACFFR_PCF ((u32)0x000000C0) /* Pass control frames: 3 cases */
#define ETH_MACFFR_PCF_BlockAll ((u32)0x00000040) /* MAC filters all control frames from reaching the application */
#define ETH_MACFFR_PCF_ForwardAll ((u32)0x00000080) /* MAC forwards all control frames to application even if they fail the Address Filter */
#define ETH_MACFFR_PCF_ForwardPassedAddrFilter ((u32)0x000000C0) /* MAC forwards control frames that pass the Address Filter. */
#define ETH_MACFFR_BFD ((u32)0x00000020) /* Broadcast frame disable */
#define ETH_MACFFR_PAM ((u32)0x00000010) /* Pass all mutlicast */
#define ETH_MACFFR_DAIF ((u32)0x00000008) /* DA Inverse filtering */
#define ETH_MACFFR_HM ((u32)0x00000004) /* Hash multicast */
#define ETH_MACFFR_HU ((u32)0x00000002) /* Hash unicast */
#define ETH_MACFFR_PM ((u32)0x00000001) /* Promiscuous mode */
/* Bit definition for Ethernet MAC Hash Table High Register */
#define ETH_MACHTHR_HTH ((u32)0xFFFFFFFF) /* Hash table high */
/* Bit definition for Ethernet MAC Hash Table Low Register */
#define ETH_MACHTLR_HTL ((u32)0xFFFFFFFF) /* Hash table low */
/* Bit definition for Ethernet MAC MII Address Register */
#define ETH_MACMIIAR_PA ((u32)0x0000F800) /* Physical layer address */
#define ETH_MACMIIAR_MR ((u32)0x000007C0) /* MII register in the selected PHY */
#define ETH_MACMIIAR_CR ((u32)0x0000001C) /* CR clock range: 6 cases */
#define ETH_MACMIIAR_CR_Div42 ((u32)0x00000000) /* HCLK:60-72 MHz; MDC clock= HCLK/42 */
#define ETH_MACMIIAR_CR_Div16 ((u32)0x00000008) /* HCLK:20-35 MHz; MDC clock= HCLK/16 */
#define ETH_MACMIIAR_CR_Div26 ((u32)0x0000000C) /* HCLK:35-60 MHz; MDC clock= HCLK/26 */
#define ETH_MACMIIAR_MW ((u32)0x00000002) /* MII write */
#define ETH_MACMIIAR_MB ((u32)0x00000001) /* MII busy */
/* Bit definition for Ethernet MAC MII Data Register */
#define ETH_MACMIIDR_MD ((u32)0x0000FFFF) /* MII data: read/write data from/to PHY */
/* Bit definition for Ethernet MAC Flow Control Register */
#define ETH_MACFCR_PT ((u32)0xFFFF0000) /* Pause time */
#define ETH_MACFCR_ZQPD ((u32)0x00000080) /* Zero-quanta pause disable */
#define ETH_MACFCR_PLT ((u32)0x00000030) /* Pause low threshold: 4 cases */
#define ETH_MACFCR_PLT_Minus4 ((u32)0x00000000) /* Pause time minus 4 slot times */
#define ETH_MACFCR_PLT_Minus28 ((u32)0x00000010) /* Pause time minus 28 slot times */
#define ETH_MACFCR_PLT_Minus144 ((u32)0x00000020) /* Pause time minus 144 slot times */
#define ETH_MACFCR_PLT_Minus256 ((u32)0x00000030) /* Pause time minus 256 slot times */
#define ETH_MACFCR_UPFD ((u32)0x00000008) /* Unicast pause frame detect */
#define ETH_MACFCR_RFCE ((u32)0x00000004) /* Receive flow control enable */
#define ETH_MACFCR_TFCE ((u32)0x00000002) /* Transmit flow control enable */
#define ETH_MACFCR_FCBBPA ((u32)0x00000001) /* Flow control busy/backpressure activate */
/* Bit definition for Ethernet MAC VLAN Tag Register */
#define ETH_MACVLANTR_VLANTC ((u32)0x00010000) /* 12-bit VLAN tag comparison */
#define ETH_MACVLANTR_VLANTI ((u32)0x0000FFFF) /* VLAN tag identifier (for receive frames) */
/* Bit definition for Ethernet MAC Remote Wake-UpFrame Filter Register */
#define ETH_MACRWUFFR_D ((u32)0xFFFFFFFF) /* Wake-up frame filter register data */
/* Eight sequential Writes to this address (offset 0x28) will write all Wake-UpFrame Filter Registers.
Eight sequential Reads from this address (offset 0x28) will read all Wake-UpFrame Filter Registers. */
/* Wake-UpFrame Filter Reg0 : Filter 0 Byte Mask
Wake-UpFrame Filter Reg1 : Filter 1 Byte Mask
Wake-UpFrame Filter Reg2 : Filter 2 Byte Mask
Wake-UpFrame Filter Reg3 : Filter 3 Byte Mask
Wake-UpFrame Filter Reg4 : RSVD - Filter3 Command - RSVD - Filter2 Command -
RSVD - Filter1 Command - RSVD - Filter0 Command
Wake-UpFrame Filter Re5 : Filter3 Offset - Filter2 Offset - Filter1 Offset - Filter0 Offset
Wake-UpFrame Filter Re6 : Filter1 CRC16 - Filter0 CRC16
Wake-UpFrame Filter Re7 : Filter3 CRC16 - Filter2 CRC16 */
/* Bit definition for Ethernet MAC PMT Control and Status Register */
#define ETH_MACPMTCSR_WFFRPR ((u32)0x80000000) /* Wake-Up Frame Filter Register Pointer Reset */
#define ETH_MACPMTCSR_GU ((u32)0x00000200) /* Global Unicast */
#define ETH_MACPMTCSR_WFR ((u32)0x00000040) /* Wake-Up Frame Received */
#define ETH_MACPMTCSR_MPR ((u32)0x00000020) /* Magic Packet Received */
#define ETH_MACPMTCSR_WFE ((u32)0x00000004) /* Wake-Up Frame Enable */
#define ETH_MACPMTCSR_MPE ((u32)0x00000002) /* Magic Packet Enable */
#define ETH_MACPMTCSR_PD ((u32)0x00000001) /* Power Down */
/* Bit definition for Ethernet MAC Status Register */
#define ETH_MACSR_TSTS ((u32)0x00000200) /* Time stamp trigger status */
#define ETH_MACSR_MMCTS ((u32)0x00000040) /* MMC transmit status */
#define ETH_MACSR_MMMCRS ((u32)0x00000020) /* MMC receive status */
#define ETH_MACSR_MMCS ((u32)0x00000010) /* MMC status */
#define ETH_MACSR_PMTS ((u32)0x00000008) /* PMT status */
/* Bit definition for Ethernet MAC Interrupt Mask Register */
#define ETH_MACIMR_TSTIM ((u32)0x00000200) /* Time stamp trigger interrupt mask */
#define ETH_MACIMR_PMTIM ((u32)0x00000008) /* PMT interrupt mask */
/* Bit definition for Ethernet MAC Address0 High Register */
#define ETH_MACA0HR_MACA0H ((u32)0x0000FFFF) /* MAC address0 high */
/* Bit definition for Ethernet MAC Address0 Low Register */
#define ETH_MACA0LR_MACA0L ((u32)0xFFFFFFFF) /* MAC address0 low */
/* Bit definition for Ethernet MAC Address1 High Register */
#define ETH_MACA1HR_AE ((u32)0x80000000) /* Address enable */
#define ETH_MACA1HR_SA ((u32)0x40000000) /* Source address */
#define ETH_MACA1HR_MBC ((u32)0x3F000000) /* Mask byte control: bits to mask for comparison of the MAC Address bytes */
#define ETH_MACA1HR_MBC_HBits15_8 ((u32)0x20000000) /* Mask MAC Address high reg bits [15:8] */
#define ETH_MACA1HR_MBC_HBits7_0 ((u32)0x10000000) /* Mask MAC Address high reg bits [7:0] */
#define ETH_MACA1HR_MBC_LBits31_24 ((u32)0x08000000) /* Mask MAC Address low reg bits [31:24] */
#define ETH_MACA1HR_MBC_LBits23_16 ((u32)0x04000000) /* Mask MAC Address low reg bits [23:16] */
#define ETH_MACA1HR_MBC_LBits15_8 ((u32)0x02000000) /* Mask MAC Address low reg bits [15:8] */
#define ETH_MACA1HR_MBC_LBits7_0 ((u32)0x01000000) /* Mask MAC Address low reg bits [7:0] */
#define ETH_MACA1HR_MACA1H ((u32)0x0000FFFF) /* MAC address1 high */
/* Bit definition for Ethernet MAC Address1 Low Register */
#define ETH_MACA1LR_MACA1L ((u32)0xFFFFFFFF) /* MAC address1 low */
/* Bit definition for Ethernet MAC Address2 High Register */
#define ETH_MACA2HR_AE ((u32)0x80000000) /* Address enable */
#define ETH_MACA2HR_SA ((u32)0x40000000) /* Source address */
#define ETH_MACA2HR_MBC ((u32)0x3F000000) /* Mask byte control */
#define ETH_MACA2HR_MBC_HBits15_8 ((u32)0x20000000) /* Mask MAC Address high reg bits [15:8] */
#define ETH_MACA2HR_MBC_HBits7_0 ((u32)0x10000000) /* Mask MAC Address high reg bits [7:0] */
#define ETH_MACA2HR_MBC_LBits31_24 ((u32)0x08000000) /* Mask MAC Address low reg bits [31:24] */
#define ETH_MACA2HR_MBC_LBits23_16 ((u32)0x04000000) /* Mask MAC Address low reg bits [23:16] */
#define ETH_MACA2HR_MBC_LBits15_8 ((u32)0x02000000) /* Mask MAC Address low reg bits [15:8] */
#define ETH_MACA2HR_MBC_LBits7_0 ((u32)0x01000000) /* Mask MAC Address low reg bits [70] */
#define ETH_MACA2HR_MACA2H ((u32)0x0000FFFF) /* MAC address1 high */
/* Bit definition for Ethernet MAC Address2 Low Register */
#define ETH_MACA2LR_MACA2L ((u32)0xFFFFFFFF) /* MAC address2 low */
/* Bit definition for Ethernet MAC Address3 High Register */
#define ETH_MACA3HR_AE ((u32)0x80000000) /* Address enable */
#define ETH_MACA3HR_SA ((u32)0x40000000) /* Source address */
#define ETH_MACA3HR_MBC ((u32)0x3F000000) /* Mask byte control */
#define ETH_MACA2HR_MBC_HBits15_8 ((u32)0x20000000) /* Mask MAC Address high reg bits [15:8] */
#define ETH_MACA2HR_MBC_HBits7_0 ((u32)0x10000000) /* Mask MAC Address high reg bits [7:0] */
#define ETH_MACA2HR_MBC_LBits31_24 ((u32)0x08000000) /* Mask MAC Address low reg bits [31:24] */
#define ETH_MACA2HR_MBC_LBits23_16 ((u32)0x04000000) /* Mask MAC Address low reg bits [23:16] */
#define ETH_MACA2HR_MBC_LBits15_8 ((u32)0x02000000) /* Mask MAC Address low reg bits [15:8] */
#define ETH_MACA2HR_MBC_LBits7_0 ((u32)0x01000000) /* Mask MAC Address low reg bits [70] */
#define ETH_MACA3HR_MACA3H ((u32)0x0000FFFF) /* MAC address3 high */
/* Bit definition for Ethernet MAC Address3 Low Register */
#define ETH_MACA3LR_MACA3L ((u32)0xFFFFFFFF) /* MAC address3 low */
/******************************************************************************/
/* Ethernet MMC Registers bits definition */
/******************************************************************************/
/* Bit definition for Ethernet MMC Contol Register */
#define ETH_MMCCR_MCF ((u32)0x00000008) /* MMC Counter Freeze */
#define ETH_MMCCR_ROR ((u32)0x00000004) /* Reset on Read */
#define ETH_MMCCR_CSR ((u32)0x00000002) /* Counter Stop Rollover */
#define ETH_MMCCR_CR ((u32)0x00000001) /* Counters Reset */
/* Bit definition for Ethernet MMC Receive Interrupt Register */
#define ETH_MMCRIR_RGUFS ((u32)0x00020000) /* Set when Rx good unicast frames counter reaches half the maximum value */
#define ETH_MMCRIR_RFAES ((u32)0x00000040) /* Set when Rx alignment error counter reaches half the maximum value */
#define ETH_MMCRIR_RFCES ((u32)0x00000020) /* Set when Rx crc error counter reaches half the maximum value */
/* Bit definition for Ethernet MMC Transmit Interrupt Register */
#define ETH_MMCTIR_TGFS ((u32)0x00200000) /* Set when Tx good frame count counter reaches half the maximum value */
#define ETH_MMCTIR_TGFMSCS ((u32)0x00008000) /* Set when Tx good multi col counter reaches half the maximum value */
#define ETH_MMCTIR_TGFSCS ((u32)0x00004000) /* Set when Tx good single col counter reaches half the maximum value */
/* Bit definition for Ethernet MMC Receive Interrupt Mask Register */
#define ETH_MMCRIMR_RGUFM ((u32)0x00020000) /* Mask the interrupt when Rx good unicast frames counter reaches half the maximum value */
#define ETH_MMCRIMR_RFAEM ((u32)0x00000040) /* Mask the interrupt when when Rx alignment error counter reaches half the maximum value */
#define ETH_MMCRIMR_RFCEM ((u32)0x00000020) /* Mask the interrupt when Rx crc error counter reaches half the maximum value */
/* Bit definition for Ethernet MMC Transmit Interrupt Mask Register */
#define ETH_MMCTIMR_TGFM ((u32)0x00200000) /* Mask the interrupt when Tx good frame count counter reaches half the maximum value */
#define ETH_MMCTIMR_TGFMSCM ((u32)0x00008000) /* Mask the interrupt when Tx good multi col counter reaches half the maximum value */
#define ETH_MMCTIMR_TGFSCM ((u32)0x00004000) /* Mask the interrupt when Tx good single col counter reaches half the maximum value */
/* Bit definition for Ethernet MMC Transmitted Good Frames after Single Collision Counter Register */
#define ETH_MMCTGFSCCR_TGFSCC ((u32)0xFFFFFFFF) /* Number of successfully transmitted frames after a single collision in Half-duplex mode. */
/* Bit definition for Ethernet MMC Transmitted Good Frames after More than a Single Collision Counter Register */
#define ETH_MMCTGFMSCCR_TGFMSCC ((u32)0xFFFFFFFF) /* Number of successfully transmitted frames after more than a single collision in Half-duplex mode. */
/* Bit definition for Ethernet MMC Transmitted Good Frames Counter Register */
#define ETH_MMCTGFCR_TGFC ((u32)0xFFFFFFFF) /* Number of good frames transmitted. */
/* Bit definition for Ethernet MMC Received Frames with CRC Error Counter Register */
#define ETH_MMCRFCECR_RFCEC ((u32)0xFFFFFFFF) /* Number of frames received with CRC error. */
/* Bit definition for Ethernet MMC Received Frames with Alignement Error Counter Register */
#define ETH_MMCRFAECR_RFAEC ((u32)0xFFFFFFFF) /* Number of frames received with alignment (dribble) error */
/* Bit definition for Ethernet MMC Received Good Unicast Frames Counter Register */
#define ETH_MMCRGUFCR_RGUFC ((u32)0xFFFFFFFF) /* Number of good unicast frames received. */
/******************************************************************************/
/* Ethernet PTP Registers bits definition */
/******************************************************************************/
/* Bit definition for Ethernet PTP Time Stamp Contol Register */
#define ETH_PTPTSCR_TSARU ((u32)0x00000020) /* Addend register update */
#define ETH_PTPTSCR_TSITE ((u32)0x00000010) /* Time stamp interrupt trigger enable */
#define ETH_PTPTSCR_TSSTU ((u32)0x00000008) /* Time stamp update */
#define ETH_PTPTSCR_TSSTI ((u32)0x00000004) /* Time stamp initialize */
#define ETH_PTPTSCR_TSFCU ((u32)0x00000002) /* Time stamp fine or coarse update */
#define ETH_PTPTSCR_TSE ((u32)0x00000001) /* Time stamp enable */
/* Bit definition for Ethernet PTP Sub-Second Increment Register */
#define ETH_PTPSSIR_STSSI ((u32)0x000000FF) /* System time Sub-second increment value */
/* Bit definition for Ethernet PTP Time Stamp High Register */
#define ETH_PTPTSHR_STS ((u32)0xFFFFFFFF) /* System Time second */
/* Bit definition for Ethernet PTP Time Stamp Low Register */
#define ETH_PTPTSLR_STPNS ((u32)0x80000000) /* System Time Positive or negative time */
#define ETH_PTPTSLR_STSS ((u32)0x7FFFFFFF) /* System Time sub-seconds */
/* Bit definition for Ethernet PTP Time Stamp High Update Register */
#define ETH_PTPTSHUR_TSUS ((u32)0xFFFFFFFF) /* Time stamp update seconds */
/* Bit definition for Ethernet PTP Time Stamp Low Update Register */
#define ETH_PTPTSLUR_TSUPNS ((u32)0x80000000) /* Time stamp update Positive or negative time */
#define ETH_PTPTSLUR_TSUSS ((u32)0x7FFFFFFF) /* Time stamp update sub-seconds */
/* Bit definition for Ethernet PTP Time Stamp Addend Register */
#define ETH_PTPTSAR_TSA ((u32)0xFFFFFFFF) /* Time stamp addend */
/* Bit definition for Ethernet PTP Target Time High Register */
#define ETH_PTPTTHR_TTSH ((u32)0xFFFFFFFF) /* Target time stamp high */
/* Bit definition for Ethernet PTP Target Time Low Register */
#define ETH_PTPTTLR_TTSL ((u32)0xFFFFFFFF) /* Target time stamp low */
/******************************************************************************/
/* Ethernet DMA Registers bits definition */
/******************************************************************************/
/* Bit definition for Ethernet DMA Bus Mode Register */
#define ETH_DMABMR_AAB ((u32)0x02000000) /* Address-Aligned beats */
#define ETH_DMABMR_FPM ((u32)0x01000000) /* 4xPBL mode */
#define ETH_DMABMR_USP ((u32)0x00800000) /* Use separate PBL */
#define ETH_DMABMR_RDP ((u32)0x007E0000) /* RxDMA PBL */
/* Values to be confirmed: maybe they are inversed */
#define ETH_DMABMR_RDP_1Beat ((u32)0x00020000) /* maximum number of beats to be transferred in one RxDMA transaction is 1 */
#define ETH_DMABMR_RDP_2Beat ((u32)0x00040000) /* maximum number of beats to be transferred in one RxDMA transaction is 2 */
#define ETH_DMABMR_RDP_4Beat ((u32)0x00080000) /* maximum number of beats to be transferred in one RxDMA transaction is 4 */
#define ETH_DMABMR_RDP_8Beat ((u32)0x00100000) /* maximum number of beats to be transferred in one RxDMA transaction is 8 */
#define ETH_DMABMR_RDP_16Beat ((u32)0x00200000) /* maximum number of beats to be transferred in one RxDMA transaction is 16 */
#define ETH_DMABMR_RDP_32Beat ((u32)0x00400000) /* maximum number of beats to be transferred in one RxDMA transaction is 32 */
#define ETH_DMABMR_RDP_4xPBL_4Beat ((u32)0x01020000) /* maximum number of beats to be transferred in one RxDMA transaction is 4 */
#define ETH_DMABMR_RDP_4xPBL_8Beat ((u32)0x01040000) /* maximum number of beats to be transferred in one RxDMA transaction is 8 */
#define ETH_DMABMR_RDP_4xPBL_16Beat ((u32)0x01080000) /* maximum number of beats to be transferred in one RxDMA transaction is 16 */
#define ETH_DMABMR_RDP_4xPBL_32Beat ((u32)0x01100000) /* maximum number of beats to be transferred in one RxDMA transaction is 32 */
#define ETH_DMABMR_RDP_4xPBL_64Beat ((u32)0x01200000) /* maximum number of beats to be transferred in one RxDMA transaction is 64 */
#define ETH_DMABMR_RDP_4xPBL_128Beat ((u32)0x01400000) /* maximum number of beats to be transferred in one RxDMA transaction is 128 */
#define ETH_DMABMR_FB ((u32)0x00010000) /* Fixed Burst */
#define ETH_DMABMR_RTPR ((u32)0x0000C000) /* Rx Tx priority ratio */
#define ETH_DMABMR_RTPR_1_1 ((u32)0x00000000) /* Rx Tx priority ratio */
#define ETH_DMABMR_RTPR_2_1 ((u32)0x00004000) /* Rx Tx priority ratio */
#define ETH_DMABMR_RTPR_3_1 ((u32)0x00008000) /* Rx Tx priority ratio */
#define ETH_DMABMR_RTPR_4_1 ((u32)0x0000C000) /* Rx Tx priority ratio */
#define ETH_DMABMR_PBL ((u32)0x00003F00) /* Programmable burst length */
/* Values to be confirmed: maybe they are inversed */
#define ETH_DMABMR_PBL_1Beat ((u32)0x00000100) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */
#define ETH_DMABMR_PBL_2Beat ((u32)0x00000200) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */
#define ETH_DMABMR_PBL_4Beat ((u32)0x00000400) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */
#define ETH_DMABMR_PBL_8Beat ((u32)0x00000800) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */
#define ETH_DMABMR_PBL_16Beat ((u32)0x00001000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */
#define ETH_DMABMR_PBL_32Beat ((u32)0x00002000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */
#define ETH_DMABMR_PBL_4xPBL_4Beat ((u32)0x01000100) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */
#define ETH_DMABMR_PBL_4xPBL_8Beat ((u32)0x01000200) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */
#define ETH_DMABMR_PBL_4xPBL_16Beat ((u32)0x01000400) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */
#define ETH_DMABMR_PBL_4xPBL_32Beat ((u32)0x01000800) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */
#define ETH_DMABMR_PBL_4xPBL_64Beat ((u32)0x01001000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */
#define ETH_DMABMR_PBL_4xPBL_128Beat ((u32)0x01002000) /* maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */
#define ETH_DMABMR_DSL ((u32)0x0000007C) /* Descriptor Skip Length */
#define ETH_DMABMR_DA ((u32)0x00000002) /* DMA arbitration scheme */
#define ETH_DMABMR_SR ((u32)0x00000001) /* Software reset */
/* Bit definition for Ethernet DMA Transmit Poll Demand Register */
#define ETH_DMATPDR_TPD ((u32)0xFFFFFFFF) /* Transmit poll demand */
/* Bit definition for Ethernet DMA Receive Poll Demand Register */
#define ETH_DMARPDR_RPD ((u32)0xFFFFFFFF) /* Receive poll demand */
/* Bit definition for Ethernet DMA Receive Descriptor List Address Register */
#define ETH_DMARDLAR_SRL ((u32)0xFFFFFFFF) /* Start of receive list */
/* Bit definition for Ethernet DMA Transmit Descriptor List Address Register */
#define ETH_DMATDLAR_STL ((u32)0xFFFFFFFF) /* Start of transmit list */
/* Bit definition for Ethernet DMA Status Register */
#define ETH_DMASR_TSTS ((u32)0x20000000) /* Time-stamp trigger status */
#define ETH_DMASR_PMTS ((u32)0x10000000) /* PMT status */
#define ETH_DMASR_MMCS ((u32)0x08000000) /* MMC status */
#define ETH_DMASR_EBS ((u32)0x03800000) /* Error bits status */
/* combination with EBS[2:0] for GetFlagStatus function */
#define ETH_DMASR_EBS_DescAccess ((u32)0x02000000) /* Error bits 0-data buffer, 1-desc. access */
#define ETH_DMASR_EBS_ReadTransf ((u32)0x01000000) /* Error bits 0-write trnsf, 1-read transfr */
#define ETH_DMASR_EBS_DataTransfTx ((u32)0x00800000) /* Error bits 0-Rx DMA, 1-Tx DMA */
#define ETH_DMASR_TPS ((u32)0x00700000) /* Transmit process state */
#define ETH_DMASR_TPS_Stopped ((u32)0x00000000) /* Stopped - Reset or Stop Tx Command issued */
#define ETH_DMASR_TPS_Fetching ((u32)0x00100000) /* Running - fetching the Tx descriptor */
#define ETH_DMASR_TPS_Waiting ((u32)0x00200000) /* Running - waiting for status */
#define ETH_DMASR_TPS_Reading ((u32)0x00300000) /* Running - reading the data from host memory */
#define ETH_DMASR_TPS_Suspended ((u32)0x00600000) /* Suspended - Tx Descriptor unavailabe */
#define ETH_DMASR_TPS_Closing ((u32)0x00700000) /* Running - closing Rx descriptor */
#define ETH_DMASR_RPS ((u32)0x000E0000) /* Receive process state */
#define ETH_DMASR_RPS_Stopped ((u32)0x00000000) /* Stopped - Reset or Stop Rx Command issued */
#define ETH_DMASR_RPS_Fetching ((u32)0x00020000) /* Running - fetching the Rx descriptor */
#define ETH_DMASR_RPS_Waiting ((u32)0x00060000) /* Running - waiting for packet */
#define ETH_DMASR_RPS_Suspended ((u32)0x00080000) /* Suspended - Rx Descriptor unavailable */
#define ETH_DMASR_RPS_Closing ((u32)0x000A0000) /* Running - closing descriptor */
#define ETH_DMASR_RPS_Queuing ((u32)0x000E0000) /* Running - queuing the recieve frame into host memory */
#define ETH_DMASR_NIS ((u32)0x00010000) /* Normal interrupt summary */
#define ETH_DMASR_AIS ((u32)0x00008000) /* Abnormal interrupt summary */
#define ETH_DMASR_ERS ((u32)0x00004000) /* Early receive status */
#define ETH_DMASR_FBES ((u32)0x00002000) /* Fatal bus error status */
#define ETH_DMASR_ETS ((u32)0x00000400) /* Early transmit status */
#define ETH_DMASR_RWTS ((u32)0x00000200) /* Receive watchdog timeout status */
#define ETH_DMASR_RPSS ((u32)0x00000100) /* Receive process stopped status */
#define ETH_DMASR_RBUS ((u32)0x00000080) /* Receive buffer unavailable status */
#define ETH_DMASR_RS ((u32)0x00000040) /* Receive status */
#define ETH_DMASR_TUS ((u32)0x00000020) /* Transmit underflow status */
#define ETH_DMASR_ROS ((u32)0x00000010) /* Receive overflow status */
#define ETH_DMASR_TJTS ((u32)0x00000008) /* Transmit jabber timeout status */
#define ETH_DMASR_TBUS ((u32)0x00000004) /* Transmit buffer unavailable status */
#define ETH_DMASR_TPSS ((u32)0x00000002) /* Transmit process stopped status */
#define ETH_DMASR_TS ((u32)0x00000001) /* Transmit status */
/* Bit definition for Ethernet DMA Operation Mode Register */
#define ETH_DMAOMR_DTCEFD ((u32)0x04000000) /* Disable Dropping of TCP/IP checksum error frames */
#define ETH_DMAOMR_RSF ((u32)0x02000000) /* Receive store and forward */
#define ETH_DMAOMR_DFRF ((u32)0x01000000) /* Disable flushing of received frames */
#define ETH_DMAOMR_TSF ((u32)0x00200000) /* Transmit store and forward */
#define ETH_DMAOMR_FTF ((u32)0x00100000) /* Flush transmit FIFO */
#define ETH_DMAOMR_TTC ((u32)0x0001C000) /* Transmit threshold control */
#define ETH_DMAOMR_TTC_64Bytes ((u32)0x00000000) /* threshold level of the MTL Transmit FIFO is 64 Bytes */
#define ETH_DMAOMR_TTC_128Bytes ((u32)0x00004000) /* threshold level of the MTL Transmit FIFO is 128 Bytes */
#define ETH_DMAOMR_TTC_192Bytes ((u32)0x00008000) /* threshold level of the MTL Transmit FIFO is 192 Bytes */
#define ETH_DMAOMR_TTC_256Bytes ((u32)0x0000C000) /* threshold level of the MTL Transmit FIFO is 256 Bytes */
#define ETH_DMAOMR_TTC_40Bytes ((u32)0x00010000) /* threshold level of the MTL Transmit FIFO is 40 Bytes */
#define ETH_DMAOMR_TTC_32Bytes ((u32)0x00014000) /* threshold level of the MTL Transmit FIFO is 32 Bytes */
#define ETH_DMAOMR_TTC_24Bytes ((u32)0x00018000) /* threshold level of the MTL Transmit FIFO is 24 Bytes */
#define ETH_DMAOMR_TTC_16Bytes ((u32)0x0001C000) /* threshold level of the MTL Transmit FIFO is 16 Bytes */
#define ETH_DMAOMR_ST ((u32)0x00002000) /* Start/stop transmission command */
#define ETH_DMAOMR_FEF ((u32)0x00000080) /* Forward error frames */
#define ETH_DMAOMR_FUGF ((u32)0x00000040) /* Forward undersized good frames */
#define ETH_DMAOMR_RTC ((u32)0x00000018) /* receive threshold control */
#define ETH_DMAOMR_RTC_64Bytes ((u32)0x00000000) /* threshold level of the MTL Receive FIFO is 64 Bytes */
#define ETH_DMAOMR_RTC_32Bytes ((u32)0x00000008) /* threshold level of the MTL Receive FIFO is 32 Bytes */
#define ETH_DMAOMR_RTC_96Bytes ((u32)0x00000010) /* threshold level of the MTL Receive FIFO is 96 Bytes */
#define ETH_DMAOMR_RTC_128Bytes ((u32)0x00000018) /* threshold level of the MTL Receive FIFO is 128 Bytes */
#define ETH_DMAOMR_OSF ((u32)0x00000004) /* operate on second frame */
#define ETH_DMAOMR_SR ((u32)0x00000002) /* Start/stop receive */
/* Bit definition for Ethernet DMA Interrupt Enable Register */
#define ETH_DMAIER_NISE ((u32)0x00010000) /* Normal interrupt summary enable */
#define ETH_DMAIER_AISE ((u32)0x00008000) /* Abnormal interrupt summary enable */
#define ETH_DMAIER_ERIE ((u32)0x00004000) /* Early receive interrupt enable */
#define ETH_DMAIER_FBEIE ((u32)0x00002000) /* Fatal bus error interrupt enable */
#define ETH_DMAIER_ETIE ((u32)0x00000400) /* Early transmit interrupt enable */
#define ETH_DMAIER_RWTIE ((u32)0x00000200) /* Receive watchdog timeout interrupt enable */
#define ETH_DMAIER_RPSIE ((u32)0x00000100) /* Receive process stopped interrupt enable */
#define ETH_DMAIER_RBUIE ((u32)0x00000080) /* Receive buffer unavailable interrupt enable */
#define ETH_DMAIER_RIE ((u32)0x00000040) /* Receive interrupt enable */
#define ETH_DMAIER_TUIE ((u32)0x00000020) /* Transmit Underflow interrupt enable */
#define ETH_DMAIER_ROIE ((u32)0x00000010) /* Receive Overflow interrupt enable */
#define ETH_DMAIER_TJTIE ((u32)0x00000008) /* Transmit jabber timeout interrupt enable */
#define ETH_DMAIER_TBUIE ((u32)0x00000004) /* Transmit buffer unavailable interrupt enable */
#define ETH_DMAIER_TPSIE ((u32)0x00000002) /* Transmit process stopped interrupt enable */
#define ETH_DMAIER_TIE ((u32)0x00000001) /* Transmit interrupt enable */
/* Bit definition for Ethernet DMA Missed Frame and Buffer Overflow Counter Register */
#define ETH_DMAMFBOCR_OFOC ((u32)0x10000000) /* Overflow bit for FIFO overflow counter */
#define ETH_DMAMFBOCR_MFA ((u32)0x0FFE0000) /* Number of frames missed by the application */
#define ETH_DMAMFBOCR_OMFC ((u32)0x00010000) /* Overflow bit for missed frame counter */
#define ETH_DMAMFBOCR_MFC ((u32)0x0000FFFF) /* Number of frames missed by the controller */
/* Bit definition for Ethernet DMA Current Host Transmit Descriptor Register */
#define ETH_DMACHTDR_HTDAP ((u32)0xFFFFFFFF) /* Host transmit descriptor address pointer */
/* Bit definition for Ethernet DMA Current Host Receive Descriptor Register */
#define ETH_DMACHRDR_HRDAP ((u32)0xFFFFFFFF) /* Host receive descriptor address pointer */
/* Bit definition for Ethernet DMA Current Host Transmit Buffer Address Register */
#define ETH_DMACHTBAR_HTBAP ((u32)0xFFFFFFFF) /* Host transmit buffer address pointer */
/* Bit definition for Ethernet DMA Current Host Receive Buffer Address Register */
#define ETH_DMACHRBAR_HRBAP ((u32)0xFFFFFFFF) /* Host receive buffer address pointer */
/******************************************************************************/
/* Macros */
/******************************************************************************/
#define SET_BIT(REG, BIT) ((REG) |= (BIT))
#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT))
#define READ_BIT(REG, BIT) ((REG) & (BIT))
/******************************************************************************/
/* Peripheral memory map */
/******************************************************************************/
/* ETHERNET registers base address */
#define ETH_BASE ((u32)0x40028000)
#define ETH_MAC_BASE (ETH_BASE)
#define ETH_MMC_BASE (ETH_BASE + 0x0100)
#define ETH_PTP_BASE (ETH_BASE + 0x0700)
#define ETH_DMA_BASE (ETH_BASE + 0x1000)
/******************************************************************************/
/* Peripheral declaration */
/******************************************************************************/
/*------------------------ Non Debug Mode ------------------------------------*/
#ifndef ETH_DEBUG
#ifdef _ETH_MAC
#define ETH_MAC ((ETH_MAC_TypeDef *) ETH_MAC_BASE)
#endif /*_ETH_MAC */
#ifdef _ETH_MMC
#define ETH_MMC ((ETH_MMC_TypeDef *) ETH_MMC_BASE)
#endif /*_ETH_MMC */
#ifdef _ETH_PTP
#define ETH_PTP ((ETH_PTP_TypeDef *) ETH_PTP_BASE)
#endif /*_ETH_PTP */
#ifdef _ETH_DMA
#define ETH_DMA ((ETH_DMA_TypeDef *) ETH_DMA_BASE)
#endif /*_ETH_DMA */
/*------------------------ Debug Mode ----------------------------------------*/
#else /* ETH_DEBUG */
#ifdef _ETH_MAC
EXT ETH_MAC_TypeDef *ETH_MAC;
#endif /*_ETH_MAC */
#ifdef _ETH_MMC
EXT ETH_MMC_TypeDef *ETH_MMC;
#endif /*_ETH_MMC */
#ifdef _ETH_PTP
EXT ETH_PTP_TypeDef *ETH_PTP;
#endif /*_ETH_PTP */
#ifdef _ETH_DMA
EXT ETH_DMA_TypeDef *ETH_DMA;
#endif /*_ETH_DMA */
#endif /* ETH_DEBUG */
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
#endif /* __STM32FXXX_ETH_MAP_H */
/******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/
|
akshaykumar19002/FamilyLocator
|
app/src/main/java/com/kumar/akshay/familylocator/Database/FamilyDBContract.java
|
<reponame>akshaykumar19002/FamilyLocator
package com.kumar.akshay.familylocator.Database;
import android.provider.BaseColumns;
public final class FamilyDBContract implements BaseColumns {
//Database Name
public static final String DATABASE_NAME = "OUR_FAMILY_LOCATOR_DB";
//Database Version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_URL = "https://akshayakshaykumar929.000webhostapp.com/";
//Tables' name
public static final String LOCATIONS_TABLE_NAME = "LOCATION_TABLE";
public static final String USERS_TABLE_NAME = "USERS_TABLE";
public static final String GEOFENCE_LIST_TABLE_NAME = "GEOFENCES_LIST";
public static final String GROUPS_TABLE_NAME = "GROUPS";
public static final String REQUESTS_TABLE_NAME = "REQUESTS";
//Columns in locations tableA
public static final String LOCATION_ID_COLUMN = "LOCATION_ID";
public static final String LOCATIONS_COLUMN_LOCATION = "LOCATION";
public static final String LOCATIONS_COLUMN_USER = "LOCATION_USER_ID";
public static final String LOCATIONS_COLUMN_TIME = "LOCATION_TIME";
//Columns in users table
public static final String USER_UID = "UID";
public static final String USER_COLUMN_USER_EMAIL = "USER_EMAIL";
public static final String USER_COLUMN_USER_NAME = "USER_NAME";
public static final String USER_COLUMN_USER_PASSWORD = "<PASSWORD>";
public static final String USER_COLUMN_CURRENT_USER = "CURRENT_USER";
//Columns in geofences table
public static final String GEOFENCE_COLUMN_ID = "GEOFENCE_ID";
public static final String GEOFENCE_NAME_COLUMN = "GEOFENCE_NAME";
public static final String GEOFENCE_UID_COLUMN = "GEOFENCE_UID";
public static final String GEOFENCE_LATITUDE_COLUMN = "GEOFENCE_LATITUDE";
public static final String GEOFENCE_LONGITUDE_COLUMN = "GEOFENCE_LONGITUDE";
//Columns in Groups table
public static final String GROUPS_COLUMN_ID = "GROUP_ID";
public static final String GROUPS_NAME_COLUMN = "GROUP_NAME";
public static final String GROUPS_ADMIN_NAME_COLUMN = "GROUP_ADMIN_NAME";
public static final String GROUPS_USERS_COLUMN = "GROUP_USERS";
//Columns for request table
public static final String REQUEST_COLUMN_ID = "REQUEST_ID";
public static final String REQUEST_INIT_UID = "REQUEST_INIT_UID";
public static final String REQUEST_GID = "REQUEST_GID";
public static final String REQUEST_END_UID = "REQUEST_END_UID";
}
|
tobby2002/tradyai-api
|
strategies/Gekko-Strategies-master/!WORKSOP/chang.js
|
<filename>strategies/Gekko-Strategies-master/!WORKSOP/chang.js
// This is a basic example strategy for Gekko.
// For more information on everything please refer
// to this document:
//
// https://gekko.wizb.it/docs/strategies/creating_a_strategy.html
//
// The example below is pretty bad investment advice: on every new candle there is
// a 10% chance it will recommend to change your position (to either
// long or short).
// helpers
var _ = require('lodash');
var log = require('../core/log.js');
// Let's create our own strat
var strat = {};
// Prepare everything our method needs
strat.init = function() {
// keep state about the current trend
// here, on every new candle we use this
// state object to check if we need to
// report it.
this.trend = {
direction: 'none',
duration: 0,
persisted: false,
adviced: false,
flagHasShort: false
};
this.firstUpwardPriceDetected = 0;
this.firstDownwardPriceDetected = 0;
// how many candles do we need as a base
// before we can start giving advice?
this.requiredHistory = this.tradingAdvisor.historySize;
// define the indicators we need
this.addIndicator('macd', 'MACD', this.settings);
}
// What happens on every new candle?
strat.update = function(candle) {
// Get a random number between 0 and 1.
this.randomNumber = Math.random();
// There is a 10% chance it is smaller than 0.1
this.toUpdate = this.randomNumber < 0.1;
}
// for debugging purposes: log the last calculated
// EMAs and diff.
strat.log = function() {
var digits = 8;
var macd = this.indicators.macd;
var diff = macd.diff;
var signal = macd.signal.result;
var deltaLift = macd.currentPrice - this.firstUpwardPriceDetected;
var pctDeltaLift = deltaLift * 100 / this.firstUpwardPriceDetected;
//TODO: add MACD slope
// https://www.wealth-lab.com/Forum/Posts/Identify-the-price-at-which-the-slope-of-MACD-changes-its-sign-intra-bar-38478
log.debug('calculated MACD properties for candle:');
log.debug('\t', 'short:', macd.short.result.toFixed(digits));
log.debug('\t', 'long:', macd.long.result.toFixed(digits));
log.debug('\t', 'macd:', diff.toFixed(digits));
log.debug('\t', 'signal:', signal.toFixed(digits));
log.debug('\t', 'macdiff:', macd.result.toFixed(digits));
log.debug('Historical:');
log.debug('\t', 'current price:', macd.currentPrice.toFixed(digits));
if(this.trend.direction == 'up'){
deltaLift = macd.currentPrice - this.firstUpwardPriceDetected;
pctDeltaLift = deltaLift * 100 / this.firstUpwardPriceDetected;
log.debug('\t', 'price when lift detected:', this.firstUpwardPriceDetected.toFixed(digits));
log.debug('\t', 'delta (current - initial):', deltaLift.toFixed(digits));
log.debug('\t', '% changed since detection:', pctDeltaLift.toFixed(digits));
} else if(this.trend.direction == 'down'){
deltaLift = macd.currentPrice - this.firstDownwardPriceDetected;
pctDeltaLift = deltaLift * 100 / this.firstDownwardPriceDetected;
log.debug('\t', 'price when fall detected:', this.firstDownwardPriceDetected.toFixed(digits));
log.debug('\t', 'delta (current - initial):', deltaLift.toFixed(digits));
log.debug('\t', '% changed since detection:', pctDeltaLift.toFixed(digits));
}
//log.debug('calculated random number:');
//log.debug('\t', this.randomNumber.toFixed(3));
}
// Based on the newly calculated
// information, check if we should
// update or not.
strat.check = function() {
/*
// Only continue if we have a new update.
if(!this.toUpdate)
return;
if(this.currentTrend === 'long') {
// If it was long, set it to short
this.currentTrend = 'short';
this.advice('short');
} else {
// If it was short, set it to long
this.currentTrend = 'long';
this.advice('long');
}
*/
//TODO: Add variable for manual pausing on giving no advice
//TODO: Add short after 8 upward candles, don't wait for trend to go down.
// If short early, don't advise to go long until next cycle. Therefore add flagDoNotLongUntilShort.
// Add percent increase to get before jumping, or 8 candles change number for speed
//TODO: If we went long and bought, we want to short after we are profitable by x%.
//TODO: IF YOU can't buy in 7 candles, cancel the order, wait for the next wave
var macddiff = this.indicators.macd.result;
if(macddiff > this.settings.thresholds.up) {
// new trend detected
if(this.trend.direction !== 'up')
// reset the state for the new trend
this.trend = {
duration: 0,
persisted: false,
direction: 'up',
adviced: false,
flagHasShort: false
};
if(this.trend.duration == 0)
this.firstUpwardPriceDetected = this.indicators.macd.currentPrice;
this.trend.duration++;
log.debug('In uptrend since', this.trend.duration, 'candle(s)');
if(this.trend.duration >= this.settings.thresholds.persistence)
this.trend.persisted = true;
if(this.trend.persisted && !this.trend.adviced) {
this.trend.adviced = true;
this.advice('long');
} else {
if(!this.trend.flagHasShort && this.trend.adviced && this.trend.persisted && this.trend.duration > this.indicators.macd.maxCandleToRunSize && this.trend.direction == 'up'){
log.debug('Lets short this shit early! ', this.trend.duration, 'candle(s)');
this.advice('short');
this.trend.flagHasShort = true;
} else {
this.advice();
}
}
} else if(macddiff < this.settings.thresholds.down) {
// new trend detected
if(this.trend.direction !== 'down')
// reset the state for the new trend
this.trend = {
duration: 0,
persisted: false,
direction: 'down',
adviced: false,
flagHasShort: false
};
if(this.trend.duration == 0)
this.firstDownwardPriceDetected = this.indicators.macd.currentPrice;
this.trend.duration++;
log.debug('In downtrend since', this.trend.duration, 'candle(s)');
if(this.trend.duration >= this.settings.thresholds.persistence)
this.trend.persisted = true;
if(!this.trend.flagHasShort &&this.trend.persisted && !this.trend.adviced) {
this.trend.adviced = true;
this.advice('short');
} else
this.advice();
} else {
log.debug('In no trend');
// we're not in an up nor in a downtrend
// but for now we ignore sideways trends
//
// read more @link:
//
// https://github.com/askmike/gekko/issues/171
// this.trend = {
// direction: 'none',
// duration: 0,
// persisted: false,
// adviced: false
// };
this.advice();
}
}
module.exports = strat;
|
Tsvetelin98/Solar
|
net.solarnetwork.node.ocpp.mock/src/net/solarnetwork/node/ocpp/mock/MockMeterDataSource.java
|
/* ==================================================================
* MockMeterDataSource.java - 10/06/2015 1:28:07 pm
*
* Copyright 2007-2015 SolarNetwork.net Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
* ==================================================================
*/
package net.solarnetwork.node.ocpp.mock;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicLong;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import net.solarnetwork.node.DatumDataSource;
import net.solarnetwork.node.MultiDatumDataSource;
import net.solarnetwork.node.domain.ACEnergyDatum;
import net.solarnetwork.node.domain.ACPhase;
import net.solarnetwork.node.domain.Datum;
import net.solarnetwork.node.domain.GeneralNodeACEnergyDatum;
import net.solarnetwork.node.ocpp.ChargeSessionManager;
import net.solarnetwork.node.settings.SettingSpecifier;
import net.solarnetwork.node.settings.SettingSpecifierProvider;
import net.solarnetwork.node.settings.support.BasicTextFieldSettingSpecifier;
import net.solarnetwork.node.util.ClassUtils;
import net.solarnetwork.util.OptionalService;
/**
* Mock implementation of {@link DatumDataSource} to simulate a power meter used
* in an OCPP charge point.
*
* @author matt
* @version 1.0
*/
public class MockMeterDataSource implements DatumDataSource<GeneralNodeACEnergyDatum>,
MultiDatumDataSource<GeneralNodeACEnergyDatum>, SettingSpecifierProvider, EventHandler {
private OptionalService<EventAdmin> eventAdmin;
private MessageSource messageSource;
private long sampleCacheMs = 5000;
private String uid = "MockMeter";
private String socketId = "/socket/mock";
private String groupUID;
private double watts = 5;
private double wattsRandomness = 0.2;
private double chargingWatts = 2400;
private double chargingWattsRandomness = 0.1;
private boolean charging;
private GeneralNodeACEnergyDatum sample;
private final Logger log = LoggerFactory.getLogger(getClass());
private final AtomicLong mockMeter = new AtomicLong(meterStartValue());
/**
* Get a mock starting value for our meter. As we expect meters to only
* increase, the value returned here is based on the current time. Thus
* starting/stopping this service won't roll the meter back.
*
* @return a starting meter value
*/
private long meterStartValue() {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Date now = cal.getTime();
cal.set(2010, cal.getMinimum(Calendar.MONTH), 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
return (now.getTime() - cal.getTimeInMillis()) / (1000L * 60);
}
private GeneralNodeACEnergyDatum getCurrentSample() {
GeneralNodeACEnergyDatum currSample = sample;
if ( isSampleExpired(currSample) ) {
GeneralNodeACEnergyDatum newSample = new GeneralNodeACEnergyDatum();
newSample.setCreated(new Date());
newSample.setSourceId(uid);
newSample.setPhase(ACPhase.Total);
if ( currSample == null ) {
newSample.setWattHourReading(mockMeter.get());
} else {
double diffHours = ((newSample.getCreated().getTime()
- currSample.getCreated().getTime()) / (double) (1000 * 60 * 60));
double power;
if ( charging ) {
power = chargingWatts;
} else {
// we expect very little draw (ideally 0, but let's allow for a little)
power = watts;
}
power += (power
* (Math.random() * (charging ? chargingWattsRandomness : wattsRandomness))
* (Math.random() < 0.5 ? -1 : 1));
long wh = (long) (power * diffHours);
long newWh = currSample.getWattHourReading() + wh;
if ( mockMeter.compareAndSet(currSample.getWattHourReading(), newWh) ) {
newSample.setWattHourReading(newWh);
newSample.setWatts((int) power);
} else {
newSample.setWattHourReading(currSample.getWattHourReading());
}
}
log.debug("Read mock data: {}", newSample);
currSample = newSample;
sample = newSample;
}
return currSample;
}
private boolean isSampleExpired(GeneralNodeACEnergyDatum datum) {
if ( datum == null ) {
return true;
}
final long lastReadDiff = System.currentTimeMillis() - datum.getCreated().getTime();
if ( lastReadDiff > sampleCacheMs ) {
return true;
}
return false;
}
@Override
public String getUID() {
return uid;
}
@Override
public String getGroupUID() {
return groupUID;
}
@Override
public String getSettingUID() {
return "net.solarnetwork.node.ocpp.mock.meter";
}
@Override
public String getDisplayName() {
return getClass().getSimpleName();
}
@Override
public MessageSource getMessageSource() {
return messageSource;
}
@Override
public List<SettingSpecifier> getSettingSpecifiers() {
MockMeterDataSource defaults = new MockMeterDataSource();
List<SettingSpecifier> results = new ArrayList<SettingSpecifier>(8);
results.add(new BasicTextFieldSettingSpecifier("uid", defaults.uid));
results.add(new BasicTextFieldSettingSpecifier("groupUID", defaults.groupUID));
results.add(new BasicTextFieldSettingSpecifier("socketId", defaults.socketId));
results.add(new BasicTextFieldSettingSpecifier("watts", String.valueOf(defaults.watts)));
results.add(new BasicTextFieldSettingSpecifier("wattsRandomness",
String.valueOf(defaults.wattsRandomness)));
results.add(new BasicTextFieldSettingSpecifier("chargingWatts",
String.valueOf(defaults.chargingWatts)));
results.add(new BasicTextFieldSettingSpecifier("chargingWattsRandomness",
String.valueOf(defaults.chargingWattsRandomness)));
return results;
}
@Override
public Class<? extends GeneralNodeACEnergyDatum> getMultiDatumType() {
return getDatumType();
}
@Override
public Collection<GeneralNodeACEnergyDatum> readMultipleDatum() {
return Collections.singletonList(readCurrentDatum());
}
@Override
public Class<? extends GeneralNodeACEnergyDatum> getDatumType() {
return GeneralNodeACEnergyDatum.class;
}
@Override
public GeneralNodeACEnergyDatum readCurrentDatum() {
final long start = System.currentTimeMillis();
final GeneralNodeACEnergyDatum d = getCurrentSample();
if ( d.getCreated().getTime() >= start ) {
// we read from the meter
postDatumCapturedEvent(d, ACEnergyDatum.class);
}
return d;
}
/**
* Post a {@link DatumDataSource#EVENT_TOPIC_DATUM_CAPTURED} {@link Event}.
*
* <p>
* This method calls {@link #createDatumCapturedEvent(Datum, Class)} to
* create the actual Event, which may be overridden by extending classes.
* </p>
*
* @param datum
* the {@link Datum} to post the event for
* @param eventDatumType
* the Datum class to use for the
* {@link DatumDataSource#EVENT_DATUM_CAPTURED_DATUM_TYPE} property
* @since 1.3
*/
protected final void postDatumCapturedEvent(final Datum datum,
final Class<? extends Datum> eventDatumType) {
EventAdmin ea = (eventAdmin == null ? null : eventAdmin.service());
if ( ea == null || datum == null ) {
return;
}
Event event = createDatumCapturedEvent(datum, eventDatumType);
ea.postEvent(event);
}
/**
* Create a new {@link DatumDataSource#EVENT_TOPIC_DATUM_CAPTURED}
* {@link Event} object out of a {@link Datum}.
*
* <p>
* This method will populate all simple properties of the given
* {@link Datum} into the event properties, along with the
* {@link DatumDataSource#EVENT_DATUM_CAPTURED_DATUM_TYPE}.
*
* @param datum
* the datum to create the event for
* @param eventDatumType
* the Datum class to use for the
* {@link DatumDataSource#EVENT_DATUM_CAPTURED_DATUM_TYPE} property
* @return the new Event instance
* @since 1.3
*/
protected Event createDatumCapturedEvent(final Datum datum,
final Class<? extends Datum> eventDatumType) {
Map<String, Object> props = ClassUtils.getSimpleBeanProperties(datum, null);
props.put(DatumDataSource.EVENT_DATUM_CAPTURED_DATUM_TYPE, eventDatumType.getName());
log.debug("Created {} event with props {}", DatumDataSource.EVENT_TOPIC_DATUM_CAPTURED, props);
return new Event(DatumDataSource.EVENT_TOPIC_DATUM_CAPTURED, props);
}
@Override
public void handleEvent(Event event) {
final String topic = event.getTopic();
final String socketId = (String) event
.getProperty(ChargeSessionManager.EVENT_PROPERTY_SOCKET_ID);
if ( socketId == null || !socketId.equals(this.socketId) ) {
return;
}
if ( ChargeSessionManager.EVENT_TOPIC_SOCKET_ACTIVATED.equals(topic) ) {
setCharging(true);
log.info("Mock OCPP meter {} simulating charging load ACTIVATED on socket {}", uid,
socketId);
} else if ( ChargeSessionManager.EVENT_TOPIC_SOCKET_DEACTIVATED.equals(topic) ) {
setCharging(false);
log.info("Mock OCPP meter {} simulating charging load DEACTIVATED on socket {}", uid,
socketId);
}
}
public void setSampleCacheMs(long sampleCacheMs) {
this.sampleCacheMs = sampleCacheMs;
}
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public void setGroupUID(String groupUID) {
this.groupUID = groupUID;
}
public boolean isCharging() {
return charging;
}
public void setCharging(boolean charging) {
this.charging = charging;
}
public void setEventAdmin(OptionalService<EventAdmin> eventAdmin) {
this.eventAdmin = eventAdmin;
}
public String getSocketId() {
return socketId;
}
public void setSocketId(String socketId) {
this.socketId = socketId;
}
public void setWatts(double watts) {
this.watts = watts;
}
public void setWattsRandomness(double wattRandomness) {
this.wattsRandomness = wattRandomness;
}
public void setChargingWatts(double chargingWatts) {
this.chargingWatts = chargingWatts;
}
public void setChargingWattsRandomness(double chargingWattRandomness) {
this.chargingWattsRandomness = chargingWattRandomness;
}
}
|
ryanloney/openvino-1
|
src/bindings/python/src/pyopenvino/graph/types/element_type.cpp
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "openvino/core/type/element_type.hpp"
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "openvino/op/parameter.hpp"
#include "pyopenvino/graph/types/element_type.hpp"
namespace py = pybind11;
void regclass_graph_Type(py::module m) {
py::class_<ov::element::Type, std::shared_ptr<ov::element::Type>> type(m, "Type");
type.doc() = "openvino.runtime.Type wraps ov::element::Type";
type.attr("boolean") = ov::element::boolean;
type.attr("f16") = ov::element::f16;
type.attr("f32") = ov::element::f32;
type.attr("f64") = ov::element::f64;
type.attr("i8") = ov::element::i8;
type.attr("i16") = ov::element::i16;
type.attr("i32") = ov::element::i32;
type.attr("i64") = ov::element::i64;
type.attr("u1") = ov::element::u1;
type.attr("u8") = ov::element::u8;
type.attr("u16") = ov::element::u16;
type.attr("u32") = ov::element::u32;
type.attr("u64") = ov::element::u64;
type.attr("bf16") = ov::element::bf16;
type.attr("undefined") = ov::element::undefined;
type.def("__repr__", [](const ov::element::Type& self) {
std::string bitwidth = std::to_string(self.bitwidth());
if (self == ov::element::undefined) {
return "<Type: '" + self.c_type_string() + "'>";
} else if (self.is_signed()) {
return "<Type: '" + self.c_type_string() + bitwidth + "'>";
}
return "<Type: 'u" + self.c_type_string() + bitwidth + "'>";
});
type.def("__hash__", &ov::element::Type::hash);
type.def(
"__eq__",
[](const ov::element::Type& a, const ov::element::Type& b) {
return a == b;
},
py::is_operator());
type.def_property_readonly("bitwidth", &ov::element::Type::bitwidth);
type.def_property_readonly("is_real", &ov::element::Type::is_real);
type.def("get_type_name", &ov::element::Type::get_type_name);
}
|
Ivo-Balbaert/cone
|
src/c-compiler/ir/stmt/break.h
|
/** Handling for break nodes
* @file
*
* This source file is part of the Cone Programming Language C compiler
* See Copyright Notice in conec.h
*/
#ifndef break_h
#define break_h
// Node info used by break, return, blockret, and continue statement nodes
// Such statements are only (and must be) found at the end of a loop/regular block.
// We share the same structure across all block-ending statements
// so that we can substitute one for another (return -> break) and to find
// field info in same place (even when not all are populated)
typedef struct {
INodeHdr;
INode *exp; // value returned by break's/return's block (may be 'nil')
INode *life; // lifetime for block scope to escape/re-start (null if none specified)
BlockNode *block; // Block that this break/return applies to
Nodes *dealias; // Nodes used to de-alias/unwind current block scope-allocated values
} BreakRetNode;
BreakRetNode *newBreakNode();
// Name resolution for break
void breakNameRes(NameResState *pstate, BreakRetNode *node);
// Clone break
INode *cloneBreakNode(CloneState *cstate, BreakRetNode *node);
void breakTypeCheck(TypeCheckState *pstate, BreakRetNode *node);
#endif
|
blockchainreg/kava
|
x/bep3/client/rest/query.go
|
package rest
import (
"encoding/hex"
"fmt"
"net/http"
"strconv"
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/gorilla/mux"
"github.com/kava-labs/kava/x/bep3/types"
)
const restSwapID = "swap-id"
const restDenom = "denom"
func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) {
r.HandleFunc(fmt.Sprintf("/%s/swap/{%s}", types.ModuleName, restSwapID), queryAtomicSwapHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/swaps", types.ModuleName), queryAtomicSwapsHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/supply/{%s}", types.ModuleName, restDenom), queryAssetSupplyHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/supplies", types.ModuleName), queryAssetSuppliesHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc(fmt.Sprintf("/%s/parameters", types.ModuleName), queryParamsHandlerFn(cliCtx)).Methods("GET")
}
func queryAtomicSwapHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Parse the query height
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}
// Prepare params for querier
vars := mux.Vars(r)
if len(vars[restSwapID]) == 0 {
err := fmt.Errorf("%s required but not specified", restSwapID)
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
swapID, err := hex.DecodeString(vars[restSwapID])
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
bz, err := cliCtx.Codec.MarshalJSON(types.QueryAtomicSwapByID{SwapID: swapID})
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
// Query
res, height, err := cliCtx.QueryWithData(fmt.Sprintf("/custom/%s/%s", types.ModuleName, types.QueryGetAtomicSwap), bz)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
// Decode and return results
cliCtx = cliCtx.WithHeight(height)
var swap types.AugmentedAtomicSwap
err = cliCtx.Codec.UnmarshalJSON(res, &swap)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, cliCtx.Codec.MustMarshalJSON(swap))
}
}
// HTTP request handler to query list of atomic swaps filtered by optional params
func queryAtomicSwapsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, page, limit, err := rest.ParseHTTPArgsWithLimit(r, 0)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}
var (
involveAddr sdk.AccAddress
expiration uint64
swapStatus types.SwapStatus
swapDirection types.SwapDirection
)
if x := r.URL.Query().Get(RestInvolve); len(x) != 0 {
involveAddr, err = sdk.AccAddressFromBech32(x)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
}
if x := r.URL.Query().Get(RestExpiration); len(x) != 0 {
expiration, err = strconv.ParseUint(x, 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
}
if x := r.URL.Query().Get(RestStatus); len(x) != 0 {
swapStatus = types.NewSwapStatusFromString(x)
if !swapStatus.IsValid() {
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("invalid swap status %s", swapStatus))
return
}
}
if x := r.URL.Query().Get(RestDirection); len(x) != 0 {
swapDirection = types.NewSwapDirectionFromString(x)
if !swapDirection.IsValid() {
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("invalid swap direction %s", swapDirection))
return
}
}
params := types.NewQueryAtomicSwaps(page, limit, involveAddr, expiration, swapStatus, swapDirection)
bz, err := cliCtx.Codec.MarshalJSON(params)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryGetAtomicSwaps)
res, height, err := cliCtx.QueryWithData(route, bz)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
cliCtx = cliCtx.WithHeight(height)
rest.PostProcessResponse(w, cliCtx, res)
}
}
func queryAssetSupplyHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Parse the query height
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}
// Prepare params for querier
vars := mux.Vars(r)
denom := vars[restDenom]
params := types.NewQueryAssetSupply(denom)
bz, err := cliCtx.Codec.MarshalJSON(params)
if err != nil {
rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())
return
}
// Query
res, height, err := cliCtx.QueryWithData(fmt.Sprintf("/custom/%s/%s", types.ModuleName, types.QueryGetAssetSupply), bz)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
// Decode and return results
cliCtx = cliCtx.WithHeight(height)
var assetSupply types.AssetSupply
err = cliCtx.Codec.UnmarshalJSON(res, &assetSupply)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, cliCtx.Codec.MustMarshalJSON(assetSupply))
}
}
func queryAssetSuppliesHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Parse the query height
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}
route := fmt.Sprintf("custom/%s/%s", types.ModuleName, types.QueryGetAssetSupplies)
res, height, err := cliCtx.QueryWithData(route, nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
// Decode and return results
cliCtx = cliCtx.WithHeight(height)
var supplies types.AssetSupplies
err = cliCtx.Codec.UnmarshalJSON(res, &supplies)
if err != nil {
rest.WriteErrorResponse(w, http.StatusNotFound, err.Error())
return
}
// using empty slice so json returns [] instead of null when there's no swaps
sliceSupplies := types.AssetSupplies{}
for _, s := range supplies {
sliceSupplies = append(sliceSupplies, s)
}
rest.PostProcessResponse(w, cliCtx, cliCtx.Codec.MustMarshalJSON(sliceSupplies))
}
}
func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}
route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryGetParams)
res, height, err := cliCtx.QueryWithData(route, nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
cliCtx = cliCtx.WithHeight(height)
rest.PostProcessResponse(w, cliCtx, res)
}
}
|
kolly83/kore
|
pkg/persistence/audit_entry.go
|
<reponame>kolly83/kore
/**
* Copyright 2020 Appvia Ltd <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package persistence
import (
"context"
"github.com/appvia/kore/pkg/persistence/model"
"github.com/jinzhu/gorm"
)
// entryImpl implements the recoreentry interface
type entryImpl struct {
filter *ListOptions
// ctx is the context
ctx context.Context
// event is the event being added
event *model.AuditEvent
// db is the database connection
db *gorm.DB
}
// newQuery creates and returns a query
func newQuery(ctx context.Context, db *gorm.DB, opts ...ListFunc) *entryImpl {
return &entryImpl{
ctx: ctx,
db: db,
filter: ApplyListOptions(opts...),
}
}
// newEntry creates a new entry for use
func newEntry(ctx context.Context, db *gorm.DB, fields ...AuditFunc) *entryImpl {
m := &model.AuditEvent{}
for _, method := range fields {
method(m)
}
return &entryImpl{ctx: ctx, db: db, event: m}
}
// Find is used to return a search from the audit log
func (e *entryImpl) Do() ([]*model.AuditEvent, error) {
// @step: construct the query
q := e.db.
Model(&model.AuditEvent{}).
Select("q.*").
Table("audit_events q")
if e.filter.HasVerb() {
q = q.Where("q.type = ?", e.filter.GetVerb())
}
if e.filter.HasTeam() {
q = q.Where("q.team = ?", e.filter.GetTeam())
}
if e.filter.HasTeams() {
q = q.Where("q.team IN (?)", e.filter.GetTeams())
}
if e.filter.HasTeamsNotNull() {
q = q.Where("q.team != \"\"")
}
if e.filter.HasUser() {
q = q.Where("q.user = ?", e.filter.GetUser())
}
if e.filter.HasDuration() {
q = q.Where("timestampdiff(minute, q.created_at, NOW()) < ?", int(e.filter.GetDuration().Minutes()))
}
list := []*model.AuditEvent{}
return list, q.Find(&list).Error
}
// Event records the entry into the audit log
func (e *entryImpl) Event(message string) {
if e.event.Verb == "" || message == "" {
return
}
e.event.Message = message
e.db.Model(&model.AuditEvent{}).Save(e.event)
}
|
bworkman1/Network4Rentals
|
assets/themes/default/js/assoc/payment-settings.js
|
<reponame>bworkman1/Network4Rentals<gh_stars>0
$(function() {
// validate that there is a first and last name
$('#card-holder-name').focusout(function() {
var name = $(this).val();
var name_array = name.split(' ');
if(name_array.length<2) {
$(this).tooltip('show');
$(this).parent().parent().addClass('has-error').removeClass('has-success');
$(this).addClass('isError');
} else {
$(this).parent().parent().removeClass('has-error').addClass('has-success');
$(this).tooltip('destroy');
$(this).removeClass('isError');
}
});
// validate credit card
$('#card-number').focusout(function() {
var cc = $(this).val();
if(valid_credit_card(cc)) {
$(this).parent().parent().removeClass('has-error').addClass('has-success');
$(this).tooltip('destroy');
$(this).removeClass('isError');
} else {
$(this).addClass('isError');
$(this).parent().parent().addClass('has-error').removeClass('has-success');
$(this).tooltip('show');
}
});
$('#expiry-month').focusout(function() {
var month = $(this).val();
if(month.length>0) {
$(this).removeClass('isError');
$(this).css({'border-color':'#3c763d !important;'});
} else {
$(this).addClass('isError');
$(this).css({'border-color':'#a94442 !important;'});
}
});
$('#expiry-year').focusout(function() {
var year = $(this).val();
if(year.length>0) {
$(this).css({'border-color':'#3c763d;'});
$(this).removeClass('isError');
} else {
$(this).addClass('isError');
$(this).css({'border-color':'#a94442;'});
}
});
$('#cvv').focusout(function() {
var cvv = $(this).val();
if(cvv.length>0) {
$(this).removeClass('isError');
$(this).parent().parent().removeClass('has-error').addClass('has-success');
} else {
$(this).addClass('isError');
$(this).parent().parent().addClass('has-error').removeClass('has-success');
}
});
$('#card-number').mask('9999-9999-9999-9999');
$('#payment').submit(function(e) {
console.log('test');
e.preventDefault();
var formSubmit = true;
if(formSubmit) {
$(this).submit();
$('.submitError').html('');
} else {
$('.submitError').html('<div class="text-danger">Fix the errors before submitting your payment</div>');
}
});
});
function valid_credit_card(value) {
// accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) return false;
// The Luhn Algorithm. It's so pretty.
var nCheck = 0, nDigit = 0, bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
|
yashashrirane/interlok
|
interlok-core/src/main/java/com/adaptris/core/transform/schema/BasicXmlSchemaValidator.java
|
/*
* Copyright 2020 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.adaptris.core.transform.schema;
import java.io.InputStream;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Validator;
import org.apache.commons.collections4.IterableUtils;
import org.xml.sax.InputSource;
import com.adaptris.annotation.ComponentProfile;
import com.adaptris.annotation.DisplayOrder;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.CoreException;
import com.adaptris.core.ServiceException;
import com.adaptris.core.services.cache.CacheConnection;
import com.adaptris.core.transform.XmlValidationService;
import com.adaptris.core.util.ExceptionHelper;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* Used with {@link XmlValidationService} to validate an XML message against a schema.
* <p>
* This validates an input XML document against a schema and fails with an exception logging all the
* exceptions found.
* </p>
*
* @config basic-xml-schema-validator
*
*/
@XStreamAlias("basic-xml-schema-validator")
@DisplayOrder(order = {"schema", "schemaCache"})
@ComponentProfile(summary = "Validate an XML document against a schema",
recommended = {CacheConnection.class}, since = "3.10.2", tag="xml,schema")
public class BasicXmlSchemaValidator extends XmlSchemaValidatorImpl {
@Override
public void validate(AdaptrisMessage msg) throws CoreException {
// Since we don't throw SAXParseExceptions in the collector, any exceptions
// shouldn't be schema violations we're basically in the normal error handler chain
CollectingSaxErrorHandler violationCollector = new CollectingSaxErrorHandler();
try (InputStream in = msg.getInputStream()) {
Validator validator = this.resolveSchema(msg).newValidator();
validator.setErrorHandler(violationCollector);
validator.validate(new SAXSource(new InputSource(in)));
} catch (Exception e) {
throw ExceptionHelper.wrapServiceException("Failed to validate message", e);
}
if (violationCollector.hasErrors()) {
violationHandler().handle(IterableUtils.chainedIterable(violationCollector.fatalErrors(),
violationCollector.errors()), msg);
}
}
protected SchemaViolationHandler violationHandler() {
return (iterable, msg) -> {
iterable.forEach((e) -> {
log.error("Error validating message[{}] line [{}] column[{}]", e.getMessage(),
e.getLineNumber(), e.getColumnNumber());
});
throw new ServiceException("Schema Violations logged and error thrown");
};
}
}
|
devloper96/whitehall
|
app/services/edition_publisher.rb
|
require 'data_hygiene/govspeak_link_validator'
class EditionPublisher < EditionService
def failure_reason
@failure_reason ||= failure_reasons.first
end
def failure_reasons
return @failure_reasons if @failure_reasons
reasons = []
reasons << "This edition is invalid: #{edition.errors.full_messages.to_sentence}" unless edition.valid?
reasons << "This edition contains bad links" if govspeak_link_errors.any?
reasons << "An edition that is #{edition.current_state} cannot be #{past_participle}" unless can_transition?
reasons << "Scheduled editions cannot be published. This edition is scheduled for publication on #{edition.scheduled_publication.to_s}" if scheduled_for_publication?
@failure_reasons = reasons
end
def govspeak_link_errors
@govspeak_link_errors ||= DataHygiene::GovspeakLinkValidator.new(edition.body).errors
end
def verb
'publish'
end
private
def prepare_edition
edition.access_limited = false
edition.major_change_published_at = Time.zone.now unless edition.minor_change?
edition.make_public_at(edition.major_change_published_at)
edition.increment_version_number
end
def fire_transition!
super
supersede_previous_editions!
end
def supersede_previous_editions!
edition.document.editions.published.each do |e|
if e != edition
e.supersede
e.save(validate: false)
end
end
end
def scheduled_for_publication?
# Just using edition.scheduled? misses submitted editions
edition.scheduled_publication.present?
end
end
|
shock/hfhinv
|
test/system/donors_test.rb
|
require "application_system_test_case"
class DonorsTest < ApplicationSystemTestCase
# test "visiting the index" do
# visit donors_url
#
# assert_selector "h1", text: "Donor"
# end
end
|
vaclav/Physics
|
languages/jetbrains.mps.samples.Physics/source_gen/jetbrains/mps/samples/Physics/findUsages/FindOverridenValue_Finder.java
|
<gh_stars>1-10
package jetbrains.mps.samples.Physics.findUsages;
/*Generated by MPS */
import jetbrains.mps.ide.findusages.findalgorithm.finders.GeneratedFinder;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.model.SNode;
import org.jetbrains.mps.openapi.module.SearchScope;
import jetbrains.mps.ide.findusages.findalgorithm.finders.IFinder;
import org.jetbrains.mps.openapi.util.ProgressMonitor;
import jetbrains.mps.samples.Physics.behavior.ICanBeOverridden__BehaviorDescriptor;
import jetbrains.mps.samples.Physics.behavior.OverrideRule__BehaviorDescriptor;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.model.SNodeReference;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
public class FindOverridenValue_Finder extends GeneratedFinder {
public FindOverridenValue_Finder() {
}
@Override
public String getDescription() {
return "Overridden Value";
}
@Override
public String getLongDescription() {
return "";
}
@Override
public SAbstractConcept getSConcept() {
return CONCEPTS.OverrideRule$Db;
}
@Override
protected void doFind0(@NotNull SNode node, SearchScope scope, IFinder.FindCallback callback, ProgressMonitor monitor) {
monitor.start(getDescription(), 0);
try {
SNode valueTarget = ICanBeOverridden__BehaviorDescriptor.getNodeTarget_id6ZPff_L2lbX.invoke(OverrideRule__BehaviorDescriptor.getTarget_id2AM6gIjLTgY.invoke(node));
if ((valueTarget != null)) {
callback.onUsageFound(createSingleResult(valueTarget));
}
} finally {
monitor.done();
}
}
@Override
public String getNodeCategory(SNode node) {
return "Overridden Value";
}
@Nullable
@Override
public SNodeReference getDeclarationNode() {
return buildNodePointer(FindUsagesDescriptor.DECLARING_MODEL, "8067421349545066944");
}
private static final class CONCEPTS {
/*package*/ static final SConcept OverrideRule$Db = MetaAdapterFactory.getConcept(0xbe81eb124eda4d0eL, 0x89be7493500ab874L, 0x3238375e772f9fedL, "jetbrains.mps.samples.Physics.structure.OverrideRule");
}
}
|
psibi/eta
|
rts/src/eta/runtime/Utils.java
|
<reponame>psibi/eta
package eta.runtime;
import java.util.ListIterator;
public class Utils {
public static <E> E peekPrevious(ListIterator<E> it) {
E e = null;
if (it.hasPrevious()) {
e = it.previous();
it.next();
}
return e;
}
public static <E> E peekNext(ListIterator<E> it) {
E e = null;
if (it.hasNext()) {
e = it.next();
it.previous();
}
return e;
}
}
|
arc03/30-DaysOfCode-March-2021
|
answers/Aryan Goyal/Day 11/Que 2.py
|
<reponame>arc03/30-DaysOfCode-March-2021
s=input("")
no=int(input(""))
list234=[]
for i in range(no):
s1=input("")
s2=list(s1)
base = []
count=0
lists = [base]
for i in range(len(s)):
orig = lists[:]
new = s[i]
for j in range(len(lists)):
lists[j] = lists[j] + [new]
lists = orig + lists
for q in lists:
if q==s2:
count+=1
list234.append(count)
for li in list234:
print(li)
|
tobli/selenium
|
javascript/safari-driver/inject/message/message.js
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* @fileoverview Utilities for working with messages in an injected script.
*/
goog.provide('safaridriver.inject.message');
/**
* Checks whether the given message event originated from the DOMWindow running
* this script. These messages are exchanged between the injected script and its
* corresponding content page.
* @param {!MessageEvent.<*>} e The message event to check.
* @return {boolean} Whether the message came from this window.
*/
safaridriver.inject.message.isFromSelf = function(e) {
return e.source === window;
};
/**
* Checks whether the given message event was sent by a frame belonging to the
* same browser window as this script's context.
* @param {!MessageEvent.<*>} e The message event to check.
* @return {boolean} Whether the message came from a frame belonging to this
* browser window.
*/
safaridriver.inject.message.isFromFrame = function(e) {
return !!e.source && e.source.top === window.top;
};
/**
* Checks whether the given message event was sent by the top most window.
* @param {!MessageEvent.<*>} e The message event to check.
* @return {boolean} Whether the message came from the topmost frame.
*/
safaridriver.inject.message.isFromTop = function(e) {
return !!e.source && e.source === window.top;
};
|
desdamo/Currency-Converter-React
|
node_modules/@bundle-stats/utils/lib/config/delta.js
|
<reponame>desdamo/Currency-Converter-React
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DELTA_TYPE_HIGH_POSITIVE = exports.DELTA_TYPE_LOW_POSITIVE = exports.DELTA_TYPE_HIGH_NEGATIVE = exports.DELTA_TYPE_LOW_NEGATIVE = exports.DELTA_TYPE_LEVEL_HIGH = exports.DELTA_TYPE_LEVEL_LOW = exports.DELTA_TYPE_POSITIVE = exports.DELTA_TYPE_NO_CHANGE = exports.DELTA_TYPE_NEGATIVE = void 0;
const DELTA_TYPE_NEGATIVE = 'NEGATIVE';
exports.DELTA_TYPE_NEGATIVE = DELTA_TYPE_NEGATIVE;
const DELTA_TYPE_NO_CHANGE = 'NO_CHANGE';
exports.DELTA_TYPE_NO_CHANGE = DELTA_TYPE_NO_CHANGE;
const DELTA_TYPE_POSITIVE = 'POSITIVE';
exports.DELTA_TYPE_POSITIVE = DELTA_TYPE_POSITIVE;
const DELTA_TYPE_LEVEL_LOW = 'LOW';
exports.DELTA_TYPE_LEVEL_LOW = DELTA_TYPE_LEVEL_LOW;
const DELTA_TYPE_LEVEL_HIGH = 'HIGH';
exports.DELTA_TYPE_LEVEL_HIGH = DELTA_TYPE_LEVEL_HIGH;
const DELTA_TYPE_LOW_NEGATIVE = `${DELTA_TYPE_LEVEL_LOW}_${DELTA_TYPE_NEGATIVE}`;
exports.DELTA_TYPE_LOW_NEGATIVE = DELTA_TYPE_LOW_NEGATIVE;
const DELTA_TYPE_HIGH_NEGATIVE = `${DELTA_TYPE_LEVEL_HIGH}_${DELTA_TYPE_NEGATIVE}`;
exports.DELTA_TYPE_HIGH_NEGATIVE = DELTA_TYPE_HIGH_NEGATIVE;
const DELTA_TYPE_LOW_POSITIVE = `${DELTA_TYPE_LEVEL_LOW}_${DELTA_TYPE_POSITIVE}`;
exports.DELTA_TYPE_LOW_POSITIVE = DELTA_TYPE_LOW_POSITIVE;
const DELTA_TYPE_HIGH_POSITIVE = `${DELTA_TYPE_LEVEL_HIGH}_${DELTA_TYPE_POSITIVE}`;
exports.DELTA_TYPE_HIGH_POSITIVE = DELTA_TYPE_HIGH_POSITIVE;
|
anatagadaisukidesu/gzlkisp
|
app/src/main/java/com/gzlk/android/isp/nim/model/extension/SigningNotifyAttachment.java
|
<reponame>anatagadaisukidesu/gzlkisp
package com.gzlk.android.isp.nim.model.extension;
import com.gzlk.android.isp.R;
import com.gzlk.android.isp.etc.Utils;
import com.gzlk.android.isp.helper.StringHelper;
import org.json.JSONObject;
/**
* <b>功能描述:</b>签到的提醒消息<br />
* <b>创建作者:</b><NAME> <br />
* <b>创建时间:</b>2017/06/19 15:58 <br />
* <b>作者邮箱:</b><EMAIL> <br />
* <b>最新版本:</b>Version: 1.0.0 <br />
* <b>修改时间:</b>2017/06/19 15:58 <br />
* <b>修改人员:</b><br />
* <b>修改备注:</b><br />
*/
public class SigningNotifyAttachment extends CustomAttachment {
public SigningNotifyAttachment() {
super(AttachmentType.SIGN);
}
/**
* 签到提醒类型(目前提醒只是创建者手动提醒,没有自动发布提醒功能):
* <ul>
* <li>0=发布签到提醒</li>
* <li>1=准备签到提醒(比如提前5分钟提醒大家签到)</li>
* <li>2=开始签到提醒</li>
* <li>3=签到即将结束提醒</li>
* <li>4=签到已结束(预览签到成果)</li>
* </ul>
*/
private int notifyType;
// 群聊的tid
private String tid;
// 签到应用的id
private String setupId;
// 签到的title
private String title;
// 提醒内容
private String content;
// 签到的地址
private String address;
// 开始时间
private String beginTime;
// 结束时间
private String endTime;
public int getNotifyType() {
return notifyType;
}
public void setNotifyType(int notifyType) {
this.notifyType = notifyType;
}
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getSetupId() {
if (isEmpty(setupId)) {
setupId = getCustomId();
}
return setupId;
}
public void setSetupId(String setupId) {
this.setupId = setupId;
}
public String getTitle() {
if (isEmpty(title)) {
title = "未设置标题";
}
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAddress() {
if (isEmpty(address)) {
address = "未设置签到地址";
}
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
@Override
protected void parseData(JSONObject data) {
super.parseData(data);
try {
if (data.has("notifyType")) {
notifyType = data.getInt("notifyType");
}
if (data.has("tid")) {
tid = data.getString("tid");
}
if (data.has("setupId")) {
setupId = data.getString("setupId");
}
if (data.has("title")) {
title = data.getString("title");
}
if (data.has("content")) {
content = data.getString("content");
}
if (data.has("address")) {
address = data.getString("address");
}
if (data.has("beginTime")) {
beginTime = data.getString("beginTime");
}
if (data.has("endTime")) {
endTime = data.getString("endTime");
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected JSONObject packData() {
JSONObject data = super.packData();
try {
data.put("notifyType", notifyType)
.put("tid", tid)
.put("setupId", setupId)
.put("title", title)
.put("content", content)
.put("address", address)
.put("beginTime", beginTime)
.put("endTime", endTime);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
}
|
empd2/empd2.github.io
|
node_modules/testcafe-browser-tools/lib/api/bring-to-front.js
|
'use strict';
var _regeneratorRuntime = require('babel-runtime/regenerator').default;
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default').default;
exports.__esModule = true;
var _osFamily = require('os-family');
var _osFamily2 = _interopRequireDefault(_osFamily);
var _findWindow = require('./find-window');
var _findWindow2 = _interopRequireDefault(_findWindow);
var _utilsExec = require('../utils/exec');
var _binaries = require('../binaries');
var _binaries2 = _interopRequireDefault(_binaries);
/**
* Brings the browser window on top of all other windows.
* @function
* @async
* @name bringWindowToFront
* @param {string | object} windowDescriptor - The title of the web page opened in the window or a descriptor returned by findWindow.
*/
exports.default = function callee$0$0(windowDescriptor) {
var windowDescription, bringWindowToFrontArguments;
return _regeneratorRuntime.async(function callee$0$0$(context$1$0) {
while (1) switch (context$1$0.prev = context$1$0.next) {
case 0:
if (!(typeof windowDescriptor === 'string')) {
context$1$0.next = 6;
break;
}
context$1$0.next = 3;
return _regeneratorRuntime.awrap(_findWindow2.default(windowDescriptor));
case 3:
context$1$0.t0 = context$1$0.sent;
context$1$0.next = 7;
break;
case 6:
context$1$0.t0 = windowDescriptor;
case 7:
windowDescription = context$1$0.t0;
if (windowDescription) {
context$1$0.next = 10;
break;
}
return context$1$0.abrupt('return');
case 10:
bringWindowToFrontArguments = void 0;
if (!_osFamily2.default.win) {
context$1$0.next = 15;
break;
}
bringWindowToFrontArguments = [windowDescription.hwnd];
context$1$0.next = 24;
break;
case 15:
if (!_osFamily2.default.linux) {
context$1$0.next = 19;
break;
}
bringWindowToFrontArguments = [windowDescription.windowId];
context$1$0.next = 24;
break;
case 19:
if (!_osFamily2.default.mac) {
context$1$0.next = 23;
break;
}
bringWindowToFrontArguments = [windowDescription.processId, windowDescription.windowId];
context$1$0.next = 24;
break;
case 23:
return context$1$0.abrupt('return');
case 24:
context$1$0.next = 26;
return _regeneratorRuntime.awrap(_utilsExec.execFile(_binaries2.default.bringToFront, bringWindowToFrontArguments));
case 26:
case 'end':
return context$1$0.stop();
}
}, null, this);
};
module.exports = exports.default;
|
billyfrost418/james-project
|
server/container/guice/memory-guice/src/test/java/org/apache/james/GuiceLifecycleHeathCheckTest.java
|
/****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james;
import static io.restassured.RestAssured.when;
import static io.restassured.config.EncoderConfig.encoderConfig;
import static io.restassured.config.RestAssuredConfig.newConfig;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import org.apache.james.modules.TestJMAPServerModule;
import org.apache.james.utils.WebAdminGuiceProbe;
import org.apache.james.webadmin.WebAdminConfiguration;
import org.apache.james.webadmin.WebAdminServer;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoProcessor;
import reactor.core.scheduler.Schedulers;
class GuiceLifecycleHeathCheckTest {
private static final int LIMIT_TO_10_MESSAGES = 10;
private static JamesServerBuilder extensionBuilder() {
return new JamesServerBuilder()
.server(configuration -> GuiceJamesServer.forConfiguration(configuration)
.combineWith(MemoryJamesServerMain.IN_MEMORY_SERVER_AGGREGATE_MODULE)
.overrideWith(new TestJMAPServerModule(LIMIT_TO_10_MESSAGES))
.overrideWith(binder -> binder.bind(WebAdminConfiguration.class)
.toInstance(WebAdminConfiguration.TEST_CONFIGURATION)));
}
private static void configureRequestSpecification(GuiceJamesServer server) {
WebAdminGuiceProbe webAdminGuiceProbe = server.getProbe(WebAdminGuiceProbe.class);
RestAssured.requestSpecification = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.setConfig(newConfig().encoderConfig(encoderConfig().defaultContentCharset(StandardCharsets.UTF_8)))
.setPort(webAdminGuiceProbe.getWebAdminPort().getValue())
.build();
}
@Nested
class Healthy {
@RegisterExtension
JamesServerExtension jamesServerExtension = extensionBuilder().build();
@Test
void startedJamesServerShouldBeHealthy(GuiceJamesServer server) {
configureRequestSpecification(server);
when()
.get("/healthcheck")
.then()
.statusCode(HttpStatus.OK_200);
}
}
static class DestroyedBeforeWebAdmin {
WebAdminServer webAdminServer;
CountDownLatch latch;
@Inject
DestroyedBeforeWebAdmin(WebAdminServer webAdminServer, CountDownLatch latch) {
this.webAdminServer = webAdminServer;
this.latch = latch;
}
@PreDestroy
void cleanup() {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@Nested
class Unhealthy {
CountDownLatch latch = new CountDownLatch(1);
@RegisterExtension
JamesServerExtension jamesServerExtension = extensionBuilder()
.overrideServerModule(binder -> binder.bind(CountDownLatch.class).toInstance(latch))
.overrideServerModule(binder -> binder.bind(DestroyedBeforeWebAdmin.class).asEagerSingleton())
.build();
@Test
void stoppingJamesServerShouldBeUnhealthy(GuiceJamesServer server) {
Mono<Void> stopMono = Mono.fromRunnable(() -> { });
try {
configureRequestSpecification(server);
stopMono = Mono.fromRunnable(server::stop);
stopMono
.publishOn(Schedulers.elastic())
.subscribeWith(MonoProcessor.create());
when()
.get("/healthcheck")
.then()
.statusCode(HttpStatus.INTERNAL_SERVER_ERROR_500);
} finally {
latch.countDown();
stopMono.block();
}
}
}
}
|
honeyhugh/PythonCurso
|
ex014.py
|
c=float(input('Digite a temperatura em ºC: '))
f=(9*c+160)/5
print('{:.1f}ºC equivalem a {:.1f}ºF.'.format(c,f))
|
lechium/iOS1351Headers
|
System/Library/Frameworks/PhotosUI.framework/PUAlbumsGadgetProvider.h
|
<reponame>lechium/iOS1351Headers<gh_stars>1-10
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:16:46 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/Frameworks/PhotosUI.framework/PhotosUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <PhotosUICore/PXGadgetProvider.h>
#import <libobjc.A.dylib/PXCollectionsDataSourceManagerObserver.h>
#import <libobjc.A.dylib/PXChangeObserver.h>
#import <libobjc.A.dylib/PUAlbumGadgetDelegate.h>
#import <libobjc.A.dylib/PUHorizontalAlbumListGadgetLayoutDelegate.h>
@class PXPhotoKitCollectionsDataSourceManager, PUAlbumListCellContentViewHelper, PXExtendedTraitCollection, NSString;
@interface PUAlbumsGadgetProvider : PXGadgetProvider <PXCollectionsDataSourceManagerObserver, PXChangeObserver, PUAlbumGadgetDelegate, PUHorizontalAlbumListGadgetLayoutDelegate> {
BOOL _hasGeneratedGadgets;
PXPhotoKitCollectionsDataSourceManager* _dataSourceManager;
PUAlbumListCellContentViewHelper* _contentViewHelper;
unsigned long long _albumListType;
PXExtendedTraitCollection* _extendedTraitCollection;
unsigned long long _currentDataSourceIdentifier;
}
@property (assign,nonatomic) unsigned long long currentDataSourceIdentifier; //@synthesize currentDataSourceIdentifier=_currentDataSourceIdentifier - In the implementation block
@property (nonatomic,retain) PUAlbumListCellContentViewHelper * contentViewHelper; //@synthesize contentViewHelper=_contentViewHelper - In the implementation block
@property (assign,nonatomic) BOOL hasGeneratedGadgets; //@synthesize hasGeneratedGadgets=_hasGeneratedGadgets - In the implementation block
@property (nonatomic,readonly) unsigned long long albumListType; //@synthesize albumListType=_albumListType - In the implementation block
@property (nonatomic,readonly) PXPhotoKitCollectionsDataSourceManager * dataSourceManager; //@synthesize dataSourceManager=_dataSourceManager - In the implementation block
@property (nonatomic,readonly) PXExtendedTraitCollection * extendedTraitCollection; //@synthesize extendedTraitCollection=_extendedTraitCollection - In the implementation block
@property (nonatomic,readonly) BOOL shouldShowSeeAllAccessoryButton;
@property (nonatomic,readonly) NSString * seeAllAccessoryButtonTitle;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(id)init;
-(unsigned long long)albumListType;
-(void)observable:(id)arg1 didChange:(unsigned long long)arg2 context:(void*)arg3 ;
-(void)loadDataForGadgets;
-(void)startLoadingRemainingData;
-(unsigned long long)estimatedNumberOfGadgets;
-(void)generateGadgets;
-(PXPhotoKitCollectionsDataSourceManager *)dataSourceManager;
-(PXExtendedTraitCollection *)extendedTraitCollection;
-(BOOL)hasGeneratedGadgets;
-(void)setHasGeneratedGadgets:(BOOL)arg1 ;
-(id)albumListCellContentViewHelperForAlbum:(id)arg1 ;
-(id)albumListCellContentViewHelperForLayout:(id)arg1 ;
-(id)initWithAlbumListType:(unsigned long long)arg1 dataSourceManager:(id)arg2 extendedTraitCollection:(id)arg3 ;
-(PUAlbumListCellContentViewHelper *)contentViewHelper;
-(BOOL)shouldShowSeeAllAccessoryButton;
-(NSString *)seeAllAccessoryButtonTitle;
-(id)gadgetForIndexPath:(id)arg1 ;
-(id)gadgetForCollection:(id)arg1 ;
-(void)_reconfigureGadgets;
-(id)_newGadgetForCollection:(id)arg1 ;
-(Class)_albumGadgetClassForCollection:(id)arg1 ;
-(void)_updateDataSourceWithChangeDetails:(id)arg1 ;
-(void)setContentViewHelper:(PUAlbumListCellContentViewHelper *)arg1 ;
-(unsigned long long)currentDataSourceIdentifier;
-(void)setCurrentDataSourceIdentifier:(unsigned long long)arg1 ;
@end
|
sarang-apps/darshan_browser
|
chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/tab_capture/tab_capture_registry.h"
#include <memory>
#include <utility>
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/values.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/sessions/content/session_tab_helper.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/extension.h"
#include "url/origin.h"
using content::BrowserThread;
using extensions::tab_capture::TabCaptureState;
namespace extensions {
namespace tab_capture = api::tab_capture;
// Stores values associated with a tab capture request, maintains lifecycle
// state, and monitors WebContents for fullscreen transition events and
// destruction.
class TabCaptureRegistry::LiveRequest : public content::WebContentsObserver {
public:
LiveRequest(content::WebContents* target_contents,
const std::string& extension_id,
bool is_anonymous,
TabCaptureRegistry* registry)
: content::WebContentsObserver(target_contents),
extension_id_(extension_id),
is_anonymous_(is_anonymous),
registry_(registry),
capture_state_(tab_capture::TAB_CAPTURE_STATE_NONE),
is_verified_(false),
// TODO(miu): This initial value for |is_fullscreened_| is a faulty
// assumption. http://crbug.com/350491
is_fullscreened_(false),
render_process_id_(
target_contents->GetMainFrame()->GetProcess()->GetID()),
render_frame_id_(target_contents->GetMainFrame()->GetRoutingID()) {
DCHECK(web_contents());
DCHECK(registry_);
}
~LiveRequest() override {}
// Accessors.
const std::string& extension_id() const { return extension_id_; }
bool is_anonymous() const { return is_anonymous_; }
TabCaptureState capture_state() const { return capture_state_; }
bool is_verified() const { return is_verified_; }
void SetIsVerified() {
DCHECK(!is_verified_);
is_verified_ = true;
}
bool WasTargettingRenderFrameID(int render_process_id,
int render_frame_id) const {
return render_process_id_ == render_process_id &&
render_frame_id_ == render_frame_id;
}
void UpdateCaptureState(TabCaptureState next_capture_state) {
// This method can get duplicate calls if both audio and video were
// requested, so return early to avoid duplicate dispatching of status
// change events.
if (capture_state_ == next_capture_state)
return;
capture_state_ = next_capture_state;
registry_->DispatchStatusChangeEvent(this);
}
void GetCaptureInfo(tab_capture::CaptureInfo* info) const {
info->tab_id = sessions::SessionTabHelper::IdForTab(web_contents()).id();
info->status = capture_state_;
info->fullscreen = is_fullscreened_;
}
protected:
void DidShowFullscreenWidget() override {
is_fullscreened_ = true;
if (capture_state_ == tab_capture::TAB_CAPTURE_STATE_ACTIVE)
registry_->DispatchStatusChangeEvent(this);
}
void DidDestroyFullscreenWidget() override {
is_fullscreened_ = false;
if (capture_state_ == tab_capture::TAB_CAPTURE_STATE_ACTIVE)
registry_->DispatchStatusChangeEvent(this);
}
void DidToggleFullscreenModeForTab(bool entered_fullscreen,
bool will_cause_resize) override {
is_fullscreened_ = entered_fullscreen;
if (capture_state_ == tab_capture::TAB_CAPTURE_STATE_ACTIVE)
registry_->DispatchStatusChangeEvent(this);
}
void WebContentsDestroyed() override {
registry_->KillRequest(this); // Deletes |this|.
}
private:
const std::string extension_id_;
const bool is_anonymous_;
TabCaptureRegistry* const registry_;
TabCaptureState capture_state_;
bool is_verified_;
bool is_fullscreened_;
// These reference the originally targetted RenderFrameHost by its ID. The
// RenderFrameHost may have gone away long before a LiveRequest closes, but
// calls to OnRequestUpdate() will always refer to this request by this ID.
int render_process_id_;
int render_frame_id_;
DISALLOW_COPY_AND_ASSIGN(LiveRequest);
};
TabCaptureRegistry::TabCaptureRegistry(content::BrowserContext* context)
: browser_context_(context) {
MediaCaptureDevicesDispatcher::GetInstance()->AddObserver(this);
extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context_));
}
TabCaptureRegistry::~TabCaptureRegistry() {
MediaCaptureDevicesDispatcher::GetInstance()->RemoveObserver(this);
}
// static
TabCaptureRegistry* TabCaptureRegistry::Get(content::BrowserContext* context) {
return BrowserContextKeyedAPIFactory<TabCaptureRegistry>::Get(context);
}
static base::LazyInstance<BrowserContextKeyedAPIFactory<TabCaptureRegistry>>::
DestructorAtExit g_tab_capture_registry_factory = LAZY_INSTANCE_INITIALIZER;
// static
BrowserContextKeyedAPIFactory<TabCaptureRegistry>*
TabCaptureRegistry::GetFactoryInstance() {
return g_tab_capture_registry_factory.Pointer();
}
void TabCaptureRegistry::GetCapturedTabs(
const std::string& extension_id,
base::ListValue* list_of_capture_info) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(list_of_capture_info);
list_of_capture_info->Clear();
for (const std::unique_ptr<LiveRequest>& request : requests_) {
if (request->is_anonymous() || !request->is_verified() ||
request->extension_id() != extension_id)
continue;
tab_capture::CaptureInfo info;
request->GetCaptureInfo(&info);
list_of_capture_info->Append(info.ToValue());
}
}
void TabCaptureRegistry::OnExtensionUnloaded(
content::BrowserContext* browser_context,
const Extension* extension,
UnloadedExtensionReason reason) {
// Cleanup all the requested media streams for this extension.
for (auto it = requests_.begin(); it != requests_.end();) {
if ((*it)->extension_id() == extension->id()) {
it = requests_.erase(it);
} else {
++it;
}
}
}
std::string TabCaptureRegistry::AddRequest(
content::WebContents* target_contents,
const std::string& extension_id,
bool is_anonymous,
const GURL& origin,
content::DesktopMediaID source,
const std::string& extension_name,
content::WebContents* caller_contents) {
std::string device_id;
LiveRequest* const request = FindRequest(target_contents);
// Currently, we do not allow multiple active captures for same tab.
if (request != NULL) {
if (request->capture_state() == tab_capture::TAB_CAPTURE_STATE_PENDING ||
request->capture_state() == tab_capture::TAB_CAPTURE_STATE_ACTIVE) {
return device_id;
} else {
// Delete the request before creating its replacement (below).
KillRequest(request);
}
}
requests_.push_back(std::make_unique<LiveRequest>(
target_contents, extension_id, is_anonymous, this));
content::RenderFrameHost* const main_frame = caller_contents->GetMainFrame();
if (main_frame) {
device_id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
main_frame->GetProcess()->GetID(), main_frame->GetRoutingID(),
url::Origin::Create(origin), source, extension_name,
content::kRegistryStreamTypeTab);
}
return device_id;
}
bool TabCaptureRegistry::VerifyRequest(int render_process_id,
int render_frame_id,
const std::string& extension_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
LiveRequest* const request = FindRequest(render_process_id, render_frame_id);
if (!request) {
return false; // Unknown RenderFrameHost ID, or frame has gone away.
}
if (request->is_verified() ||
(request->capture_state() != tab_capture::TAB_CAPTURE_STATE_NONE &&
request->capture_state() != tab_capture::TAB_CAPTURE_STATE_PENDING))
return false;
request->SetIsVerified();
return true;
}
void TabCaptureRegistry::OnRequestUpdate(
int target_render_process_id,
int target_render_frame_id,
blink::mojom::MediaStreamType stream_type,
const content::MediaRequestState new_state) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (stream_type != blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE &&
stream_type != blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE) {
return;
}
LiveRequest* request =
FindRequest(target_render_process_id, target_render_frame_id);
if (!request) {
return; // Stale or invalid request update.
}
TabCaptureState next_state = tab_capture::TAB_CAPTURE_STATE_NONE;
switch (new_state) {
case content::MEDIA_REQUEST_STATE_PENDING_APPROVAL:
next_state = tab_capture::TAB_CAPTURE_STATE_PENDING;
break;
case content::MEDIA_REQUEST_STATE_DONE:
next_state = tab_capture::TAB_CAPTURE_STATE_ACTIVE;
break;
case content::MEDIA_REQUEST_STATE_CLOSING:
next_state = tab_capture::TAB_CAPTURE_STATE_STOPPED;
break;
case content::MEDIA_REQUEST_STATE_ERROR:
next_state = tab_capture::TAB_CAPTURE_STATE_ERROR;
break;
case content::MEDIA_REQUEST_STATE_OPENING:
return;
case content::MEDIA_REQUEST_STATE_REQUESTED:
case content::MEDIA_REQUEST_STATE_NOT_REQUESTED:
NOTREACHED();
return;
}
if (next_state == tab_capture::TAB_CAPTURE_STATE_PENDING &&
request->capture_state() != tab_capture::TAB_CAPTURE_STATE_PENDING &&
request->capture_state() != tab_capture::TAB_CAPTURE_STATE_NONE &&
request->capture_state() != tab_capture::TAB_CAPTURE_STATE_STOPPED &&
request->capture_state() != tab_capture::TAB_CAPTURE_STATE_ERROR) {
// If we end up trying to grab a new stream while the previous one was never
// terminated, then something fishy is going on.
NOTREACHED() << "Trying to capture tab with existing stream.";
return;
}
request->UpdateCaptureState(next_state);
}
void TabCaptureRegistry::DispatchStatusChangeEvent(
const LiveRequest* request) const {
if (request->is_anonymous())
return;
EventRouter* router = EventRouter::Get(browser_context_);
if (!router)
return;
std::unique_ptr<base::ListValue> args(new base::ListValue());
tab_capture::CaptureInfo info;
request->GetCaptureInfo(&info);
args->Append(info.ToValue());
auto event = std::make_unique<Event>(events::TAB_CAPTURE_ON_STATUS_CHANGED,
tab_capture::OnStatusChanged::kEventName,
std::move(args), browser_context_);
router->DispatchEventToExtension(request->extension_id(), std::move(event));
}
TabCaptureRegistry::LiveRequest* TabCaptureRegistry::FindRequest(
const content::WebContents* target_contents) const {
for (const auto& request : requests_) {
if (request->web_contents() == target_contents)
return request.get();
}
return nullptr;
}
TabCaptureRegistry::LiveRequest* TabCaptureRegistry::FindRequest(
int target_render_process_id,
int target_render_frame_id) const {
for (const std::unique_ptr<LiveRequest>& request : requests_) {
if (request->WasTargettingRenderFrameID(target_render_process_id,
target_render_frame_id)) {
return request.get();
}
}
return nullptr;
}
void TabCaptureRegistry::KillRequest(LiveRequest* request) {
for (auto it = requests_.begin(); it != requests_.end(); ++it) {
if (it->get() == request) {
requests_.erase(it);
return;
}
}
NOTREACHED();
}
} // namespace extensions
|
mauguignard/cbmc
|
regression/systemc/Masc1/main.cpp
|
#if 1
typedef unsigned uint;
#endif
#include "masc.h"
#include <cassert>
mv<int,char> init_mv()
{
char z=1;
mv<int,char> m(0,z);
return m;
}
void test_mv()
{
mv<int,char> m = init_mv();
int x;
char y;
m.assign(x,y);
assert(x==0);
assert(y==1);
}
#define SIZE 5
array<SIZE,int> init_array()
{
array<SIZE,int> a;
for(int i=0;i<SIZE;i++)
a.elt[i] = i*i;
return a;
}
void test_array()
{
array<SIZE,int> a = init_array();
assert(a.elt[SIZE-1]==(SIZE-1)*(SIZE-1));
}
int main (int argc, char *argv[])
{
test_mv();
test_array();
return 0;
}
|
HelioGuilherme66/jitsi
|
src/net/java/sip/communicator/plugin/update/UpdateServiceImpl.java
|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.plugin.update;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.text.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.httputil.*;
import net.java.sip.communicator.service.update.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.Logger;
import org.jitsi.service.resources.*;
import org.jitsi.service.version.*;
import org.jitsi.util.*;
/**
* Implements checking for software updates, downloading and applying them i.e.
* the very logic of the update plug-in.
*
* @author <NAME>
* @author <NAME>
*/
public class UpdateServiceImpl
implements UpdateService
{
/**
* The link pointing to the ChangeLog of the update.
*/
private static String changesLink;
/**
* The <tt>JDialog</tt>, if any, which is associated with the currently
* executing "Check for Updates". While the "Check for Updates"
* functionality cannot be entered, clicking the "Check for Updates" menu
* item will bring it to the front.
*/
private static JDialog checkForUpdatesDialog;
/**
* The link pointing at the download of the update.
*/
private static String downloadLink;
/**
* The indicator/counter which determines how many methods are currently
* executing the "Check for Updates" functionality so that it is known
* whether it can be entered.
*/
private static int inCheckForUpdates = 0;
/**
* The latest version of the software found at the configured update
* location.
*/
private static String latestVersion;
/**
* The <tt>Logger</tt> used by the <tt>UpdateServiceImpl</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(UpdateServiceImpl.class);
/**
* The name of the property which specifies the update link in the
* configuration file.
*/
private static final String PROP_UPDATE_LINK
= "net.java.sip.communicator.UPDATE_LINK";
/**
* Initializes a new Web browser <tt>Component</tt> instance and navigates
* it to a specific URL.
*
* @param url the URL to navigate the new Web browser <tt>Component</tt>
* instance
* @return the new Web browser <tt>Component</tt> instance which has been
* navigated to the specified <tt>url</tt>
*/
private static Component createBrowser(String url)
{
// Initialize the user interface.
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(editorPane);
// Navigate the user interface to the specified URL.
try
{
Document document = editorPane.getDocument();
if (document instanceof AbstractDocument)
((AbstractDocument) document).setAsynchronousLoadPriority(0);
editorPane.setPage(new URL(url));
}
catch (Throwable t)
{
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
{
logger.error(
"Failed to navigate the Web browser to: " + url,
t);
}
}
return scrollPane;
}
/**
* Tries to create a new <tt>FileOutputStream</tt> for a temporary file into
* which the setup is to be downloaded. Because temporary files generally
* have random characters in their names and the name of the setup may be
* shown to the user, first tries to use the name of the URL to be
* downloaded because it likely is prettier.
*
* @param url the <tt>URL</tt> of the file to be downloaded
* @param extension the extension of the <tt>File</tt> to be created or
* <tt>null</tt> for the default (which may be derived from <tt>url</tt>)
* @param dryRun <tt>true</tt> to generate a <tt>File</tt> in
* <tt>tempFile</tt> and not open it or <tt>false</tt> to generate a
* <tt>File</tt> in <tt>tempFile</tt> and open it
* @param tempFile a <tt>File</tt> array of at least one element which is to
* receive the created <tt>File</tt> instance at index zero (if successful)
* @return the newly created <tt>FileOutputStream</tt>
* @throws IOException if anything goes wrong while creating the new
* <tt>FileOutputStream</tt>
*/
private static FileOutputStream createTempFileOutputStream(
URL url,
String extension,
boolean dryRun,
File[] tempFile)
throws IOException
{
/*
* Try to use the name from the URL because it isn't a "randomly"
* generated one.
*/
String path = url.getPath();
File tf = null;
FileOutputStream tfos = null;
if ((path != null) && (path.length() != 0))
{
int nameBeginIndex =path.lastIndexOf('/');
String name;
if (nameBeginIndex > 0)
{
name = path.substring(nameBeginIndex + 1);
nameBeginIndex = name.lastIndexOf('\\');
if (nameBeginIndex > 0)
name = name.substring(nameBeginIndex + 1);
}
else
name = path;
/*
* Make sure the extension of the name is EXE so that we're able to
* execute it later on.
*/
int nameLength = name.length();
if (nameLength != 0)
{
int baseNameEnd = name.lastIndexOf('.');
if (extension == null)
extension = ".exe";
if (baseNameEnd == -1)
name += extension;
else if (baseNameEnd == 0)
{
if (!extension.equalsIgnoreCase(name))
name += extension;
}
else
name = name.substring(0, baseNameEnd) + extension;
try
{
String tempDir = System.getProperty("java.io.tmpdir");
if ((tempDir != null) && (tempDir.length() != 0))
{
tf = new File(tempDir, name);
if (!dryRun)
tfos = new FileOutputStream(tf);
}
}
catch (FileNotFoundException fnfe)
{
// Ignore it because we'll try File#createTempFile().
}
catch (SecurityException se)
{
// Ignore it because we'll try File#createTempFile().
}
}
}
// Well, we couldn't use a pretty name so try File#createTempFile().
if ((tfos == null) && !dryRun)
{
tf = File.createTempFile("setup", ".exe");
tfos = new FileOutputStream(tf);
}
tempFile[0] = tf;
return tfos;
}
/**
* Downloads a remote file specified by its URL into a local file.
*
* @param url the URL of the remote file to download
* @return the local <tt>File</tt> into which <tt>url</tt> has been
* downloaded or <tt>null</tt> if there was no response from the
* <tt>url</tt>
* @throws IOException if an I/O error occurs during the download
*/
private static File download(String url)
throws IOException
{
final File[] tempFile = new File[1];
FileOutputStream tempFileOutputStream = null;
boolean deleteTempFile = true;
tempFileOutputStream
= createTempFileOutputStream(
new URL(url),
/*
* The default extension, possibly derived from url, is
* fine. Besides, we do not really have information about
* any preference.
*/
null,
/* Do create a FileOutputStream. */
false,
tempFile);
try
{
HttpUtils.HTTPResponseResult res
= HttpUtils.openURLConnection(url);
if (res != null)
{
InputStream content = res.getContent();
// Track the progress of the download.
ProgressMonitorInputStream input
= new ProgressMonitorInputStream(null, url, content);
/*
* Set the maximum value of the ProgressMonitor to the size of
* the file to download.
*/
input.getProgressMonitor().setMaximum(
(int) res.getContentLength());
try
{
final BufferedOutputStream output
= new BufferedOutputStream(tempFileOutputStream);
try
{
int read = -1;
byte[] buff = new byte[1024];
while((read = input.read(buff)) != -1)
output.write(buff, 0, read);
}
finally
{
output.close();
tempFileOutputStream = null;
}
deleteTempFile = false;
}
finally
{
try
{
input.close();
}
catch (IOException ioe)
{
/*
* Ignore it because we've already downloaded the setup
* and that's what matters most.
*/
}
}
}
}
finally
{
try
{
if (tempFileOutputStream != null)
tempFileOutputStream.close();
}
finally
{
if (deleteTempFile && (tempFile[0] != null))
{
tempFile[0].delete();
tempFile[0] = null;
}
}
}
return tempFile[0];
}
/**
* Notifies this <tt>UpdateCheckActivator</tt> that a method is entering the
* "Check for Updates" functionality and it is thus not allowed to enter it
* again.
*
* @param checkForUpdatesDialog the <tt>JDialog</tt> associated with the
* entry in the "Check for Updates" functionality if any. While "Check for
* Updates" cannot be entered again, clicking the "Check for Updates" menu
* item will bring the <tt>checkForUpdatesDialog</tt> to the front.
*/
private static synchronized void enterCheckForUpdates(
JDialog checkForUpdatesDialog)
{
inCheckForUpdates++;
if (checkForUpdatesDialog != null)
UpdateServiceImpl.checkForUpdatesDialog = checkForUpdatesDialog;
}
/**
* Notifies this <tt>UpdateCheckActivator</tt> that a method is exiting the
* "Check for Updates" functionality and it may thus be allowed to enter it
* again.
*
* @param checkForUpdatesDialog the <tt>JDialog</tt> which was associated
* with the matching call to {@link #enterCheckForUpdates(JDialog)} if any
*/
private static synchronized void exitCheckForUpdates(
JDialog checkForUpdatesDialog)
{
if (inCheckForUpdates == 0)
throw new IllegalStateException("inCheckForUpdates");
else
{
inCheckForUpdates--;
if ((checkForUpdatesDialog != null)
&& (UpdateServiceImpl.checkForUpdatesDialog
== checkForUpdatesDialog))
UpdateServiceImpl.checkForUpdatesDialog = null;
}
}
/**
* Gets the current (software) version.
*
* @return the current (software) version
*/
private static Version getCurrentVersion()
{
return getVersionService().getCurrentVersion();
}
/**
* Returns the currently registered instance of version service.
* @return the current version service.
*/
private static VersionService getVersionService()
{
return ServiceUtils.getService(
UpdateActivator.bundleContext,
VersionService.class);
}
/**
* Determines whether we are currently running the latest version.
*
* @return <tt>true</tt> if we are currently running the latest version;
* otherwise, <tt>false</tt>
*/
private static boolean isLatestVersion()
{
try
{
String updateLink
= UpdateActivator.getConfiguration().getString(
PROP_UPDATE_LINK);
if(updateLink == null)
{
updateLink
= Resources.getUpdateConfigurationString("update_link");
}
if(updateLink == null)
{
if (logger.isDebugEnabled())
logger.debug(
"Updates are disabled, faking latest version.");
}
else
{
HttpUtils.HTTPResponseResult res
= HttpUtils.openURLConnection(updateLink);
if (res != null)
{
InputStream in = null;
Properties props = new Properties();
try
{
in = res.getContent();
props.load(in);
}
finally
{
in.close();
}
latestVersion = props.getProperty("last_version");
downloadLink = props.getProperty("download_link");
/*
* Make sure that download_link points to the architecture
* of the running application.
*/
if (downloadLink != null)
{
if (OSUtils.IS_LINUX32)
{
downloadLink
= downloadLink.replace("amd64", "i386");
}
else if (OSUtils.IS_LINUX64)
{
downloadLink
= downloadLink.replace("i386", "amd64");
}
else if (OSUtils.IS_WINDOWS32)
{
downloadLink = downloadLink.replace("x64", "x86");
}
else if (OSUtils.IS_WINDOWS64)
{
downloadLink = downloadLink.replace("x86", "x64");
}
}
changesLink
= updateLink.substring(
0,
updateLink.lastIndexOf("/") + 1)
+ props.getProperty("changes_html");
try
{
VersionService versionService = getVersionService();
Version latestVersionObj =
versionService.parseVersionString(latestVersion);
if(latestVersionObj != null)
return latestVersionObj.compareTo(
getCurrentVersion()) <= 0;
else
logger.error("Version obj not parsed("
+ latestVersion + ")");
}
catch(Throwable t)
{
logger.error("Error parsing version string", t);
}
// fallback to lexicographically compare
// of version strings in case of an error
return latestVersion.compareTo(
getCurrentVersion().toString()) <= 0;
}
}
}
catch (Exception e)
{
logger.warn(
"Could not retrieve latest version or compare it to current"
+ " version",
e);
/*
* If we get an exception, then we will return that the current
* version is the newest one in order to prevent opening the dialog
* notifying about the availability of a new version.
*/
}
return true;
}
/**
* Runs in a daemon/background <tt>Thread</tt> dedicated to checking whether
* a new version of the application is available and notifying the user
* about the result of the check.
*
* @param notifyAboutNewestVersion <tt>true</tt> to notify the user in case
* she is running the newest/latest version available already; otherwise,
* <tt>false</tt>
*/
private static void runInCheckForUpdatesThread(
boolean notifyAboutNewestVersion)
{
if(isLatestVersion())
{
if(notifyAboutNewestVersion)
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
UIService ui = UpdateActivator.getUIService();
ResourceManagementService r
= Resources.getResources();
ui.getPopupDialog().showMessagePopupDialog(
r.getI18NString(
"plugin.updatechecker."
+ "DIALOG_NOUPDATE"),
r.getI18NString(
"plugin.updatechecker."
+ "DIALOG_NOUPDATE_TITLE"),
PopupDialog.INFORMATION_MESSAGE);
}
});
}
}
else
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
if (OSUtils.IS_WINDOWS)
showWindowsNewVersionAvailableDialog();
else
showGenericNewVersionAvailableDialog();
}
});
}
}
/**
* Shows dialog informing about the availability of a new version with a
* Download button which launches the system Web browser.
*/
private static void showGenericNewVersionAvailableDialog()
{
/*
* Before showing the dialog, we'll enterCheckForUpdates() in order to
* notify that it is not safe to enter "Check for Updates" again. If we
* don't manage to show the dialog, we'll have to exitCheckForUpdates().
* If we manage though, we'll have to exitCheckForUpdates() but only
* once depending on its modality.
*/
final boolean[] exitCheckForUpdates = new boolean[] { false };
final JDialog dialog = new SIPCommDialog()
{
private static final long serialVersionUID = 0L;
@Override
protected void close(boolean escaped)
{
synchronized (exitCheckForUpdates)
{
if (exitCheckForUpdates[0])
exitCheckForUpdates(this);
}
}
};
ResourceManagementService resources = Resources.getResources();
dialog.setTitle(
resources.getI18NString("plugin.updatechecker.DIALOG_TITLE"));
JEditorPane contentMessage = new JEditorPane();
contentMessage.setContentType("text/html");
contentMessage.setOpaque(false);
contentMessage.setEditable(false);
String dialogMsg
= resources.getI18NString(
"plugin.updatechecker.DIALOG_MESSAGE",
new String[]
{
resources.getSettingsString(
"service.gui.APPLICATION_NAME")
});
if(latestVersion != null)
dialogMsg
+= resources.getI18NString(
"plugin.updatechecker.DIALOG_MESSAGE_2",
new String[]
{
resources.getSettingsString(
"service.gui.APPLICATION_NAME"),
latestVersion
});
contentMessage.setText(dialogMsg);
JPanel contentPane = new TransparentPanel(new BorderLayout(5,5));
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.add(contentMessage, BorderLayout.CENTER);
JPanel buttonPanel
= new TransparentPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
final JButton closeButton
= new JButton(
resources.getI18NString(
"plugin.updatechecker.BUTTON_CLOSE"));
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dialog.dispose();
if (exitCheckForUpdates[0])
exitCheckForUpdates(dialog);
}
});
if(downloadLink != null)
{
JButton downloadButton
= new JButton(
resources.getI18NString(
"plugin.updatechecker.BUTTON_DOWNLOAD"));
downloadButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
UpdateActivator.getBrowserLauncher().openURL(downloadLink);
/*
* Do the same as the Close button in order to not duplicate
* the code.
*/
closeButton.doClick();
}
});
buttonPanel.add(downloadButton);
}
buttonPanel.add(closeButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
dialog.setContentPane(contentPane);
dialog.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(
screenSize.width/2 - dialog.getWidth()/2,
screenSize.height/2 - dialog.getHeight()/2);
synchronized (exitCheckForUpdates)
{
enterCheckForUpdates(dialog);
exitCheckForUpdates[0] = true;
}
try
{
dialog.setVisible(true);
}
finally
{
synchronized (exitCheckForUpdates)
{
if (exitCheckForUpdates[0] && dialog.isModal())
exitCheckForUpdates(dialog);
}
}
}
/**
* Shows dialog informing about new version with button Install
* which triggers the update process.
*/
private static void showWindowsNewVersionAvailableDialog()
{
/*
* Before showing the dialog, we'll enterCheckForUpdates() in order to
* notify that it is not safe to enter "Check for Updates" again. If we
* don't manage to show the dialog, we'll have to exitCheckForUpdates().
* If we manage though, we'll have to exitCheckForUpdates() but only
* once depending on its modality.
*/
final boolean[] exitCheckForUpdates = new boolean[] { false };
@SuppressWarnings("serial")
final JDialog dialog
= new SIPCommDialog()
{
@Override
protected void close(boolean escaped)
{
synchronized (exitCheckForUpdates)
{
if (exitCheckForUpdates[0])
exitCheckForUpdates(this);
}
}
};
ResourceManagementService r = Resources.getResources();
dialog.setTitle(r.getI18NString("plugin.updatechecker.DIALOG_TITLE"));
JEditorPane contentMessage = new JEditorPane();
contentMessage.setContentType("text/html");
contentMessage.setOpaque(false);
contentMessage.setEditable(false);
/*
* Use the font of the dialog because contentMessage is just like a
* label.
*/
contentMessage.putClientProperty(
JEditorPane.HONOR_DISPLAY_PROPERTIES,
Boolean.TRUE);
String dialogMsg
= r.getI18NString(
"plugin.updatechecker.DIALOG_MESSAGE",
new String[]
{
r.getSettingsString(
"service.gui.APPLICATION_NAME")
});
if(latestVersion != null)
{
dialogMsg
+= r.getI18NString(
"plugin.updatechecker.DIALOG_MESSAGE_2",
new String[]
{
r.getSettingsString(
"service.gui.APPLICATION_NAME"),
latestVersion
});
}
contentMessage.setText(dialogMsg);
JPanel contentPane = new SIPCommFrame.MainContentPane();
contentMessage.setBorder(BorderFactory.createEmptyBorder(10, 0, 20, 0));
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
contentPane.add(contentMessage, BorderLayout.NORTH);
Component browser = createBrowser(changesLink);
if (browser != null)
{
browser.setPreferredSize(new Dimension(550, 200));
contentPane.add(browser, BorderLayout.CENTER);
}
JPanel buttonPanel
= new TransparentPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
final JButton closeButton
= new JButton(
r.getI18NString(
"plugin.updatechecker.BUTTON_CLOSE"));
closeButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dialog.dispose();
if (exitCheckForUpdates[0])
exitCheckForUpdates(dialog);
}
});
if(downloadLink != null)
{
JButton installButton
= new JButton(
r.getI18NString("plugin.updatechecker.BUTTON_INSTALL"));
installButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enterCheckForUpdates(null);
try
{
/*
* Do the same as the Close button in order to
* not duplicate the code.
*/
closeButton.doClick();
}
finally
{
boolean windowsUpdateThreadHasStarted = false;
try
{
new Thread()
{
@Override
public void run()
{
try
{
windowsUpdate();
}
finally
{
exitCheckForUpdates(null);
}
}
}.start();
windowsUpdateThreadHasStarted = true;
}
finally
{
if (!windowsUpdateThreadHasStarted)
exitCheckForUpdates(null);
}
}
}
});
buttonPanel.add(installButton);
}
buttonPanel.add(closeButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
dialog.setContentPane(contentPane);
dialog.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(
screenSize.width/2 - dialog.getWidth()/2,
screenSize.height/2 - dialog.getHeight()/2);
synchronized (exitCheckForUpdates)
{
enterCheckForUpdates(dialog);
exitCheckForUpdates[0] = true;
}
try
{
dialog.setVisible(true);
}
finally
{
synchronized (exitCheckForUpdates)
{
if (exitCheckForUpdates[0] && dialog.isModal())
exitCheckForUpdates(dialog);
}
}
}
/**
* Implements the very update procedure on Windows which includes without
* being limited to:
* <ol>
* <li>Downloads the setup in a temporary directory.</li>
* <li>Warns that the update procedure will shut down the application.</li>
* <li>Executes the setup in a separate process and shuts down the
* application.</li>
* </ol>
*/
private static void windowsUpdate()
{
/*
* Firstly, try a delta update which contains a bspatch file to be used
* to reconstruct the latest MSI from the locally-cached one. If it
* fails, fall back to a full update.
*/
File delta = null;
boolean deleteDelta = true;
File msi = null;
try
{
String deltaTarget = null;
Version ver = getCurrentVersion();
if(ver.isNightly())
deltaTarget = ver.getNightlyBuildID();
else
deltaTarget = ver.toString();
String deltaLink
= downloadLink.replace(
latestVersion,
latestVersion + "-delta-" + deltaTarget);
if (!deltaLink.equalsIgnoreCase(downloadLink))
delta = download(deltaLink);
if (delta != null)
{
File[] deltaMsi = new File[1];
createTempFileOutputStream(
delta.toURI().toURL(),
".msi",
/*
* Do not actually create a FileOutputStream, we just
* want the File (name).
*/
true,
deltaMsi);
Process process
= new ProcessBuilder(
delta.getCanonicalPath(),
"--quiet",
deltaMsi[0].getCanonicalPath())
.start();
int exitCode = 1;
while (true)
{
try
{
exitCode = process.waitFor();
break;
}
catch (InterruptedException ie)
{
/*
* Ignore it, we're interested in the exit code of the
* process.
*/
}
}
if (0 == exitCode)
{
deleteDelta = false;
msi = deltaMsi[0];
}
}
}
catch (Exception e)
{
/* Ignore it, we'll try the full update. */
}
finally
{
if (deleteDelta && (delta != null))
{
delta.delete();
delta = null;
}
}
/*
* Secondly, either apply the delta update or download and apply a full
* update.
*/
boolean deleteMsi = true;
deleteDelta = true;
try
{
if (msi == null)
msi = download(downloadLink);
if (msi != null)
{
ResourceManagementService resources = Resources.getResources();
if(UpdateActivator.getUIService()
.getPopupDialog().showConfirmPopupDialog(
resources.getI18NString(
"plugin.updatechecker.DIALOG_WARN",
new String[]{
resources.getSettingsString(
"service.gui.APPLICATION_NAME")
}),
resources.getI18NString(
"plugin.updatechecker.DIALOG_TITLE"),
PopupDialog.YES_NO_OPTION,
PopupDialog.QUESTION_MESSAGE)
== PopupDialog.YES_OPTION)
{
List<String> command = new ArrayList<String>();
/*
* If a delta update is in effect, the delta will execute
* the latest MSI it has previously recreated from the
* locally-cached MSI. Otherwise, a full update is in effect
* and it will just execute itself.
*/
command.add(
((delta == null) ? msi : delta).getCanonicalPath());
command.add("--wait-parent");
if (delta != null)
{
command.add("--msiexec");
command.add(msi.getCanonicalPath());
}
command.add(
"SIP_COMMUNICATOR_AUTOUPDATE_INSTALLDIR=\""
+ System.getProperty("user.dir")
+ "\"");
deleteMsi = false;
deleteDelta = false;
/*
* The setup has been downloaded. Now start it and shut
* down.
*/
new ProcessBuilder(command).start();
UpdateActivator.getShutdownService().beginShutdown();
}
}
}
catch(FileNotFoundException fnfe)
{
ResourceManagementService resources = Resources.getResources();
UpdateActivator.getUIService()
.getPopupDialog().showMessagePopupDialog(
resources.getI18NString(
"plugin.updatechecker.DIALOG_MISSING_UPDATE"),
resources.getI18NString(
"plugin.updatechecker.DIALOG_NOUPDATE_TITLE"),
PopupDialog.INFORMATION_MESSAGE);
}
catch (Exception e)
{
if (logger.isInfoEnabled())
logger.info("Could not update", e);
}
finally
{
/*
* If we've failed, delete the temporary file into which the setup
* was supposed to be or has already been downloaded.
*/
if (deleteMsi && (msi != null))
{
msi.delete();
msi = null;
}
if (deleteDelta && (delta != null))
{
delta.delete();
delta = null;
}
}
}
/**
* Invokes "Check for Updates".
*
* @param notifyAboutNewestVersion <tt>true</tt> if the user is to be
* notified if they have the newest version already; otherwise,
* <tt>false</tt>
*/
public synchronized void checkForUpdates(
final boolean notifyAboutNewestVersion)
{
if (inCheckForUpdates > 0)
{
if (checkForUpdatesDialog != null)
checkForUpdatesDialog.toFront();
return;
}
Thread checkForUpdatesThread
= new Thread()
{
@Override
public void run()
{
try
{
runInCheckForUpdatesThread(notifyAboutNewestVersion);
}
finally
{
exitCheckForUpdates(null);
}
}
};
checkForUpdatesThread.setDaemon(true);
checkForUpdatesThread.setName(
getClass().getName() + ".checkForUpdates");
enterCheckForUpdates(null);
try
{
checkForUpdatesThread.start();
checkForUpdatesThread = null;
}
finally
{
if (checkForUpdatesThread != null)
exitCheckForUpdates(null);
}
}
}
|
Ch1rag02/JPlotter
|
jplotter/src/test/java/hageldave/jplotter/PrecisionTest.java
|
package hageldave.jplotter;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import hageldave.jplotter.canvas.BlankCanvas;
import hageldave.jplotter.interaction.CoordSysScrollZoom;
import hageldave.jplotter.misc.DefaultGlyph;
import hageldave.jplotter.renderables.Curves;
import hageldave.jplotter.renderables.Lines;
import hageldave.jplotter.renderables.Points;
import hageldave.jplotter.renderables.Text;
import hageldave.jplotter.renderables.Triangles;
import hageldave.jplotter.renderers.CompleteRenderer;
import hageldave.jplotter.renderers.CoordSysRenderer;
import hageldave.jplotter.util.Utils;
public class PrecisionTest {
public static void main(String[] args) {
JFrame frame = Boilerplate.createJFrameWithBoilerPlate("Precision Test");
BlankCanvas canvas = new BlankCanvas();
frame.getContentPane().add(canvas.asComponent());
canvas.addCleanupOnWindowClosingListener(frame);
CoordSysRenderer csr = new CoordSysRenderer();
canvas.setRenderer(csr);
CompleteRenderer content = new CompleteRenderer();
csr.setContent(content);
new CoordSysScrollZoom(canvas, csr).register();
JCheckBox cbxDoublePrecision = new JCheckBox("GL double precision");
cbxDoublePrecision.addChangeListener(e->{
content.setGLDoublePrecisionEnabled(cbxDoublePrecision.isSelected());
canvas.scheduleRepaint();
});
content.setGLDoublePrecisionEnabled(cbxDoublePrecision.isSelected());
frame.getContentPane().add(cbxDoublePrecision, BorderLayout.NORTH);
Points p = new Points(DefaultGlyph.CIRCLE);
Lines l = new Lines();
Curves c = new Curves();
Triangles t = new Triangles();
content
.addItemToRender(t)
.addItemToRender(c)
.addItemToRender(l)
.addItemToRender(p);
// create spiral going inwards
final double cx=1e-4,cy=1e-4;
double radius = 1;
double rad = 0;
final double pi2 = Math.PI*2;
ArrayList<Point2D> points = new ArrayList<>();
while(radius > 1e-16) {
double x = Math.cos(rad)*radius + cx;
double y = Math.sin(rad)*radius + cy;
points.add(new Point2D.Double(x, y));
rad = (rad + 0.8)%pi2;
radius *= 0.8;
}
Point2D[] pointarray = points.toArray(new Point2D[0]);
points=null;
System.gc();
l.addLineStrip(pointarray);
c.addCurvesThrough(pointarray);
for(int i=0; i<pointarray.length; i++) {
p.addPoint(pointarray[i]);
}
for(int i=0; i<pointarray.length-1; i++) {
Point2D p1 = pointarray[i];
Point2D p2 = pointarray[i+1];
double dx = p2.getX()-p1.getX();
double dy = p2.getY()-p1.getY();
double x = p1.getX()+dx*0.5;
double y = p1.getY()+dy*0.5;
x -= 0.5*dy;
y += 0.5*dx;
t.addTriangle(p1, p2, new Point2D.Double(x, y));
}
for(int i=0; i < pointarray.length; i+=1) {
Point2D point = pointarray[i];
double dx = point.getX()-cx;
double dy = point.getY()-cy;
double atan2 = Math.atan2(dy, dx);
if(atan2 < 1.3 && atan2 > 0.5) {
Text label = new Text(String.format("r=%e", Utils.hypot(dx, dy)), 10, Font.PLAIN);
label.setOrigin(new Point2D.Double(cx+1.1*dx,cy+1.1*dy));
content.addItemToRender(label);
}
}
csr.setCoordinateView(cx-1, cy-1, cx+1, cy+1);
SwingUtilities.invokeLater(()->{
frame.pack();
frame.setVisible(true);
});
}
}
|
amgadmadkour/knowledgecubes
|
src/main/scala/edu/purdue/knowledgecubes/storage/persistent/Store.scala
|
package edu.purdue.knowledgecubes.storage.persistent
import scala.collection.mutable.{ListBuffer, Map}
import com.typesafe.scalalogging.Logger
import org.apache.jena.riot.Lang
import org.apache.spark.sql.{Dataset, SaveMode, SparkSession}
import org.apache.spark.sql.functions.col
import org.fusesource.leveldbjni.JniDBFactory.{asString, bytes}
import org.slf4j.LoggerFactory
import edu.purdue.knowledgecubes.GEFI.GEFIType
import edu.purdue.knowledgecubes.GEFI.join.GEFIJoinUtils
import edu.purdue.knowledgecubes.metadata.Catalog
import edu.purdue.knowledgecubes.rdf.RDFTriple
import edu.purdue.knowledgecubes.utils.NTParser
class Store(spark: SparkSession,
dbPath: String,
localPath: String,
filterType: GEFIType.Value,
falsePositiveRate: Double) {
val catalog = new Catalog(localPath, dbPath, spark)
val LOG = Logger(LoggerFactory.getLogger(classOf[Store]))
def create(triplesDataset: Dataset[RDFTriple]): Unit = {
LOG.info("Identifying Property Based Files ...")
// Get all unique predicates
val iter = triplesDataset.select("p").distinct.toLocalIterator
var uris = ListBuffer[String]()
var uriCounter = 0
while (iter.hasNext) {
val uri = iter.next.getInt(0).toString
uris += uri
uriCounter += 1
}
val numProperties = uriCounter
val numTuples = triplesDataset.count
LOG.debug(s"Number of properties : $numProperties")
// Catalog information about the data currently ntriple the database
catalog.dbInfo += ("numProperties" -> numProperties.toString)
catalog.dbInfo += ("numTuples" -> numTuples.toString)
catalog.dbInfo += ("dbPath" -> dbPath)
var count = 0
val lang: Lang = Lang.NTRIPLES
for (uri <- uris) {
count += 1
val data = triplesDataset.filter(col("p").equalTo(uri))
data.cache()
val size = data.count()
// Statistics
val propTable = Map[String, String]()
val predicateName = asString(catalog.dictionaryId2Str.get(bytes(uri)))
propTable += ("uri" -> uri)
propTable += ("predicate" -> predicateName)
propTable += ("numTuples" -> size.toString)
propTable += ("ratio" -> (size.toFloat / numTuples.toFloat).toString)
val subData = data.select(col("s")).distinct()
val uniqSub = subData.count()
propTable += ("unique_s" -> uniqSub.toString)
val objData = data.select(col("o")).distinct()
val uniqObj = objData.count()
propTable += ("unique_o" -> uniqObj.toString)
data.write.mode(SaveMode.Overwrite).parquet(catalog.dataPath + uri)
LOG.info(s"Processed ($count/$numProperties) : $predicateName - File: $uri ($size)")
catalog.addTable(propTable.toMap)
if (!filterType.equals(GEFIType.NONE)) {
val filteredObjData = objData.where(!col("o").startsWith("\""))
GEFIJoinUtils.create(filterType, uniqSub, falsePositiveRate, subData, "s", uri, catalog.localPath)
GEFIJoinUtils.create(filterType, uniqObj, falsePositiveRate, filteredObjData, "o", uri, catalog.localPath)
}
data.unpersist()
}
triplesDataset.unpersist()
catalog.save()
}
def create(ntPath: String): Unit = {
val triplesDataFrame = NTParser.parse(spark, ntPath)
triplesDataFrame.cache()
create(triplesDataFrame)
}
def close(): Unit = {
catalog.dictionaryStr2Id.close()
}
}
object Store {
def apply(spark: SparkSession,
dbPath: String,
localPath: String,
filterType: GEFIType.Value,
falsePositiveRate: Double): Store = new Store(spark, dbPath, localPath, filterType, falsePositiveRate)
def apply(spark: SparkSession,
dbPath: String,
localPath: String): Store = new Store(spark, dbPath, localPath, GEFIType.NONE, 0)
}
|
pradeshm/infinispan
|
client/rest-client/src/main/java/org/infinispan/client/rest/RestResponse.java
|
package org.infinispan.client.rest;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.infinispan.client.rest.configuration.Protocol;
import org.infinispan.commons.util.Experimental;
/**
* @author <NAME> <<EMAIL>>
* @since 10.0
**/
@Experimental
public interface RestResponse extends RestEntity, AutoCloseable {
int getStatus();
Map<String, List<String>> headers();
/**
* Returns the value of a header as a String. For multi-valued headers, values are separated by comma.
*/
String getHeader(String header);
InputStream getBodyAsStream();
byte[] getBodyAsByteArray();
Protocol getProtocol();
void close();
boolean usedAuthentication();
}
|
WeLogix/welogix-saas-web
|
client/apps/corp/message.i18n.js
|
import { defineMessages } from 'react-intl';
import { formati18n } from 'client/common/i18n/helpers';
import globalMessages from 'client/common/root.i18n';
const messages = defineMessages({
corpAdmin: {
id: 'corp.admin',
defaultMessage: '企业控制台',
},
overview: {
id: 'corp.overview',
defaultMessage: '概览',
},
corpBasic: {
id: 'corp.basic',
defaultMessage: '基础',
},
corpInfo: {
id: 'corp.info',
defaultMessage: '企业信息',
},
corpSubscription: {
id: 'corp.subscription',
defaultMessage: '订购信息',
},
corpDeptMember: {
id: 'corp.org.dept.member',
defaultMessage: '部门与成员',
},
corpRole: {
id: 'corp.role',
defaultMessage: '角色权限',
},
corpConnect: {
id: 'corp.connect',
defaultMessage: '互联',
},
affiliate: {
id: 'corp.connect.affiliate',
defaultMessage: '集团联盟',
},
collabAuth: {
id: 'corp.connect.collab.license',
defaultMessage: '协作授权',
},
collabInvitation: {
id: 'corp.connect.collab.invitation',
defaultMessage: '协作邀请',
},
collabEmpower: {
id: 'corp.connect.collab.manage',
defaultMessage: '协作管理',
},
corpAudit: {
id: 'corp.audit',
defaultMessage: '审计',
},
auditTrial: {
id: 'corp.audit.trial',
defaultMessage: '审计日志',
},
recycle: {
id: 'corp.audit.recycle',
defaultMessage: '数据回收',
},
usageMeter: {
id: 'corp.usage.meter',
defaultMessage: '用量',
},
controlPanel: {
id: 'corp.control.panel',
defaultMessage: '控制面板',
},
updateSuccess: {
id: 'corp.info.updateSuccess',
defaultMessage: '更新成功',
},
formValidateErr: {
id: 'corp.info.form.validate.error',
defaultMessage: '表单检验存在错误',
},
companyName: {
id: 'corp.info.companyName',
defaultMessage: '企业名称',
},
companyNameTip: {
id: 'corp.info.companyName.tip',
defaultMessage: '请与营业执照名称一致',
},
companyNameRequired: {
id: 'corp.info.companyName.required',
defaultMessage: '公司名称必填',
},
companyShortName: {
id: 'corp.info.companyShortName',
defaultMessage: '企业简称',
},
shortNameMessage: {
id: 'corp.info.shortName.message',
defaultMessage: '公司简称必须2位以上中英文',
},
corpUUID: {
id: 'corp.info.uuid',
defaultMessage: '企业帐号ID',
},
corpType: {
id: 'corp.info.type',
defaultMessage: '企业类型',
},
enterpriseCode: {
id: 'corp.info.enterprise.code',
defaultMessage: '统一社会信用代码',
},
tenantLevel: {
id: 'corp.info.tenant.level',
defaultMessage: '租户级别',
},
companyAbout: {
id: 'corp.info.company.about',
defaultMessage: '企业简介',
},
basicInfo: {
id: 'corp.info.basic',
defaultMessage: '基本信息',
},
});
export default messages;
export const formatMsg = formati18n({ ...globalMessages, ...messages });
|
facebookincubator/InjK
|
TransformCore/src/test/java/com/facebook/ads/injkit/crashshield/CrashShieldViewsInjectionTest.java
|
// Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package com.facebook.ads.injkit.crashshield;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import com.facebook.ads.injkit.TransformationEnvironment;
import com.facebook.ads.injkit.crashshield.safe_components.SafeView;
import java.lang.reflect.Field;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@FakeHandleExceptionsAnnotation
@RunWith(RobolectricTestRunner.class)
@SuppressLint("CatchGeneralException")
public class CrashShieldViewsInjectionTest {
@Rule public TemporaryFolder temporaryFolderRule = new TemporaryFolder();
private TransformationEnvironment environment;
private final String SAFE_VIEW_INAME =
"com/facebook/ads/injkit/crashshield/safe_components/SafeView";
private final String SAFE_VIEW_GROUP_INAME =
"com/facebook/ads/injkit/crashshield/safe_components/SafeViewGroup";
@Before
public void before() throws Exception {
environment = new TransformationEnvironment(temporaryFolderRule);
CrashShieldInjector.setSafeNames(SAFE_VIEW_INAME, SAFE_VIEW_GROUP_INAME);
}
@Test
public void fakeViewAOnMeasure_throwsExceptionBeforeSuperCall_catchException() throws Exception {
ClassLoader classLoader =
processClasses(
FakeViewA.class, FakeViewB.class, Class.forName(FakeViewA.class.getName() + "$1"));
Class<?> cls = classLoader.loadClass(FakeViewB.class.getName());
SafeView instance =
(SafeView) cls.getConstructor(Context.class).newInstance(RuntimeEnvironment.application);
setBooleanFieldValueForView(instance, "throwsExceptionABefore", true);
instance.measure(1, 1);
assertTrue(getBooleanFieldValueView(instance, "isMethodBBeforeException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodBAfterException"));
assertTrue(getBooleanFieldValueView(instance, "isMethodABeforeException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodAAfterException"));
}
@Test
public void fakeViewAOnMeasure_throwsExceptionAfterSuperCall_catchException() throws Exception {
ClassLoader classLoader =
processClasses(
FakeViewA.class, FakeViewB.class, Class.forName(FakeViewA.class.getName() + "$1"));
Class<?> cls = classLoader.loadClass(FakeViewB.class.getName());
SafeView instance =
(SafeView) cls.getConstructor(Context.class).newInstance(RuntimeEnvironment.application);
setBooleanFieldValueForView(instance, "throwsExceptionAAfter", true);
instance.measure(1, 1);
assertTrue(getBooleanFieldValueView(instance, "isMethodBBeforeException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodBAfterException"));
assertTrue(getBooleanFieldValueView(instance, "isMethodABeforeException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodAAfterException"));
}
@Test
public void fakeViewBOnMeasure_throwsExceptionBeforeSuperCall_catchException() throws Exception {
ClassLoader classLoader =
processClasses(
FakeViewA.class, FakeViewB.class, Class.forName(FakeViewA.class.getName() + "$1"));
Class<?> cls = classLoader.loadClass(FakeViewB.class.getName());
SafeView instance =
(SafeView) cls.getConstructor(Context.class).newInstance(RuntimeEnvironment.application);
setBooleanFieldValueForView(instance, "throwsExceptionBBefore", true);
instance.measure(1, 1);
assertTrue(getBooleanFieldValueView(instance, "isMethodBBeforeException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodBAfterException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodABeforeException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodAAfterException"));
}
@Test
public void fakeViewBOnMeasure_throwsExceptionAfterSuperCall_catchException() throws Exception {
ClassLoader classLoader =
processClasses(
FakeViewA.class, FakeViewB.class, Class.forName(FakeViewA.class.getName() + "$1"));
Class<?> cls = classLoader.loadClass(FakeViewB.class.getName());
SafeView instance =
(SafeView) cls.getConstructor(Context.class).newInstance(RuntimeEnvironment.application);
setBooleanFieldValueForView(instance, "throwsExceptionBAfter", true);
instance.measure(1, 1);
assertTrue(getBooleanFieldValueView(instance, "isMethodBBeforeException"));
assertFalse(getBooleanFieldValueView(instance, "isMethodBAfterException"));
assertTrue(getBooleanFieldValueView(instance, "isMethodABeforeException"));
assertTrue(getBooleanFieldValueView(instance, "isMethodAAfterException"));
}
@Test
public void processFakeViewA_withAnonymousClass_shouldRenameInAnonymousClass() throws Exception {
ClassLoader classLoader =
processClasses(FakeViewA.class, Class.forName(FakeViewA.class.getName() + "$1"));
Class<?> cls = classLoader.loadClass(FakeViewA.class.getName());
View fakeViewA =
(View) cls.getConstructor(Context.class).newInstance(RuntimeEnvironment.application);
Field rField = fakeViewA.getClass().getDeclaredField("r");
rField.setAccessible(true);
Runnable r = ((Runnable) rField.get(fakeViewA));
r.run();
// verify that call inside run() renamed from onMeasure() to safe_onMeasure()
assertFalse(((SafeView) fakeViewA).onMeasureCalled);
assertTrue(((SafeView) fakeViewA).safe_onMeasureCalled);
}
public static void setBooleanFieldValueForView(
View instance, String fieldName, boolean fieldValue) {
try {
Field field = instance.getClass().getField(fieldName);
field.set(instance, fieldValue);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean getBooleanFieldValueView(View instance, String methodName) {
try {
Field field = instance.getClass().getField(methodName);
return (Boolean) field.get(instance);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private ClassLoader processClasses(Class<?>... processingClass) throws Exception {
for (Class clazz : processingClass) {
environment.addProcessingClass(clazz);
}
ClassLoader classLoader =
environment
.newLoadableConfigurationWriter()
.enable(new CrashShieldConfigurationWriter.Factory<>())
.noTransformAnnotation(FakeDoNotHandleExceptionAnnotation.class)
.transformAnnotation(FakeHandleExceptionsAnnotation.class)
.handler(FakeExceptionHandler.class)
.shouldProcessViews(true)
.processPackage(processingClass)
.done()
.transformAndLoad();
return classLoader;
}
public static boolean getBooleanFieldValue(View.OnClickListener instance, String methodName) {
try {
Field field = instance.getClass().getField(methodName);
return (Boolean) field.get(instance);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@FakeHandleExceptionsAnnotation
public static class FakeViewA extends View {
public boolean isMethodABeforeException = false;
public boolean isMethodAAfterException = false;
public boolean throwsExceptionABefore = false;
public boolean throwsExceptionAAfter = false;
public Runnable r;
public FakeViewA(Context context) {
super(context);
r =
new Runnable() {
@FakeHandleExceptionsAnnotation
@Override
public void run() {
FakeViewA.super.onMeasure(0, 0);
}
};
}
@Override
public void onMeasure(int a, int b) {
isMethodABeforeException = true;
if (throwsExceptionABefore) {
throw new RuntimeException("");
}
super.onMeasure(a, b);
if (throwsExceptionAAfter) {
throw new RuntimeException("");
}
isMethodAAfterException = true;
}
}
public static class FakeViewB extends FakeViewA {
public boolean isMethodBBeforeException = false;
public boolean isMethodBAfterException = false;
public boolean throwsExceptionBBefore = false;
public boolean throwsExceptionBAfter = false;
public FakeViewB(Context context) {
super(context);
}
@Override
public void onMeasure(int a, int b) {
isMethodBBeforeException = true;
if (throwsExceptionBBefore) {
throw new RuntimeException("");
}
super.onMeasure(a, b);
if (throwsExceptionBAfter) {
throw new RuntimeException("");
}
isMethodBAfterException = true;
}
}
}
|
gentaprima/skirpsinurul
|
assets/dashboard/plugins/ckeditor/plugins/showblocks/lang/ro.js
|
<reponame>gentaprima/skirpsinurul<filename>assets/dashboard/plugins/ckeditor/plugins/showblocks/lang/ro.js
CKEDITOR.plugins.setLang("showblocks","ro",{toolbar:"Arată blocurile"});
|
giraffe/jrate
|
gcc/libjava/java/awt/Shape.java
|
<reponame>giraffe/jrate
/* Shape.java -- the classic Object-Oriented shape interface
Copyright (C) 1999, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.awt;
import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* This interface represents an abstract shape. The shape is described by
* a {@link PathIterator}, and has callbacks for determining bounding box,
* where points and rectangles lie in relation to the shape, and tracing
* the trajectory.
*
* <p>A point is inside if it is completely inside, or on the boundary and
* adjacent points in the increasing x or y direction are completely inside.
* Unclosed shapes are considered as implicitly closed when performing
* <code>contains</code> or <code>intersects</code>.
*
* @author <NAME> <<EMAIL>>
* @see PathIterator
* @see AffineTransform
* @see FlatteningPathIterator
* @see GeneralPath
* @since 1.0
* @status updated to 1.4
*/
public interface Shape
{
/**
* Returns a <code>Rectange</code> that bounds the shape. There is no
* guarantee that this is the minimum bounding box, particularly if
* the shape overflows the finite integer range of a bound. Generally,
* <code>getBounds2D</code> returns a tighter bound.
*
* @return the shape's bounding box
* @see #getBounds2D()
*/
Rectangle getBounds();
/**
* Returns a high precision bounding box of the shape. There is no guarantee
* that this is the minimum bounding box, but at least it never overflows.
*
* @return the shape's bounding box
* @see #getBounds()
* @since 1.2
*/
Rectangle2D getBounds2D();
/**
* Test if the coordinates lie in the shape.
*
* @param x the x coordinate
* @param y the y coordinate
* @return true if (x,y) lies inside the shape
* @since 1.2
*/
boolean contains(double x, double y);
/**
* Test if the point lie in the shape.
*
* @param p the high-precision point
* @return true if p lies inside the shape
* @throws NullPointerException if p is null
* @since 1.2
*/
boolean contains(Point2D p);
/**
* Test if a high-precision rectangle intersects the shape. This is true
* if any point in the rectangle is in the shape, with the caveat that the
* operation may include high probability estimates when the actual
* calculation is prohibitively expensive. The {@link Area} class can
* be used for more precise answers.
*
* @param x the x coordinate of the rectangle
* @param y the y coordinate of the rectangle
* @param w the width of the rectangle, undefined results if negative
* @param h the height of the rectangle, undefined results if negative
* @return true if the rectangle intersects this shape
* @see Area
* @since 1.2
*/
boolean intersects(double x, double y, double w, double h);
/**
* Test if a high-precision rectangle intersects the shape. This is true
* if any point in the rectangle is in the shape, with the caveat that the
* operation may include high probability estimates when the actual
* calculation is prohibitively expensive. The {@link Area} class can
* be used for more precise answers.
*
* @param r the rectangle
* @return true if the rectangle intersects this shape
* @throws NullPointerException if r is null
* @see #intersects(double, double, double, double)
* @since 1.2
*/
boolean intersects(Rectangle2D r);
/**
* Test if a high-precision rectangle lies completely in the shape. This is
* true if all points in the rectangle are in the shape, with the caveat
* that the operation may include high probability estimates when the actual
* calculation is prohibitively expensive. The {@link Area} class can
* be used for more precise answers.
*
* @param x the x coordinate of the rectangle
* @param y the y coordinate of the rectangle
* @param w the width of the rectangle, undefined results if negative
* @param h the height of the rectangle, undefined results if negative
* @return true if the rectangle is contained in this shape
* @see Area
* @since 1.2
*/
boolean contains(double x, double y, double w, double h);
/**
* Test if a high-precision rectangle lies completely in the shape. This is
* true if all points in the rectangle are in the shape, with the caveat
* that the operation may include high probability estimates when the actual
* calculation is prohibitively expensive. The {@link Area} class can
* be used for more precise answers.
*
* @param r the rectangle
* @return true if the rectangle is contained in this shape
* @throws NullPointerException if r is null
* @see #contains(double, double, double, double)
* @since 1.2
*/
boolean contains(Rectangle2D r);
/**
* Return an iterator along the shape boundary. If the optional transform
* is provided, the iterator is transformed accordingly. Each call returns
* a new object, independent from others in use. It is recommended, but
* not required, that the Shape isolate iterations from future changes to
* the boundary, and document this fact.
*
* @param transform an optional transform to apply to the iterator
* @return a new iterator over the boundary
* @since 1.2
*/
PathIterator getPathIterator(AffineTransform transform);
/**
* Return an iterator along the flattened version of the shape boundary.
* Only SEG_MOVETO, SEG_LINETO, and SEG_CLOSE points are returned in the
* iterator. The flatness paramter controls how far points are allowed to
* differ from the real curve; although a limit on accuracy may cause this
* parameter to be enlarged if needed.
*
* <p>If the optional transform is provided, the iterator is transformed
* accordingly. Each call returns a new object, independent from others in
* use. It is recommended, but not required, that the Shape isolate
* iterations from future changes to the boundary, and document this fact.
*
* @param transform an optional transform to apply to the iterator
* @param double the maximum distance for deviation from the real boundary
* @return a new iterator over the boundary
* @since 1.2
*/
PathIterator getPathIterator(AffineTransform transform, double flatness);
} // interface Shape
|
bedhubgrid/whitehall
|
app/workers/publishing_api_withdrawal_worker.rb
|
<filename>app/workers/publishing_api_withdrawal_worker.rb
class PublishingApiWithdrawalWorker < PublishingApiWorker
# `explanation` and `unpublished_at` come from the unpublishing object. Rather than
# performing a database query here to look up the `unpublishing` linked to the most
# recent edition, we pass it in directly because the `unpublishing` isn't always
# saved in the database yet when this worker runs.
def perform(content_id, explanation, locale, allow_draft = false, unpublished_at = nil)
check_if_locked_document(content_id: content_id)
Services.publishing_api.unpublish(
content_id,
type: "withdrawal",
locale: locale,
explanation: Whitehall::GovspeakRenderer.new.govspeak_to_html(explanation),
allow_draft: allow_draft,
unpublished_at: find_unpublished_at(content_id, unpublished_at),
)
rescue GdsApi::HTTPNotFound, GdsApi::HTTPUnprocessableEntity
# nothing to do here as we can't unpublish something that doesn't exist
nil
end
private
def find_unpublished_at(content_id, given_unpublished_at)
if given_unpublished_at
# We call this job both directly and via Sidekiq. When called by Sidekiq, the date gets turned
# into a string (because jobs must be JSON serialisable) and `Services.publishing_api.unpublish`
# rejects it.
Time.zone.parse(given_unpublished_at.to_s)
else
# Temporary code to handle old workers that are still in the queue without an `unpublished_at`
Edition
.joins(:document)
.where(documents: { content_id: content_id })
.where(state: "withdrawn")
.pick(:updated_at)
end
end
end
|
chokomancarr/chokoengine2
|
include/ce2/asset/enums/shader_queue.hpp
|
#pragma once
#include "chokoengine.hpp"
CE_BEGIN_NAMESPACE
enum class ShaderQueue {
Opaque,
Transparent,
Overlay
};
CE_END_NAMESPACE
|
ethansaxenian/RosettaDecode
|
lang/C++/hello-world-graphical-1.cpp
|
<filename>lang/C++/hello-world-graphical-1.cpp<gh_stars>1-10
#include <gtkmm.h>
int main(int argc, char *argv[])
{
Gtk::Main app(argc, argv);
Gtk::MessageDialog msg("Goodbye, World!");
msg.run();
}
|
inamukhan-eforte/plugins
|
kibana/wazuh/public/services/reporting.js
|
/*
* Wazuh app - Reporting service
* Copyright (C) 2015-2020 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Find more information about this on the LICENSE file.
*/
import $ from 'jquery';
import moment from 'moment';
import { WazuhConfig } from '../react-services/wazuh-config';
import { GenericRequest } from '../react-services/generic-request';
import { ErrorHandler } from '../react-services/error-handler';
export class ReportingService {
constructor(
$rootScope,
vis2png,
rawVisualizations,
visHandlers,
errorHandler
) {
this.$rootScope = $rootScope;
this.vis2png = vis2png;
this.rawVisualizations = rawVisualizations;
this.visHandlers = visHandlers;
this.genericReq = GenericRequest;
this.errorHandler = errorHandler;
this.wazuhConfig = new WazuhConfig();
}
removeTableVis(visList) {
const attributes = JSON.parse(visList.attributes.visState);
return attributes.type !== 'table';
}
removeAgentStatusVis(idArray) {
const monitoringEnabled = this.wazuhConfig.getConfig()[
'wazuh.monitoring.enabled'
];
if (!monitoringEnabled) {
const visArray = idArray.filter(vis => {
return vis !== 'Wazuh-App-Overview-General-Agents-status';
});
return visArray;
}
return idArray;
}
async startVis2Png(tab, isAgents = false, syscollectorFilters = null) {
try {
if (this.vis2png.isWorking()) {
ErrorHandler.handle('Report in progress', 'Reporting', { warning: true });
return;
}
this.$rootScope.reportBusy = true;
this.$rootScope.reportStatus = 'Generating report...0%';
this.$rootScope.$applyAsync();
this.vis2png.clear();
const rawVisualizations = this.rawVisualizations
.getList()
.filter(this.removeTableVis);
let idArray = [];
if (tab === 'general') {
idArray = this.removeAgentStatusVis(
rawVisualizations.map(item => item.id)
);
} else {
idArray = rawVisualizations.map(item => item.id);
}
for (const item of idArray) {
const tmpHTMLElement = $(`#${item}`);
this.vis2png.assignHTMLItem(item, tmpHTMLElement);
}
const appliedFilters = await this.visHandlers.getAppliedFilters(
syscollectorFilters
);
const array = await this.vis2png.checkArray(idArray);
const name = `wazuh-${
isAgents ? 'agents' : 'overview'
}-${tab}-${(Date.now() / 1000) | 0}.pdf`;
const browserTimezone = moment.tz.guess(true);
const data = {
array,
name,
title: isAgents ? `Agents ${tab}` : `Overview ${tab}`,
filters: appliedFilters.filters,
time: appliedFilters.time,
searchBar: appliedFilters.searchBar,
tables: appliedFilters.tables,
tab,
section: isAgents ? 'agents' : 'overview',
isAgents,
browserTimezone
};
await this.genericReq.request('POST', '/reports', data);
this.$rootScope.reportBusy = false;
this.$rootScope.reportStatus = false;
this.$rootScope.$applyAsync();
ErrorHandler.info(
'Success. Go to Wazuh > Management > Reporting',
'Reporting'
);
return;
} catch (error) {
this.$rootScope.reportBusy = false;
this.$rootScope.reportStatus = false;
ErrorHandler.handle(error.message || error);
}
}
async startConfigReport(obj, type, components) {
try {
this.$rootScope.reportBusy = true;
this.$rootScope.reportStatus = 'Generating PDF document...';
this.$rootScope.$applyAsync();
const docType =
type === 'agentConfig'
? `wazuh-agent-${obj.id}`
: `wazuh-group-${obj.name}`;
const name = `${docType}-configuration-${(Date.now() / 1000) | 0}.pdf`;
const browserTimezone = moment.tz.guess(true);
const data = {
array: [],
name,
filters: [
type === 'agentConfig' ? { agent: obj.id } : { group: obj.name }
],
time: '',
searchBar: '',
tables: [],
tab: type,
browserTimezone,
components
};
await this.genericReq.request('POST', '/reports', data);
this.$rootScope.reportBusy = false;
this.$rootScope.reportStatus = false;
this.$rootScope.$applyAsync();
ErrorHandler.info(
'Success. Go to Wazuh > Management > Reporting',
'Reporting'
);
return;
} catch (error) {
this.$rootScope.reportBusy = false;
this.$rootScope.reportStatus = false;
ErrorHandler.handle(error.message || error);
this.$rootScope.$applyAsync();
}
}
}
|
ministryofjustice/smart-answers
|
app/presenters/node_presenter.rb
|
<reponame>ministryofjustice/smart-answers
class NodePresenter
include ActionView::Helpers::NumberHelper
def initialize(i18n_prefix, node, state = nil)
@i18n_prefix = i18n_prefix
@node = node
@state = state || SmartAnswer::State.new(nil)
end
def translate!(subkey)
I18n.translate!("#{@i18n_prefix}.#{@node.name}.#{subkey}", state_for_interpolation)
rescue I18n::MissingTranslationData
nil
end
def translate_and_render(subkey)
markup = translate!(subkey)
markup && GovspeakPresenter.new(markup.strip).html
end
def state_for_interpolation(nested = false)
Hash[@state.to_hash.map { |k, v| [k, value_for_interpolation(v, nested)] }]
end
def value_for_interpolation(value, nested = false)
case value
when Date then I18n.localize(value, format: :long)
when ::SmartAnswer::Money then
number_to_currency(value, precision: ((value.to_f == value.to_f.round) ? 0 : 2))
when ::SmartAnswer::Salary then
number_to_currency(value.amount, precision: 0) + " per " + value.period
when ::SmartAnswer::PhraseList then
if nested == false
value.phrase_keys.map do |phrase_key|
I18n.translate!("#{@i18n_prefix}.phrases.#{phrase_key}", state_for_interpolation(true)) rescue phrase_key
end.join("\n\n")
else
false
end
else value
end
end
def to_response(input)
@node.to_response(input)
end
def title
translate!('title') || @node.name.to_s.humanize
end
def has_title?
!!title
end
def error
if @state.error.present?
translate!(@state.error.to_sym) || error_message || I18n.translate('flow.defaults.error_message')
end
end
def error_message
translate!('error_message')
end
def has_error_message?
!!error_message
end
def body
translate_and_render('body')
end
def has_body?
!!body
end
#Post-body on questions is only supported on Smartdown questions
def has_post_body?
false
end
def hint
translate!('hint')
end
def has_hint?
!!hint
end
def label
translate!('label')
end
def has_label?
!!label
end
def suffix_label
translate!('suffix_label')
end
def has_suffix_label?
!!suffix_label
end
def has_labels?
!!label or !!suffix_label
end
def next_steps
translate_and_render('next_steps')
end
def has_next_steps?
!!next_steps
end
def options
@node.options.map do |option|
OpenStruct.new(label: translate_option(option), value: option)
end
end
def translate_option(option)
translate!("options.#{option}") ||
begin
I18n.translate!("#{@i18n_prefix}.options.#{option}", @state.to_hash)
rescue I18n::MissingTranslationData
option
end
end
def method_missing(method, *args)
if @node.respond_to?(method)
@node.send(method, *args)
else
super
end
end
def respond_to_missing?(method, include_private)
@node.respond_to?(method, include_private)
end
end
|
colealbon/royale
|
src/lib/encryptCleartextMulti.js
|
'use strict';
import {getFromStorage} from './getFromStorage';
import {determineContentType} from './determineContentType';
import {encryptClearText} from './encryptClearText';
const PGPPUBKEY = 'PGPPubkey';
export function encryptCleartextMulti(content) {
// usage: encryptCleartextMulti(content)(openpgp)(localStorage).then(result => result)
return (!content) ?
Promise.reject('Error: missing content'):
(openpgp) => {
return (!openpgp) ?
Promise.reject('Error: missing openpgp'):
(localStorage) => {
return (!localStorage) ?
Promise.reject('Error: missing localStorage'):
new Promise((resolve, reject) => {
try {
let encryptQueue = [];
getFromStorage(localStorage)()
.then((storageArr) => {
storageArr
.map((storageItem) => {
try {
determineContentType(storageItem)(openpgp)
.then((contentType) => {
if (contentType === PGPPUBKEY) {
encryptQueue.push(encryptClearText(openpgp)(storageItem)(content))
}
})
} catch (error) {}
})
})
process.nextTick(() => {
Promise.all(encryptQueue)
.then((encryptedArr) => {
resolve(encryptedArr)
})
})
} catch (err) {
reject (new Error (err));
}
})
}
}
}
|
refdiff-data/gocd
|
server/src/com/thoughtworks/go/server/service/dd/DependencyFanInNode.java
|
<filename>server/src/com/thoughtworks/go/server/service/dd/DependencyFanInNode.java
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.server.service.dd;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;
import com.thoughtworks.go.domain.PipelineTimelineEntry;
import com.thoughtworks.go.domain.StageIdentifier;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.domain.materials.dependency.DependencyMaterialRevision;
import com.thoughtworks.go.server.domain.PipelineTimeline;
import com.thoughtworks.go.server.service.NoCompatibleUpstreamRevisionsException;
import com.thoughtworks.go.util.Pair;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import static com.thoughtworks.go.server.service.dd.DependencyFanInNode.RevisionAlteration.*;
public class DependencyFanInNode extends FanInNode {
private static final Logger LOGGER = Logger.getLogger(DependencyFanInNode.class);
private int totalInstanceCount = Integer.MAX_VALUE;
private int maxBackTrackLimit = Integer.MAX_VALUE;
private int currentCount;
StageIdentifier currentRevision;
private Map<StageIdentifier, Set<FaninScmMaterial>> stageIdentifierScmMaterial = new LinkedHashMap<StageIdentifier, Set<FaninScmMaterial>>();
public Set<FanInNode> children = new HashSet<FanInNode>();
public Set<? extends FaninScmMaterial> stageIdentifierScmMaterialForCurrentRevision() {
return stageIdentifierScmMaterial.get(currentRevision);
}
enum RevisionAlteration {
NOT_APPLICABLE, SAME_AS_CURRENT_REVISION, ALTERED_TO_CORRECT_REVISION, ALL_OPTIONS_EXHAUSTED, NEED_MORE_REVISIONS
}
DependencyFanInNode(MaterialConfig material) {
super(material);
}
public void populateRevisions(CaseInsensitiveString pipelineName, FanInGraphContext context) {
initialize(context);
fillNextRevisions(context);
if (initRevision(context) == ALL_OPTIONS_EXHAUSTED) {
throw NoCompatibleUpstreamRevisionsException.noValidRevisionsForUpstream(pipelineName, materialConfig);
}
}
private void setCurrentRevision() {
currentRevision = stageIdentifierScmMaterial.keySet().toArray(new StageIdentifier[0])[0];
}
private RevisionAlteration initRevision(FanInGraphContext context) {
if (!stageIdentifierScmMaterial.isEmpty()) {
setCurrentRevision();
} else {
return handleNeedMoreRevisions(context);
}
return ALTERED_TO_CORRECT_REVISION;
}
private RevisionAlteration handleNeedMoreRevisions(FanInGraphContext context) {
while (hasMoreInstances()) {
fillNextRevisions(context);
if (!stageIdentifierScmMaterial.isEmpty()) {
setCurrentRevision();
return ALTERED_TO_CORRECT_REVISION;
}
}
return ALL_OPTIONS_EXHAUSTED;
}
public RevisionAlteration setRevisionTo(StageIdFaninScmMaterialPair revisionToSet, FanInGraphContext context) {
RevisionAlteration revisionAlteration = alterRevision(revisionToSet, context);
while (revisionAlteration == NEED_MORE_REVISIONS) {
fillNextRevisions(context);
revisionAlteration = alterRevision(revisionToSet, context);
}
return revisionAlteration;
}
public void initialize(FanInGraphContext context) {
totalInstanceCount = context.pipelineTimeline.instanceCount(((DependencyMaterialConfig) materialConfig).getPipelineName());
maxBackTrackLimit = context.maxBackTrackLimit;
}
public PipelineTimelineEntry latestPipelineTimelineEntry(FanInGraphContext context) {
if (totalInstanceCount == 0) {
return null;
}
return context.pipelineTimeline.instanceFor(((DependencyMaterialConfig) materialConfig).getPipelineName(), totalInstanceCount - 1);
}
private void fillNextRevisions(FanInGraphContext context) {
if (!hasMoreInstances()) {
return;
}
int batchOffset = currentCount;
for (int i = 1; i <= context.revBatchCount; ++i) {
final Pair<StageIdentifier, List<FaninScmMaterial>> sIdScmPair = getRevisionNthFor(i + batchOffset, context);
if (!validateAllScmRevisionsAreSameWithinAFingerprint(sIdScmPair)) {
++currentCount;
if (!hasMoreInstances()) {
break;
}
continue;
}
validateIfRevisionMatchesTheCurrentConfigAndUpdateTheMaterialMap(context, sIdScmPair);
if (!hasMoreInstances()) {
break;
}
}
}
private Pair<StageIdentifier, List<FaninScmMaterial>> getRevisionNthFor(int n, FanInGraphContext context) {
List<FaninScmMaterial> scmMaterials = new ArrayList<FaninScmMaterial>();
PipelineTimeline pipelineTimeline = context.pipelineTimeline;
Queue<PipelineTimelineEntry.Revision> revisionQueue = new ConcurrentLinkedQueue<PipelineTimelineEntry.Revision>();
DependencyMaterialConfig dependencyMaterial = (DependencyMaterialConfig) materialConfig;
PipelineTimelineEntry entry = pipelineTimeline.instanceFor(dependencyMaterial.getPipelineName(), totalInstanceCount - n);
Set<CaseInsensitiveString> visitedNodes = new HashSet<CaseInsensitiveString>();
StageIdentifier dependentStageIdentifier = dependentStageIdentifier(context, entry, CaseInsensitiveString.str(dependencyMaterial.getStageName()));
if (!StageIdentifier.NULL.equals(dependentStageIdentifier)) {
addToRevisionQueue(entry, revisionQueue, scmMaterials, context, visitedNodes);
} else {
return null;
}
while (!revisionQueue.isEmpty()) {
PipelineTimelineEntry.Revision revision = revisionQueue.poll();
DependencyMaterialRevision dmr = DependencyMaterialRevision.create(revision.revision, null);
PipelineTimelineEntry pte = pipelineTimeline.getEntryFor(new CaseInsensitiveString(dmr.getPipelineName()), dmr.getPipelineCounter());
addToRevisionQueue(pte, revisionQueue, scmMaterials, context, visitedNodes);
}
return new Pair<StageIdentifier, List<FaninScmMaterial>>(dependentStageIdentifier, scmMaterials);
}
private boolean validateAllScmRevisionsAreSameWithinAFingerprint(Pair<StageIdentifier, List<FaninScmMaterial>> pIdScmPair) {
if (pIdScmPair == null) {
return false;
}
Map<FaninScmMaterial, PipelineTimelineEntry.Revision> versionsByMaterial = new HashMap<FaninScmMaterial, PipelineTimelineEntry.Revision>();
List<FaninScmMaterial> scmMaterialList = pIdScmPair.last();
for (final FaninScmMaterial scmMaterial : scmMaterialList) {
PipelineTimelineEntry.Revision revision = versionsByMaterial.get(scmMaterial);
if (revision == null) {
versionsByMaterial.put(scmMaterial, scmMaterial.revision);
} else if (!revision.equals(scmMaterial.revision)) {
return false;
}
}
return true;
}
private void validateIfRevisionMatchesTheCurrentConfigAndUpdateTheMaterialMap(FanInGraphContext context, Pair<StageIdentifier, List<FaninScmMaterial>> stageIdentifierScmPair) {
final Set<MaterialConfig> currentScmMaterials = context.pipelineScmDepMap.get(materialConfig);
final Set<FaninScmMaterial> scmMaterials = new HashSet<FaninScmMaterial>(stageIdentifierScmPair.last());
final Set<String> currentScmFingerprint = new HashSet<String>();
for (MaterialConfig currentScmMaterial : currentScmMaterials) {
currentScmFingerprint.add(currentScmMaterial.getFingerprint());
}
final Set<String> scmMaterialsFingerprint = new HashSet<String>();
for (FaninScmMaterial scmMaterial : scmMaterials) {
scmMaterialsFingerprint.add(scmMaterial.fingerprint);
}
final Collection commonMaterials = CollectionUtils.intersection(currentScmFingerprint, scmMaterialsFingerprint);
if (commonMaterials.size() == scmMaterials.size() && commonMaterials.size() == currentScmMaterials.size()) {
stageIdentifierScmMaterial.put(stageIdentifierScmPair.first(), scmMaterials);
++currentCount;
} else {
Collection disjunctionWithConfig = CollectionUtils.disjunction(currentScmFingerprint, commonMaterials);
Collection disjunctionWithInstance = CollectionUtils.disjunction(scmMaterialsFingerprint, commonMaterials);
LOGGER.warn(String.format("[Fan-in] - Incompatible materials for %s. Config: %s. Instance: %s.", stageIdentifierScmPair.first().getStageLocator(), disjunctionWithConfig, disjunctionWithInstance));
//This is it. We will not go beyond this revision in history
totalInstanceCount = currentCount;
}
}
private StageIdentifier dependentStageIdentifier(FanInGraphContext context, PipelineTimelineEntry entry, final String stageName) {
return context.pipelineDao.latestPassedStageIdentifier(entry.getId(), stageName);
}
private void addToRevisionQueue(PipelineTimelineEntry entry, Queue<PipelineTimelineEntry.Revision> revisionQueue, List<FaninScmMaterial> scmMaterials,
FanInGraphContext context, Set<CaseInsensitiveString> visitedNodes) {
for (Map.Entry<String, List<PipelineTimelineEntry.Revision>> revisionList : entry.revisions().entrySet()) {
String fingerprint = revisionList.getKey();
PipelineTimelineEntry.Revision revision = revisionList.getValue().get(0);
if (isScmMaterial(fingerprint, context)) {
scmMaterials.add(new FaninScmMaterial(fingerprint, revision));
continue;
}
if (isDependencyMaterial(fingerprint, context) && !visitedNodes.contains(new CaseInsensitiveString(revision.revision))) {
revisionQueue.add(revision);
visitedNodes.add(new CaseInsensitiveString(revision.revision));
}
}
}
private boolean isDependencyMaterial(String fingerprint, FanInGraphContext context) {
return context.fingerprintDepMaterialMap.containsKey(fingerprint);
}
private boolean isScmMaterial(String fingerprint, FanInGraphContext context) {
return context.fingerprintScmMaterialMap.containsKey(fingerprint);
}
private boolean hasMoreInstances() {
if (currentCount > maxBackTrackLimit) {
throw new MaxBackTrackLimitReachedException(materialConfig);
}
return currentCount < totalInstanceCount;
}
private RevisionAlteration alterRevision(StageIdFaninScmMaterialPair revisionToSet, FanInGraphContext context) {
if (currentRevision == revisionToSet.stageIdentifier) {
return RevisionAlteration.SAME_AS_CURRENT_REVISION;
}
if (!stageIdentifierScmMaterial.get(currentRevision).contains(revisionToSet.faninScmMaterial)) {
return RevisionAlteration.NOT_APPLICABLE;
}
List<StageIdentifier> stageIdentifiers = new ArrayList<StageIdentifier>(stageIdentifierScmMaterial.keySet());
int currentRevIndex = stageIdentifiers.indexOf(currentRevision);
for (int i = currentRevIndex; i < stageIdentifiers.size(); i++) {
final StageIdentifier key = stageIdentifiers.get(i);
final List<FaninScmMaterial> materials = new ArrayList<FaninScmMaterial>(stageIdentifierScmMaterial.get(key));
final int index = materials.indexOf(revisionToSet.faninScmMaterial);
if (index == -1) {
return ALL_OPTIONS_EXHAUSTED;
}
final FaninScmMaterial faninScmMaterial = materials.get(index);
if (faninScmMaterial.revision.equals(revisionToSet.faninScmMaterial.revision)) {
currentRevision = key;
return ALTERED_TO_CORRECT_REVISION;
}
if (faninScmMaterial.revision.lessThan(revisionToSet.faninScmMaterial.revision)) {
currentRevision = key;
return ALTERED_TO_CORRECT_REVISION;
}
}
if (!hasMoreInstances()) {
return ALL_OPTIONS_EXHAUSTED;
}
return NEED_MORE_REVISIONS;
}
public List<StageIdFaninScmMaterialPair> getCurrentFaninScmMaterials() {
List<StageIdFaninScmMaterialPair> stageIdScmPairs = new ArrayList<StageIdFaninScmMaterialPair>();
Set<FaninScmMaterial> faninScmMaterials = stageIdentifierScmMaterial.get(currentRevision);
for (FaninScmMaterial faninScmMaterial : faninScmMaterials) {
StageIdFaninScmMaterialPair pIdScmPair = new StageIdFaninScmMaterialPair(currentRevision, faninScmMaterial);
stageIdScmPairs.add(pIdScmPair);
}
return stageIdScmPairs;
}
}
|
shaojiankui/iOS10-Runtime-Headers
|
protocols/NSKeyedArchiverDelegate.h
|
<gh_stars>10-100
/* Generated by RuntimeBrowser.
*/
@protocol NSKeyedArchiverDelegate <NSObject>
@optional
- (void)archiver:(NSKeyedArchiver *)arg1 didEncodeObject:(id)arg2;
- (id)archiver:(NSKeyedArchiver *)arg1 willEncodeObject:(id)arg2;
- (void)archiver:(NSKeyedArchiver *)arg1 willReplaceObject:(id)arg2 withObject:(id)arg3;
- (void)archiverDidFinish:(NSKeyedArchiver *)arg1;
- (void)archiverWillFinish:(NSKeyedArchiver *)arg1;
@end
|
mike-jumper/guacamole-website
|
doc/1.3.0/libguac/search/files_2.js
|
var searchData=
[
['error_2dtypes_2eh',['error-types.h',['../error-types_8h.html',1,'']]],
['error_2eh',['error.h',['../error_8h.html',1,'']]]
];
|
BBN-E/serif
|
src/Arabic/edt/discmodel/ar_DTCorefFeatureTypes.cpp
|
<gh_stars>1-10
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h"
// This is where the _new instances of the feature types live.
#include "Arabic/edt/discmodel/ar_DTCorefFeatureTypes.h"
#include "Arabic/edt/discmodel/featuretypes/AdjNationality.h"
void ArabicDTCorefFeatureTypes::ensureFeatureTypesInstantiated() {
if (DTCorefFeatureTypes::_instantiated)
return;
// get the language independent featureTypes
DTCorefFeatureTypes::ensureBaseFeatureTypesInstantiated();
// here add the additional arabic only features
_new ArabicAdjNationality();
}
|
Hearthstonepp/Hearthstonepp
|
Includes/Rosetta/PlayMode/Tasks/SimpleTasks/ChangeEntityTask.hpp
|
// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 <NAME>, <NAME>, <NAME>
#ifndef ROSETTASTONE_PLAYMODE_CHANGE_ENTITY_TASK_HPP
#define ROSETTASTONE_PLAYMODE_CHANGE_ENTITY_TASK_HPP
#include <Rosetta/PlayMode/Tasks/ITask.hpp>
namespace RosettaStone::PlayMode::SimpleTasks
{
//!
//! \brief ChangeEntityTask class.
//!
//! This class represents the task for transforming the given type of entities
//! into random cards satisfying the criteria.
//!
class ChangeEntityTask : public ITask
{
public:
//! Constructs task with given various arguments.
//! \param entityType The entity type to change.
//! \param protoType The another entity type to change.
//! \param cardType The type of card to filter.
//! \param cardClass The class of card to filter.
//! \param race The race of card to filter.
//! \param rarity The rarity of card to filter.
//! \param cardID The card ID.
//! \param removeEnchantments The flag that removes any applied enchantments
//! during this transformation.
//! \param useRandomCard The flag that indicates it uses random card.
explicit ChangeEntityTask(
EntityType entityType, EntityType protoType, CardType cardType,
CardClass cardClass = CardClass::INVALID, Race race = Race::INVALID,
Rarity rarity = Rarity::INVALID, const std::string& cardID = "",
bool removeEnchantments = false, bool useRandomCard = false);
//! Constructs task with given various arguments.
//! \param entityType The entity type to change.
//! \param cardType The type of card to filter.
//! \param cardClass The class of card to filter.
//! \param race The race of card to filter.
//! \param rarity The rarity of card to filter.
//! \param removeEnchantments The flag that removes any applied enchantments
//! during this transformation.
explicit ChangeEntityTask(EntityType entityType, CardType cardType,
CardClass cardClass = CardClass::INVALID,
Race race = Race::INVALID,
Rarity rarity = Rarity::INVALID,
bool removeEnchantments = false);
//! Constructs task with given \p cardID and \p entityType.
//! \param cardID The card ID.
//! \param entityType The entity type to change.
explicit ChangeEntityTask(const std::string& cardID,
EntityType entityType = EntityType::SOURCE);
//! Constructs task with given \p sourceType and \p protoType.
//! \param sourceType The entity type to change.
//! \param protoType The another entity type to change.
explicit ChangeEntityTask(EntityType sourceType, EntityType protoType);
private:
//! Processes task logic internally and returns meta data.
//! \param player The player to run task.
//! \return The result of task processing.
TaskStatus Impl(Player* player) override;
//! Internal method of Clone().
//! \return The cloned task.
std::unique_ptr<ITask> CloneImpl() override;
EntityType m_protoType = EntityType::INVALID;
CardType m_cardType = CardType::INVALID;
CardClass m_cardClass = CardClass::INVALID;
Race m_race = Race::INVALID;
Rarity m_rarity = Rarity::INVALID;
Card* m_card = nullptr;
bool m_removeEnchantments = false;
bool m_useRandomCard = false;
};
} // namespace RosettaStone::PlayMode::SimpleTasks
#endif // ROSETTASTONE_PLAYMODE_CHANGE_ENTITY_TASK_HPP
|
michiels/intercity-next
|
app/models/ssh_execution.rb
|
class SshExecution
class_attribute :executioner
self.executioner = Net::SSH
def initialize(server)
@server = server
end
def execute(command:)
execute_with_block do |ssh|
return ssh.exec!(command)
end
end
def scp(from:, to:, direction: :download)
ssh_key_maintainer.create_key_for_connection
case direction
when :upload
# rubocop:disable Metrics/LineLength
cmd = "scp -oStrictHostKeyChecking=no -i #{ssh_key_maintainer.key} #{from} #{@server.username}@#{@server.ip}:#{to}"
else
cmd = "scp -oStrictHostKeyChecking=no -i #{ssh_key_maintainer.key} #{@server.username}@#{@server.ip}:#{from} #{to}"
# rubocop:enable Metrics/LineLength
end
system(cmd)
ensure
ssh_key_maintainer.delete_ssh_key_for_connection
end
def execute_with_block
ssh_key_maintainer.create_key_for_connection
executioner.start(@server.ip, @server.username,
port: 22,
keys: [ssh_key_maintainer.key], paranoid: false,
timeout: ssh_timeout,
number_of_password_prompts: 0) do |ssh|
yield ssh
end
ensure
ssh_key_maintainer.delete_ssh_key_for_connection
end
private
def ssh_key_maintainer
@ssh_key_maintainer ||= SshKeyMaintainer.new(@server)
end
def ssh_timeout
5
end
end
|
thinn5/5WORK2019
|
Proofs of Concept/srv-electron/src/controllers/userController.js
|
<reponame>thinn5/5WORK2019
'use strict';
var crypto = require('crypto');
const CONTROLLER = {};
const PATH = require('path');
const POOL = require(PATH.join(__dirname, '..', 'config', 'database'));
const TABLE = 'users';
const FIELD_ID = 'id';
const LIST = 'SELECT * FROM ' + TABLE;
const INSERT = 'INSERT INTO ' + TABLE + ' SET ?';
const LIST_BY_ID = 'SELECT * FROM ' + TABLE + ' WHERE ' + FIELD_ID + ' = ?';
const UPDATE = 'UPDATE ' + TABLE + ' SET ? WHERE ' + FIELD_ID + ' = ?';
const DELETE = 'DELETE FROM ' + TABLE + ' WHERE ' + FIELD_ID + ' = ?';
CONTROLLER.list = (req, res) => {
req.getConnection((err, conn) => {
conn.query(LIST, (err, results) => {
if (err) {
next(err);
}
res.render(PATH.join(__dirname, '..', 'views', 'admin', 'users', 'users'), {
data: results
});
});
});
};
CONTROLLER.add = (req, res) => {
const data = req.body;
var salt = genRandomString(16); /** Gives us salt of length 16 */
var hashedPass = sha512(data.password, salt);
data.password = <PASSWORD>;
req.getConnection((err, conn) => {
conn.query(INSERT, [data], (err, results) => {
if (err) {
next(err);
}
res.redirect('/');
});
});
};
CONTROLLER.edit = (req, res) => {
const id = req.params.id;
req.getConnection((err, conn) => {
conn.query(LIST_BY_ID, [id], (err, result) => {
if (err) {
next(err);
}
res.render('user_edit', {
data: result[0]
});
});
});
};
CONTROLLER.update = (req, res) => {
const id = req.params.id;
const newUser = req.body;
var salt = genRandomString(16); /** Gives us salt of length 16 */
var hashedPass = <PASSWORD>12(newUser.password, salt);
newUser.password = <PASSWORD>;
console.log(newUser.password);
req.getConnection((err, conn) => {
conn.query(UPDATE, [newUser, id], (err, results) => {
console.log(req);
if (err) {
next(err);
}
res.redirect('/');
});
});
};
CONTROLLER.delete = (req, res) => {
const id = req.params.id;
req.getConnection((err, conn) => {
conn.query(DELETE, [id], (err, results) => {
if (err) {
next(err);
}
res.redirect('/');
})
})
};
var genRandomString = function (length) {
return crypto.randomBytes(Math.ceil(length / 2))
.toString('hex') /** convert to hexadecimal format */
.slice(0, length); /** return required number of characters */
};
var sha512 = function (password, salt) {
var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
hash.update(password);
var value = hash.digest('hex');
return {
salt: salt,
passwordHash: value
};
};
module.exports = CONTROLLER;
|
nitehawk42/jadira
|
scanner/src/main/java/org/jadira/scanner/core/api/Allocator.java
|
package org.jadira.scanner.core.api;
public interface Allocator<T,E> {
T allocate(E e);
}
|
RolandWarburton/simple-sso
|
sso-consumer/app/app/app.js
|
const express = require("express");
const app = express();
const engine = require("ejs-mate");
const errorHandler = require("./errorHandler");
const debug = require("debug")("app:server");
const path = require("path");
const isAuthenticated = require("../middleware/isAuthenticated");
const cookieParser = require("cookie-parser");
const checkReceiveToken = require("../middleware/checkReceivingToken");
const session = require("express-session");
// ##──── middleware ────────────────────────────────────────────────────────────────────────
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 100000,
},
})
);
app.use(express.json());
app.use(cookieParser());
app.use(checkReceiveToken);
// ##──── ejs rendering ─────────────────────────────────────────────────────────────────────
app.engine("ejs", engine);
app.set("views", path.resolve(__dirname, "../views"));
app.set("view engine", "ejs");
// ##──── root route ────────────────────────────────────────────────────────────────────────
app.get("/", [isAuthenticated], (req, res, next) => {
debug("root");
// print information about the session
// debug(req.session.user);
// debug(`This session is: ${req.session.id}`);
res.render("helloWorld", {
test: "hello world",
});
});
app.get("/logout", (req, res, next) => {
req.session.destroy();
res.status(200).send("logged out");
});
// ##──── error handling ────────────────────────────────────────────────────────────────────
// catch 404 and forward to error handler
// app.use(errorHandler);
module.exports = app;
|
FogChainInc/RadJavPrivate
|
library/src/RadJav/cpp/android/RadJavCPPMUINavigatorFrame.cpp
|
<reponame>FogChainInc/RadJavPrivate<gh_stars>0
/*
MIT-LICENSE
Copyright (c) 2018 Higher Edge Software, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "cpp/android/RadJavCPPMUINavigatorFrame.h"
#include "cpp/android/RadJavCPPMUIViewFrame.h"
#include "android/RadJavAndroid.h"
namespace RadJAV
{
namespace CPP
{
namespace MUI
{
using namespace Android;
jmethodID NavigatorFrame::nativeConstructor = nullptr;
jmethodID NavigatorFrame::nativeAddView = nullptr;
jmethodID NavigatorFrame::nativeRemoveView = nullptr;
jmethodID NavigatorFrame::nativeSetLayoutTransition = nullptr;
jclass NavigatorFrame::nativeLayoutTransitionClass = nullptr;
jclass NavigatorFrame::nativeLayoutClass = nullptr;
NavigatorFrame::NavigatorFrame(ViewFrame *view)
{
JNIEnv* env = Jni::getJniEnv();
if (!nativeLayoutClass)
{
Jni& jni = Jni::instance();
nativeLayoutTransitionClass = jni.findClass("android/animation/LayoutTransition");
nativeLayoutClass = jni.findClass("com/fogchain/radjavvm/RadJavLayout");
nativeConstructor = env->GetMethodID(nativeLayoutTransitionClass, "<init>", "()V");
nativeAddView = env->GetMethodID(nativeLayoutClass, "addView", "(Landroid/view/View;)V");
nativeRemoveView = env->GetMethodID(nativeLayoutClass, "removeView", "(Landroid/view/View;)V");
nativeSetLayoutTransition = env->GetMethodID(nativeLayoutClass, "setLayoutTransition", "(Landroid/animation/LayoutTransition;)V");
}
if (view)
{
rootView = view->getNativeWidget();
}
else
{
rootView = RadJavAndroid::instance()->getJavaViewGroup();
}
auto layoutTransition = wrap_local(env, env->NewObject(nativeLayoutTransitionClass, nativeConstructor));
env->CallVoidMethod(rootView, nativeSetLayoutTransition, layoutTransition.get());
}
NavigatorFrame::~NavigatorFrame()
{
//Remove LayoutTransition from rootView
//TODO: need to add implementation
}
void NavigatorFrame::push(ViewFrame* view, bool replace)
{
//Do nothing if there is no view provided
if (!view || !rootView)
return;
ViewFrame* viewToRemove = nullptr;
if (!viewStack.empty())
{
viewToRemove = viewStack.top();
if (replace)
{
viewStack.pop();
}
}
viewStack.push(view);
JNIEnv* env = Jni::getJniEnv();
env->CallVoidMethod(rootView, nativeAddView, view->getNativeWidget());
if (viewToRemove)
env->CallVoidMethod(rootView, nativeRemoveView, viewToRemove->getNativeWidget());
}
void NavigatorFrame::pop(ViewFrame* view)
{
if (!rootView)
return;
//Do nothing if stack is empty or top most view is the same object(view)
if (viewStack.empty() || viewStack.top() == view)
return;
//We always remove top most view
ViewFrame* viewToRemove = nullptr;
viewToRemove = viewStack.top();
//And replace it with new one
ViewFrame* viewToAdd = nullptr;
//Inspect stack
while (!viewStack.empty() &&
viewStack.top() != view)
{
viewToAdd = viewStack.top();
viewStack.pop();
}
//When view was not found
if (viewStack.empty())
{
//We add view provided into empty view stack
if (view)
viewToAdd = view;
//Or we add an old view from the stack back to it
viewStack.push(viewToAdd);
}
else
{
//View to activate was found in the stack
viewToAdd = viewStack.top();
}
JNIEnv* env = Jni::getJniEnv();
//Activate view
env->CallVoidMethod(rootView, nativeAddView, viewToAdd->getNativeWidget());
//Deactivate previous view
if (viewToRemove)
env->CallVoidMethod(rootView, nativeRemoveView, viewToRemove->getNativeWidget());
}
void NavigatorFrame::pop()
{
if (viewStack.size() <= 1)
return;
ViewFrame* viewToRemove = viewStack.top();
viewStack.pop();
ViewFrame* viewToAdd = viewStack.top();
JNIEnv* env = Jni::getJniEnv();
env->CallVoidMethod(rootView, nativeAddView, viewToAdd->getNativeWidget());
env->CallVoidMethod(rootView, nativeRemoveView, viewToRemove->getNativeWidget());
}
}
}
}
|
niquola/health_seven
|
lib/health_seven/2.4/datatypes/dr.rb
|
module HealthSeven::V2_4
class Dr < ::HealthSeven::DataType
# range start date/time
attribute :range_start_date_time, Ts, position: "DR.1"
# range end date/time
attribute :range_end_date_time, Ts, position: "DR.2"
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.