repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
zlsun/ProjectEuler
|
092.py
|
#-*- encoding: utf-8 -*-
"""
Square digit chains
A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.
For example,
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?
"""
from utils import *
#
|
Javitronxo/AdventOfCode
|
2015/day_11.py
|
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
def is_valid_password(password: str) -> bool:
# Passwords may not contain the letters i, o, or l
invalid_chars = ['i', 'o', 'l']
if True in [char in password for char in invalid_chars]:
return False
# Passwords must contain at least two different, non-overlapping pairs of letters
pairs_of_letters = 0
positions_pairs_of_letters = list()
for i in range(len(password) - 1):
if password[i] == password[i + 1] and \
i not in positions_pairs_of_letters and (i + 1) not in positions_pairs_of_letters:
pairs_of_letters += 1
positions_pairs_of_letters.extend([i, i + 1])
if pairs_of_letters < 2:
return False
# Passwords must include one increasing straight of at least three letters
for i in range(len(password) - 2):
if ALPHABET.index(password[i]) == (ALPHABET.index(password[i + 1]) - 1) == (
ALPHABET.index(password[i + 2]) - 2):
return True
return False
def increment_password(password: str) -> str:
reversed_password = password[::-1]
new_password = ''
for i in range(len(reversed_password)):
try:
new_char = ALPHABET[ALPHABET.index(reversed_password[i]) + 1]
new_password += new_char + reversed_password[i + 1:]
break
except IndexError:
new_char = 'a'
new_password += new_char
return new_password[::-1]
def main():
password = open('day_11_input.txt').read()
for _ in range(2):
password = increment_password(password)
while not is_valid_password(password):
password = <PASSWORD>password(password)
print("Next Santa's password is %s" % password)
if __name__ == '__main__':
main()
|
delock/Deep-learning-math-kernel-research
|
src/eld_conv.cpp
|
#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include "euler.hpp"
#include "el_def.hpp"
#include "el_isa.hpp"
#include "el_utils.hpp"
#include "elx_conv.hpp"
#include "elx_conv_wino.hpp"
#include "elx_conv_wino_lp.hpp"
#include "elx_conv_direct_1x1.hpp"
#include "elx_conv_direct_1x1_lp.hpp"
#include "elx_conv_direct.hpp"
#include "elx_conv_direct_vmg.hpp"
#include "elx_conv_direct_lp.hpp"
#include "elx_conv_direct_depthwise_lp.hpp"
#include "elx_deconv_direct.hpp"
namespace euler {
eld_conv_t::eld_conv_t()
{
dims.g = 1;
pads = { 1, 1, 1, 1 };
strides = { 1, 1 };
dilations = { 1, 1 };
sizes = { 0, 0, 0, 0 };
algorithm = CONV_DIRECT;
tile_size = 0;
with_relu = false;
with_bias = false;
with_ip_sum = false;
with_op_sum = false;
with_argmax = false;
f16c_opt = false;
xc = nullptr;
nthreads = 0;
execution_mode = 0;
blocking = { 0, 0 };
flatting = { 0, 0 };
partition = { 1, 1 };
streaming_hint = { 0, 0 };
format_as_blocked = { false, false, false };
input_quant = {EL_NO_CALI, EL_NO_CALI};
output_quant = {EL_NO_CALI, EL_NO_CALI};
sampling_kind = FINE;
eager_mode = true;
stream_sync = false;
}
eld_conv_t::~eld_conv_t()
{
if (xc != nullptr) {
delete xc;
}
}
int eld_conv_t::setup(bool fully_setup)
{
// Dimensions
const int V = cpu_vector_length() / 4;
const int g = dims.g;
const int ic = dims.ic / g;
const int oc = dims.oc / g;
bool depthwise = (g == dims.ic && g == dims.oc);
if (V != 16) {
// TODO: V == 8
el_error("CPU vector not support");
}
if ((dims.ic % g != 0) || (dims.oc % g != 0)) {
el_error("dims: groups: ic|oc != g * x");
}
// Select format
if (formats.input == format_undef) {
formats.input = (g == 1 && ic < V) ? nchw : V == 16 ? nChw16c : nChw8c;
}
if (formats.weights == format_undef) {
formats.weights = g == 1 ? hwio : ghwio;
}
if (formats.output == format_undef) {
formats.output = V == 16 ? nChw16c : nChw8c;
}
using dt = decltype(data_type);
uint32_t user_type = data_type.flat;
uint32_t user_type_f32 = dt{ { { f32, f32, f32, f32 } } }.flat;
uint32_t user_type_f16o = dt{ { { f32, f32, f16, f32 } } }.flat;
uint32_t user_type_u8f32f32f32 = dt{ { { u8, f32, f32, f32 } } }.flat;
uint32_t user_type_u8f32u8f32 = dt{ { { u8, f32, u8, f32 } } }.flat;
uint32_t user_type_u8f32s8f32 = dt{ { { u8, f32, s8, f32 } } }.flat;
#ifdef ENABLE_USER_FP16
uint32_t user_type_f16 = dt{ { { f16, f16, f16, f16 } } }.flat;
#endif
sizes.input = dims.n * dims.ih * dims.iw *
(estl::any_of(formats.input, nChw16c, nChw8c) ? ALIGNUP(dims.ic, V)
: dims.ic);
sizes.weights = dims.g * dims.kh * dims.kw *
(estl::any_of(formats.weights, OIhw16i16o, OIhw8i8o, gOIhw16i16o, gOIhw8i8o)
? ALIGNUP(ic, V) * ALIGNUP(oc, V)
: oc * ic) + 4 * V; // for weights pipeline
sizes.output = dims.n * dims.oh * dims.ow *
(estl::any_of(formats.output, nChw16c, nChw8c) ? ALIGNUP(dims.oc, V)
: dims.oc);
sizes.bias = estl::any_of(formats.output, nChw16c, nChw8c)
? ALIGNUP(dims.oc, V)
: dims.oc;
auto get_elem_size = [](uint8_t dtype) -> size_t {
switch (dtype) {
case f32: return sizeof(float);
case f16: return sizeof(short);
case u8:
case s8: return sizeof(uint8_t);
default: return 0;
}
};
byte_sizes.input = get_elem_size(data_type.input) * sizes.input;
byte_sizes.weights = get_elem_size(data_type.weights) * sizes.weights;
byte_sizes.output = get_elem_size(data_type.output) * sizes.output;
byte_sizes.bias = get_elem_size(data_type.bias) * sizes.bias;
// Validate padding
int oh, ow;
if (algorithm == DECONV_DIRECT) {
oh = (dims.ih - 1) * strides.h + dims.kh - pads.t - pads.b;
ow = (dims.iw - 1) * strides.w + dims.kw - pads.l - pads.r;
} else { // CONV
oh = (dims.ih + pads.t + pads.b - dims.kh) / strides.h + 1;
ow = (dims.iw + pads.l + pads.r - dims.kw) / strides.w + 1;
}
if (oh != dims.oh || ow != dims.ow) {
el_error("Padding parameter error");
return ELX_GENERAL_ERROR;
}
xc = nullptr;
if (prop_kind != forward_inference) {
el_error("Propagation kind error");
return ELD_GENERAL_ERROR;
}
if (algorithm == CONV_AUTO) {
if (dims.kh == 1 && dims.kw == 1) {
algorithm = CONV_DIRECT_1X1;
} else if (ic >= V && dims.kh == 3 && dims.kw == 3
&& dilations.h == 1 && dilations.w == 1 && strides.h == 1
&& strides.w == 1 && pads.l == 1 && pads.r == 1 && pads.t == 1
&& pads.b == 1) {
algorithm = CONV_WINOGRAD;
} else {
algorithm = CONV_DIRECT;
}
}
if (!fully_setup) {
return ELD_OK;
}
// Direct
if (algorithm == CONV_DIRECT) {
if (user_type == user_type_f32) {
if (f16c_opt)
xc = new elx_conv_direct_t<conv::FP32, conv_impl::FP32_F16w, 16, ISA_SKX_AVX512>(*this);
else
xc = new elx_conv_direct_t<conv::FP32, conv_impl::FP32, 16, ISA_SKX_AVX512>(*this);
} else if (user_type == user_type_u8f32u8f32) {
if (depthwise)
xc = new elx_conv_direct_depthwise_lp_t<conv::U8F32U8F32, conv_impl::INT8_F32, 16, ISA_SKX_AVX512>(*this);
else
xc = new elx_conv_direct_lp_t<conv::U8F32U8F32, conv_impl::INT8_F32, 16, ISA_SKX_AVX512>(*this);
} else if (user_type == user_type_u8f32s8f32) {
if (depthwise)
xc = new elx_conv_direct_depthwise_lp_t<conv::U8F32S8F32, conv_impl::INT8_F32, 16, ISA_SKX_AVX512>(*this);
else
xc = new elx_conv_direct_lp_t<conv::U8F32S8F32, conv_impl::INT8_F32, 16, ISA_SKX_AVX512>(*this);
} else if (user_type == user_type_u8f32f32f32) {
xc = new elx_conv_direct_lp_t<conv::U8F32F32F32, conv_impl::INT8_F32, 16, ISA_SKX_AVX512>(*this);
#ifdef ENABLE_USER_FP16
} else if (user_type == user_type_f16o) {
xc = new elx_conv_direct_t<conv::FP16O, conv_impl::FP32_F16o, 16, ISA_SKX_AVX512>(*this);
#endif
} else
el_error("TODO: FP16 UserTypes for DIRECT.");
} else if (algorithm == CONV_DIRECT_VMG) {
if (user_type == user_type_f32) {
if (f16c_opt)
xc = new elx_conv_direct_vmg_t<conv::FP32, conv_impl::FP32_F16w, 16, ISA_SKX_AVX512>(*this);
else
xc = new elx_conv_direct_vmg_t<conv::FP32, conv_impl::FP32, 16, ISA_SKX_AVX512>(*this);
#ifdef ENABLE_USER_FP16
} else if (user_type == user_type_f16o)
xc = new elx_conv_direct_vmg_t<conv::FP16O, conv_impl::FP32_F16o, 16, ISA_SKX_AVX512>(*this);
#endif
} else
el_error("TODO: FP16 UserTypes for DIRECT_VMG.");
} else if (algorithm == CONV_DIRECT_1X1) {
if (dims.kh != 1 || dims.kw != 1) {
el_error("Algorithm CONV_DIRECT_1X1 not supported for this shape.");
return ELD_GENERAL_ERROR;
}
if (user_type == user_type_f32) {
if (f16c_opt)
xc = new elx_conv_direct_1x1_t<conv::FP32, conv_impl::FP32_F16w, 16, ISA_SKX_AVX512>(*this);
else
xc = new elx_conv_direct_1x1_t<conv::FP32, conv_impl::FP32, 16, ISA_SKX_AVX512>(*this);
} else if (user_type == user_type_u8f32u8f32) {
xc = new elx_conv_direct_1x1_lp_t<conv::U8F32U8F32, conv_impl::INT8_F32, 16, ISA_SKX_AVX512>(*this);
} else if (user_type == user_type_u8f32s8f32) {
xc = new elx_conv_direct_1x1_lp_t<conv::U8F32S8F32, conv_impl::INT8_F32, 16, ISA_SKX_AVX512>(*this);
} else
el_error("TODO: FP16 UserTypes for DIRECT 1x1.");
} else if (algorithm == CONV_WINOGRAD) {
// Winograd
if (dilations.h > 1 || dilations.w > 1 ||
strides.h != 1 || strides.w != 1 ||
dims.kh != 3 || dims.kw != 3) {
el_error("Algorithm CONV_WINOGRAD: data shape not supported");
return ELD_UNIMPLEMENTED;
}
if ((user_type == user_type_u8f32u8f32 ||
user_type == user_type_u8f32s8f32 ||
user_type == user_type_u8f32f32f32) &&
input_quant.z != 0) {
el_error("Support abs-max scaling for input only in Conv Winograd ...");
}
if (tile_size == 0) {
int t = dims.n * ((dims.oh + 3) / 4) * ((dims.ow + 3) / 4);
float mac_per_read = (t * ALIGNUP(oc, 16)) * 1.0f / (t + ALIGNUP(oc, V));
#define MAC_PER_READ_A6_LIMIT (25.0f)
tile_size = mac_per_read > MAC_PER_READ_A6_LIMIT ? 6 : 4;
}
#define F_5_3_OFF_CASE(UT, TT, type) \
case 7: break
#define F_5_3_ON_CASE(UT, TT, type) \
case 7: \
xc = new elx_conv_##type##_t<UT, TT, 7, 3, 16, \
ISA_SKX_AVX512>(*this); \
break
#define create_conv_wino(UT, TT, prefix, type) \
switch (tile_size) { \
case 4: \
xc = new elx_conv_##type##_t<UT, TT, 4, 3, 16, \
ISA_SKX_AVX512>(*this); \
break; \
case 5: \
xc = new elx_conv_##type##_t<UT, TT, 5, 3, 16, \
ISA_SKX_AVX512>(*this); \
break; \
case 6: \
xc = new elx_conv_##type##_t<UT, TT, 6, 3, 16, \
ISA_SKX_AVX512>(*this); \
break; \
prefix##_CASE(UT, TT, type); \
default: \
el_error("Unimplemented tile size"); \
break; \
}
if (!disable_autoparam) f16c_opt = true;
// User int8
if (user_type == user_type_u8f32u8f32) {
create_conv_wino(
conv::U8F32U8F32, conv_impl::INT8_F32, F_5_3_OFF, wino_lp);
} else if (user_type == user_type_u8f32s8f32) {
create_conv_wino(
conv::U8F32S8F32, conv_impl::INT8_F32, F_5_3_OFF, wino_lp);
} else if (user_type == user_type_u8f32f32f32) {
create_conv_wino(
conv::U8F32F32F32, conv_impl::INT8_F32, F_5_3_OFF, wino_lp);
} else {
// User fp32
if ((execution_mode & 0xF00) != 0x100) {
// Impl. fp32
if (f16c_opt && user_type == user_type_f32) {
create_conv_wino(conv::FP32, conv_impl::FP32_F16iwo, F_5_3_ON, wino);
#ifdef ENABLE_USER_FP16
} else if (user_type == user_type_f16) {
create_conv_wino(conv::FP16, conv_impl::FP32_F16wob, F_5_3_ON, wino);
#endif
} else if (user_type != user_type_f16o) {
create_conv_wino(conv::FP32, conv_impl::FP32, F_5_3_ON, wino);
}
} else {
// Impl. int8
if (f16c_opt && user_type == user_type_f32) {
create_conv_wino(
conv::FP32, conv_impl::INT8_F16o, F_5_3_OFF, wino_lp);
#ifdef ENABLE_USER_FP16
} else if (user_type == user_type_f16) {
create_conv_wino(
conv::FP16, conv_impl::INT8_F16b, F_5_3_OFF, wino_lp);
#endif
} else if (user_type != user_type_f16o) {
create_conv_wino(conv::FP32, conv_impl::INT8_F32, F_5_3_ON, wino_lp);
}
}
}
} else if (algorithm == DECONV_DIRECT) {
if (user_type == user_type_f32) {
xc = new elx_deconv_direct_t<conv::FP32, conv_impl::FP32, 16, ISA_SKX_AVX512>(*this);
} else
el_error("TODO: FP16 UserTypes for DECONV_DIRECT.");
}
return ELD_OK;
}
} // namespace euler
|
AY2122S1-CS2103T-THUNDERCATS/tp
|
src/test/java/seedu/address/logic/commands/CommandResultTest.java
|
package seedu.address.logic.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.testutil.TypicalGroups.CS2103T_GROUP_BUILDER;
import org.junit.jupiter.api.Test;
import seedu.address.logic.state.ApplicationState;
import seedu.address.logic.state.GroupInformationState;
import seedu.address.logic.state.HomeState;
import seedu.address.model.group.Group;
public class CommandResultTest {
@Test
public void build_onlyFeedbackSpecified_defaultValuesReturned() {
// Equivalence Partition {isGoingToShowHelp, isGoingToExit, nextApplicationState, isGoingToCauseUndo}: None
// specified
CommandResult commandResult = new CommandResult.Builder("feedback")
.build();
assertFalse(commandResult.isGoingToShowHelp());
assertFalse(commandResult.isGoingToExit());
assertEquals(new HomeState(), commandResult.getNextApplicationState());
assertFalse(commandResult.isGoingToCauseUndo());
}
@Test
public void build_setShowHelp_success() {
// Equivalence Partition {isGoingToShowHelp}: Specified false
CommandResult commandResult = new CommandResult.Builder("feedback")
.setGoShowHelp(false)
.build();
assertFalse(commandResult.isGoingToShowHelp());
// Equivalence Partition {isGoingToShowHelp}: Specified true
commandResult = new CommandResult.Builder("feedback")
.setGoShowHelp(true)
.build();
assertTrue(commandResult.isGoingToShowHelp());
commandResult = new CommandResult.Builder("feedback")
.goShowHelp()
.build();
assertTrue(commandResult.isGoingToShowHelp());
}
@Test
public void build_setGoExit_success() {
// Equivalence Partition {isGoingToExit}: Specified false
CommandResult commandResult = new CommandResult.Builder("feedback")
.setGoExit(false)
.build();
assertFalse(commandResult.isGoingToExit());
// Equivalence Partition {isGoingToExit}: Specified true
commandResult = new CommandResult.Builder("feedback")
.setGoExit(true)
.build();
assertTrue(commandResult.isGoingToExit());
commandResult = new CommandResult.Builder("feedback")
.goExit()
.build();
assertTrue(commandResult.isGoingToExit());
}
@Test
public void build_setNextApplicationState_success() {
ApplicationState nextApplicationState = new HomeState();
// Equivalence Partition {nextApplicationState}: Specified as HomeState
CommandResult commandResult = new CommandResult.Builder("feedback")
.setNextApplicationState(nextApplicationState)
.build();
assertEquals(nextApplicationState, commandResult.getNextApplicationState());
commandResult = new CommandResult.Builder("feedback")
.goToHome()
.build();
assertEquals(nextApplicationState, commandResult.getNextApplicationState());
// Equivalence Partition {nextApplicationState}: Specified as GroupInformationState
Group group = CS2103T_GROUP_BUILDER.build();
nextApplicationState = new GroupInformationState(group);
commandResult = new CommandResult.Builder("feedback")
.setNextApplicationState(nextApplicationState)
.build();
assertEquals(nextApplicationState, commandResult.getNextApplicationState());
commandResult = new CommandResult.Builder("feedback")
.displayGroupInformation(group)
.build();
assertEquals(nextApplicationState, commandResult.getNextApplicationState());
}
@Test
public void build_setGoCauseUndo_success() {
// Equivalence Partition {isGoingToCauseUndo}: Specified false
CommandResult commandResult = new CommandResult.Builder("feedback")
.setGoCauseUndo(false)
.build();
assertFalse(commandResult.isGoingToCauseUndo());
// Equivalence Partition {isGoingToCauseUndo}: Specified true
commandResult = new CommandResult.Builder("feedback")
.setGoCauseUndo(true)
.build();
assertTrue(commandResult.isGoingToCauseUndo());
commandResult = new CommandResult.Builder("feedback")
.goCauseUndo()
.build();
assertTrue(commandResult.isGoingToCauseUndo());
}
@Test
public void equals() {
CommandResult commandResult = new CommandResult("feedback");
// same values -> returns true
assertTrue(commandResult.equals(new CommandResult("feedback")));
assertTrue(commandResult.equals(new CommandResult("feedback", false, false)));
assertTrue(commandResult.equals(new CommandResult.Builder("feedback").build()));
// same object -> returns true
assertTrue(commandResult.equals(commandResult));
// null -> returns false
assertFalse(commandResult.equals(null));
// different types -> returns false
assertFalse(commandResult.equals(0.5f));
// different feedbackToUser value -> returns false
assertFalse(commandResult.equals(new CommandResult("different")));
assertFalse(commandResult.equals(
new CommandResult.Builder("different")
.build()
));
// different isGoingToShowHelp value -> returns false
assertFalse(commandResult.equals(new CommandResult("feedback", true, false)));
assertFalse(commandResult.equals(
new CommandResult.Builder("feedback")
.goShowHelp()
.build()
));
// different isGoingToExit value -> returns false
assertFalse(commandResult.equals(new CommandResult("feedback", false, true)));
assertFalse(commandResult.equals(
new CommandResult.Builder("feedback")
.goExit()
.build()
));
// different nextApplicationState value -> returns false
assertFalse(commandResult.equals(
new CommandResult.Builder("feedback")
.displayGroupInformation(CS2103T_GROUP_BUILDER.build())
.build()
));
// different isGoingToCauseUndo value -> returns false
assertFalse(commandResult.equals(
new CommandResult.Builder("feedback")
.goCauseUndo()
.build()
));
}
@Test
public void hashcode() {
CommandResult commandResult = new CommandResult("feedback");
// same values -> returns same hashcode
assertEquals(commandResult.hashCode(), new CommandResult("feedback").hashCode());
// different feedbackToUser value -> returns different hashcode
assertNotEquals(commandResult.hashCode(), new CommandResult("different").hashCode());
assertNotEquals(commandResult.hashCode(), new CommandResult.Builder("different")
.build().hashCode());
// different isGoingToShowHelp value -> returns different hashcode
assertNotEquals(commandResult.hashCode(), new CommandResult("feedback", true, false).hashCode());
assertNotEquals(commandResult.hashCode(), new CommandResult.Builder("feedback")
.goShowHelp()
.build().hashCode());
// different isGoingToExit value -> returns different hashcode
assertNotEquals(commandResult.hashCode(), new CommandResult("feedback", false, true).hashCode());
assertNotEquals(commandResult.hashCode(), new CommandResult.Builder("feedback")
.goExit()
.build().hashCode());
// different nextApplicationState value -> returns different hashcode
assertNotEquals(commandResult.hashCode(), new CommandResult.Builder("feedback")
.displayGroupInformation(CS2103T_GROUP_BUILDER.build())
.build().hashCode());
// different isGoingToCauseUndo value -> returns different hashcode
assertNotEquals(commandResult.hashCode(), new CommandResult.Builder("feedback")
.goCauseUndo()
.build().hashCode());
}
}
|
kupl/starlab-benchmarks
|
Benchmarks_with_Safety_Bugs/C/inetutils-1.9.4/src/talk/invite.c
|
<filename>Benchmarks_with_Safety_Bugs/C/inetutils-1.9.4/src/talk/invite.c
/*
Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014,
2015 Free Software Foundation, Inc.
This file is part of GNU Inetutils.
GNU Inetutils is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
GNU Inetutils is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see `http://www.gnu.org/licenses/'. */
/*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 <config.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <netinet/in.h>
#include <protocols/talkd.h>
#include <errno.h>
#include <unistd.h>
#include <setjmp.h>
#include <unused-parameter.h>
#include "talk_ctl.h"
#include "talk.h"
static char *answers[] = {
"answer #0", /* SUCCESS */
"Your party is not logged on", /* NOT_HERE */
"Target machine is too confused to talk to us", /* FAILED */
"Target machine does not recognize us", /* MACHINE_UNKNOWN */
"Your party is refusing messages", /* PERMISSION_REFUSED */
"Target machine cannot handle remote talk", /* UNKNOWN_REQUEST */
"Target machine indicates protocol mismatch", /* BADVERSION */
"Target machine indicates protocol botch (addr)", /* BADADDR */
"Target machine indicates protocol botch (ctl_addr)", /* BADCTLADDR */
};
#define NANSWERS (sizeof (answers) / sizeof (answers[0]))
/*
* The msg.id's for the invitations
* on the local and remote machines.
* These are used to delete the
* invitations.
*/
int local_id, remote_id;
jmp_buf invitebuf;
/*
* Transmit the invitation and process the response
*/
int
announce_invite (void)
{
CTL_RESPONSE response;
current_state = "Trying to connect to your party's talk daemon";
ctl_transact (his_machine_addr, msg, ANNOUNCE, &response);
remote_id = response.id_num;
if (response.answer != SUCCESS)
{
if (response.answer < NANSWERS)
message (answers[response.answer]);
quit ();
}
/* leave the actual invitation on my talk daemon */
ctl_transact (my_machine_addr, msg, LEAVE_INVITE, &response);
local_id = response.id_num;
return 0;
}
/*
* Routine called on interupt to re-invite the callee
*/
void
re_invite (int sig _GL_UNUSED_PARAMETER)
{
message ("Ringing your party again");
current_line++;
/* force a re-announce */
msg.id_num = htonl (remote_id + 1);
announce_invite ();
longjmp (invitebuf, 1);
}
int
invite_remote (void)
{
int new_sockt;
struct itimerval itimer;
CTL_RESPONSE response;
itimer.it_value.tv_sec = RING_WAIT;
itimer.it_value.tv_usec = 0;
itimer.it_interval = itimer.it_value;
if (listen (sockt, 5) != 0)
p_error ("Error on attempt to listen for caller");
msg.addr.sa_family = htons (my_addr.sin_family);
memcpy (msg.addr.sa_data,
((struct sockaddr *) &my_addr)->sa_data,
sizeof ((struct sockaddr *) & my_addr)->sa_data);
msg.id_num = htonl (-1); /* an impossible id_num */
invitation_waiting = 1;
announce_invite ();
/*
* Shut off the automatic messages for a while,
* so we can use the interupt timer to resend the invitation
*/
end_msgs ();
setitimer (ITIMER_REAL, &itimer, (struct itimerval *) 0);
message ("Waiting for your party to respond");
signal (SIGALRM, re_invite);
setjmp (invitebuf);
while ((new_sockt = accept (sockt, 0, 0)) < 0)
{
if (errno == EINTR)
continue;
p_error ("Unable to connect with your party");
}
close (sockt);
sockt = new_sockt;
/*
* Have the daemons delete the invitations now that we
* have connected.
*/
current_state = "Waiting for your party to respond";
start_msgs ();
msg.id_num = htonl (local_id);
ctl_transact (my_machine_addr, msg, DELETE, &response);
msg.id_num = htonl (remote_id);
ctl_transact (his_machine_addr, msg, DELETE, &response);
invitation_waiting = 0;
return 0;
}
/*
* Tell the daemon to remove your invitation
*/
int
send_delete (void)
{
msg.type = DELETE;
/*
* This is just a extra clean up, so just send it
* and don't wait for an answer
*/
msg.id_num = htonl (remote_id);
daemon_addr.sin_family = AF_INET;
#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
daemon_addr.sin_len = sizeof (daemon_addr);
#endif
daemon_addr.sin_addr = his_machine_addr;
if (sendto (ctl_sockt, (const char *) &msg, sizeof (msg), 0,
(struct sockaddr *) &daemon_addr,
sizeof (daemon_addr)) != sizeof (msg))
perror ("send_delete (remote)");
msg.id_num = htonl (local_id);
daemon_addr.sin_addr = my_machine_addr;
if (sendto (ctl_sockt, (const char *) &msg, sizeof (msg), 0,
(struct sockaddr *) &daemon_addr,
sizeof (daemon_addr)) != sizeof (msg))
perror ("send_delete (local)");
return 0;
}
|
tarsic99/Python_coursera
|
Python training/First steps/Exercise_9.py
|
n = input()
print(int(n[-1])+int(n[-2])+int(n[-3]))
|
rjw57/tiw-computer
|
emulator/src/mame/video/atari400.cpp
|
<filename>emulator/src/mame/video/atari400.cpp
// license:GPL-2.0+
// copyright-holders:<NAME>
/******************************************************************************
Atari 400/800
Video handler
<NAME>, June 1998
******************************************************************************/
#include "emu.h"
#include "includes/atari400.h"
#include "screen.h"
#define VERBOSE 0
#define LOG(x) do { if (VERBOSE) logerror x; } while (0)
/************************************************************************
* video_start
* Initialize the ATARI800 video emulation
************************************************************************/
void atari_common_state::video_start()
{
device_palette_interface &palette = m_screen->palette();
for (int i = 0; i < 256; i++)
m_gtia->set_color_lookup(i, (palette.pen(0) << 8) + palette.pen(0));
}
/**************************************************************
*
* Palette
*
**************************************************************/
static const uint8_t atari_palette[256*3] =
{
/* Grey */
0x00,0x00,0x00, 0x25,0x25,0x25, 0x34,0x34,0x34, 0x4e,0x4e,0x4e,
0x68,0x68,0x68, 0x75,0x75,0x75, 0x8e,0x8e,0x8e, 0xa4,0xa4,0xa4,
0xb8,0xb8,0xb8, 0xc5,0xc5,0xc5, 0xd0,0xd0,0xd0, 0xd7,0xd7,0xd7,
0xe1,0xe1,0xe1, 0xea,0xea,0xea, 0xf4,0xf4,0xf4, 0xff,0xff,0xff,
/* Gold */
0x41,0x20,0x00, 0x54,0x28,0x00, 0x76,0x37,0x00, 0x9a,0x50,0x00,
0xc3,0x68,0x06, 0xe4,0x7b,0x07, 0xff,0x91,0x1a, 0xff,0xab,0x1d,
0xff,0xc5,0x1f, 0xff,0xd0,0x3b, 0xff,0xd8,0x4c, 0xff,0xe6,0x51,
0xff,0xf4,0x56, 0xff,0xf9,0x70, 0xff,0xff,0x90, 0xff,0xff,0xaa,
/* Orange */
0x45,0x19,0x04, 0x72,0x1e,0x11, 0x9f,0x24,0x1e, 0xb3,0x3a,0x20,
0xc8,0x51,0x20, 0xe3,0x69,0x20, 0xfc,0x81,0x20, 0xfd,0x8c,0x25,
0xfe,0x98,0x2c, 0xff,0xae,0x38, 0xff,0xb9,0x46, 0xff,0xbf,0x51,
0xff,0xc6,0x6d, 0xff,0xd5,0x87, 0xff,0xe4,0x98, 0xff,0xe6,0xab,
/* Red-Orange */
0x5d,0x1f,0x0c, 0x7a,0x24,0x0d, 0x98,0x2c,0x0e, 0xb0,0x2f,0x0f,
0xbf,0x36,0x24, 0xd3,0x4e,0x2a, 0xe7,0x62,0x3e, 0xf3,0x6e,0x4a,
0xfd,0x78,0x54, 0xff,0x8a,0x6a, 0xff,0x98,0x7c, 0xff,0xa4,0x8b,
0xff,0xb3,0x9e, 0xff,0xc2,0xb2, 0xff,0xd0,0xc3, 0xff,0xda,0xd0,
/* Pink */
0x4a,0x17,0x00, 0x72,0x1f,0x00, 0xa8,0x13,0x00, 0xc8,0x21,0x0a,
0xdf,0x25,0x12, 0xec,0x3b,0x24, 0xfa,0x52,0x36, 0xfc,0x61,0x48,
0xff,0x70,0x5f, 0xff,0x7e,0x7e, 0xff,0x8f,0x8f, 0xff,0x9d,0x9e,
0xff,0xab,0xad, 0xff,0xb9,0xbd, 0xff,0xc7,0xce, 0xff,0xca,0xde,
/* Purple */
0x49,0x00,0x36, 0x66,0x00,0x4b, 0x80,0x03,0x5f, 0x95,0x0f,0x74,
0xaa,0x22,0x88, 0xba,0x3d,0x99, 0xca,0x4d,0xa9, 0xd7,0x5a,0xb6,
0xe4,0x67,0xc3, 0xef,0x72,0xce, 0xfb,0x7e,0xda, 0xff,0x8d,0xe1,
0xff,0x9d,0xe5, 0xff,0xa5,0xe7, 0xff,0xaf,0xea, 0xff,0xb8,0xec,
/* Purple-Blue */
0x48,0x03,0x6c, 0x5c,0x04,0x88, 0x65,0x0d,0x90, 0x7b,0x23,0xa7,
0x93,0x3b,0xbf, 0x9d,0x45,0xc9, 0xa7,0x4f,0xd3, 0xb2,0x5a,0xde,
0xbd,0x65,0xe9, 0xc5,0x6d,0xf1, 0xce,0x76,0xfa, 0xd5,0x83,0xff,
0xda,0x90,0xff, 0xde,0x9c,0xff, 0xe2,0xa9,0xff, 0xe6,0xb6,0xff,
/* Blue 1 */
0x05,0x1e,0x81, 0x06,0x26,0xa5, 0x08,0x2f,0xca, 0x26,0x3d,0xd4,
0x44,0x4c,0xde, 0x4f,0x5a,0xec, 0x5a,0x68,0xff, 0x65,0x75,0xff,
0x71,0x83,0xff, 0x80,0x91,0xff, 0x90,0xa0,0xff, 0x97,0xa9,0xff,
0x9f,0xb2,0xff, 0xaf,0xbe,0xff, 0xc0,0xcb,0xff, 0xcd,0xd3,0xff,
/* Blue 2 */
0x0b,0x07,0x79, 0x20,0x1c,0x8e, 0x35,0x31,0xa3, 0x46,0x42,0xb4,
0x57,0x53,0xc5, 0x61,0x5d,0xcf, 0x6d,0x69,0xdb, 0x7b,0x77,0xe9,
0x89,0x85,0xf7, 0x91,0x8d,0xff, 0x9c,0x98,0xff, 0xa7,0xa4,0xff,
0xb2,0xaf,0xff, 0xbb,0xb8,0xff, 0xc3,0xc1,0xff, 0xd3,0xd1,0xff,
/* Light-Blue */
0x1d,0x29,0x5a, 0x1d,0x38,0x76, 0x1d,0x48,0x92, 0x1d,0x5c,0xac,
0x1d,0x71,0xc6, 0x32,0x86,0xcf, 0x48,0x9b,0xd9, 0x4e,0xa8,0xec,
0x55,0xb6,0xff, 0x69,0xca,0xff, 0x74,0xcb,0xff, 0x82,0xd3,0xff,
0x8d,0xda,0xff, 0x9f,0xd4,0xff, 0xb4,0xe2,0xff, 0xc0,0xeb,0xff,
/* Turquoise */
0x00,0x4b,0x59, 0x00,0x5d,0x6e, 0x00,0x6f,0x84, 0x00,0x84,0x9c,
0x00,0x99,0xbf, 0x00,0xab,0xca, 0x00,0xbc,0xde, 0x00,0xd0,0xf5,
0x10,0xdc,0xff, 0x3e,0xe1,0xff, 0x64,0xe7,0xff, 0x76,0xea,0xff,
0x8b,0xed,0xff, 0x9a,0xef,0xff, 0xb1,0xf3,0xff, 0xc7,0xf6,0xff,
/* Green-Blue */
0x00,0x48,0x00, 0x00,0x54,0x00, 0x03,0x6b,0x03, 0x0e,0x76,0x0e,
0x18,0x80,0x18, 0x27,0x92,0x27, 0x36,0xa4,0x36, 0x4e,0xb9,0x4e,
0x51,0xcd,0x51, 0x72,0xda,0x72, 0x7c,0xe4,0x7c, 0x85,0xed,0x85,
0x99,0xf2,0x99, 0xb3,0xf7,0xb3, 0xc3,0xf9,0xc3, 0xcd,0xfc,0xcd,
/* Green */
0x16,0x40,0x00, 0x1c,0x53,0x00, 0x23,0x66,0x00, 0x28,0x78,0x00,
0x2e,0x8c,0x00, 0x3a,0x98,0x0c, 0x47,0xa5,0x19, 0x51,0xaf,0x23,
0x5c,0xba,0x2e, 0x71,0xcf,0x43, 0x85,0xe3,0x57, 0x8d,0xeb,0x5f,
0x97,0xf5,0x69, 0xa0,0xfe,0x72, 0xb1,0xff,0x8a, 0xbc,0xff,0x9a,
/* Yellow-Green */
0x2c,0x35,0x00, 0x38,0x44,0x00, 0x44,0x52,0x00, 0x49,0x56,0x00,
0x60,0x71,0x00, 0x6c,0x7f,0x00, 0x79,0x8d,0x0a, 0x8b,0x9f,0x1c,
0x9e,0xb2,0x2f, 0xab,0xbf,0x3c, 0xb8,0xcc,0x49, 0xc2,0xd6,0x53,
0xcd,0xe1,0x53, 0xdb,0xef,0x6c, 0xe8,0xfc,0x79, 0xf2,0xff,0xab,
/* Orange-Green */
0x46,0x3a,0x09, 0x4d,0x3f,0x09, 0x54,0x45,0x09, 0x6c,0x58,0x09,
0x90,0x76,0x09, 0xab,0x8b,0x0a, 0xc1,0xa1,0x20, 0xd0,0xb0,0x2f,
0xde,0xbe,0x3d, 0xe6,0xc6,0x45, 0xed,0xcd,0x4c, 0xf5,0xd8,0x62,
0xfb,0xe2,0x76, 0xfc,0xee,0x98, 0xfd,0xf3,0xa9, 0xfd,0xf3,0xbe,
/* Light-Orange */
0x40,0x1a,0x02, 0x58,0x1f,0x05, 0x70,0x24,0x08, 0x8d,0x3a,0x13,
0xab,0x51,0x1f, 0xb5,0x64,0x27, 0xbf,0x77,0x30, 0xd0,0x85,0x3a,
0xe1,0x93,0x44, 0xed,0xa0,0x4e, 0xf9,0xad,0x58, 0xfc,0xb7,0x5c,
0xff,0xc1,0x60, 0xff,0xca,0x69, 0xff,0xcf,0x7e, 0xff,0xda,0x96
};
/* Initialise the palette */
PALETTE_INIT_MEMBER(atari_common_state, atari)
{
int i;
for ( i = 0; i < sizeof(atari_palette) / 3; i++ )
{
palette.set_pen_color(i, atari_palette[i*3], atari_palette[i*3+1], atari_palette[i*3+2]);
}
}
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/arm/bics_3.c
|
<filename>gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/arm/bics_3.c
/* { dg-do run } */
/* { dg-options "-O2 --save-temps -fno-inline" } */
/* { dg-require-effective-target arm32 } */
extern void abort (void);
int
bics_si_test (int a, int b)
{
if (a & ~b)
return 1;
else
return 0;
}
int
bics_si_test2 (int a, int b)
{
if (a & ~ (b << 2))
return 1;
else
return 0;
}
int
main (void)
{
int a = 5;
int b = 5;
int c = 20;
if (bics_si_test (a, b))
abort ();
if (bics_si_test2 (c, b))
abort ();
return 0;
}
/* { dg-final { scan-assembler-times "bics\tr\[0-9\]+, r\[0-9\]+, r\[0-9\]+" 2 } } */
/* { dg-final { scan-assembler-times "bics\tr\[0-9\]+, r\[0-9\]+, r\[0-9\]+, .sl #2" 1 } } */
|
crazysnailboy/Halloween
|
src/main/java/net/crazysnailboy/mods/halloween/entity/projectile/fake/EntityFakeArrow.java
|
<reponame>crazysnailboy/Halloween
package net.crazysnailboy.mods.halloween.entity.projectile.fake;
import net.crazysnailboy.mods.halloween.entity.monster.fake.EntityFakeSkeleton;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.World;
/**
* A "fake" arrow. Used by {@link EntityFakeSkeleton} during it's attack.
*
*/
public class EntityFakeArrow extends EntityArrow
{
public EntityFakeArrow(World world)
{
super(world);
this.setDamage(0.0D);
}
public EntityFakeArrow(World world, double x, double y, double z)
{
super(world, x, y, z);
this.setDamage(0.0D);
}
public EntityFakeArrow(World world, EntityLivingBase shooter)
{
super(world, shooter);
this.setDamage(0.0D);
}
@Override
protected ItemStack getArrowStack()
{
return null;
}
@Override
protected void onHit(RayTraceResult result)
{
this.playSound(SoundEvents.ENTITY_ARROW_HIT, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
this.setDead();
}
}
|
anthonydelgado/pinocchio
|
geppetto/code/compiler/src/cpp/EncodingArithQap.cpp
|
<filename>geppetto/code/compiler/src/cpp/EncodingArithQap.cpp<gh_stars>0
#include <assert.h>
#include "EncodingArithQap.h"
#include <bitset>
#include <intrin.h>
#include "Poly.h"
#include "FieldPrime.h"
#include "EncodingEnigmaBN.h"
#include "ArithQapWrappers.h"
// Protect ourselves from ARITH's #define
#ifdef mul
#undef mul
#endif
EncodingArithQap::EncodingArithQap()
{
members = new EncodingArithQapMembers;
QapInterface_init(&members->qap_interface);
members->msft_encoding = new EncodingEnigmaBN();
this->srcField = members->msft_encoding->getSrcField();
QapFp_wp_init(members->Lg.me);
QapFp_wp_copy(members->Lg.me, members->qap_interface.Lg);
QapFp2_wp_init(members->Rg.me);
QapFp2_wp_copy(members->Rg.me, members->qap_interface.Rg);
QapFp_wp_init(members->Lzero.me);
QapFp_wp_copy(members->Lzero.me, members->qap_interface.Lzero);
QapFp2_wp_init(members->Rzero.me);
QapFp2_wp_copy(members->Rzero.me, members->qap_interface.Rzero);
}
EncodingArithQap::~EncodingArithQap() {
delete members->msft_encoding; // Delete the encoding that provided our srcField, not the srcField itself
#if 0 // TODO fill in corresponding destruction sequence
QapFp_wp_free(members->Lzero.me);
QapFp2_wp_free(members->Rzero.me);
QapFp_free (members->b);
QapFp2_free (members->B);
QapFp2_free (members->B3);
QapFp2_free (members->l00);
QapFp2_free (members->l01);
QapFp2_free (members->l10);
QapFp2_wp_free (members->Rg.me);
QapFp_wp_free (members->Lg.me);
bn_bls12_finalexpo_free_config ();
bn_bls12_miller_free_config ();
QapFp12_free_config ();
QapFp6_free_config ();
QapFp4_free_config ();
QapFp2_free_weierstrass ();
QapFp2_free_config ();
QapFp_free_config ();
#endif
}
// TODO: Adjust to count pointers as well
uint32_t EncodingArithQap::bytes_per(elt_t t) {
if (t == L) {
return num_L_digits*sizeof(digit_t);
} else {
assert(t == R);
return num_R_digits*sizeof(digit_t);
}
}
uint32_t EncodingArithQap::num_exponent_bits() {
return 4*sizeof(digit_t)*8 - 1; // BN_curve uses 4 digits, but doesn't use them all (only uses 254 bits)
}
EncodedElt* EncodingArithQap::new_elt(elt_t t) {
if (t == L) {
LEncodedEltQapArith* elt = new LEncodedEltQapArith;
QapFp_wp_init(elt->me);
return elt;
} else {
assert(t == R);
REncodedEltQapArith* elt = new REncodedEltQapArith;
QapFp2_wp_init(elt->me);
return elt;
}
}
EncodedEltArray* EncodingArithQap::new_elt_array(elt_t t, uint32_t len, bool preallocate) {
return new EncodedEltQapArithArray(t, this, len, preallocate);
}
void EncodingArithQap::del_elt(elt_t t, EncodedElt* elt) {
assert(elt);
if (t == L) {
QapFp_wp_free(((LEncodedEltQapArith*)elt)->me);
} else {
assert(t == R);
QapFp2_wp_free(((REncodedEltQapArith*)elt)->me);
}
delete elt;
}
EncodedProduct* EncodingArithQap::new_prod() {
EncodedProductQapArith* ret = new EncodedProductQapArith();
QapFp12_init(ret->me);
return ret;
}
uint32_t EncodingArithQap::size_of_prod() {
return sizeof(QapFp12_t);
}
void EncodingArithQap::print_raw(elt_t t, EncodedElt* e) {
if (t == L) {
LEncodedEltQapArith* en = (LEncodedEltQapArith*)e;
printf("( ");
QapFp_print(en->me->X);
printf(", ");
QapFp_print(en->me->Y);
printf(")");
} else {
assert(t == R);
REncodedEltQapArith* en = (REncodedEltQapArith*)e;
printf("( ");
QapFp2_print(en->me->X);
printf(", ");
QapFp2_print(en->me->Y);
printf(")");
}
}
void EncodingArithQap::print(elt_t t, EncodedElt* e) {
if (isZero(t, e))
{
printf("(ZERO)\n");
}
else
{
if (t == L) {
LEncodedEltQapArith* en = (LEncodedEltQapArith*)e;
printf("( ");
QapFp_print(en->me->X);
printf(", ");
QapFp_print(en->me->Y);
printf(")");
}
else {
assert(t == R);
REncodedEltQapArith* en = (REncodedEltQapArith*)e;
printf("( ");
QapFp2_print(en->me->X);
printf(", ");
QapFp2_print(en->me->Y);
printf(")");
}
}
}
void EncodingArithQap::print(EncodedProduct* p) {
EncodedProductQapArith* ep = (EncodedProductQapArith*)p;
QapFp12_print(ep->me);
}
void EncodingArithQap::copy(elt_t t, EncodedElt* src, EncodedElt* dst) {
if (t == L) {
QapFp_wp_copy(((LEncodedEltQapArith*)dst)->me, ((LEncodedEltQapArith*)src)->me);
} else {
assert(t == R);
QapFp2_wp_copy(((REncodedEltQapArith*)dst)->me, ((REncodedEltQapArith*)src)->me);
}
}
bool EncodingArithQap::equal(elt_t t, EncodedElt* a, EncodedElt* b) {
assert(a && b);
testOnCurve(t, a);
testOnCurve(t, b);
bool ret = false;
// Short circuit 0, since affinizing 0 spins into infinity
if (isZero(t, a)) { return isZero(t, b); }
else if (isZero(t, b)) { return false; }
if (t == L) {
LEncodedEltQapArith* ae = (LEncodedEltQapArith*)a;
LEncodedEltQapArith* be = (LEncodedEltQapArith*)b;
ret = 0 != QapFp_weierstrass_equal_aff(ae->me, be->me);
} else {
assert(t == R);
REncodedEltQapArith* ae = (REncodedEltQapArith*)a;
REncodedEltQapArith* be = (REncodedEltQapArith*)b;
ret = 0 != QapFp2_weierstrass_equal_aff(ae->me, be->me);
}
return ret;
}
void EncodingArithQap::zero(elt_t t, EncodedElt* a) {
if (t == L) {
copy(t, &members->Lzero, a); // Use our precomputed value
} else {
assert(t == R);
copy(t, &members->Rzero, a); // Use our precomputed value
}
}
void EncodingArithQap::one(elt_t t, EncodedElt* a) {
if (t == L) {
copy(t, &members->Lg, a); // Use our precomputed value
} else {
assert(t == R);
copy(t, &members->Rg, a); // Use our precomputed value
}
}
// Adds two encoded elements. Result goes in r.
void EncodingArithQap::add(elt_t t, EncodedElt* a, EncodedElt* b, EncodedElt* r) {
add(t, a, b, r, false);
}
// Adds two encoded elements. Result goes in r.
void EncodingArithQap::add(elt_t t, EncodedElt* a, EncodedElt* b, EncodedElt* r, bool definitely_distinct) {
assert(a && b && r);
testOnCurve(t, a);
testOnCurve(t, b);
if (t == L) {
LEncodedEltQapArith* ae = (LEncodedEltQapArith*)a;
LEncodedEltQapArith* be = (LEncodedEltQapArith*)b;
LEncodedEltQapArith* re = (LEncodedEltQapArith*)r;
if (isZero(t, a)) {
QapFp_wp_copy(re->me, be->me);
} else if (isZero(t, b)) {
QapFp_wp_copy(re->me, ae->me);
} else if (!definitely_distinct && this->equal(t, a, b)) {
// Library doesn't support addition of a point to itself
QapFp_weierstrass_affdbl(re->me, ae->me);
} else {
QapFp_weierstrass_affadd(re->me, ae->me, be->me);
}
} else {
assert(t == R);
REncodedEltQapArith* ae = (REncodedEltQapArith*)a;
REncodedEltQapArith* be = (REncodedEltQapArith*)b;
REncodedEltQapArith* re = (REncodedEltQapArith*)r;
if (isZero(t, a)) {
QapFp2_wp_copy(re->me, be->me);
} else if (isZero(t, b)) {
QapFp2_wp_copy(re->me, ae->me);
} else if (!definitely_distinct && this->equal(t, a, b)) {
// Library doesn't support addition of a point to itself
QapFp2_weierstrass_affdbl(re->me, ae->me);
} else {
QapFp2_weierstrass_affadd(re->me, ae->me, be->me);
}
}
testOnCurve(t, r);
}
// Subtracts two encoded elements. Result goes in r.
void EncodingArithQap::sub(elt_t t, EncodedElt* a, EncodedElt* b, EncodedElt* r) {
assert(a && b && r);
testOnCurve(t, a);
testOnCurve(t, b);
if (t == L) {
LEncodedEltQapArith* ae = (LEncodedEltQapArith*)a;
LEncodedEltQapArith* be = (LEncodedEltQapArith*)b;
LEncodedEltQapArith* re = (LEncodedEltQapArith*)r;
LEncodedEltQapArith neg_b;
QapFp_wp_init(neg_b.me);
QapFp_wp_neg(neg_b.me, be->me);
// printf("\n");
// printf("b:"); print(t, be);
// printf("neg_b:"); print(t, &neg_b);
add(t, ae, &neg_b, re);
// printf("a:"); print(t, ae);
// printf("result:"); print(t, re);
QapFp_wp_free(neg_b.me);
} else {
assert(t == R);
REncodedEltQapArith* ae = (REncodedEltQapArith*)a;
REncodedEltQapArith* be = (REncodedEltQapArith*)b;
REncodedEltQapArith* re = (REncodedEltQapArith*)r;
REncodedEltQapArith neg_b;
QapFp2_wp_init(neg_b.me);
QapFp2_wp_neg(neg_b.me, be->me);
add(t, ae, &neg_b, re);
QapFp2_wp_free(neg_b.me);
}
testOnCurve(t, r);
}
void EncodingArithQap::doubleIt(elt_t t, EncodedElt* a, EncodedElt* b) {
assert(a && b);
testOnCurve(t, a);
if (t == L) {
LEncodedEltQapArith* ae = (LEncodedEltQapArith*)a;
LEncodedEltQapArith* be = (LEncodedEltQapArith*)b;
if (isZero(L, ae)) {
zero(L, be);
} else {
QapFp_weierstrass_affdbl(be->me, ae->me);
}
} else {
assert(t == R);
REncodedEltQapArith* ae = (REncodedEltQapArith*)a;
REncodedEltQapArith* be = (REncodedEltQapArith*)b;
if (isZero(R, ae)) {
zero(R, be);
} else {
QapFp2_weierstrass_affdbl(be->me, ae->me);
}
}
testOnCurve(t, b);
}
// Multiplies the value encoded in g by the constant c. Result goes in r.
// For pairings, we compute r <- g^c
void EncodingArithQap::mul(elt_t t, EncodedElt* g, FieldElt* c, EncodedElt* r) {
assert(g && c && r);
testOnCurve(t, g);
EncodedElt* result;
if (g == r) { // Don't want to clobber our input
result = new_elt(t);
} else {
result = r;
}
// Naive square and multiply
zero(t, result);
for (int bit_index = num_exponent_bits(); bit_index >= 0; bit_index--) {
doubleIt(t, result, result);
if (srcField->getBits(c, bit_index, 1)) {
add(t, g, result, result, true);
}
}
if (g == r) {
// Copy over the result
copy(t, result, r);
del_elt(t, result);
}
testOnCurve(t, r);
}
void EncodingArithQap::mul(LEncodedElt* a, REncodedElt* b, EncodedProduct* r) {
pair(a, b, r);
}
void EncodingArithQap::pair(LEncodedElt* L1, REncodedElt* R1, EncodedProduct* result) {
assert(L1 && R1 && result);
testOnCurve(L, L1);
testOnCurve(R, R1);
LEncodedEltQapArith* L1e = (LEncodedEltQapArith*)L1;
REncodedEltQapArith* R1e = (REncodedEltQapArith*)R1;
EncodedProductQapArith* resulte = (EncodedProductQapArith*)result;
if (isZero(L, L1) || isZero(R, R1)) {
// Library doesn't handle g^0 values properly, so we special-case it
QapFp12_set_one(resulte->me);
} else {
Qapbn_optimal_ate_miller_aff(resulte->me, R1e->me, L1e->me);
Qapbn_finalexpo_neg(resulte->me, resulte->me);
}
}
bool EncodingArithQap::isZero(elt_t t, EncodedElt* elt) {
assert(elt);
//testOnCurve(t, elt);
bool ret = false;
if (t == L) {
LEncodedEltQapArith* elte = (LEncodedEltQapArith*)elt;
ret = 0 == QapFp_cmp(elte->me->Y, members->Lzero.me->Y); // Our internal representation of 0
} else {
assert(t == R);
REncodedEltQapArith* elte = (REncodedEltQapArith*)elt;
ret = 0 != QapFp2_cmpeq(elte->me->Y, members->Rzero.me->Y); // Check if the Y coord is 0 ==> pt at infinity
}
return ret;
}
void EncodingArithQap::add(EncodedProduct* a, EncodedProduct* b, EncodedProduct* r) {
assert(a && b && r);
EncodedProductQapArith* ae = (EncodedProductQapArith*)a;
EncodedProductQapArith* be = (EncodedProductQapArith*)b;
EncodedProductQapArith* re = (EncodedProductQapArith*)r;
QapFp12_mul(re->me, ae->me, be->me);
}
void EncodingArithQap::sub(EncodedProduct* a, EncodedProduct* b, EncodedProduct* r) {
assert(a && b && r);
EncodedProductQapArith* ae = (EncodedProductQapArith*)a;
EncodedProductQapArith* be = (EncodedProductQapArith*)b;
EncodedProductQapArith* re = (EncodedProductQapArith*)r;
EncodedProductQapArith* inv = (EncodedProductQapArith*)this->new_prod();
QapFp12_inv(inv->me, be->me);
QapFp12_mul(re->me, ae->me, inv->me);
}
bool EncodingArithQap::equals(EncodedProduct* a, EncodedProduct* b) {
assert(a && b);
EncodedProductQapArith* ae = (EncodedProductQapArith*)a;
EncodedProductQapArith* be = (EncodedProductQapArith*)b;
return 1 == QapFp12_cmpeq(ae->me, be->me);
}
// Checks whether the plaintexts inside the encodings obey:
// L1*R1 - L2*R2 == L3*R3
bool EncodingArithQap::mulSubEquals(LEncodedElt* L1, REncodedElt* R1, LEncodedElt* L2, REncodedElt* R2, LEncodedElt* L3, REncodedElt* R3) {
assert(L1 && R1 && L2 && R2 && L3 && R3);
EncodedProductQapArith pairing1;
EncodedProductQapArith pairing2;
EncodedProductQapArith pairing3;
QapFp12_init(pairing1.me);
QapFp12_init(pairing2.me);
QapFp12_init(pairing3.me);
testOnCurve(L, L1); testOnCurve(R, R1);
testOnCurve(L, L2); testOnCurve(R, R2);
testOnCurve(L, L3); testOnCurve(R, R3);
// Compute the three pairings
pair(L1, R1, &pairing1);
pair(L2, R2, &pairing2);
pair(L3, R3, &pairing3);
// Compute (with some notation abuse) L1*R1 - L2*R2 (in the exponents), i.e., pairing1 <- pairing1 / pairing2
sub(&pairing1, &pairing2, &pairing1);
bool result = equals(&pairing1, &pairing3);
QapFp12_free(pairing1.me);
QapFp12_free(pairing2.me);
QapFp12_free(pairing3.me);
return result != 0; // The != 0 supresses a compiler warning about casting a BOOL (int) to a bool
}
// Checks whether the plaintexts inside the encodings obey:
// L1*R1 == L2*R2
bool EncodingArithQap::mulEquals(LEncodedElt* L1, REncodedElt* R1, LEncodedElt* L2, REncodedElt* R2) {
assert(L1 && R1 && L2 && R2);
EncodedProductQapArith pairing1;
EncodedProductQapArith pairing2;
QapFp12_init(pairing1.me);
QapFp12_init(pairing2.me);
testOnCurve(L, L1); testOnCurve(R, R1);
testOnCurve(L, L2); testOnCurve(R, R2);
// Compute the two pairings
pair(L1, R1, &pairing1);
pair(L2, R2, &pairing2);
BOOL result = equals(&pairing1, &pairing2);
QapFp12_free(pairing1.me);
QapFp12_free(pairing2.me);
return result != 0; // The != 0 supresses a compiler warning about casting a BOOL (int) to a bool
}
void EncodingArithQap::compress(elt_t t, EncodedElt* elt) {
assert(false); // Not yet implemented
}
void EncodingArithQap::decompress(elt_t t, digit_t* compressed_elt, EncodedElt* elt) {
assert(false); // Not yet implemented
}
void EncodingArithQap::write(Archiver* arc, elt_t t, EncodedElt* e, bool simple) {
assert(false); // Not yet implemented
}
void EncodingArithQap::read (Archiver* arc, elt_t t, EncodedElt* e) {
assert(false); // Not yet implemented
}
void EncodingArithQap::affinize(elt_t t, EncodedElt* in, EncodedElt* out) {
assert(in && out);
testOnCurve(t, in);
copy(t, in, out);
}
void EncodingArithQap::testOnCurve(elt_t t, EncodedElt* a) {
#ifdef DEBUG_EC
assert(a);
if (t == L) {
LEncodedEltQapArith* ae = (LEncodedEltQapArith*)a;
QapFp_weierstrass_oncurve_aff(ae->me);
} else {
assert(t == R);
REncodedEltQapArith* ae = (REncodedEltQapArith*)a;
QapFp2_weierstrass_oncurve_aff(ae->me);
}
#endif
}
void EncodingArithQap::encodeSlow(elt_t t, FieldElt* in, EncodedElt* out) {
assert(in && out);
if (t == L) {
mul(t, &members->Lg, in, out);
} else {
assert(t == R);
mul(t, &members->Rg, in, out);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Arrays
//////////////////////////////////////////////////////////////////////////////////////////////////////
EncodedEltQapArithArray::EncodedEltQapArithArray(elt_t type, Encoding* encoding, uint32_t len, bool preallocate) {
this->type = type;
this->len = len;
elts = new EncodedEltQapArith*[len];
allocated = preallocate;
for (uint32_t i = 0; i < len; i++) {
if (preallocate) {
elts[i] = (EncodedEltQapArith*)encoding->new_elt(type);
} else {
elts[i] = NULL;
}
}
}
EncodedEltQapArithArray::~EncodedEltQapArithArray() {
if (allocated) {
for (uint32_t i = 0; i < len; i++) {
delete elts[i];
}
}
delete [] elts;
}
EncodedElt* EncodedEltQapArithArray::elt(uint32_t index) {
assert(index < len);
assert(elts[index] != NULL);
return elts[index];
}
void EncodedEltQapArithArray::set(uint32_t index, EncodedElt* elt) {
assert(index < len);
assert(elts[index] == NULL); // Otherwise we're overwriting and existing value!
elts[index] = (EncodedEltQapArith*)elt;
}
void EncodedEltQapArithArray::reset() {
assert(!allocated);
for (uint32_t i = 0; i < len; i++) {
elts[i] = NULL;
}
}
|
abhinavsri360/Allcodes
|
cpac/codeforces/1400/freq.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
void countFreq(ll arr[], ll n)
{
vector<bool> visited(n, false);
for (int i = 0; i < n; i++) {
if (visited[i] == true)
continue;
ll count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
cout << arr[i] << ":" << count << endl;
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
ll arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr,arr+n);
countFreq(arr, n);
}
return 0;
}
|
kmsiapps/maplestory_dpm_calc
|
dpmModule/jobs/nightwalker.py
|
<filename>dpmModule/jobs/nightwalker.py
from ..kernel import core
from ..kernel.core import VSkillModifier as V
from ..character import characterKernel as ck
from functools import partial
from ..status.ability import Ability_tool
from . import globalSkill
from .jobclass import cygnus
from .jobbranch import thieves
#TODO : 5차 신스킬 적용
###### Passive Skill ######
class JobGenerator(ck.JobGenerator):
def __init__(self):
super(JobGenerator, self).__init__()
self.vEnhanceNum = 9
self.jobtype = "luk"
self.ability_list = Ability_tool.get_ability_set('boss_pdamage', 'crit', 'buff_rem')
self.preEmptiveSkills = 1
def get_passive_skill_list(self):
ElementalExpert = core.InformedCharacterModifier("엘리멘탈 엑스퍼트",stat_main = self.chtr.level // 2)
ElementalHarmony = core.InformedCharacterModifier("엘리멘탈 하모니",patt = 10)
ThrowingMastery = core.InformedCharacterModifier("스로잉 마스터리",pdamage = 30)
CriticalThrowing = core.InformedCharacterModifier("크리티컬 스로잉",crit = 35, crit_damage = 10)
PhisicalTraining = core.InformedCharacterModifier("피지컬 트레이닝",stat_main = 60)
Adrenalin = core.InformedCharacterModifier("아드레날린",crit_damage = 10)
ThrowingExpert = core.InformedCharacterModifier("스로잉 엑스퍼트",att = 30, crit_damage = 10)
DarknessBlessing = core.InformedCharacterModifier("다크니스 블레싱",att = 30, armor_ignore = 15)
ReadyToDiePassive = thieves.ReadyToDiePassiveWrapper(self.vEhc, 3, 3)
return [ElementalExpert, ElementalHarmony, ThrowingMastery, CriticalThrowing, PhisicalTraining,
Adrenalin, ThrowingExpert, DarknessBlessing,
ReadyToDiePassive]
def get_not_implied_skill_list(self):
WeaponConstant = core.InformedCharacterModifier("무기상수",pdamage_indep = 75)
Mastery = core.InformedCharacterModifier("숙련도",pdamage_indep = -7.5) #오더스 기본적용!
return [WeaponConstant, Mastery]
def generate(self, vEhc, chtr : ck.AbstractCharacter, combat : bool = False):
'''
하이퍼 스킬 :
퀸터플 3종 + 다크니스 오멘 2개
V코어 : 9개
퀸터플, 배트, 도미니언, 다크니스 오멘 : 1티어
스피어 배트에도 발동
매 퀸터플마다 스피어 1개
점샷 가동률 100%
배트 사출률 0.22 (0.333이 아님)
퀸터-배트
'''
###### Skill ######
JUMPRATE = 1
BATRATE = 0.3333
ElementalDarkness = core.BuffSkill("엘리멘탈 : 다크니스", 1440, 180000, armor_ignore = (4+1+1+1) * (2+1+1+1)).wrap(core.BuffSkillWrapper)
ElementalDarknessDOT = core.DotSkill("엘리멘탈 : 다크니스(도트)", (80 + 40 + 50 + 50) * (2+1+1+1), 100000000).wrap(core.SummonSkillWrapper)
Heist = core.BuffSkill("헤이스트", 0, 180000, rem = True).wrap(core.BuffSkillWrapper)
Booster = core.BuffSkill("부스터", 0, 180000, rem = True).wrap(core.BuffSkillWrapper)
ShadowServent = core.BuffSkill("쉐도우 서번트", 990, 180000).wrap(core.BuffSkillWrapper)
SpiritThrowing = core.BuffSkill("스피릿 스로잉", 0, 180000, rem = True).wrap(core.BuffSkillWrapper)
ShadowBat = core.DamageSkill("쉐도우 배트", 0, 150 + 120 + 150 + 200 - 30, BATRATE).setV(vEhc, 1, 2, True).wrap(core.DamageSkillWrapper) #3회 공격당 1번 소환
#점샷기준(400ms)
QuintupleThrow = core.DamageSkill("퀸터플 스로우", (400 * JUMPRATE + 630 * (1-JUMPRATE)), 340, 4, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
QuintupleThrowFinal = core.DamageSkill("퀸터플 스로우(막타)", 0, 475, 1, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
QuintupleThrow_Sv = core.DamageSkill("퀸터플 스로우(서번트)", 0, 340*0.7, 4, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
QuintupleThrowFinal_Sv = core.DamageSkill("퀸터플 스로우(서번트)(막타)", 0, 475*0.7, 1, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
QuintupleThrow_I = core.DamageSkill("퀸터플 스로우(일루젼)", 0, 340*1.5, 4, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
QuintupleThrowFinal_I = core.DamageSkill("퀸터플 스로우(일루젼)(막타)", 0, 475*1.5, 1, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
QuintupleThrow_V = core.DamageSkill("퀸터플 스로우(5차)", 0, 340 * 0.01 * (20+vEhc.getV(0,0)), 4, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
QuintupleThrowFinal_V = core.DamageSkill("퀸터플 스로우(5차)(막타)", 0, 475 * 0.01 * (20+vEhc.getV(0,0)), 1, modifier = core.CharacterModifier(pdamage = 20, boss_pdamage = 20, crit = 10, pdamage_indep = (JUMPRATE*15))).setV(vEhc, 0, 2, False).wrap(core.DamageSkillWrapper)
#하이퍼스킬
ShadowElusion = core.BuffSkill("쉐도우 일루전", 990, 30000, cooltime = 180000).wrap(core.BuffSkillWrapper)
Dominion = core.BuffSkill("도미니언", 2680, 30000, crit = 100, pdamage_indep = 20, cooltime = 180000).wrap(core.BuffSkillWrapper)
DominionAttack = core.DamageSkill("도미니언(공격)", 0, 1000, 10).setV(vEhc, 2, 2, False).wrap(core.DamageSkillWrapper)
GloryOfGuardians = core.BuffSkill("글로리 오브 가디언즈", 0, 60*1000, cooltime = 120 * 1000, pdamage = 10).wrap(core.BuffSkillWrapper)
CygnusPalanks = cygnus.PhalanxChargeWrapper(vEhc, 4, 4)
ReadyToDie = thieves.ReadyToDieWrapper(vEhc, 3, 3)
ShadowSpear = core.BuffSkill("쉐도우 스피어", 600, (50+vEhc.getV(0,0))*1000, red = True, cooltime = (181-vEhc.getV(0,0)//2)*1000).isV(vEhc,0,0).wrap(core.BuffSkillWrapper)
ShadowSpearSmall = core.DamageSkill("쉐도우 스피어(창)", 0, 100+4*vEhc.getV(0,0), 4).isV(vEhc,0,0).wrap(core.DamageSkillWrapper)
ShadowSpearSmallBat = core.DamageSkill("쉐도우 스피어(창)(배트)", 0, 100+4*vEhc.getV(0,0), 4.0*BATRATE).isV(vEhc,0,0).wrap(core.DamageSkillWrapper)
ShadowSpearLarge = core.SummonSkill("쉐도우 스피어(거대 창)", 0, 3000, 400 + 32*vEhc.getV(0,0), 6, (50+vEhc.getV(0,0))*1000 - 1, cooltime = -1).isV(vEhc,0,0).wrap(core.SummonSkillWrapper)
ShadowServentExtend = core.BuffSkill("쉐도우 서번트 익스텐드", 570, (25+vEhc.getV(1,1))*1000, red = True, cooltime = 60000).isV(vEhc,1,1).wrap(core.BuffSkillWrapper)
ShadowBite = core.DamageSkill("쉐도우 바이트", 810, 600+24*vEhc.getV(2,2), 14).isV(vEhc,2,2).wrap(core.DamageSkillWrapper)
ShadowBiteBuff = core.BuffSkill("쉐도우 바이트(버프)", 0, (15+vEhc.getV(2,2)//10)*1000, pdamage_indep = (8+vEhc.getV(2,2)//4), red = True, cooltime = 20000).isV(vEhc,2,2).wrap(core.BuffSkillWrapper)
###### Skill Wrapper ######
#_VenomBurst = core.DamageSkill("베놈 버스트", ??) ## 패시브 50%확률로 10초간 160+6*vlevel dot. 사용시 도트뎀 모두 피해 + (500+20*vlevel) * 5. 어차피 안쓰는 스킬이므로 작성X
ShadowSpearTickBat = core.OptionalElement(ShadowSpear.is_active, ShadowSpearSmallBat, name = "스피어ON")
ShadowSpearTick = core.OptionalElement(ShadowSpear.is_active, ShadowSpearSmall, name = "스피어ON")
ShadowSpear.onAfter(ShadowSpearLarge)
for start, end in [[QuintupleThrow, QuintupleThrowFinal],
[QuintupleThrow_Sv, QuintupleThrowFinal_Sv],
[QuintupleThrow_I, QuintupleThrowFinal_I],
[QuintupleThrow_V, QuintupleThrowFinal_V]]:
start.onAfter(end)
for i in [start, end]:
i.onAfter(ShadowBat)
i.onAfter(ShadowSpearTick)
#ShadowBat.onAfter(ShadowSpearTickBat)
QuintupleThrow_Shadow = core.OptionalElement(ShadowElusion.is_active, QuintupleThrow_I, QuintupleThrow_Sv, name = "일루전 여부")
QuintupleThrow_V_Use = core.OptionalElement(ShadowServentExtend.is_active, QuintupleThrow_V, name = "익스텐드 여부")
QuintupleThrow.onAfters([QuintupleThrow_Shadow, QuintupleThrow_V_Use])
#도미니언
Dominion.onAfter(DominionAttack)
#쉐도우 바이트
ShadowBiteBuff.onAfter(ShadowBite)
return( QuintupleThrow,
[globalSkill.maple_heros(chtr.level), globalSkill.useful_sharp_eyes(),
ElementalDarkness, Heist, Booster, ShadowServent, SpiritThrowing,
ShadowElusion, ReadyToDie, Dominion, GloryOfGuardians, ShadowSpear, ShadowServentExtend, ShadowBiteBuff,
globalSkill.soul_contract()] +\
[CygnusPalanks] +\
[ElementalDarknessDOT, ShadowSpearLarge] +\
[] +\
[QuintupleThrow])
|
rudneff/ClickHouse
|
dbms/src/Functions/tests/logical_functions_performance.cpp
|
<filename>dbms/src/Functions/tests/logical_functions_performance.cpp<gh_stars>1-10
#include <DB/DataTypes/DataTypesNumberFixed.h>
#include <DB/Functions/IFunction.h>
#include <DB/Common/Stopwatch.h>
#include <iomanip>
namespace DB
{
template<typename B>
struct AndImpl
{
static inline UInt8 apply(UInt8 a, B b)
{
return a && b;
}
};
template<typename B>
struct OrImpl
{
static inline UInt8 apply(UInt8 a, B b)
{
return a || b;
}
};
template<typename B>
struct XorImpl
{
static inline UInt8 apply(UInt8 a, B b)
{
return (!a) != (!b);
}
};
using UInt8Container = ColumnUInt8::Container_t;
using UInt8ColumnPtrs = std::vector<const ColumnUInt8 *>;
template <typename Op, size_t N>
struct AssociativeOperationImpl
{
/// Выбрасывает N последних столбцов из in (если их меньше, то все) и кладет в result их комбинацию.
static void execute(UInt8ColumnPtrs & in, UInt8Container & result)
{
if (N > in.size())
{
AssociativeOperationImpl<Op, N - 1>::execute(in, result);
return;
}
AssociativeOperationImpl<Op, N> operation(in);
in.erase(in.end() - N, in.end());
size_t n = result.size();
for (size_t i = 0; i < n; ++i)
{
result[i] = operation.apply(i);
}
}
const UInt8Container & vec;
AssociativeOperationImpl<Op, N - 1> continuation;
/// Запоминает последние N столбцов из in.
AssociativeOperationImpl(UInt8ColumnPtrs & in)
: vec(in[in.size() - N]->getData()), continuation(in) {}
/// Возвращает комбинацию значений в i-й строке всех столбцов, запомненных в конструкторе.
inline UInt8 apply(size_t i) const
{
//return vec[i] ? continuation.apply(i) : 0;
return Op::apply(vec[i], continuation.apply(i));
//return vec[i] && continuation.apply(i);
}
};
template <typename Op>
struct AssociativeOperationImpl<Op, 1>
{
static void execute(UInt8ColumnPtrs & in, UInt8Container & result)
{
throw Exception("Logical error: AssociativeOperationImpl<Op, 1>::execute called", ErrorCodes::LOGICAL_ERROR);
}
const UInt8 * vec;
AssociativeOperationImpl(UInt8ColumnPtrs & in)
: vec(&in[in.size() - 1]->getData()[0]) {}
inline UInt8 apply(size_t i) const
{
return vec[i];
}
};
template <template <typename> class Impl, typename Name>
class FunctionAnyArityLogical : public IFunction
{
private:
bool extractConstColumns(ColumnPlainPtrs & in, UInt8 & res)
{
bool has_res = false;
for (int i = static_cast<int>(in.size()) - 1; i >= 0; --i)
{
if (in[i]->isConst())
{
Field val = (*in[i])[0];
UInt8 x = !!val.get<UInt64>();
if (has_res)
{
res = Impl<UInt8>::apply(res, x);
}
else
{
res = x;
has_res = true;
}
in.erase(in.begin() + i);
}
}
return has_res;
}
template <typename T>
bool convertTypeToUInt8(const IColumn * column, UInt8Container & res)
{
auto col = typeid_cast<const ColumnVector<T> *>(column);
if (!col)
return false;
const typename ColumnVector<T>::Container_t & vec = col->getData();
size_t n = res.size();
for (size_t i = 0; i < n; ++i)
{
res[i] = !!vec[i];
}
return true;
}
void convertToUInt8(const IColumn * column, UInt8Container & res)
{
if (!convertTypeToUInt8< Int8 >(column, res) &&
!convertTypeToUInt8< Int16>(column, res) &&
!convertTypeToUInt8< Int32>(column, res) &&
!convertTypeToUInt8< Int64>(column, res) &&
!convertTypeToUInt8< UInt16>(column, res) &&
!convertTypeToUInt8< UInt32>(column, res) &&
!convertTypeToUInt8< UInt64>(column, res) &&
!convertTypeToUInt8<Float32>(column, res) &&
!convertTypeToUInt8<Float64>(column, res))
throw Exception("Unexpected type of column: " + column->getName(), ErrorCodes::ILLEGAL_COLUMN);
}
template <typename T>
bool executeUInt8Type(const UInt8Container & uint8_vec, IColumn * column, UInt8Container & res)
{
auto col = typeid_cast<const ColumnVector<T> *>(column);
if (!col)
return false;
const typename ColumnVector<T>::Container_t & other_vec = col->getData();
size_t n = res.size();
for (size_t i = 0; i < n; ++i)
{
res[i] = Impl<T>::apply(uint8_vec[i], other_vec[i]);
}
return true;
}
void executeUInt8Other(const UInt8Container & uint8_vec, IColumn * column, UInt8Container & res)
{
if (!executeUInt8Type< Int8 >(uint8_vec, column, res) &&
!executeUInt8Type< Int16>(uint8_vec, column, res) &&
!executeUInt8Type< Int32>(uint8_vec, column, res) &&
!executeUInt8Type< Int64>(uint8_vec, column, res) &&
!executeUInt8Type< UInt16>(uint8_vec, column, res) &&
!executeUInt8Type< UInt32>(uint8_vec, column, res) &&
!executeUInt8Type< UInt64>(uint8_vec, column, res) &&
!executeUInt8Type<Float32>(uint8_vec, column, res) &&
!executeUInt8Type<Float64>(uint8_vec, column, res))
throw Exception("Unexpected type of column: " + column->getName(), ErrorCodes::ILLEGAL_COLUMN);
}
public:
/// Получить имя функции.
String getName() const
{
return Name::get();
}
/// Получить типы результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
DataTypePtr getReturnType(const DataTypes & arguments) const
{
if (arguments.size() < 2)
throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
+ toString(arguments.size()) + ", should be at least 2.",
ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
for (size_t i = 0; i < arguments.size(); ++i)
{
if (!arguments[i]->isNumeric())
throw Exception("Illegal type ("
+ arguments[i]->getName()
+ ") of " + toString(i + 1) + " argument of function " + getName(),
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
}
return std::make_shared<DataTypeUInt8>();
}
/// Выполнить функцию над блоком.
void execute(Block & block, const ColumnNumbers & arguments, size_t result)
{
//Stopwatch sw;
ColumnPlainPtrs in(arguments.size());
for (size_t i = 0; i < arguments.size(); ++i)
{
in[i] = block.getByPosition(arguments[i]).column.get();
}
size_t n = in[0]->size();
/// Скомбинируем все константные столбцы в одно значение.
UInt8 const_val = 0;
bool has_consts = extractConstColumns(in, const_val);
// Если это значение однозначно определяет результат, вернем его.
if (has_consts && (in.empty() || Impl<UInt8>::apply(const_val, 0) == Impl<UInt8>::apply(const_val, 1)))
{
if (!in.empty())
const_val = Impl<UInt8>::apply(const_val, 0);
auto col_res = std::make_shared<ColumnConst<UInt8>>(n, const_val);
block.getByPosition(result).column = col_res;
return;
}
/// Если это значение - нейтральный элемент, забудем про него.
if (has_consts && Impl<UInt8>::apply(const_val, 0) == 0 && Impl<UInt8>::apply(const_val, 1) == 1)
has_consts = false;
auto col_res = std::make_shared<ColumnUInt8>();
block.getByPosition(result).column = col_res;
UInt8Container & vec_res = col_res->getData();
if (has_consts)
{
vec_res.assign(n, const_val);
in.push_back(col_res.get());
}
else
{
vec_res.resize(n);
}
/// Разделим входные столбцы на UInt8 и остальные. Первые обработаем более эффективно.
/// col_res в каждый момент будет либо находится в конце uint8_in, либо не содержаться в uint8_in.
UInt8ColumnPtrs uint8_in;
ColumnPlainPtrs other_in;
for (IColumn * column : in)
{
if (auto uint8_column = typeid_cast<const ColumnUInt8 *>(column))
uint8_in.push_back(uint8_column);
else
other_in.push_back(column);
}
/// Нужен хотя бы один столбец в uint8_in, чтобы было с кем комбинировать столбцы из other_in.
if (uint8_in.empty())
{
if (other_in.empty())
throw Exception("Hello, I'm a bug", ErrorCodes::LOGICAL_ERROR);
convertToUInt8(other_in.back(), vec_res);
other_in.pop_back();
uint8_in.push_back(col_res.get());
}
/// Эффективно скомбинируем все столбцы правильного типа.
while (uint8_in.size() > 1)
{
AssociativeOperationImpl<Impl<UInt8>, 10>::execute(uint8_in, vec_res);
uint8_in.push_back(col_res.get());
}
/// По одному добавим все столбцы неправильного типа.
while (!other_in.empty())
{
executeUInt8Other(uint8_in[0]->getData(), other_in.back(), vec_res);
other_in.pop_back();
uint8_in[0] = col_res.get();
}
/// Такое возможно, если среди аргументов ровно один неконстантный, и он имеет тип UInt8.
if (uint8_in[0] != col_res.get())
{
vec_res.assign(uint8_in[0]->getData());
}
//double seconds = sw.elapsedSeconds();
//std::cerr << seconds << " seconds" << std::endl;
}
};
struct NameAnd { static const char * get() { return "and"; } };
struct NameOr { static const char * get() { return "or"; } };
struct NameXor { static const char * get() { return "xor"; } };
using FunctionAnd = FunctionAnyArityLogical <AndImpl, NameAnd>;
using FunctionOr = FunctionAnyArityLogical <OrImpl, NameOr> ;
using FunctionXor = FunctionAnyArityLogical <XorImpl, NameXor>;
}
using namespace DB;
int main(int argc, char ** argv)
{
try
{
size_t block_size = 1 << 20;
if (argc > 1)
{
block_size = atoi(argv[1]);
if (block_size < 50)
block_size = 1l << block_size;
}
size_t block_count = (100000000 - 1) / block_size + 1;
size_t columns = 10;
size_t repeats = 3;
std::vector<Block> blocks(block_count);
for (size_t b = 0; b < block_count; ++b)
{
for (size_t i = 0; i < columns; ++i)
{
auto column = std::make_shared<ColumnUInt8>(block_size);
blocks[b].insert(ColumnWithTypeAndName(column, std::make_shared<DataTypeUInt8>(), "v" + toString(i)));
ColumnUInt8::Container_t & vec = column->getData();
vec.resize(block_size);
for (size_t j = 0; j < block_size; ++j)
{
vec[j] = rand() % 2;
}
}
}
for (size_t b = 0; b < block_count; ++b)
{
auto result_column = std::make_shared<ColumnUInt8>();
blocks[b].insert(ColumnWithTypeAndName(result_column, std::make_shared<DataTypeUInt8>(), "x"));
result_column->getData().resize(block_size);
}
for (size_t arity = 2; arity <= columns; ++arity)
{
FunctionPtr function = std::make_shared<FunctionAnd>();
function->getReturnType(DataTypes(arity, DataTypePtr(std::make_shared<DataTypeUInt8>())));
ColumnNumbers arguments(arity);
for (size_t i = 0; i < arity; ++i)
{
arguments[i] = i;
}
std::cerr << arity << "-ary:" << std::endl;
Stopwatch outer_sw;
for (size_t i = 0; i < repeats; ++i)
{
Stopwatch inner_sw;
for (size_t b = 0; b < block_count; ++b)
{
function->execute(blocks[b], arguments, columns);
}
std::cerr << "iteration " << i + 1 << ": " << std::setprecision(3) << inner_sw.elapsedSeconds() << " seconds." << std::endl;
}
double seconds = outer_sw.elapsedSeconds();
std::cout << arity << "-ary average: " << std::setprecision(3) << seconds / repeats << " seconds, " << seconds / repeats / (arity - 1) << " seconds per operation." << std::endl;
}
}
catch (Exception & e)
{
std::cerr << "exception" << std::endl;
}
return 0;
}
|
zjp693/Learning-diary
|
2019年下学期/每日作业/js基础/Js基础-day13-10.10/02.总和.js
|
<filename>2019年下学期/每日作业/js基础/Js基础-day13-10.10/02.总和.js
//2. 100以内7的倍数的总和(while实现)
var a=1
var b=0
while(a<100){
a%7==0
b+=a
a++
}console.log(b);
|
PatrickShaw/QuixBugs
|
correct_python_programs/kth.py
|
<reponame>PatrickShaw/QuixBugs<filename>correct_python_programs/kth.py
def kth(arr, k):
pivot = arr[0]
below = [x for x in arr if x < pivot]
above = [x for x in arr if x > pivot]
num_less = len(below)
num_lessoreq = len(arr) - len(above)
if k < num_less:
return kth(below, k)
elif k >= num_lessoreq:
return kth(above, k - num_lessoreq)
else:
return pivot
|
ebubekirtrkr/gef
|
tests/functions/elf_sections.py
|
"""
GDB function test module for ELF section convenience functions
"""
from tests.utils import _target, gdb_run_cmd, gdb_run_silent_cmd, gdb_start_silent_cmd, is_64b
from tests.utils import GefUnitTestGeneric
class ElfSectionGdbFunction(GefUnitTestGeneric):
"""GDB functions test module"""
def test_func_base(self):
"""`$_base()` GDB function test"""
cmd = "x/s $_base()"
self.assertFailIfInactiveSession(gdb_run_cmd(cmd))
res = gdb_start_silent_cmd(cmd)
self.assertNoException(res)
self.assertIn("\\177ELF", res)
addr = res.splitlines()[-1].split()[0][:-1]
cmd = "x/s $_base(\"libc\")"
res = gdb_start_silent_cmd(cmd)
self.assertNoException(res)
self.assertIn("\\177ELF", res)
addr2 = res.splitlines()[-1].split()[0][:-1]
self.assertNotEqual(addr, addr2)
def test_func_bss(self):
"""`$_bss()` GDB function test"""
cmd = "deref $_bss()"
target = _target("bss")
self.assertFailIfInactiveSession(gdb_run_cmd(cmd, target=target))
res = gdb_run_silent_cmd(cmd, target=target)
self.assertNoException(res)
self.assertIn("Hello world!", res)
def test_func_got(self):
"""`$_got()` GDB function test"""
cmd = "deref $_got()"
target = _target("heap")
self.assertFailIfInactiveSession(gdb_run_cmd(cmd, target=target))
res = gdb_run_silent_cmd(cmd, target=target)
self.assertNoException(res)
self.assertIn("malloc", res)
def test_func_heap(self):
"""`$_heap()` GDB function test"""
cmd = "deref $_heap()"
target = _target("heap")
self.assertFailIfInactiveSession(gdb_run_cmd(cmd, target=target))
res = gdb_run_silent_cmd(cmd, target=target)
self.assertNoException(res)
if is_64b():
self.assertIn("+0x0048:", res)
else:
self.assertIn("+0x0024:", res)
cmd = "deref $_heap(0x10+0x10)"
res = gdb_run_silent_cmd(cmd, target=target)
self.assertNoException(res)
if is_64b():
self.assertIn("+0x0048:", res)
else:
self.assertIn("+0x0024:", res)
def test_func_stack(self):
"""`$_stack()` GDB function test"""
cmd = "deref $_stack()"
self.assertFailIfInactiveSession(gdb_run_cmd(cmd))
res = gdb_start_silent_cmd(cmd)
self.assertNoException(res)
if is_64b():
self.assertRegex(res, r"\+0x0*20: *0x0000000000000000\n")
else:
self.assertRegex(res, r"\+0x0.*20: *0x00000000\n")
|
agrc/parole-and-probation
|
src/ClientApp/src/components/Filters/FilterAgent/FilterAgent.stories.js
|
<gh_stars>0
import * as React from 'react';
import { useImmerReducer } from 'use-immer';
import { agents, supervisors } from '../lookupData';
import FilterAgent from './FilterAgent';
/* eslint import/no-anonymous-default-export: [2, {"allowObject": true}] */
export default {
title: 'Filters/Agent Filter',
component: FilterAgent,
argTypes: {
dispatch: { action: 'dispatched' },
},
};
const vanityUser = {
value: 'somebody famous',
id: 999,
};
const defaultAgent = {
loggedInUser: vanityUser,
agentList: [],
supervisor: null,
vanity: true,
};
const vanityCheck = (agentList, loggedInUser) => {
console.log(`Filters:vanity check for ${loggedInUser.value}`);
const agentArray = Array.from(agentList);
return agentArray.some((item) => item.value.toLowerCase() === loggedInUser.value.toLowerCase());
};
export const Empty = (args) => {
const [criteria, dispatcher] = useImmerReducer(
(draft, action) => {
console.log(`Filter:reducing state ${action.type}`, action);
switch (action.type) {
case 'UPDATE_AGENT_LIST': {
if (action.meta === 'agent') {
if (action.payload.add) {
if (
draft.agent.agentList.some(
(item) => item.value.toLowerCase() === action.payload.item.value.toLowerCase()
)
) {
return;
}
draft.agent.agentList = [action.payload.item].concat(draft.agent.agentList);
} else {
draft.agent.supervisorList = [];
draft.agent.agentList = draft.agent.agentList.filter(
(item) => item.value.toLowerCase() !== action.payload.item.value.toLowerCase()
);
}
} else if (action.meta === 'supervisor') {
if (draft.agent.vanity && !vanityCheck(draft.agent.agentList, draft.agent.loggedInUser)) {
draft.agent.agentList = agents.some(
(item) => item.value.toLowerCase() === draft.agent.loggedInUser.value.toLowerCase()
);
}
if (!action.payload.supervisor) {
draft.agent.agentList = [];
if (draft.agent.vanity) {
draft.agent.agentList = agents.some(
(item) => item.value.toLowerCase() === draft.agent.loggedInUser.value.toLowerCase()
);
}
} else {
draft.agent.agentList = [];
draft.agent.supervisor = [];
if (draft.agent.vanity) {
draft.agent.agentList.push(draft.agent.loggedInUser);
}
const agentsForSupervisor = agents.filter(
(agent) => agent.supervisor_Id.toLowerCase() === action.payload.supervisor.id.toLowerCase()
);
draft.agent.supervisor = [action.payload.supervisor];
draft.agent.agentList = draft.agent.agentList.concat(agentsForSupervisor);
}
}
draft.agent.vanity = vanityCheck(draft.agent.agentList, draft.agent.loggedInUser);
return;
}
default:
throw new Error();
}
},
{
agent: {
...defaultAgent,
vanity: false,
},
}
);
return (
<FilterAgent
data={{ agents, supervisors }}
criteria={criteria.agent}
update={(action) => {
dispatcher(action);
args.dispatch(action);
}}
/>
);
};
export const Vanity = (args) => {
const [criteria, dispatcher] = useImmerReducer(
(draft, action) => {
console.log(`Filter:reducing state ${action.type}`, action);
switch (action.type) {
case 'UPDATE_AGENT_LIST': {
if (action.meta === 'agent') {
if (action.payload.add) {
if (
draft.agent.agentList.some(
(item) => item.value.toLowerCase() === action.payload.item.value.toLowerCase()
)
) {
return;
}
draft.agent.agentList = [action.payload.item].concat(draft.agent.agentList);
} else {
draft.agent.supervisorList = [];
draft.agent.agentList = draft.agent.agentList.filter(
(item) => item.value.toLowerCase() !== action.payload.item.value.toLowerCase()
);
}
} else if (action.meta === 'supervisor') {
if (draft.agent.vanity && !vanityCheck(draft.agent.agentList, draft.agent.loggedInUser)) {
draft.agent.agentList = agents.some(
(item) => item.value.toLowerCase() === draft.agent.loggedInUser.value.toLowerCase()
);
}
if (!action.payload.supervisor) {
draft.agent.agentList = [];
if (draft.agent.vanity) {
draft.agent.agentList = agents.some(
(item) => item.value.toLowerCase() === draft.agent.loggedInUser.value.toLowerCase()
);
}
} else {
draft.agent.agentList = [];
draft.agent.supervisor = [];
if (draft.agent.vanity) {
draft.agent.agentList.push(draft.agent.loggedInUser);
}
const agentsForSupervisor = agents.filter(
(agent) => agent.supervisor_Id.toLowerCase() === action.payload.supervisor.id.toLowerCase()
);
draft.agent.supervisor = [action.payload.supervisor];
draft.agent.agentList = draft.agent.agentList.concat(agentsForSupervisor);
}
}
draft.agent.vanity = vanityCheck(draft.agent.agentList, draft.agent.loggedInUser);
return;
}
default:
throw new Error();
}
},
{
agent: {
...defaultAgent,
agentList: [vanityUser],
},
}
);
return (
<FilterAgent
data={{ agents, supervisors }}
criteria={criteria.agent}
update={(action) => {
dispatcher(action);
args.dispatch(action);
}}
/>
);
};
export const AgentsSelected = (args) => {
const [criteria, dispatcher] = useImmerReducer(
(draft, action) => {
console.log(`Filter:reducing state ${action.type}`, action);
switch (action.type) {
case 'UPDATE_AGENT_LIST': {
if (action.meta === 'agent') {
if (action.payload.add) {
if (
draft.agent.agentList.some(
(item) => item.value.toLowerCase() === action.payload.item.value.toLowerCase()
)
) {
return;
}
draft.agent.agentList = [action.payload.item].concat(draft.agent.agentList);
} else {
draft.agent.supervisorList = [];
draft.agent.agentList = draft.agent.agentList.filter(
(item) => item.value.toLowerCase() !== action.payload.item.value.toLowerCase()
);
}
} else if (action.meta === 'supervisor') {
if (draft.agent.vanity && !vanityCheck(draft.agent.agentList, draft.agent.loggedInUser)) {
draft.agent.agentList = agents.some(
(item) => item.value.toLowerCase() === draft.agent.loggedInUser.value.toLowerCase()
);
}
if (!action.payload.supervisor) {
draft.agent.agentList = [];
if (draft.agent.vanity) {
draft.agent.agentList = agents.some(
(item) => item.value.toLowerCase() === draft.agent.loggedInUser.value.toLowerCase()
);
}
} else {
draft.agent.agentList = [];
draft.agent.supervisor = [];
if (draft.agent.vanity) {
draft.agent.agentList.push(draft.agent.loggedInUser);
}
const agentsForSupervisor = agents.filter(
(agent) => agent.supervisor_Id.toLowerCase() === action.payload.supervisor.id.toLowerCase()
);
draft.agent.supervisor = [action.payload.supervisor];
draft.agent.agentList = draft.agent.agentList.concat(agentsForSupervisor);
}
}
draft.agent.vanity = vanityCheck(draft.agent.agentList, draft.agent.loggedInUser);
return;
}
default:
throw new Error();
}
},
{
agent: {
...defaultAgent,
vanity: false,
agentList: [
{
id: -1,
value: 'Storybook',
supervisor: 'Airbnb',
},
],
},
}
);
return (
<FilterAgent
data={{ agents, supervisors }}
criteria={criteria.agent}
update={(action) => {
dispatcher(action);
args.dispatch(action);
}}
/>
);
};
|
JohnsonMauro/rocket-lab
|
src/components/common/Form/TextArea/TextArea.spec.js
|
import React from 'react';
import { render } from '@testing-library/react';
import GlobalsContainer from '@test/GlobalsContainer';
import TextArea from './index';
describe('<TextArea />', () => {
it('Renders the TextArea component', () => {
const { container } = render(
<TextArea id="sample" maxLength="2000" name="sample" rows="5" />,
{
wrapper: GlobalsContainer,
}
);
expect(container).toMatchSnapshot();
});
});
|
bluebackblue/brownie
|
source/bsys/opengl/opengl_shaderlayout.cpp
|
<reponame>bluebackblue/brownie
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief OpenGL。
*/
/** include
*/
#include <bsys_pch.h>
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../types/types.h"
#pragma warning(pop)
/** include
*/
#include "./opengl_shaderlayout.h"
/** warning
4710 : この関数はインライン展開のために選択されましたが、コンパイラはインライン展開を実行しませんでした。
*/
#pragma warning(disable:4710)
/** NBsys::NOpengl
*/
#if(BSYS_OPENGL_ENABLE)
namespace NBsys{namespace NOpengl
{
/** constructor
*/
Opengl_ShaderLayout::Opengl_ShaderLayout()
{
}
/** destructor
*/
Opengl_ShaderLayout::~Opengl_ShaderLayout()
{
}
/** AddItem
*/
void Opengl_ShaderLayout::AddItem(Opengl_ShaderLayout::Item& a_item)
{
this->list.push_back(a_item);
}
/** IsBusy
*/
bool Opengl_ShaderLayout::IsBusy() const
{
u32 ii_max = static_cast<u32>(this->list.size());
for(u32 ii=0;ii<ii_max;ii++){
if(this->list[ii].vertex_fileobject->IsBusy() == true){
return true;
}
if(this->list[ii].fragment_fileobject->IsBusy() == true){
return true;
}
}
return false;
}
/** GetMax
*/
s32 Opengl_ShaderLayout::GetMax() const
{
return static_cast<s32>(this->list.size());
}
/** GetItem
*/
Opengl_ShaderLayout::Item& Opengl_ShaderLayout::GetItem(s32 a_index)
{
return this->list[static_cast<std::size_t>(a_index)];
}
}}
#endif
|
yuanbaojian/OpenOlat
|
src/main/java/org/olat/resource/references/ReferenceManager.java
|
/**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <hr>
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
*/
package org.olat.resource.references;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.olat.basesecurity.GroupRoles;
import org.olat.basesecurity.OrganisationRoles;
import org.olat.core.commons.persistence.DB;
import org.olat.core.gui.translator.Translator;
import org.olat.core.id.Identity;
import org.olat.core.id.OLATResourceable;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.StringHelper;
import org.olat.core.util.Util;
import org.olat.course.CourseFactory;
import org.olat.course.CourseModule;
import org.olat.course.ICourse;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryEntryManagedFlag;
import org.olat.repository.manager.RepositoryEntryDAO;
import org.olat.repository.manager.RepositoryEntryRelationDAO;
import org.olat.resource.OLATResource;
import org.olat.resource.OLATResourceImpl;
import org.olat.resource.OLATResourceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Initial Date: May 27, 2004
*
* @author <NAME>
*
* Comment:
*
*/
@Service("referenceManager")
public class ReferenceManager {
private static final OLog log = Tracing.createLoggerFor(ReferenceManager.class);
@Autowired
private DB dbInstance;
@Autowired
private RepositoryEntryDAO repositoryEntryDAO;
@Autowired
private OLATResourceManager olatResourceManager;
@Autowired
private RepositoryEntryRelationDAO reToGroupDao;
/**
* Add a new reference. The meaning of source and target is
* such as the source references the target.
*
* @param source
* @param target
* @param userdata
*/
public void addReference(OLATResourceable source, OLATResourceable target, String userdata) {
OLATResourceImpl sourceImpl = (OLATResourceImpl)olatResourceManager.findResourceable(source);
OLATResourceImpl targetImpl = (OLATResourceImpl)olatResourceManager.findResourceable(target);
ReferenceImpl ref = new ReferenceImpl();
ref.setSource(sourceImpl);
ref.setTarget(targetImpl);
ref.setUserdata(userdata);
ref.setCreationDate(new Date());
dbInstance.getCurrentEntityManager().persist(ref);
}
/**
* List all references the source holds.
*
* @param source
* @return List of renerences.
*/
public List<Reference> getReferences(OLATResourceable source) {
Long sourceKey = getResourceKey(source);
if (sourceKey == null) {
return new ArrayList<>(0);
}
return dbInstance.getCurrentEntityManager()
.createNamedQuery("referencesBySourceId", Reference.class)
.setParameter("sourceKey", sourceKey)
.getResultList();
}
/**
* List all sources which hold references to the target.
*
* @param target
* @return List of references.
*/
public List<Reference> getReferencesTo(OLATResourceable target) {
Long targetKey = getResourceKey(target);
if (targetKey == null) {
return new ArrayList<>(0);
}
return dbInstance.getCurrentEntityManager()
.createNamedQuery("referencesByTargetId", Reference.class)
.setParameter("targetKey", targetKey)
.getResultList();
}
public List<Reference> getReferencesTo(OLATResourceable target, String sourceResName) {
Long targetKey = getResourceKey(target);
if (targetKey == null) {
return new ArrayList<>(0);
}
StringBuilder sb = new StringBuilder();
sb.append("select v");
sb.append(" from references as v");
sb.append(" where v.target.key = :targetKey");
sb.append(" and v.source.resName = :resName");
return dbInstance.getCurrentEntityManager()
.createQuery(sb.toString(), Reference.class)
.setParameter("targetKey", targetKey)
.setParameter("resName", sourceResName)
.getResultList();
}
public List<RepositoryEntry> getRepositoryReferencesTo(OLATResourceable target) {
Long targetKey = getResourceKey(target);
StringBuilder sb = new StringBuilder();
sb.append("select v from ").append(RepositoryEntry.class.getName()).append(" as v")
.append(" where v.olatResource in (select ref.source from references as ref where ref.target.key=:targetKey)");
return dbInstance.getCurrentEntityManager()
.createQuery(sb.toString(), RepositoryEntry.class)
.setParameter("targetKey", targetKey)
.getResultList();
}
public List<ReferenceInfos> getReferencesInfos(List<RepositoryEntry> res, Identity identity) {
if(res == null || res.isEmpty()) return Collections.emptyList();
List<Long> sourceKeys = new ArrayList<>();
for(RepositoryEntry re:res) {
sourceKeys.add(re.getOlatResource().getKey());
}
StringBuilder sb = new StringBuilder();
sb.append("select ref from references ref")
.append(" where ref.target.key in (select orig.target.key from references orig where orig.source.key in (:sourceKeys))");
List<Reference> references = dbInstance.getCurrentEntityManager()
.createQuery(sb.toString(), Reference.class)
.setParameter("sourceKeys", sourceKeys)
.getResultList();
Set<Long> targetResourceKeys = new HashSet<>();
Set<Long> notOrphansResourceKeys = new HashSet<>();
for(Iterator<Reference> itRef = references.iterator(); itRef.hasNext(); ) {
Reference reference = itRef.next();
OLATResource source = reference.getSource();
OLATResource target = reference.getTarget();
targetResourceKeys.add(target.getKey());
if(!sourceKeys.contains(source.getKey())) {
notOrphansResourceKeys.add(target.getKey());
}
}
List<RepositoryEntry> entries = repositoryEntryDAO.loadByResourceKeys(targetResourceKeys);
List<ReferenceInfos> infos = new ArrayList<>(entries.size());
for(RepositoryEntry entry:entries) {
Long resourceKey = entry.getOlatResource().getKey();
boolean notOrphan = notOrphansResourceKeys.contains(resourceKey);
boolean deleteManaged = RepositoryEntryManagedFlag.isManaged(entry, RepositoryEntryManagedFlag.delete);
boolean isOwner = reToGroupDao.hasRole(identity, entry, true,
OrganisationRoles.administrator.name(), OrganisationRoles.learnresourcemanager.name(),
GroupRoles.owner.name());
infos.add(new ReferenceInfos(entry, !notOrphan, isOwner, deleteManaged));
}
return infos;
}
/**
* find the references source -> target -> source
*
*
* @param source
* @return
*/
public List<Reference> getReferencesOfReferences(OLATResource source) {
StringBuilder sb = new StringBuilder();
sb.append("select ref from references ref")
.append(" where ref.source.key != :sourceKey and ref.target.key in (select orig.target.key from references orig where orig.source.key=:sourceKey)");
return dbInstance.getCurrentEntityManager()
.createQuery(sb.toString(), Reference.class)
.setParameter("sourceKey", source.getKey())
.getResultList();
}
private Long getResourceKey(OLATResourceable resource) {
Long sourceKey;
if(resource instanceof OLATResource) {
sourceKey = ((OLATResource)resource).getKey();
} else {
OLATResource sourceImpl = olatResourceManager.findResourceable(resource);
if (sourceImpl == null) {
sourceKey = null;
} else {
sourceKey = sourceImpl.getKey();
}
}
return sourceKey;
}
/**
* Get an HTML summary of existing references or null if no references exist.
* @param target
* @param locale
* @return HTML fragment or null if no references exist.
*/
public String getReferencesToSummary(OLATResourceable target, Locale locale) {
Translator translator = Util.createPackageTranslator(this.getClass(), locale);
StringBuilder result = new StringBuilder(100);
List<Reference> refs = getReferencesTo(target);
if (refs.size() == 0) return null;
for (Reference ref:refs) {
if(result.length() > 0) result.append(", ");
OLATResource source = ref.getSource();
// special treatment for referenced courses: find out the course title
if (source.getResourceableTypeName().equals(CourseModule.getCourseTypeName())) {
try {
ICourse course = CourseFactory.loadCourse(source);
result.append(translator.translate("ref.course", new String[] { StringHelper.escapeHtml(course.getCourseTitle()) }));
} catch (Exception e) {
log.error("", e);
result.append(translator.translate("ref.course", new String[] { "<strike>" + source.getKey().toString() + "</strike>" }));
}
} else {
result.append(source.getKey().toString());
}
}
return result.toString();
}
public List<String> getReferencesToSummary(OLATResourceable target) {
List<Reference> refs = getReferencesTo(target);
List<String> refNames = new ArrayList<>(refs.size());
if (refs.size() > 0) {
for (Reference ref:refs) {
OLATResource source = ref.getSource();
// special treatment for referenced courses: find out the course title
if (source.getResourceableTypeName().equals(CourseModule.getCourseTypeName())) {
try {
ICourse course = CourseFactory.loadCourse(source);
refNames.add(StringHelper.escapeHtml(course.getCourseTitle()));
} catch (Exception e) {
log.error("", e);
refNames.add("<strike>" + source.getKey().toString() + "</strike>");
}
} else {
refNames.add(source.getKey().toString());
}
}
}
return refNames;
}
/**
* Delete all references of an OLAT-resource as source or target.
* @param olatResource an OLAT-Resource
*/
public int deleteAllReferencesOf(OLATResource olatResource) {
String dq = "delete from references as refs where refs.source.key=:resourceKey or refs.target.key=:resourceKey";
return dbInstance.getCurrentEntityManager().createQuery(dq)
.setParameter("resourceKey", olatResource.getKey())
.executeUpdate();
}
/**
* @param ref
*/
public void delete(Reference ref) {
ReferenceImpl reloadedRef = dbInstance.getCurrentEntityManager()
.getReference(ReferenceImpl.class, ref.getKey());
dbInstance.getCurrentEntityManager().remove(reloadedRef);
}
}
|
pjhartout/Apollo
|
nextjs-app/views/SelectSetsView.js
|
<filename>nextjs-app/views/SelectSetsView.js
import DragDrop from "../components/DragDrop";
import SetTile from "../components/SetTile";
import styles from "./SelectSetsView.module.scss";
const SelectSetsView = (
<>
<h1 className={styles.pageTitle}>Select Gene Sets</h1>
<h2 className={styles.subTitle}>Group Tissues</h2>
<p className={styles.paragraph}>
You can group the selected tissues by dragging and dropping them in the
cards below. By default, GTEx and TCGA tissues are put in separate groups.
You can choose to either take the intersection or the union of the
selected genes of the tissues in a group.
</p>
<DragDrop />
<h2 className={styles.subTitle}>Euler Diagram</h2>
<p className={styles.paragraph}>
The Euler diagram below provides an intuitive visualization of the size
and intersection of the selected gene sets. Select a specific region of
the diagram to select a gene set for further analysis.
</p>
<SetTile />
</>
);
export default SelectSetsView;
|
gameblabla/reeee3
|
src/core/config.h
|
<filename>src/core/config.h
#pragma once
// disables (most) stuff that wasn't in original gta3.exe - check section at the bottom of this file
//#define VANILLA_DEFINES
enum Config {
NUMPLAYERS = 1, // 4 on PS2
NUMCDIMAGES = 12, // gta3.img duplicates (not used on PC)
MAX_CDIMAGES = 8, // additional cdimages
MAX_CDCHANNELS = 5,
MODELINFOSIZE = 5500, // 3150 on PS2
#if defined __MWERKS__ || defined VANILLA_DEFINES
TXDSTORESIZE = 850,
#else
TXDSTORESIZE = 1024, // for Xbox map
#endif
EXTRADIRSIZE = 128,
CUTSCENEDIRSIZE = 512,
SIMPLEMODELSIZE = 5000, // 2910 on PS2
MLOMODELSIZE = 1,
MLOINSTANCESIZE = 1,
TIMEMODELSIZE = 30,
CLUMPMODELSIZE = 5,
PEDMODELSIZE = 90,
VEHICLEMODELSIZE = 120, // 70 on PS2
XTRACOMPSMODELSIZE = 2,
TWODFXSIZE = 2000, // 1210 on PS2
MAXVEHICLESLOADED = 50, // 70 on mobile
NUMOBJECTINFO = 168, // object.dat
// Pool sizes
NUMPTRNODES = 30000, // 26000 on PS2
NUMENTRYINFOS = 5400, // 3200 on PS2
NUMPEDS = 140, // 90 on PS2
NUMVEHICLES = 110, // 70 on PS2
NUMBUILDINGS = 5500, // 4915 on PS2
NUMTREADABLES = 1214,
NUMOBJECTS = 450,
NUMDUMMIES = 2802, // 2368 on PS2
NUMAUDIOSCRIPTOBJECTS = 256,
NUMCUTSCENEOBJECTS = 50,
NUMANIMBLOCKS = 2,
NUMANIMATIONS = 250,
NUMTEMPOBJECTS = 30,
// Path data
NUM_PATHNODES = 4930,
NUM_CARPATHLINKS = 2076,
NUM_MAPOBJECTS = 1250,
NUM_PATHCONNECTIONS = 10260,
// Link list lengths
NUMALPHALIST = 20,
NUMALPHAENTITYLIST = 150,
NUMCOLCACHELINKS = 200,
NUMREFERENCES = 800,
// Zones
NUMAUDIOZONES = 36,
NUMZONES = 50,
NUMMAPZONES = 25,
// Cull zones
NUMCULLZONES = 512,
NUMATTRIBZONES = 288,
NUMZONEINDICES = 55000,
PATHNODESIZE = 4500,
NUMWEATHERS = 4,
NUMHOURS = 24,
NUMEXTRADIRECTIONALS = 4,
NUMANTENNAS = 8,
NUMCORONAS = 56,
NUMPOINTLIGHTS = 32,
NUM3DMARKERS = 32,
NUMBRIGHTLIGHTS = 32,
NUMSHINYTEXTS = 32,
NUMMONEYMESSAGES = 16,
NUMPICKUPMESSAGES = 16,
NUMBULLETTRACES = 16,
NUMMBLURSTREAKS = 4,
NUMSKIDMARKS = 32,
NUMONSCREENTIMERENTRIES = 1,
NUMRADARBLIPS = 32,
NUMGENERALPICKUPS = 320,
NUMSCRIPTEDPICKUPS = 16,
NUMPICKUPS = NUMGENERALPICKUPS + NUMSCRIPTEDPICKUPS,
NUMCOLLECTEDPICKUPS = 20,
NUMPACMANPICKUPS = 256,
NUMEVENTS = 64,
NUM_CARGENS = 160,
NUM_PATH_NODES_IN_AUTOPILOT = 8,
NUM_ACCIDENTS = 20,
NUM_FIRES = 40,
NUM_GARAGES = 32,
NUM_PROJECTILES = 32,
NUM_GLASSPANES = 45,
NUM_GLASSENTITIES = 32,
NUM_WATERCANNONS = 3,
NUMPEDROUTES = 200,
NUMPHONES = 50,
NUMPEDGROUPS = 31,
NUMMODELSPERPEDGROUP = 8,
NUMSHOTINFOS = 100,
NUMROADBLOCKS = 600,
NUMVISIBLEENTITIES = 2000,
NUMINVISIBLEENTITIES = 150,
NUM_AUDIOENTITY_EVENTS = 4,
NUM_PED_COMMENTS_BANKS = 2,
NUM_PED_COMMENTS_SLOTS = 20,
NUM_SOUNDS_SAMPLES_BANKS = 2,
NUM_SOUNDS_SAMPLES_SLOTS = 27,
NUM_AUDIOENTITIES = 200,
NUM_AUDIO_REFLECTIONS = 5,
NUM_SCRIPT_MAX_ENTITIES = 40,
NUM_GARAGE_STORED_CARS = 6,
NUM_CRANES = 8,
NUM_EXPLOSIONS = 48,
};
// We don't expect to compile for PS2 or Xbox
// but it might be interesting for documentation purposes
#define GTA_PC
//#define GTA_PS2
//#define GTA_XBOX
// This enables things from the PS2 version on PC
#define GTA_PS2_STUFF
// This is enabled for all released games.
// any debug stuff that isn't left in any game is not in FINAL
//#define FINAL
// This is enabled for all released games except mobile
// any debug stuff that is only left in mobile, is not in MASTER
//#define MASTER
// once and for all:
// pc: FINAL & MASTER
// mobile: FINAL
// MASTER builds must be FINAL
#ifdef MASTER
#define FINAL
#endif
// Version defines
#define GTA3_PS2_140 300
#define GTA3_PS2_160 301
#define GTA3_PC_10 310
#define GTA3_PC_11 311
#define GTA3_PC_STEAM 312
// TODO? maybe something for xbox or android?
#define GTA_VERSION GTA3_PC_11
// quality of life fixes that should also be in FINAL
#define NASTY_GAME // nasty game for all languages
#define NO_CDCHECK
// those infamous texts
#define DRAW_GAME_VERSION_TEXT
#ifdef DRAW_GAME_VERSION_TEXT
// unlike R* development builds, ours has runtime switch on debug menu & .ini, and disabled as default.
#define USE_OUR_VERSIONING // If you disable this then game will fetch version from peds.col, as R* did while in development
#endif
//#define DRAW_MENU_VERSION_TEXT
// Memory allocation and compression
// #define USE_CUSTOM_ALLOCATOR // use CMemoryHeap for allocation. use with care, not finished yet
//#define COMPRESSED_COL_VECTORS // use compressed vectors for collision vertices
//#define ANIM_COMPRESSION // only keep most recently used anims uncompressed
#if defined GTA_PS2
# define GTA_PS2_STUFF
# define RANDOMSPLASH
# define USE_CUSTOM_ALLOCATOR
# define VU_COLLISION
# define ANIM_COMPRESSION
#elif defined GTA_PC
# ifdef GTA_PS2_STUFF
# define USE_PS2_RAND
# define RANDOMSPLASH // use random splash as on PS2
# define PS2_MATFX
# endif
# define PC_PLAYER_CONTROLS // mouse player/cam mode
# define GTA_REPLAY
# define GTA_SCENE_EDIT
#elif defined GTA_XBOX
#endif
#ifdef VU_COLLISION
#define COMPRESSED_COL_VECTORS // currently need compressed vectors in this code
#endif
#ifdef MASTER
// only in master builds
#undef DRAW_GAME_VERSION_TEXT
#else
// not in master builds
#define VALIDATE_SAVE_SIZE
#define DEBUGMENU
#endif
#ifdef FINAL
// in all games
# define USE_MY_DOCUMENTS // use my documents directory for user files
#else
// not in any game
# define CHATTYSPLASH // print what the game is loading
# define TIMEBARS // print debug timers
#endif
#define FIX_BUGS // fixes bugs that we've came across during reversing. You can undefine this only on release builds.
#define MORE_LANGUAGES // Add more translations to the game
#define COMPATIBLE_SAVES // this allows changing structs while keeping saves compatible
#define LOAD_INI_SETTINGS // as the name suggests. fundamental for CUSTOM_FRONTEND_OPTIONS
#define NO_MOVIES // add option to disable intro videos
#if defined(__LP64__) || defined(_WIN64)
#define FIX_BUGS_64 // Must have fixes to be able to run 64 bit build
#endif
#define ASCII_STRCMP // use faster ascii str comparisons
#if !defined _WIN32 || defined __MWERKS__ || defined __MINGW32__ || defined VANILLA_DEFINES
#undef ASCII_STRCMP
#endif
// Just debug menu entries
#ifdef DEBUGMENU
#define MISSION_SWITCHER // from debug menu
#endif
// Rendering/display
//#define EXTRA_MODEL_FLAGS // from mobile to optimize rendering
//# define HARDCODED_MODEL_FLAGS // sets the flags enabled above from hardcoded model names.
// NB: keep this enabled unless your map IDEs have these flags baked in
#define ASPECT_RATIO_SCALE // Not just makes everything scale with aspect ratio, also adds support for all aspect ratios
#define PROPER_SCALING // use original DEFAULT_SCREEN_WIDTH/DEFAULT_SCREEN_HEIGHT from PS2 instead of PC(R* changed HEIGHT here to make radar look better, but broke other hud elements aspect ratio).
#define DEFAULT_NATIVE_RESOLUTION // Set default video mode to your native resolution (fixes Windows 10 launch)
#define USE_TXD_CDIMAGE // generate and load textures from txd.img
#define PS2_ALPHA_TEST // emulate ps2 alpha test
#define IMPROVED_VIDEOMODE // save and load videomode parameters instead of a magic number
#define DISABLE_LOADING_SCREEN // disable the loading screen which vastly improves the loading time
#ifdef DISABLE_LOADING_SCREEN
// enable the PC splash
#undef RANDOMSPLASH
#endif
#define DISABLE_VSYNC_ON_TEXTURE_CONVERSION // make texture conversion work faster by disabling vsync
#define ANISOTROPIC_FILTERING // set all textures to max anisotropic filtering
//#define USE_TEXTURE_POOL
#ifdef LIBRW
#define EXTENDED_COLOURFILTER // more options for colour filter (replaces mblur)
#define EXTENDED_PIPELINES // custom render pipelines (includes Neo)
#define SCREEN_DROPLETS // neo water droplets
#define NEW_RENDERER // leeds-like world rendering, needs librw
#endif
#define FIX_SPRITES // fix sprites aspect ratio(moon, coronas, particle etc)
#ifndef EXTENDED_COLOURFILTER
#undef SCREEN_DROPLETS // we need the backbuffer for this effect
#endif
// Particle
//#define PC_PARTICLE
//#define PS2_ALTERNATIVE_CARSPLASH // unused on PS2
// Pad
#if !defined(RW_GL3) && defined(_WIN32)
#define XINPUT
#endif
#if defined XINPUT || (defined RW_GL3 && !defined LIBRW_SDL2 && !defined __SWITCH__)
#define DETECT_JOYSTICK_MENU // Then we'll expect user to enter Controller->Detect joysticks if his joystick isn't detected at the start.
#endif
#define DETECT_PAD_INPUT_SWITCH // Adds automatic switch of pad related stuff between controller and kb/m
#define KANGAROO_CHEAT
#define ALLCARSHELI_CHEAT
#define ALT_DODO_CHEAT
#define REGISTER_START_BUTTON
#define BIND_VEHICLE_FIREWEAPON // Adds ability to rebind fire key for 'in vehicle' controls
#define BUTTON_ICONS // use textures to show controller buttons
// Hud, frontend and radar
//#define PS2_HUD
#define HUD_ENHANCEMENTS // Adjusts some aspects to make the HUD look/behave a little bit better.
// #define BETA_SLIDING_TEXT
#define TRIANGULAR_BLIPS // height indicating triangular radar blips, as in VC
#define FIX_RADAR // use radar size from early version before R* broke it
// #define XBOX_SUBTITLES // the infamous outlines
#define RADIO_OFF_TEXT
#define PC_MENU
#ifndef PC_MENU
# define PS2_MENU
//# define PS2_MENU_USEALLPAGEICONS
#else
# ifdef XINPUT
# define GAMEPAD_MENU // Add gamepad menu
# endif
# define SCROLLABLE_STATS_PAGE // only draggable by mouse atm
# define TRIANGLE_BACK_BUTTON
//# define CIRCLE_BACK_BUTTON
//# define PS2_LIKE_MENU // An effort to recreate PS2 menu, cycling through tabs, different bg etc.
//# define PS2_SAVE_DIALOG // PS2 style save dialog with transparent black box
# define CUSTOM_FRONTEND_OPTIONS
# ifdef CUSTOM_FRONTEND_OPTIONS
# define MENU_MAP // VC-like menu map. Won't appear if you don't have our menu.txd
# define GRAPHICS_MENU_OPTIONS // otherwise Display settings will be scrollable
# define NO_ISLAND_LOADING // disable loadscreen between islands via loading all island data at once, consumes more memory and CPU
# define CUTSCENE_BORDERS_SWITCH
# define MULTISAMPLING // adds MSAA option
# define INVERT_LOOK_FOR_PAD // add bInvertLook4Pad from VC
# endif
#endif
// Script
#define USE_DEBUG_SCRIPT_LOADER // Loads main.scm by default. Hold R for main_freeroam.scm and D for main_d.scm
#define USE_MEASUREMENTS_IN_METERS // makes game use meters instead of feet in script
#define USE_PRECISE_MEASUREMENT_CONVERTION // makes game convert feet to meeters more precisely
#ifdef PC_MENU
# define MISSION_REPLAY // mobile feature
#endif
//#define SIMPLIER_MISSIONS // apply simplifications from mobile
#define USE_ADVANCED_SCRIPT_DEBUG_OUTPUT
#define SCRIPT_LOG_FILE_LEVEL 0 // 0 == no log, 1 == overwrite every frame, 2 == full log
#if SCRIPT_LOG_FILE_LEVEL == 0
#undef USE_ADVANCED_SCRIPT_DEBUG_OUTPUT
#endif
#ifndef USE_ADVANCED_SCRIPT_DEBUG_OUTPUT
#define USE_BASIC_SCRIPT_DEBUG_OUTPUT
#endif
#ifdef MASTER
#undef USE_ADVANCED_SCRIPT_DEBUG_OUTPUT
#undef USE_BASIC_SCRIPT_DEBUG_OUTPUT
#endif
// Replay
//#define DONT_FIX_REPLAY_BUGS // keeps various bugs in CReplay, some of which are fairly cool!
//#define USE_BETA_REPLAY_MODE // adds another replay mode, a few seconds slomo (caution: buggy!)
// Vehicles
#define EXPLODING_AIRTRAIN // can blow up jumbo jet with rocket launcher
//#define REMOVE_TREADABLE_PATHFIND
// Pickups
//#define MONEY_MESSAGES
#define CAMERA_PICKUP
// Peds
#define PED_SKIN // support for skinned geometry on peds
#define ANIMATE_PED_COL_MODEL
// #define VC_PED_PORTS // various ports from VC's CPed, mostly subtle
// #define NEW_WALK_AROUND_ALGORITHM // to make walking around vehicles/objects less awkward
#define CANCELLABLE_CAR_ENTER
//#define PEDS_REPORT_CRIMES_ON_PHONE
// Camera
//#define PS2_CAM_TRANSITION // old way of transitioning between cam modes
#define IMPROVED_CAMERA // Better Debug cam, and maybe more in the future
#define FREE_CAM // Rotating cam
// Audio
#define RADIO_SCROLL_TO_PREV_STATION
#define AUDIO_CACHE
//#define PS2_AUDIO_PATHS // changes audio paths for cutscenes and radio to PS2 paths (needs vbdec on MSS builds)
//#define AUDIO_OAL_USE_SNDFILE // use libsndfile to decode WAVs instead of our internal decoder
#define AUDIO_OAL_USE_MPG123 // use mpg123 to support mp3 files
#ifdef AUDIO_OPUS
#define AUDIO_OAL_USE_OPUS // enable support of opus files
#define OPUS_AUDIO_PATHS // changes audio paths to opus paths (doesn't work if AUDIO_OAL_USE_OPUS isn't enabled)
#define OPUS_SFX // enable if your sfx.raw is encoded with opus (doesn't work if AUDIO_OAL_USE_OPUS isn't enabled)
#ifndef AUDIO_OAL_USE_OPUS
#undef OPUS_AUDIO_PATHS
#undef OPUS_SFX
#endif
#endif
// Streaming
#if !defined(_WIN32) && !defined(__SWITCH__)
//#define ONE_THREAD_PER_CHANNEL // Don't use if you're not on SSD/Flash - also not utilized too much right now(see commented LoadAllRequestedModels in Streaming.cpp)
#define FLUSHABLE_STREAMING // Make it possible to interrupt reading when processing file isn't needed anymore.
#endif
#define BIG_IMG // Not complete - allows to read larger img files
//#define SQUEEZE_PERFORMANCE
#ifdef SQUEEZE_PERFORMANCE
#undef PS2_ALPHA_TEST
#undef NO_ISLAND_LOADING
#define PC_PARTICLE
#define VC_PED_PORTS // To not process collisions always. But should be tested if that's really beneficial
#define VC_RAIN_NERF // Reduces number of rain particles
#endif
// -------
#if defined __MWERKS__ || defined VANILLA_DEFINES
#define FINAL
#undef CHATTYSPLASH
#undef TIMEBARS
//#define USE_MY_DOCUMENTS
#define MASTER
#undef VALIDATE_SAVE_SIZE
#undef NO_MOVIES
#undef DEBUGMENU
//#undef NASTY_GAME
//#undef NO_CDCHECK
#undef DRAW_GAME_VERSION_TEXT
#undef DRAW_MENU_VERSION_TEXT
#undef GTA_PS2_STUFF
#undef USE_PS2_RAND
#undef RANDOMSPLASH
#undef PS2_MATFX
#undef FIX_BUGS
#define THIS_IS_STUPID
#undef MORE_LANGUAGES
#undef COMPATIBLE_SAVES
#undef LOAD_INI_SETTINGS
#undef ASPECT_RATIO_SCALE
#undef PROPER_SCALING
//#undef DEFAULT_NATIVE_RESOLUTION
#undef PS2_ALPHA_TEST
#undef IMPROVED_VIDEOMODE
#undef DISABLE_LOADING_SCREEN
#undef DISABLE_VSYNC_ON_TEXTURE_CONVERSION
#undef ANISOTROPIC_FILTERING
//#define USE_TEXTURE_POOL // not possible because R* used custom RW33
#undef FIX_SPRITES
#define PC_PARTICLE
#undef XINPUT
#undef DETECT_PAD_INPUT_SWITCH
#undef KANGAROO_CHEAT
#undef ALLCARSHELI_CHEAT
#undef ALT_DODO_CHEAT
#undef REGISTER_START_BUTTON
#undef BIND_VEHICLE_FIREWEAPON
#undef BUTTON_ICONS
#undef HUD_ENHANCEMENTS
#undef TRIANGULAR_BLIPS
#undef FIX_RADAR
#undef RADIO_OFF_TEXT
#undef MENU_MAP
#undef GAMEPAD_MENU
#undef SCROLLABLE_STATS_PAGE
#undef CUSTOM_FRONTEND_OPTIONS
#undef GRAPHICS_MENU_OPTIONS
#undef NO_ISLAND_LOADING
#undef CUTSCENE_BORDERS_SWITCH
#undef MULTISAMPLING
#undef INVERT_LOOK_FOR_PAD
#undef USE_DEBUG_SCRIPT_LOADER
#undef USE_MEASUREMENTS_IN_METERS
#undef USE_PRECISE_MEASUREMENT_CONVERTION
#undef MISSION_REPLAY
#undef USE_ADVANCED_SCRIPT_DEBUG_OUTPUT
#undef USE_BASIC_SCRIPT_DEBUG_OUTPUT
#define DONT_FIX_REPLAY_BUGS
#undef EXPLODING_AIRTRAIN
#undef CAMERA_PICKUP
#undef PED_SKIN
#undef ANIMATE_PED_COL_MODEL
#undef CANCELLABLE_CAR_ENTER
#undef IMPROVED_CAMERA
#undef FREE_CAM
#undef RADIO_SCROLL_TO_PREV_STATION
#undef BIG_IMG
#endif
|
KadonWills/EasyMove
|
src/main/java/entities/Reservations.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author nkengasong
*/
@Entity
@Table(name = "reservations", catalog = "easymove", schema = "")
@NamedQueries({
@NamedQuery(name = "Reservations.findAll", query = "SELECT r FROM Reservations r"),
@NamedQuery(name = "Reservations.findByUsersId", query = "SELECT r FROM Reservations r WHERE r.reservationsPK.usersId = :usersId"),
@NamedQuery(name = "Reservations.findByTripsId", query = "SELECT r FROM Reservations r WHERE r.reservationsPK.tripsId = :tripsId"),
@NamedQuery(name = "Reservations.findByReservationDate", query = "SELECT r FROM Reservations r WHERE r.reservationDate = :reservationDate"),
@NamedQuery(name = "Reservations.findByQuantity", query = "SELECT r FROM Reservations r WHERE r.quantity = :quantity")})
public class Reservations implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected ReservationsPK reservationsPK;
@Column(name = "reservation_date")
@Temporal(TemporalType.TIMESTAMP)
private Date reservationDate;
@Column(name = "quantity")
private Integer quantity;
@JoinColumn(name = "trips_id", referencedColumnName = "trips_id", nullable = false, insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Trips trips;
@JoinColumn(name = "users_id", referencedColumnName = "users_id", nullable = false, insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Users users;
public Reservations() {
}
public Reservations(ReservationsPK reservationsPK) {
this.reservationsPK = reservationsPK;
}
public Reservations(int usersId, int tripsId) {
this.reservationsPK = new ReservationsPK(usersId, tripsId);
}
public ReservationsPK getReservationsPK() {
return reservationsPK;
}
public void setReservationsPK(ReservationsPK reservationsPK) {
this.reservationsPK = reservationsPK;
}
public Date getReservationDate() {
return reservationDate;
}
public void setReservationDate(Date reservationDate) {
this.reservationDate = reservationDate;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Trips getTrips() {
return trips;
}
public void setTrips(Trips trips) {
this.trips = trips;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
@Override
public int hashCode() {
int hash = 0;
hash += (reservationsPK != null ? reservationsPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Reservations)) {
return false;
}
Reservations other = (Reservations) object;
if ((this.reservationsPK == null && other.reservationsPK != null) || (this.reservationsPK != null && !this.reservationsPK.equals(other.reservationsPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entities.Reservations[ reservationsPK=" + reservationsPK + " ]";
}
}
|
sniperkit/colly
|
plugins/data/aggregate/api/krakend/extra/config/flexibleconfig/template.go
|
<gh_stars>0
package flexibleconfig
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/devopsfaith/krakend/config"
)
type Config struct {
Settings string
Partials string
Parser config.Parser
}
func NewTemplateParser(cfg Config) *TemplateParser {
t := &TemplateParser{
Partials: cfg.Partials,
Parser: cfg.Parser,
Vars: map[string]interface{}{},
}
if cfg.Settings != "" {
files, err := ioutil.ReadDir(cfg.Settings)
if err != nil {
fmt.Println("error reading settings folder:", cfg.Settings, err)
files = []os.FileInfo{}
}
for _, settingsFile := range files {
b, err := ioutil.ReadFile(filepath.Join(cfg.Settings, settingsFile.Name()))
if err != nil {
fmt.Println("error procesing settings:", settingsFile, err)
continue
}
var v map[string]interface{}
if err := json.Unmarshal(b, &v); err != nil {
fmt.Println("error procesing settings:", settingsFile, err)
continue
}
t.Vars[strings.TrimRight(filepath.Base(settingsFile.Name()), ".json")] = v
}
}
return t
}
type TemplateParser struct {
Vars map[string]interface{}
Partials string
Parser config.Parser
}
func (t *TemplateParser) Parse(configFile string) (config.ServiceConfig, error) {
tmpfile, err := ioutil.TempFile("", "KrakenD_parsed_config_template_")
if err != nil {
log.Fatal("creating the tmp file:", err)
}
defer os.Remove(tmpfile.Name())
var buf bytes.Buffer
tmpl, err := t.newConfigTemplate().ParseFiles(configFile)
if err != nil {
log.Fatal("parsing files:", err)
return t.Parser.Parse(configFile)
}
err = tmpl.ExecuteTemplate(&buf, filepath.Base(configFile), t.Vars)
if err != nil {
log.Fatal("executing template:", err)
return t.Parser.Parse(configFile)
}
if _, err = tmpfile.Write(buf.Bytes()); err != nil {
log.Fatal("writting the tmp config:", err)
return t.Parser.Parse(configFile)
}
if err = tmpfile.Close(); err != nil {
log.Fatal("closing the tmp config:", err)
}
filename := tmpfile.Name() + ".json"
if err := os.Rename(tmpfile.Name(), filename); err != nil {
return config.ServiceConfig{}, err
}
return t.Parser.Parse(filename)
}
func (t *TemplateParser) newConfigTemplate() *template.Template {
return template.New("config").Funcs(template.FuncMap{
"marshal": t.marshal,
"include": t.include,
})
}
func (t *TemplateParser) marshal(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
}
func (t *TemplateParser) include(v interface{}) string {
a, _ := ioutil.ReadFile(path.Join(t.Partials, v.(string)))
return string(a)
}
|
LambdaCalculus37/little-smalltalk
|
lst5/iup/include/iupcontrols.h
|
<filename>lst5/iup/include/iupcontrols.h
/** \file
* \brief initializes iupdial, iupgauge, iuptabs, iupcb, iupgc and iupval controls.
*
* See Copyright Notice in iup.h
* $Id: iupcontrols.h,v 1.17 2005/12/07 17:53:16 scuri Exp $
*/
#ifndef __IUPCONTROLS_H
#define __IUPCONTROLS_H
#include "iupdial.h"
#include "iupgauge.h"
#include "iuptabs.h"
#include "iupval.h"
#include "iupmatrix.h"
#include "iuptree.h"
#include "iupsbox.h"
#include "iupmask.h"
#include "iupgc.h"
#include "iupcb.h"
#include "iupspin.h"
#include "iupcolorbar.h"
#include "iupgetparam.h"
#include "iupcbox.h"
#include "iupcells.h"
#ifdef __cplusplus
extern "C" {
#endif
int IupControlsOpen(void);
void IupControlsClose(void);
void IupImageLibOpen (void);
void IupImageLibClose (void);
#ifdef __cplusplus
}
#endif
#endif
|
lvdongww/schoolnewvs
|
schoolnewvs/src/main/java/com/kgc/pojo/XiaoXi.java
|
<gh_stars>0
package com.kgc.pojo;
import java.util.Date;
public class XiaoXi {
private Integer xid;
private Integer chid;
private Integer zhu;
private String neirong;
private Date createdate;
private Integer xtype;
public Integer getXid() {
return xid;
}
public void setXid(Integer xid) {
this.xid = xid;
}
public Integer getChid() {
return chid;
}
public void setChid(Integer chid) {
this.chid = chid;
}
public Integer getZhu() {
return zhu;
}
public void setZhu(Integer zhu) {
this.zhu = zhu;
}
public String getNeirong() {
return neirong;
}
public void setNeirong(String neirong) {
this.neirong = neirong == null ? null : neirong.trim();
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
public Integer getXtype() {
return xtype;
}
public void setXtype(Integer xtype) {
this.xtype = xtype;
}
}
|
tak2004/RadonFramework
|
include/RadonFramework/Math/MathOfType.hpp
|
<gh_stars>1-10
#ifndef RF_MATH_MATHOFTYPE_HPP
#define RF_MATH_MATHOFTYPE_HPP
#if _MSC_VER > 1000
#pragma once
#endif
#include <RadonFramework/Math/Float32.hpp>
#include <RadonFramework/Math/Float64.hpp>
namespace RadonFramework::Math
{
template <class T>
struct MathOfType
{
};
template <>
struct MathOfType<RF_Type::Float32> : public Float32
{
};
template <>
struct MathOfType<RF_Type::Float64> : public Float64
{
};
} // namespace RadonFramework::Math
#ifndef RF_SHORTHAND_NAMESPACE_MATH
#define RF_SHORTHAND_NAMESPACE_MATH
namespace RF_Math = RadonFramework::Math;
#endif
#endif // RF_MATH_MATHOFTYPE_HPP
|
burdettadam/token-plugin
|
sovtokenfees/sovtokenfees/test/catchup/test_xfer_fees_nym_during_catchup.py
|
import pytest
from sovtokenfees.test.constants import (
NYM_FEES_ALIAS, XFER_PUBLIC_FEES_ALIAS, alias_to_txn_type
)
from sovtokenfees.test.catchup.helper import scenario_txns_during_catchup
@pytest.fixture(
scope='module',
params=[
{NYM_FEES_ALIAS: 0, XFER_PUBLIC_FEES_ALIAS: 8}, # no fees for NYM
{NYM_FEES_ALIAS: 4, XFER_PUBLIC_FEES_ALIAS: 8}, # fees for both
{NYM_FEES_ALIAS: 0, XFER_PUBLIC_FEES_ALIAS: 0}, # no fees
{NYM_FEES_ALIAS: 4, XFER_PUBLIC_FEES_ALIAS: 0}, # no fees for XFER_PUBLIC
], ids=lambda x: '-'.join(sorted([alias_to_txn_type[k] for k, v in x.items() if v])) or 'nofees'
)
def fees(request):
return request.param
def test_xfer_fees_nym_during_catchup(
looper, tconf, tdir, allPluginsPath,
do_post_node_creation,
nodeSetWithIntegratedTokenPlugin,
fees_set,
mint_multiple_tokens,
send_and_check_xfer,
send_and_check_nym,
):
def send_txns():
send_and_check_xfer()
send_and_check_nym()
scenario_txns_during_catchup(
looper, tconf, tdir, allPluginsPath, do_post_node_creation,
nodeSetWithIntegratedTokenPlugin,
send_txns
)
|
dk-dev/absurd
|
tests/cases/document/test.spec.js
|
describe("Test case (Document)", function() {
var Absurd = require('../../../index.js');
it("Document / js", function(done) {
Absurd(__dirname + '/code.js').compile(function(err, css) {
expect(err).toBe(null);
expect(css).toBeDefined();
expect(css).toBe('@-moz-document url-prefix(){.ui-select .ui-btn select{opacity: .0001;}}');
done();
}, { minify: true });
});
it("Document / json", function(done) {
Absurd(__dirname + '/code.json').compile(function(err, css) {
expect(err).toBe(null);
expect(css).toBeDefined();
expect(css).toBe('@-moz-document url-prefix(){.ui-select .ui-btn select{opacity: .0001;}}');
done();
}, { minify: true });
});
it("Document / css", function(done) {
Absurd(__dirname + '/code.css').compile(function(err, css) {
expect(err).toBe(null);
expect(css).toBeDefined();
expect(css).toBe('@-moz-document url-prefix(){.ui-select .ui-btn select{opacity: .0001;}}');
done();
}, { minify: true });
});
});
|
hespinoza01/polporc-coding-challenge
|
src/components/navbar.component.js
|
<filename>src/components/navbar.component.js
import { NavLink as Link } from 'react-router-dom'
// Import assets
import { Logo } from 'assets'
export default function Navbar() {
return (
<section className='Navbar'>
<img className='Navbar-logo' src={Logo} alt='app-logo' />
<nav className='Navbar-nav'>
<Link
className='nav__item'
activeClassName='active'
exact
to='/'
>
Inicio
</Link>
<Link
className='nav__item'
activeClassName='active'
to='/history'
>
Historial
</Link>
</nav>
</section>
)
}
|
duanhaoling/LdhApps
|
androidlib/src/main/java/com/ldh/androidlib/utils/AbstractSingleton.java
|
<reponame>duanhaoling/LdhApps
package com.ldh.androidlib.utils;
import java.util.concurrent.atomic.AtomicReference;
/**
* Created by ldh on 2017/8/16.
*/
public abstract class AbstractSingleton<T> {
private final AtomicReference<T> ref = new AtomicReference<>();
public T get() {
T ret = ref.get();
if (ret == null) {
synchronized (this) {
if (ref.get() == null) {
ret = newInstance();
ref.set(ret);
} else {
ret = ref.get();
}
}
}
return ret;
}
protected abstract T newInstance();
}
|
boybin/n4backend
|
public/node_modules/angular-filter/test/spec/filter/string/latinize.js
|
<filename>public/node_modules/angular-filter/test/spec/filter/string/latinize.js<gh_stars>1000+
'use strict';
describe('latinizeFilter', function () {
var filter;
beforeEach(module('a8m.latinize'));
beforeEach(inject(function ($filter) {
filter = $filter('latinize');
}));
it('should get a string and replace accents/diacritics with the ASCII equivalent', function() {
expect(filter('a ç')).toEqual('a c');
expect(filter('föo bàr baz')).toEqual('foo bar baz');
expect(filter('Lòrém Ìpsûm dölôr sít Àmet')).toEqual('Lorem Ipsum dolor sit Amet');
});
it('should get a !string and not touch it', function() {
expect(filter({})).toEqual({});
expect(filter([])).toEqual([]);
expect(filter(1)).toEqual(1);
expect(filter(!1)).toBeFalsy();
});
});
|
GDGSXY/gdbtu-admin-back
|
src/main/java/org/springblade/common/tool/PageUtil.java
|
package org.springblade.common.tool;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springblade.common.entity.PagingQuery;
/**
* @author <NAME>
* @date 2021/10/31
*/
public interface PageUtil {
/**
* 获取 {@link PagingQuery} 中的 {@link com.baomidou.mybatisplus.core.metadata.IPage}
*
* @param query 分页查询
* @param <T> 实体类型
* @return IPage
*/
static <T> IPage<T> toPage(PagingQuery query) {
return new Page<>(query.getCurrent(), query.getSize());
}
}
|
ceekay1991/AliPayForDebug
|
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/O2OAnimatedImageView.h
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <UIKit/UIImageView.h>
#import "CALayerDelegate-Protocol.h"
@class CADisplayLink, NSMutableDictionary, NSObject, NSOperationQueue, NSString, UIImage, YZAnimationImage;
@protocol OS_dispatch_semaphore;
@interface O2OAnimatedImageView : UIImageView <CALayerDelegate>
{
NSString *_runLoopMode;
_Bool _initFinished;
_Bool _shouldCustomLoopCount;
_Bool _bufferMiss;
_Bool _shouldAnimate;
UIImage *_currentFrame;
unsigned long long _currentFrameIndex;
unsigned long long _currentLoopCount;
unsigned long long _maxBufferSize;
unsigned long long _totalFrameCount;
unsigned long long _totalLoopCount;
YZAnimationImage *_animatedImage;
NSMutableDictionary *_frameBuffer;
double _currentTime;
unsigned long long _maxBufferCount;
NSOperationQueue *_fetchQueue;
NSObject<OS_dispatch_semaphore> *_lock;
double _animatedImageScale;
CADisplayLink *_displayLink;
}
+ (id)decodedImageWithImage:(id)arg1;
+ (id)defaultRunLoopMode;
@property(retain, nonatomic) CADisplayLink *displayLink; // @synthesize displayLink=_displayLink;
@property(nonatomic) double animatedImageScale; // @synthesize animatedImageScale=_animatedImageScale;
@property(retain, nonatomic) NSObject<OS_dispatch_semaphore> *lock; // @synthesize lock=_lock;
@property(retain, nonatomic) NSOperationQueue *fetchQueue; // @synthesize fetchQueue=_fetchQueue;
@property(nonatomic) unsigned long long maxBufferCount; // @synthesize maxBufferCount=_maxBufferCount;
@property(nonatomic) _Bool shouldAnimate; // @synthesize shouldAnimate=_shouldAnimate;
@property(nonatomic) _Bool bufferMiss; // @synthesize bufferMiss=_bufferMiss;
@property(nonatomic) double currentTime; // @synthesize currentTime=_currentTime;
@property(retain, nonatomic) NSMutableDictionary *frameBuffer; // @synthesize frameBuffer=_frameBuffer;
@property(retain, nonatomic) YZAnimationImage *animatedImage; // @synthesize animatedImage=_animatedImage;
@property(nonatomic) unsigned long long totalLoopCount; // @synthesize totalLoopCount=_totalLoopCount;
@property(nonatomic) unsigned long long totalFrameCount; // @synthesize totalFrameCount=_totalFrameCount;
@property(nonatomic) unsigned long long maxBufferSize; // @synthesize maxBufferSize=_maxBufferSize;
@property(nonatomic) _Bool shouldCustomLoopCount; // @synthesize shouldCustomLoopCount=_shouldCustomLoopCount;
@property(nonatomic) unsigned long long currentLoopCount; // @synthesize currentLoopCount=_currentLoopCount;
@property(nonatomic) unsigned long long currentFrameIndex; // @synthesize currentFrameIndex=_currentFrameIndex;
@property(retain, nonatomic) UIImage *currentFrame; // @synthesize currentFrame=_currentFrame;
- (void).cxx_destruct;
- (void)calculateMaxBufferCount;
- (void)displayLayer:(id)arg1;
- (_Bool)isInVisibleRect;
- (void)displayDidRefresh:(id)arg1;
- (void)updateShouldAnimate;
- (void)setHighlighted:(_Bool)arg1;
- (_Bool)isAnimating;
- (void)stopAnimating;
- (void)startAnimating;
- (void)setHidden:(_Bool)arg1;
- (void)setAlpha:(double)arg1;
- (void)didMoveToWindow;
- (void)didMoveToSuperview;
- (void)didReceiveMemoryWarning:(id)arg1;
- (void)dealloc;
@property(copy, nonatomic) NSString *runLoopMode;
- (void)setImage:(id)arg1;
- (void)resetProgressiveImage;
- (void)resetAnimatedImage;
- (void)commonInit;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
- (id)initWithImage:(id)arg1 highlightedImage:(id)arg2;
- (id)initWithImage:(id)arg1;
// Remaining properties
@property(nonatomic) long long animationRepeatCount; // @dynamic animationRepeatCount;
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
vva0901/academic
|
src/components/Test/Filter.test.js
|
<filename>src/components/Test/Filter.test.js
import React from "react";
import { create } from "react-test-renderer";
import { StudentStatus, AllProgram } from "../Filter";
describe("StudentStatus Component", () => {
it("Test StudentStatus component it work", () => {
const component = create(<StudentStatus />).toJSON();
expect(component).toMatchSnapshot();
});
exports[`Rerender StudentStatus component`] = (
<StudentStatus list={[Array]} filterByStudentStatus={[Function]} />
);
it("Test AllProgram component it work", () => {
const component = create(<AllProgram />).toJSON();
expect(component).toMatchSnapshot();
});
exports[`Rerender AllProgram component`] = (
<AllProgram list={undefined} filterByProgram={[Function]} />
);
});
|
EvgeniyKuch/job4j
|
chapter_005/src/main/java/ru/job4j/bomberman/Start.java
|
<reponame>EvgeniyKuch/job4j<filename>chapter_005/src/main/java/ru/job4j/bomberman/Start.java
package ru.job4j.bomberman;
import java.util.concurrent.ThreadLocalRandom;
public class Start {
public static void main(String[] args) throws InterruptedException {
long timeStart = System.currentTimeMillis();
boolean gameOver = false;
Board board = new Board(5, 5);
board.setBlock(2, 2);
Thread monsterOne = new Thread(new Monster(board, 4, 4));
Thread monsterTwo = new Thread(new Monster(board, 4, 0));
monsterOne.setDaemon(true);
monsterTwo.setDaemon(true);
monsterOne.start();
monsterTwo.start();
Bomberman hero = new Bomberman(board, 0, 0);
while (!gameOver) {
Thread.sleep(50);
int rnd = ThreadLocalRandom.current().nextInt(4);
hero.move(rnd);
gameOver = hero.hasQueuedThreads();
}
System.out.println("Game Over. Game duration: "
+ (System.currentTimeMillis() - timeStart)
+ " milliseconds."
);
}
}
|
jrmarino/ravensource
|
bucket_8E/gdb/dragonfly/patch-gdb_i386-bsd-nat.c
|
<reponame>jrmarino/ravensource
--- gdb/i386-bsd-nat.c.orig 2021-04-25 04:06:26 UTC
+++ gdb/i386-bsd-nat.c
@@ -360,6 +360,8 @@ _initialize_i386bsd_nat ()
#define SC_REG_OFFSET i386nbsd_sc_reg_offset
#elif defined (OpenBSD)
#define SC_REG_OFFSET i386obsd_sc_reg_offset
+#elif defined (DragonFly)
+#define SC_REG_OFFSET i386dfly_sc_reg_offset
#endif
#ifdef SC_REG_OFFSET
|
nryotaro/at_c
|
src/abc122/we_like_agc.cc
|
<gh_stars>0
#include <iostream>
using namespace std;
int a = 0;
int g = 1;
int c = 2;
int t = 3;
long long we_like_agc(int n){
long long mod = 1000000007;
long long ans[100][4][4][4][4] = {{{{{0}}}}};
if(n == 3)
return 61;
for(int j=0;j<4;j++) {
for(int k=0;k<4;k++) {
for(int l=0;l<4;l++) {
for(int m=0;m<4;m++) {
ans[3][j][k][l][m] = 0;
if((j == a && k == g && l == c) ||
(j == g && k == a && l == c) ||
(j == a && k == c && l == g) ||
(j == a && k == g && m == c) ||
( k == a && l == g && m == c) ||
(j == a && l == g && m == c) ||
( k == g && l == a && m == c) ||
( k == a && l == c && m == g)){
continue;
}
ans[3][j][k][l][m] = 1;
}
}
}
}
for(int i=4;i<n;i++) {
for(int j=0;j<4;j++) {
for(int k=0;k<4;k++) {
for(int l=0;l<4;l++) {
for(int m=0;m<4;m++) {
ans[i][j][k][l][m] = 0;
if((j == a && k == g && l == c) ||
(j == g && k == a && l == c) ||
(j == a && k == c && l == g) ||
(j == a && k == g && m == c) ||
( k == a && l == g && m == c) ||
(j == a && l == g && m == c) ||
( k == g && l == a && m == c) ||
( k == a && l == c && m == g)){
continue;
}
for(int o = 0;o<4;o++) {
ans[i][j][k][l][m] += ans[i-1][o][j][k][l];
ans[i][j][k][l][m] = ans[i][j][k][l][m] % mod;
}
}
}
}
}
}
long long rtn = 0;
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
for(int k=0;k<4;k++) {
for(int l=0;l<4;l++) {
rtn += ans[n-1][i][j][k][l];
rtn = rtn % mod;
}
}
}
}
return rtn;
}
/*
int main() {
int n;
cin >> n;
cout << we_like_agc(n);
}
*/
|
andtu7/enciclovida
|
db/migrate/20160813001120_add_auto_increment_to_base32_id_in_comentarios.rb
|
<reponame>andtu7/enciclovida
class AddAutoIncrementToBase32IdInComentarios < ActiveRecord::Migration[5.1]
def up
change_table(:comentarios) do |t|
t.remove :id
t.integer :idConsecutivo
t.string :id, :limit => 10, :primary_key => true
end
end
def down
change_table(:comentarios) do |t|
t.remove :idConsecutivo
end
end
end
|
khemlabs/readium-sdk
|
Platform/WinRT/Readium/Readium/WinErrorHandler.cpp
|
<gh_stars>100-1000
//
// WinErrorHandler.cpp
// ePub3
//
// Created by <NAME> on 2013-10-04.
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT 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 "WinErrorHandler.h"
#include <atomic>
BEGIN_READIUM_API
static ErrorHandler^ __default_error_handler = nullptr;
static ErrorHandling^ __error_handling_singleton = nullptr;
ErrorHandling::ErrorHandling()
{
if (__error_handling_singleton != nullptr && __error_handling_singleton != this)
throw ref new ::Platform::COMException(E_NOT_VALID_STATE, TEXT("The ErrorHandling singleton already exists!"));
__default_error_handler = ref new ErrorHandler([](ErrorInfo^ error) {
return ::ePub3::DefaultErrorHandler(error->CppError);
});
}
ErrorHandling^ ErrorHandling::Instance()
{
static std::atomic_flag __once_flag;
if (__once_flag.test_and_set() == false)
{
__error_handling_singleton = ref new ErrorHandling();
}
return __error_handling_singleton;
}
ErrorHandler^ ErrorHandling::Default::get()
{
return __default_error_handler;
}
ErrorHandler^ ErrorHandling::Current::get()
{
auto nativeCurrent = ::ePub3::ErrorHandler();
return ref new ErrorHandler([nativeCurrent](ErrorInfo^ error) {
return nativeCurrent(error->CppError);
});
}
void ErrorHandling::Current::set(ErrorHandler^ newHandler)
{
if (newHandler == __default_error_handler)
::ePub3::SetErrorHandler(::ePub3::DefaultErrorHandler);
::ePub3::SetErrorHandler([newHandler](const ePub3::error_details& err) {
return newHandler->Invoke(ref new ErrorInfo(err));
});
}
void ErrorHandling::HandleError(EPUBError error)
{
::ePub3::HandleError(::ePub3::EPUBError(error));
}
void ErrorHandling::HandleError(EPUBError error, ::Platform::String^ message)
{
::ePub3::string str(StringToNative(message));
::ePub3::HandleError(::ePub3::EPUBError(error), str.c_str());
}
::Platform::String^ ErrorInfo::Message::get()
{
if (__message_cached_ == nullptr)
__message_cached_ = StringFromCString(__error_.message());
return __message_cached_;
}
::Platform::String^ ErrorInfo::Category::get()
{
if (__category_cached_ == nullptr)
__category_cached_ = StringFromCString(__error_.category().name());
return __category_cached_;
}
END_READIUM_API
|
mmjiang2019/ovs
|
datapath/linux/compat/include/linux/stddef.h
|
#ifndef __LINUX_STDDEF_WRAPPER_H
#define __LINUX_STDDEF_WRAPPER_H 1
#include_next <linux/stddef.h>
#ifdef __KERNEL__
#ifndef offsetofend
#define offsetofend(TYPE, MEMBER) \
(offsetof(TYPE, MEMBER) + sizeof(((TYPE *)0)->MEMBER))
#endif
#endif /* __KERNEL__ */
#endif
|
JSybrandt/SuperSpirograph
|
src/main/java/geometry/trackshape/package-info.java
|
/**
* the trackshape package defines a couple geometric classes used by objects in the piece.track package to know shape,
* connection points, and positioning data. Each specific track class inherits from the TrackGeometry abstract class
* which defines logic relating to those male and female connection points.
*
*/
package geometry.trackshape;
|
patricksyoussef/patrickyoussef.com
|
src/components/TableOfContents.js
|
// Not the best but she'll work for now
import React from "react"
import styled from "styled-components"
const Container = styled.div`
`
const getLinkedText = (title, url) => {
return(<a href={url}>{title}</a>)
}
const TableOfContents = ({toc}) => {
let length = toc.items.length
if (length > 4) {
return(
<Container>
<h2>Table of Contents</h2>
<ul>
{toc.items.map((item, index) => {
if (typeof item.items === "undefined") {
return(<li key={index.toString()}>{getLinkedText(item.title, item.url)}</li>)
} else {
return(
<li>
{getLinkedText(item.title, item.url)}
<ul key={index}>
{item.items.map((item, index) => {
return(<li key={index.toString()}>{getLinkedText(item.title, item.url)}</li>)
})}
</ul>
</li>)
}
})}
</ul>
</Container>)
} else {
return(<div></div>)
}
}
export default TableOfContents;
|
lirizhong97/learning-gtkmm
|
eventbox/examplewindow.cc
|
#include "examplewindow.h"
ExampleWindow::ExampleWindow()
: m_Label("Click here to quit, quit, quit, quit, quit")
{
set_title ("EventBox");
set_border_width(10);
add(m_EventBox);
m_EventBox.add(m_Label);
//Clip the label short:
m_Label.set_size_request(110, 20);
//And bind an action to it:
m_EventBox.set_events(Gdk::BUTTON_PRESS_MASK);
m_EventBox.signal_button_press_event().connect(
sigc::mem_fun(*this, &ExampleWindow::on_eventbox_button_press) );
m_EventBox.set_tooltip_text("Click me!");
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
bool ExampleWindow::on_eventbox_button_press(GdkEventButton*)
{
hide();
return true;
}
|
andrebq/exp
|
graphdb/node.go
|
<gh_stars>1-10
package main
import (
"strings"
)
// keyword is a shared identifier that can be used
// to identify node types, edge types and name properties
//
// All keywords should start with ":" to be considered valid
type Keyword struct {
name string
val uint32
}
// NewKeyword prepare the string to be used as a valid keyword
// if a invalid char is found then the returned keyword is marked
// as invalid and can't be used for processing
func NewKeyword(val string) *Keyword {
if !strings.HasPrefix(val, ":") {
val = ":" + val
}
return &Keyword{
name: val,
val: 0,
}
}
// String is a visual representation of the keyword
func (k *Keyword) String() string {
return k.name
}
// Valid return true only if the keyword can be used to identify a
// property and isn't a reserverd keyword
func (k *Keyword) Valid() bool {
return k.val >= minKeywordCode
}
// ValidName returns true when the name of the keyword
// can be used by the database.
func (k *Keyword) ValidName() bool {
return strings.HasPrefix(k.name, ":")
}
// Node represent the data stored in the graphdb
type Node struct {
// The identification of this given node
Id uint64
// The kind of a node
//
// Bob is a :user
Kind uint32
// The data related to this node
Props Properties
}
// Properties is a collection of keys and values (any valid Go type)
// that represent the data of a given node
type Properties map[uint32]interface{}
// Edge represent the connection between two nodes.
type Edge struct {
// Start and End hold the nodes involved in the relation
//
// Relations might be uni-direction but the default is to
// be bi-directional
Start, End uint64
// Kind is the identification of the Edge
//
// Bob :knows Alice, :knows is maped to a uint32 value
// and used as the Kind of the Edge
Kind uint32
// The data related describing this edge.
Props Properties
}
|
JoseLora/resilience4j
|
resilience4j-circularbuffer/src/main/java/io/github/resilience4j/circularbuffer/ConcurrentCircularFifoBuffer.java
|
/*
*
* Copyright 2016 <NAME> and <NAME>
*
* 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 io.github.resilience4j.circularbuffer;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Thread safe implementation of {@link CircularFifoBuffer} on top of {@link
* ConcurrentEvictingQueue}
**/
public class ConcurrentCircularFifoBuffer<T> implements CircularFifoBuffer<T> {
private final ConcurrentEvictingQueue<T> queue;
private final int capacity;
/**
* Creates an {@code ConcurrentCircularFifoBuffer} with the given (fixed) capacity
*
* @param capacity the capacity of this {@code ConcurrentCircularFifoBuffer}
* @throws IllegalArgumentException if {@code capacity < 1}
*/
public ConcurrentCircularFifoBuffer(int capacity) {
this.capacity = capacity;
queue = new ConcurrentEvictingQueue<>(capacity);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return queue.size();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return queue.isEmpty();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFull() {
return queue.size() == capacity;
}
/**
* {@inheritDoc}
*/
@Override
public List<T> toList() {
return List.copyOf(queue);
}
/**
* {@inheritDoc}
*/
@Override
public Stream<T> toStream() {
return queue.stream();
}
/**
* {@inheritDoc}
*/
@Override
public void add(T element) {
queue.offer(element);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<T> take() {
return Optional.ofNullable(queue.poll());
}
}
|
Maarc/spring-boot-migrator
|
applications/spring-shell/src/test/java/org/springframework/sbm/BootifyJpaApplicationIntegrationTest.java
|
<reponame>Maarc/spring-boot-migrator
/*
* Copyright 2021 - 2022 the original author or authors.
*
* 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
*
* https://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.springframework.sbm;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
public class BootifyJpaApplicationIntegrationTest extends IntegrationTestBaseClass {
@Override
protected String getTestSubDir() {
return "jpa-hibernate";
}
@Test
@Tag("integration")
void migrateJpaApplication() {
intializeTestProject();
executeMavenGoals(getTestDir(), "clean", "package");
scanProject();
assertApplicableRecipesContain(
"initialize-spring-boot-migration",
"migrate-stateless-ejb",
"migrate-jpa-to-spring-boot"
);
applyRecipe(
"initialize-spring-boot-migration",
"migrate-stateless-ejb",
"migrate-jpa-to-spring-boot"
);
// TODO: add assertions
}
}
|
diegoUE8/b-here
|
src/js/forms/control-asset.component.js
|
import { getContext, isPlatformBrowser } from 'rxcomp';
import { combineLatest, EMPTY, fromEvent, merge } from 'rxjs';
import { filter, map, switchMap, takeUntil, tap } from 'rxjs/operators';
import EditorService from '../editor/editor.service';
import { Asset } from '../view/view';
import ControlComponent from './control.component';
export default class ControlAssetComponent extends ControlComponent {
get image() {
let image = null;
if (this.control.value) {
image = `${this.control.value.folder}${this.control.value.file}`;
} else if (this.previews && this.previews.length) {
image = this.previews[0];
}
return image;
}
onInit() {
this.label = this.label || 'label';
this.disabled = this.disabled || false;
this.accept = this.accept || 'image/png, image/jpeg';
this.previews = [];
const { node } = getContext(this);
const input = node.querySelector('input');
input.setAttribute('accept', this.accept);
this.drop$(input).pipe(
takeUntil(this.unsubscribe$)
).subscribe();
this.change$(input).pipe(
takeUntil(this.unsubscribe$)
).subscribe(assets => {
console.log('ControlAssetComponent.change$', assets);
this.control.value = assets[0];
});
}
change$(input) {
if (isPlatformBrowser && input) {
return fromEvent(input, 'change').pipe(
filter((event) => input.files && input.files.length),
switchMap((event) => {
console.log('ControlAssetComponent.change$', input.files);
const fileArray = Array.from(input.files);
this.previews = fileArray.map(() => null);
const uploads$ = fileArray.map((file, i) => this.read$(file, i).pipe(
switchMap(() => EditorService.upload$([file])),
tap(uploads => console.log('upload', uploads)),
switchMap((uploads) => {
const upload = uploads[0];
/*
id: 1601303293569
type: "image/jpeg"
file: "1601303293569_ambiente1_x0_y2.jpg"
originalFileName: "ambiente1_x0_y2.jpg"
url: "/uploads/1601303293569_ambiente1_x0_y2.jpg"
*/
const asset = Asset.fromUrl(upload.url);
return EditorService.assetCreate$(asset);
}),
));
return combineLatest(uploads$);
})
);
} else {
return EMPTY;
}
}
read$(file, i) {
const reader = new FileReader();
const reader$ = fromEvent(reader, 'load').pipe(
tap(event => {
const blob = event.target.result;
this.resize_(blob, (resized) => {
this.previews[i] = resized;
this.pushChanges();
});
}),
);
reader.readAsDataURL(file);
return reader$;
}
drop$(input) {
if (isPlatformBrowser && input) {
const body = document.querySelector('body');
return merge(fromEvent(body, 'drop'), fromEvent(body, 'dragover')).pipe(
map((event) => {
console.log('ControlAssetComponent.drop$', event);
event.preventDefault();
if (event.target === input) {
input.files = event.dataTransfer.files;
}
return;
})
);
} else {
return EMPTY;
}
}
resize_(blob, callback) {
if (typeof callback === 'function') {
const img = document.createElement('img');
img.onload = function() {
const MAX_WIDTH = 320;
const MAX_HEIGHT = 240;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
const dataUrl = canvas.toDataURL('image/jpeg', 0.9);
callback(dataUrl);
};
img.src = blob;
}
}
}
ControlAssetComponent.meta = {
selector: '[control-asset]',
inputs: ['control', 'label', 'disabled', 'accept'],
template: /* html */ `
<div class="group--form" [class]="{ required: control.validators.length, disabled: disabled }">
<div class="control--head">
<label [innerHTML]="label"></label>
<span class="required__badge" [innerHTML]="'required' | label"></span>
</div>
<div class="group--picture">
<div class="group--picture__info">
<!-- <svg class="icon--image"><use xlink:href="#image"></use></svg> -->
<span [innerHTML]="'browse' | label"></span>
</div>
<img [lazy]="control.value | asset" [size]="{ width: 320, height: 240 }" *if="control.value && control.value.type.name === 'image'" />
<video [src]="control.value | asset" *if="control.value && control.value.type.name === 'video'"></video>
<input type="file">
</div>
<div class="file-name" *if="control.value" [innerHTML]="control.value.file"></div>
<!--
<input type="text" class="control--text" [formControl]="control" [placeholder]="label" [disabled]="disabled" />
-->
</div>
<errors-component [control]="control"></errors-component>
`
};
|
luckylove/extra
|
3.8.1.cpp
|
#include<bits/stdc++.h>
using namespace std;
int calculategcd(int a, int b)
{
if (a == 0)
return b;
return calculategcd(b%a, a);
}
int main()
{
int test,a,b,c,d,e,f,i,j,k,m,n,q,x,y,l,r,value,countt;
cin>>n;
int arr[n];
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cin>>q;
while(q--)
{
cin>>a;
if(a==1)
{
cin>>x;
cin>>y;
arr[x-1]=y;
}
else
{
cin>>l>>r>>value;
countt=0;
for(i=l-1;i<r;i++)
{
if(arr[i]%2!=0||value%2!=0)
{
if(calculategcd(arr[i],value)==1)
countt++;
}
}
cout<<countt<<endl;
}
}
}
|
getrdbc/rdbc
|
rdbc-implbase/src/main/scala/io/rdbc/implbase/IgnoringSubscriber.scala
|
<filename>rdbc-implbase/src/main/scala/io/rdbc/implbase/IgnoringSubscriber.scala<gh_stars>10-100
/*
* Copyright 2016 rdbc contributors
*
* 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 io.rdbc.implbase
import java.util.concurrent.atomic.AtomicBoolean
import io.rdbc.util.Preconditions.checkNotNull
import org.reactivestreams.{Subscriber, Subscription}
class IgnoringSubscriber extends Subscriber[Any] {
private val subscribed = new AtomicBoolean(false)
override def onError(t: Throwable): Unit = {
checkNotNull(t)
}
override def onSubscribe(s: Subscription): Unit = {
checkNotNull(s)
if (subscribed.compareAndSet(false, true)) {
s.request(Long.MaxValue)
} else s.cancel()
}
override def onComplete(): Unit = ()
override def onNext(elem: Any): Unit = {
checkNotNull(elem)
}
}
|
fabricio7p/Ikebana-App-Frontend
|
src/components/pages/Lessons/Lessons.js
|
import React, { useEffect, useState } from 'react';
import api from 'services/api';
import { useSelector } from 'react-redux';
import './styles.scss';
import LessonCard from '../../cards/LessonCard/LessonCard';
export default function Lessons() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const authKey = useSelector(state => state.auth.keys)
const fetchLessons = async (key=authKey) => {
try {
const response = await api({
method: 'get',
url: '/list',
})
setData(response.data.filter((el) => {
return el.type === 'lesson'
}))
} catch(e) {
console.log(e)
} finally {
setLoading(false)
}
}
useEffect(() => {
window.scrollTo(0, 0)
fetchLessons()
},[])
return(
<div className="lessons-main">
<div className="lessons-main__list">
{
data.map((el, key) => <LessonCard key={key} {...el}/>)
}
</div>
</div>
);
}
|
bhatti/PlexService
|
plexsvc-framework/src/test/java/com/plexobject/util/ReflectUtilsTest.java
|
<gh_stars>1-10
package com.plexobject.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.plexobject.encode.json.JsonObjectCodec;
import com.plexobject.school.Address;
import com.plexobject.school.Course;
import com.plexobject.school.Student;
public class ReflectUtilsTest {
public static class TestService {
public List<Object> printStudent(Student s) {
return Arrays.asList(s, new Course("1001", "Python"));
}
public void nop() {
}
public Course getCourse(String id) {
return new Course(id, "Ruby");
}
public Student getStudent(Long id) {
return new Student(String.valueOf(id), "Jack");
}
public Student getStudentShort(short id) {
return new Student(String.valueOf(id), "Jack");
}
public Student getStudentInt(int id) {
return new Student(String.valueOf(id), "Jack");
}
public Student getStudentLong(long id) {
return new Student(String.valueOf(id), "Jack");
}
public Student getStudentByte(byte id) {
return new Student(String.valueOf(id), "Jack");
}
public Student getStudentChar(char id) {
return new Student(String.valueOf(id), "Jack");
}
public Student getStudentFloat(float id) {
return new Student(String.valueOf(id), "Jack");
}
public Student getStudentDouble(double id) {
return new Student(String.valueOf(id), "Jack");
}
public List<Object> printCourse(Course c) {
return Arrays.asList(c, new Student("1002", "Bill"));
}
public Collection<Course> printCourses(Collection<Course> c) {
return c;
}
public Collection<Student> printStudents(Map<String, Student> s) {
return s.values();
}
}
private static final JsonObjectCodec CODEC = new JsonObjectCodec();
private TestService service = new TestService();
@Before
public void setup() {
}
@Test
public void testGetAnnotatedClasses() {
Collection<Class<?>> classes = ReflectUtils.getAnnotatedClasses(
WebService.class, "com.plexobject.handler.ws", " ");
assertTrue(classes.size() > 0);
}
@Test
public void testJsonSimple() throws Exception {
Student student1 = buildStudent();
String json1 = CODEC.encode(student1);
Student student2 = CODEC.decode(json1, Student.class, null);
String json2 = CODEC.encode(student2);
assertEquals(json1, json2);
assertEquals(student1, student2);
}
@Test
public void testCodecJsonList() throws Exception {
Collection<Course> courses1 = buildCourses();
String json1 = CODEC.encode(courses1);
Collection<Course> courses2 = CODEC.decode(json1,
new TypeReference<List<Course>>() {
});
String json2 = CODEC.encode(courses2);
assertEquals(json1, json2);
assertEquals(courses1, courses2);
}
@SuppressWarnings("unchecked")
@Test
public void testDecodeJsonList() throws Exception {
Collection<Course> courses1 = buildCourses();
String json1 = CODEC.encode(courses1);
Method m = TestService.class
.getMethod("printCourses", Collection.class);
Class<?> klass = m.getParameterTypes()[0];
Type pKlass = m.getGenericParameterTypes()[0];
Collection<Course> courses2 = (Collection<Course>) ReflectUtils.decode(
json1, klass, pKlass, CODEC);
String json2 = CODEC.encode(courses2);
assertEquals(json1, json2);
assertEquals(courses1, courses2);
}
@SuppressWarnings("unchecked")
@Test
public void testDecodeMethodParams() throws Exception {
Student s = buildStudent();
Method m = TestService.class.getMethod("printStudent", Student.class);
String payload = CODEC.encode(s);
Object[] args = ReflectUtils.decode(m, new HashMap<String, Object>(),
null, payload, CODEC);
List<Object> result = (List<Object>) m.invoke(service, args);
assertEquals(s, result.get(0));
}
@SuppressWarnings("unchecked")
@Test
public void testDecodeMethodParamsWithCollection() throws Exception {
Collection<Course> c = buildCourses();
Method m = TestService.class
.getMethod("printCourses", Collection.class);
String payload = CODEC.encode(c);
Object[] args = ReflectUtils.decode(m, new HashMap<String, Object>(),
null, payload, CODEC);
List<Object> result = (List<Object>) m.invoke(service, args);
assertEquals(c, result);
}
@SuppressWarnings("unchecked")
@Test
public void testDecodeMethodParamsWithMap() throws Exception {
Map<String, Student> students = buildStudentsMap();
Method m = TestService.class.getMethod("printStudents", Map.class);
String payload = CODEC.encode(students);
Object[] args = ReflectUtils.decode(m, new HashMap<String, Object>(),
null, payload, CODEC);
Collection<Object> result = (Collection<Object>) m
.invoke(service, args);
assertEquals(students.size(), result.size());
for (Student s : students.values()) {
assertTrue(result.contains(s));
}
}
@SuppressWarnings("unchecked")
@Test
public void testDecodeMethodWithVoid() throws Exception {
Method m = TestService.class.getMethod("nop");
String payload = null;
Object arg = ReflectUtils.decode(payload, Void.class, null, CODEC);
assertNull(arg);
Object result = (Collection<Object>) m.invoke(service, new Object[0]);
assertNull(result);
}
@Test
public void testDecodeMethodWithString() throws Exception {
Method m = TestService.class.getMethod("getCourse", String.class);
String payload = "100";
Course c1 = new Course(payload, "Ruby");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(payload, arg);
Course c2 = (Course) m.invoke(service, new Object[] { arg });
assertEquals(c1, c2);
}
@Test
public void testDecodeMethodWithLong() throws Exception {
Method m = TestService.class.getMethod("getStudent", Long.class);
String payload = "100";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(Long.valueOf(payload), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
@Test
public void testDecodeMethodWithShort() throws Exception {
Method m = TestService.class.getMethod("getStudentShort", Short.TYPE);
String payload = "100";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(Short.valueOf(payload), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
@Test
public void testDecodeMethodWithInt() throws Exception {
Method m = TestService.class.getMethod("getStudentInt", Integer.TYPE);
String payload = "100";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(Integer.valueOf(payload), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
public Student getStudentLong(long id) {
return new Student(String.valueOf(id), "Jack");
}
@Test
public void testDecodeMethodWithlong() throws Exception {
Method m = TestService.class.getMethod("getStudentLong", Long.TYPE);
String payload = "100";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(Long.valueOf(payload), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
@Test
public void testDecodeMethodWithByte() throws Exception {
Method m = TestService.class.getMethod("getStudentByte", Byte.TYPE);
String payload = "100";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(Byte.valueOf(payload), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
public Student getStudentChar(char id) {
return new Student(String.valueOf(id), "Jack");
}
@Test
public void testDecodeMethodWithChar() throws Exception {
Method m = TestService.class
.getMethod("getStudentChar", Character.TYPE);
String payload = "1";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(new Character(payload.charAt(0)), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
@Test
public void testDecodeMethodWithFloat() throws Exception {
Method m = TestService.class.getMethod("getStudentFloat", Float.TYPE);
String payload = "100.0";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(Float.valueOf(payload), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
@Test
public void testDecodeMethodWithDouble() throws Exception {
Method m = TestService.class.getMethod("getStudentDouble", Double.TYPE);
String payload = "100.0";
Student s1 = new Student(payload, "Jack");
Object arg = ReflectUtils.decode(payload, m.getParameterTypes()[0],
null, CODEC);
assertEquals(Double.valueOf(payload), arg);
Student s2 = (Student) m.invoke(service, new Object[] { arg });
assertEquals(s1, s2);
}
private static List<Course> buildCourses() throws Exception {
return Arrays.asList(buildCourse(), buildCourse());
}
private static Map<String, Student> buildStudentsMap() throws Exception {
Map<String, Student> students = new LinkedHashMap<>();
Student s1 = buildStudent();
Student s2 = buildStudent();
students.put(s1.getId(), s1);
students.put(s2.getId(), s2);
return students;
}
private static Student buildStudent() throws Exception {
Thread.sleep(1);
long time = System.currentTimeMillis() / 1000000;
Student s = new Student(String.valueOf(time), time % 2 == 0 ? "Ken"
: "Chris");
s.getAddresses().add(new Address("100 main", "Seattle", "98101"));
s.getCourseIds().add(String.valueOf(time + 1));
s.getCourseIds().add(String.valueOf(time + 2));
return s;
}
private static Course buildCourse() throws Exception {
Thread.sleep(1);
long time = System.currentTimeMillis() / 1000000;
Course c = new Course(String.valueOf(time), time % 2 == 0 ? "Java"
: "C++");
c.getStudentIds().add(String.valueOf(time + 1));
c.getStudentIds().add(String.valueOf(time + 2));
c.getAddresses().add(new Address("100 main", "Seattle", "98101"));
return c;
}
}
|
dgimb89/glannotations
|
source/glannotations-preprocessor/include/glannotations-preprocessor/GlyphSetGenerator.h
|
<reponame>dgimb89/glannotations
#pragma once
#include <vector>
#include <string>
#include <globjects/base/ref_ptr.h>
#include <glannotations/Common/PNGImage.h>
#include <glannotations-preprocessor/glannotations-preprocessor_api.h>
namespace glannotations {
namespace preprocessor {
class GLANNOTATIONS_PREPROCESSOR_API GlyphSetGenerator
{
public:
static void generateGlyphset(std::string fontFileName, unsigned numGlyphs, bool overrideExisting = false);
protected:
static globjects::ref_ptr<PNGImage> generateGlyphImage(void* bitmap, unsigned marginLeft, int ascender, int descener, int bearingY);
static int convertFontToPixelSize(int input);
GlyphSetGenerator() {}
};
}
}
|
clovadevice/clockplus2
|
kernel/msm-4.14/drivers/media/platform/msm/camera/cam_req_mgr/cam_req_mgr_timer.h
|
<reponame>clovadevice/clockplus2<gh_stars>0
/* Copyright (c) 2016-2018, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef _CAM_REQ_MGR_TIMER_H_
#define _CAM_REQ_MGR_TIMER_H_
#include <linux/slab.h>
#include <linux/timer.h>
#include "cam_req_mgr_core_defs.h"
/** struct cam_req_mgr_timer
* @expires : timeout value for timer
* @sys_timer : system timer variable
* @parent : priv data - link pointer
* @timer_cb : callback func which will be called when timeout expires
*/
struct cam_req_mgr_timer {
int32_t expires;
struct timer_list sys_timer;
void *parent;
void (*timer_cb)(unsigned long data);
};
/**
* crm_timer_modify()
* @brief : allows ser to modify expiry time.
* @timer : timer which will be reset to expires values
*/
void crm_timer_modify(struct cam_req_mgr_timer *crm_timer,
int32_t expires);
/**
* crm_timer_reset()
* @brief : destroys the timer allocated.
* @timer : timer which will be reset to expires values
*/
void crm_timer_reset(struct cam_req_mgr_timer *timer);
/**
* crm_timer_init()
* @brief : create a new general purpose timer.
* timer utility takes care of allocating memory and deleting
* @timer : double pointer to new timer allocated
* @expires : Timeout value to fire callback
* @parent : void pointer which caller can use for book keeping
* @timer_cb : caller can chose to use its own callback function when
* timer fires the timeout. If no value is set timer util
* will use default.
*/
int crm_timer_init(struct cam_req_mgr_timer **timer,
int32_t expires, void *parent, void (*timer_cb)(unsigned long));
/**
* crm_timer_exit()
* @brief : destroys the timer allocated.
* @timer : timer pointer which will be freed
*/
void crm_timer_exit(struct cam_req_mgr_timer **timer);
extern struct kmem_cache *g_cam_req_mgr_timer_cachep;
#endif
|
schippada/code-corps-api
|
spec/policies/project_category_policy_spec.rb
|
<gh_stars>0
require "rails_helper"
describe ProjectCategoryPolicy do
subject { described_class }
let(:admin_user) { build_stubbed(:user) }
let(:contributor_user) { build_stubbed(:user) }
let(:organization) { create(:organization) }
let(:owner_user) { build_stubbed(:user) }
let(:pending_user) { build_stubbed(:user) }
let(:project) { build_stubbed(:project, organization: organization) }
let(:project_category) { build_stubbed(:project_category, project: project) }
let(:site_admin) { build_stubbed(:user, admin: true) }
let(:unaffiliated_organization) { create(:organization) }
let(:unaffiliated_project) { build_stubbed(:project, organization: unaffiliated_organization) }
let(:unaffiliated_project_category) do
build_stubbed(:project_category, project: unaffiliated_project)
end
let(:unaffiliated_user) { build_stubbed(:user) }
before do
create(:organization_membership,
organization: organization,
member: pending_user,
role: "pending")
create(:organization_membership,
organization: organization,
member: contributor_user,
role: "contributor")
create(:organization_membership,
organization: organization,
member: admin_user,
role: "admin")
create(:organization_membership,
organization: organization,
member: owner_user,
role: "owner")
end
permissions :create?, :destroy? do
context "as a logged out user" do
it "is not permitted" do
expect(subject).to_not permit(nil, create(:project))
end
end
context "as an unaffiliated user" do
it "is not permitted in other organizations" do
expect(subject).to_not permit(unaffiliated_user, unaffiliated_project_category)
end
it "is not permitted in their organization" do
expect(subject).to_not permit(unaffiliated_user, project_category)
end
end
context "as a pending user" do
it "is not permitted in other organizations" do
expect(subject).to_not permit(pending_user, unaffiliated_project_category)
end
it "is not permitted in their organization" do
expect(subject).to_not permit(pending_user, project_category)
end
end
context "as a contributor user" do
it "is not permitted in other organizations" do
expect(subject).to_not permit(contributor_user, unaffiliated_project_category)
end
it "is not permitted in their organization" do
expect(subject).to_not permit(contributor_user, project_category)
end
end
context "as an admin user" do
it "is not permitted in other organizations" do
expect(subject).to_not permit(admin_user, unaffiliated_project_category)
end
it "is permitted in their organization" do
expect(subject).to permit(admin_user, project_category)
end
end
context "as an owner user" do
it "is not permitted in other organizations" do
expect(subject).to_not permit(owner_user, unaffiliated_project_category)
end
it "is permitted in their organization" do
expect(subject).to permit(owner_user, project_category)
end
end
context "as a site admin" do
it "is permitted in other organizations" do
expect(subject).to permit(site_admin, unaffiliated_project_category)
end
it "is permitted in their organization" do
expect(subject).to permit(site_admin, project_category)
end
end
end
end
|
2020SnakeVenom/kafka-0.10.2.0-src
|
clients/src/main/java/org/apache/kafka/common/security/auth/Login.java
|
<filename>clients/src/main/java/org/apache/kafka/common/security/auth/Login.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.kafka.common.security.auth;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
/**
* Login interface for authentication.
*/
public interface Login {
/**
* Configures this login instance.
*/
void configure(Map<String, ?> configs, Configuration jaasConfig, String loginContextName);
/**
* Performs login for each login module specified for the login context of this instance.
*/
LoginContext login() throws LoginException;
/**
* Returns the authenticated subject of this login context.
*/
Subject subject();
/**
* Returns the service name to be used for SASL.
*/
String serviceName();
/**
* Closes this instance.
*/
void close();
}
|
sgholamian/log-aware-clone-detection
|
LACCPlus/Hive/163_1.java
|
//,temp,SessionHiveMetaStoreClient.java,1795,1804,temp,SessionHiveMetaStoreClient.java,1779,1794
//,3
public class xxx {
private void removePartitionedTempTable(org.apache.hadoop.hive.metastore.api.Table t) {
String qualifiedTableName = Warehouse.
getQualifiedName(t.getDbName().toLowerCase(), t.getTableName().toLowerCase());
SessionState ss = SessionState.get();
if (ss == null) {
LOG.warn("No current SessionState, skipping temp partitions for " + qualifiedTableName);
return;
}
ss.getTempPartitions().remove(Warehouse.getQualifiedName(t));
}
};
|
eduardosasso/leter
|
test/theme_test.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'test_helper'
require 'leter/theme'
require 'leter/color'
class ThemeTest < Minitest::Test
def test_css
theme = Leter::Theme.new
css = ":root {\n" \
" --background_color: #{theme.background_color};\n" \
" --page_align: #{theme.page_align};\n" \
" --text_font: #{theme.text_font};\n" \
" --text_color: #{theme.text_color};\n" \
" --text_size: #{theme.text_size};\n" \
" --heading_font: #{theme.heading_font};\n" \
" --heading_color: #{theme.heading_color};\n" \
" --accent_color: #{theme.accent_color};\n" \
" --link_color: #{theme.link_color};\n" \
"}\n"
assert_equal(css, theme.to_css)
end
def test_themes
theme = Leter::Theme
Leter::Theme.list.each do |t|
assert((begin
theme.new(t).to_css
rescue StandardError
nil
end), "check theme #{t}")
end
end
def test_attribute
banana = Leter::Theme.load('banana.yml')
theme = Leter::Theme.new('banana.yml')
assert_equal(banana['text_color'], theme.text_color)
end
def test_print_themes
theme = Leter::Theme
classic = Leter::Theme.new('classic')
assert_match(classic.description, theme.print)
end
def test_default_attribute
default = Leter::Theme.load('default.yml')
theme = Leter::Theme.new('banana.yml')
assert_equal(default['heading_color'], theme.heading_color)
end
def test_accent_color_rgba
theme = Leter::Theme.new('bungee')
rgba_css = Leter::Color.hex_to_rgba_css(theme.heading_color, Leter::Theme::RGBA_OPACITY)
assert_equal(rgba_css, theme.accent_color)
end
def test_accent_color
theme = Leter::Theme.new('bungee')
theme.accent_color = 'brown'
assert_equal('brown', theme.accent_color)
end
def test_link_color
theme = Leter::Theme.new('bungee')
theme.link_color = 'brown'
assert_equal('brown', theme.link_color)
end
def test_default_link_color
theme = Leter::Theme.new('bungee')
theme.accent_color = 'blue'
assert_equal('blue', theme.link_color)
end
def test_page_align_center
theme = Leter::Theme.new('bungee')
theme.page_align = 'center'
assert_equal(Leter::Theme::PAGE_ALIGN[:center], theme.page_align)
end
def test_page_align_left
theme = Leter::Theme.new('bungee')
theme.page_align = 'left'
assert_equal(Leter::Theme::PAGE_ALIGN[:left], theme.page_align)
end
end
|
evugar/Mcucpp
|
mcucpp/flash_crc_check.h
|
#pragma once
unsigned long FlashCrcExpected();
unsigned long FlashCrcComputed();
|
rumenNikodimov/Java-Script-Core
|
06.Lab Arrays and Matrices/08. Biggest Element.js
|
function biggestElement(matrix){
return matrix
.concat.apply([], matrix)
.sort((a, b) => b - a)[0]
}
console.log(biggestElement([[20, 50, 10],
[8, 33, 145]]
));
|
lechium/iOS1351Headers
|
System/Library/PrivateFrameworks/OfficeImport.framework/TCBackgroundThreadManager.h
|
<gh_stars>1-10
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:22:40 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
@protocol TCCancelDelegate, OS_dispatch_queue, OS_dispatch_group;
@class NSObject, TCMessageContext, TCProgressContext;
@interface TCBackgroundThreadManager : NSObject {
id<TCCancelDelegate> mCancelDelegate;
BOOL mIsWaiting;
unsigned long long mBlockCount;
NSObject*<OS_dispatch_queue> mQueue;
NSObject*<OS_dispatch_group> mGroup;
NSObject*<OS_dispatch_queue> mProgressReportingQueue;
TCMessageContext* mMessageContext;
TCProgressContext* mProgressContext;
}
@property (readonly) BOOL isCancelled;
@property (retain) TCMessageContext * messageContext;
@property (retain) TCProgressContext * progressContext;
-(void)dealloc;
-(BOOL)isCancelled;
-(void)waitUntilComplete;
-(TCMessageContext *)messageContext;
-(void)setMessageContext:(TCMessageContext *)arg1 ;
-(TCProgressContext *)progressContext;
-(void)setProgressContext:(TCProgressContext *)arg1 ;
-(id)initWithCancelDelegate:(id)arg1 ;
-(void)addASyncBlock:(/*^block*/id)arg1 ;
@end
|
Gegel85/minesweeper
|
lib/configParser/sources/dumper.c
|
<filename>lib/configParser/sources/dumper.c
#include "configParser.h"
#include <malloc.h>
#include <concatf.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int isInString(char c, char *str);
char *transformString(char *str, int length, ParserInfos *infos)
{
char *result = strdup("");
char *buffer = NULL;
for (int i = 0; i < length; i++) {
buffer = result;
if (isInString(str[i], infos->strChar) != -1)
result = concatf("%s\\%c", result, str[i]);
else if (str[i] >= ' ' && str[i] != 127)
result = concatf("%s%c", result, str[i]);
else if (str[i] == '\n')
result = concatf("%s\\n", result);
else if (str[i] == '\r')
result = concatf("%s\\r", result);
else if (str[i] == '\a')
result = concatf("%s\\a", result);
else if (str[i] == '\b')
result = concatf("%s\\b", result);
else if (str[i] == '\v')
result = concatf("%s\\v", result);
else if (str[i] == '\t')
result = concatf("%s\\t", result);
else if (str[i] == '\f')
result = concatf("%s\\f", result);
else if (str[i] == '\e')
result = concatf("%s\\e", result);
else if (str[i] == '\0')
result = concatf("%s\\x00", result);
else
result = concatf("%s\\x%s%x", result, str[i] > 15 ? "" : "0", str[i]);
free(buffer);
}
return (result);
}
char *dataToString(void *data, ParserTypes type, ParserInfos *infos, int indentation)
{
char *indent = strdup("");
char *index = NULL;
char *result = NULL;
char *buffer = NULL;
for (int i = 0; i < indentation; i++)
indent = concat(indent, "\t", true, false);
switch(type) {
case ParserBooleanType:
result = strdup(*(ParserBoolean *)data ? "true" : "false");
break;
case ParserStringType:
buffer = transformString(((ParserString *)data)->content, ((ParserString *)data)->length, infos);
result = concatf("%c%s%c", infos->strChar[0], buffer, infos->strChar[0]);
free(buffer);
break;
case ParserFloatType:
result = concatf("%f", *(ParserFloat *)data);
break;
case ParserArrayType:
result = malloc(2);
if (!result)
return (NULL);
result[0] = infos->arrOpen;
result[1] = 0;
for (int i = 0; i < ((ParserArray *)data)->length; i++) {
if (!infos->compact) {
buffer = result;
result = concatf("%s\n%s\t", result, indent);
if (!result)
return (NULL);
free(buffer);
}
result = concat(result, dataToString(ParserArray_getElement(data, i), ((ParserArray *)data)->type, infos, indentation + 1), true, true);
if (!result)
return (NULL);
buffer = result;
result = concatf("%s%c", result, infos->separator);
if (!result)
return (NULL);
free(buffer);
}
buffer = result;
result = concatf("%s%s%s%c", result, infos->compact ? "" : "\n", infos->compact ? "" : indent, infos->arrClose);
if (!result)
return (NULL);
free(buffer);
break;
case ParserObjType:
result = malloc(2);
if (!result)
return (NULL);
result[0] = infos->objOpen;
result[1] = 0;
for (ParserObj *list = data; list; list = list->next) {
buffer = result;
index = transformString(list->index, strlen(list->index), infos);
if (!infos->compact)
result = concatf("%s\n%s\t%c%s%c%c ", result, indent, infos->strChar[0], index, infos->strChar[0], infos->eqChar);
else
result = concatf("%s%c%s%c%c", result, infos->strChar[0], list->index, infos->strChar[0], infos->eqChar);
free(index);
free(buffer);
if (!result)
return (NULL);
result = concat(result, dataToString(list->data, list->type, infos, indentation + 1), true, true);
if (!result)
return (NULL);
buffer = result;
result = concatf("%s%c", result, infos->separator);
if (!result)
return (NULL);
free(buffer);
}
buffer = result;
result = concatf("%s%s%s%c", result, infos->compact ? "" : "\n", infos->compact ? "" : indent, infos->objClose);
if (!result)
return (NULL);
free(buffer);
break;
case ParserListType:
result = malloc(2);
if (!result)
return (NULL);
result[0] = infos->arrOpen;
result[1] = 0;
for (ParserList *list = data; list; list = list->next) {
if (!infos->compact) {
buffer = result;
result = concatf("%s\n%s\t", result, indent);
if (!result)
return (NULL);
free(buffer);
}
result = concat(result, dataToString(list->data, list->type, infos, indentation + 1), true, true);
if (!result)
return (NULL);
buffer = result;
result = concatf("%s%c", result, infos->separator);
if (!result)
return (NULL);
free(buffer);
}
buffer = result;
result = concatf("%s%s%s%c", result, infos->compact ? "" : "\n", infos->compact ? "" : indent, infos->arrClose);
if (!result)
return (NULL);
free(buffer);
break;
case ParserIntType:
result = concatf("%i", *(ParserInt *)data);
break;
case ParserNullType:
result = strdup("null");
break;
}
free(indent);
return (result);
}
char *Parser_createString(void *data, ParserTypes type, ParserInfos *infos)
{
if (infos && !strlen(infos->strChar))
return (NULL);
return (dataToString(data, type, infos ? infos : JSON_COMPACT, 0));
}
bool Parser_createFile(char *path, void *data, ParserTypes type, ParserInfos *infos)
{
int fd;
bool success = true;
char *buffer = NULL;
buffer = Parser_createString(data, type, infos);
remove(path);
fd = open(path, O_WRONLY | O_CREAT, 0664);
if (fd < 0)
return (false);
if (!buffer)
return (false);
success = write(fd, buffer, strlen(buffer)) == (int)strlen(buffer);
free(buffer);
close(fd);
return (success);
}
|
Pandrex247/patched-src-eclipselink
|
plugins/javax.transaction/src/javax/transaction/SystemException.java
|
/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* https://glassfish.dev.java.net/public/CDDLv1.0.html or
* glassfish/bootstrap/legal/CDDLv1.0.txt.
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at glassfish/bootstrap/legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* you own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
*/
package javax.transaction;
/**
* The SystemException is thrown by the transaction manager to
* indicate that it has encountered an unexpected error condition
* that prevents future transaction services from proceeding.
*/
public class SystemException extends java.lang.Exception {
/**
* The error code with which to create the SystemException.
*
* @serial The error code for the exception
*/
public int errorCode;
public SystemException()
{
super();
}
/**
* Create a SystemException with a given string.
*
* @param s The string message for the exception
*/
public SystemException(String s)
{
super(s);
}
/**
* Create a SystemException with a given error code.
*
* @param errcode The error code for the exception
*/
public SystemException(int errcode)
{
super();
errorCode = errcode;
}
}
|
LightSecOps/Triton
|
src/libtriton/includes/triton/pathConstraint.hpp
|
<gh_stars>1-10
//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the BSD License.
*/
#ifndef TRITON_PATHCONSTRAINT_H
#define TRITON_PATHCONSTRAINT_H
#include <tuple>
#include <vector>
#include <triton/ast.hpp>
#include <triton/dllexport.hpp>
#include <triton/tritonTypes.hpp>
//! The Triton namespace
namespace triton {
/*!
* \addtogroup triton
* @{
*/
//! The Engines namespace
namespace engines {
/*!
* \ingroup triton
* \addtogroup engines
* @{
*/
//! The Symbolic Execution namespace
namespace symbolic {
/*!
* \ingroup engines
* \addtogroup symbolic
* @{
*/
/*! \class PathConstraint
\brief The path constraint class. */
class PathConstraint {
protected:
/*!
* \brief The branches constraints
* \details Vector of `<flag, source addr, dst addr, pc>`, `flag` is set to true if the branch is taken according the concrete
* execution. The source address is the location of the branch instruction and the destination address is the destination of the jump.
* E.g: `"0x11223344: jne 0x55667788"`, 0x11223344 is the source address and 0x55667788 is the destination if and only if the
* branch is taken, otherwise the destination is the next instruction address. The SharedAbstractNode is the expression which need to be
* true to take the branch.
*/
std::vector<std::tuple<bool, triton::uint64, triton::uint64, triton::ast::SharedAbstractNode>> branches;
public:
//! Constructor.
TRITON_EXPORT PathConstraint();
//! Constructor by copy.
TRITON_EXPORT PathConstraint(const PathConstraint &other);
//! Destructor.
TRITON_EXPORT ~PathConstraint();
//! Operator.
TRITON_EXPORT PathConstraint& operator=(const PathConstraint &other);
//! Adds a branch to the path constraint.
TRITON_EXPORT void addBranchConstraint(bool taken, triton::uint64 srdAddr, triton::uint64 dstAddr, const triton::ast::SharedAbstractNode& pc);
//! Returns the branch constraints.
TRITON_EXPORT const std::vector<std::tuple<bool, triton::uint64, triton::uint64, triton::ast::SharedAbstractNode>>& getBranchConstraints(void) const;
//! Returns the address of the taken branch.
TRITON_EXPORT triton::uint64 getTakenAddress(void) const;
//! Returns the predicate of the taken branch.
TRITON_EXPORT triton::ast::SharedAbstractNode getTakenPredicate(void) const;
//! Returns true if it is not a direct jump.
TRITON_EXPORT bool isMultipleBranches(void) const;
};
/*! @} End of symbolic namespace */
};
/*! @} End of engines namespace */
};
/*! @} End of triton namespace */
};
#endif /* TRITON_PATHCONSTAINT_H */
|
VKCOM/nocolor
|
internal/walkers/block_checker.go
|
<filename>internal/walkers/block_checker.go
package walkers
import (
"github.com/VKCOM/noverify/src/ir"
"github.com/VKCOM/noverify/src/linter"
)
// BlockIndexer is a dummy walker.
type BlockIndexer struct {
linter.BlockCheckerDefaults
}
// BlockChecker is a walker that handles function calls, method calls,
// class creation, and file imports in block context (inside functions).
type BlockChecker struct {
linter.BlockCheckerDefaults
ctx *linter.BlockContext
root *RootChecker
}
// NewBlockChecker creates a new BlockChecker walker.
func NewBlockChecker(ctx *linter.BlockContext, root *RootChecker) *BlockChecker {
return &BlockChecker{
ctx: ctx,
root: root,
}
}
// EnterNode is method to use BlockChecker in the Walk method of AST nodes.
func (b *BlockChecker) EnterNode(n ir.Node) bool {
b.AfterEnterNode(n)
return true
}
// LeaveNode is method to use BlockChecker in the Walk method of AST nodes.
func (b *BlockChecker) LeaveNode(n ir.Node) {}
// AfterEnterNode is the main method for processing AST nodes.
func (b *BlockChecker) AfterEnterNode(n ir.Node) {
switch n := n.(type) {
case *ir.NewExpr:
b.root.handleNew(n, b.ctx.Scope())
case *ir.FunctionCallExpr:
b.root.handleFunctionCall(n, b.ctx.Scope(), b)
case *ir.StaticCallExpr:
b.root.handleStaticCall(n, b.ctx.Scope())
case *ir.MethodCallExpr:
b.root.handleMethodCall(n, b.ctx.Scope(), b)
case *ir.NullsafeMethodCallExpr:
b.root.handleNullsafeMethodCall(n, b.ctx.Scope(), b)
case *ir.ImportExpr:
b.root.handleImportExpr(n)
case *ir.CloneExpr:
b.root.handleCloneExpr(n, b.ctx.Scope())
case *ir.PropertyFetchExpr:
b.root.handlePropertyFetch(n, b.ctx.Scope(), b.ctx.NodePath())
case *ir.Assign:
// Because of the way we handle assignments,
// we have to redirect our walker explicitly.
n.Variable.Walk(b)
n.Expr.Walk(b)
}
}
|
markiewb/fakereplace
|
plugins/resteasy/src/main/java/org/fakereplace/integration/resteasy/ResteasyClassChangeAware.java
|
<filename>plugins/resteasy/src/main/java/org/fakereplace/integration/resteasy/ResteasyClassChangeAware.java
/*
* Copyright 2016, <NAME>, and individual contributors as indicated
* by the @authors tag.
*
* 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 org.fakereplace.integration.resteasy;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.ws.rs.Path;
import org.fakereplace.api.ChangedClass;
import org.fakereplace.api.ClassChangeAware;
import org.fakereplace.api.NewClassData;
import org.fakereplace.data.InstanceTracker;
import org.fakereplace.logging.Logger;
import javassist.bytecode.AnnotationsAttribute;
public class ResteasyClassChangeAware implements ClassChangeAware {
private static final String RESOURCES = "resteasy.scanned.resources";
private final Logger logger = Logger.getLogger(ResteasyClassChangeAware.class);
@Override
public void afterChange(final List<ChangedClass> changed, final List<NewClassData> added) {
boolean requiresRestart = false;
ClassLoader classLoader = null;
for (final ChangedClass c : changed) {
if (!c.getChangedAnnotationsByType(Path.class).isEmpty() ||
c.getChangedClass().isAnnotationPresent(Path.class)) {
requiresRestart = true;
classLoader = c.getChangedClass().getClassLoader();
break;
}
}
Set<String> addedResources = new HashSet<>();
for(NewClassData add : added) {
AnnotationsAttribute attribute = (AnnotationsAttribute) add.getClassFile().getAttribute(AnnotationsAttribute.visibleTag);
if(attribute == null) {
continue;
}
if(attribute.getAnnotation(Path.class.getName()) != null) {
addedResources.add(add.getClassName());
requiresRestart = true;
}
if(classLoader == null) {
classLoader = add.getClassLoader();
}
}
if (requiresRestart) {
for (final Object servlet : InstanceTracker.get(ResteasyExtension.SERVLET_DISPATCHER)) {
try {
final ResteasyServletConfig config = (ResteasyServletConfig) servlet.getClass().getField(ResteasyTransformer.FIELD_NAME).get(servlet);
if(config.getClassLoader() == classLoader) {
StringBuilder res = new StringBuilder(config.getServletContext().getInitParameter(RESOURCES));
for(String add : addedResources) {
res.append(",").append(add);
}
ResteasyServletContext sc = new ResteasyServletContext(config.getServletContext());
sc.getInitParams().put(RESOURCES, res.toString());
config.setServletContext(sc);
final Set<String> doNotClear = (Set<String>) servlet.getClass().getField(ResteasyTransformer.PARAMETER_FIELD_NAME).get(servlet);
clearContext(config.getServletContext(), doNotClear);
final ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
servlet.getClass().getMethod("destroy").invoke(servlet);
servlet.getClass().getMethod("init", ServletConfig.class).invoke(servlet, config);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
} catch (Exception e) {
logger.debug("Could not restart RESTeasy", e);
}
}
for (final Object filter : InstanceTracker.get(ResteasyExtension.FILTER_DISPATCHER)) {
try {
final ResteasyFilterConfig config = (ResteasyFilterConfig) filter.getClass().getField(ResteasyTransformer.FIELD_NAME).get(filter);
if(config.getClassLoader() == classLoader) {
StringBuilder res = new StringBuilder((String) config.getServletContext().getAttribute(RESOURCES));
for(String add : addedResources) {
res.append(",").append(add);
}
ResteasyServletContext sc = new ResteasyServletContext(config.getServletContext());
sc.getInitParams().put(RESOURCES, res.toString());
config.setServletContext(sc);
final Set<String> doNotClear = (Set<String>) filter.getClass().getField(ResteasyTransformer.PARAMETER_FIELD_NAME).get(filter);
clearContext(config.getServletContext(), doNotClear);
final ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
filter.getClass().getMethod("destroy").invoke(filter);
filter.getClass().getMethod("init", FilterConfig.class).invoke(filter, config);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
} catch (Exception e) {
logger.debug("Could not restart RESTeasy", e);
}
}
}
}
/**
* Clear any resteasy stuff from the context
*
*/
private void clearContext(final ServletContext servletContext, final Set<String> doNotClear) {
final Enumeration names = servletContext.getAttributeNames();
while (names.hasMoreElements()) {
final String name = names.nextElement().toString();
if (name.startsWith("org.jboss.resteasy") && !doNotClear.contains(name)) {
servletContext.removeAttribute(name);
}
}
}
}
|
yuenov/reader-android
|
app/src/main/java/com/yuenov/open/activitys/CategoryEndListActivity.java
|
package com.yuenov.open.activitys;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.yuenov.open.R;
import com.yuenov.open.activitys.baseInfo.BaseActivity;
import com.yuenov.open.adapters.CategoryListAdapter;
import com.yuenov.open.constant.ConstantInterFace;
import com.yuenov.open.interfaces.IGetCategoryListListener;
import com.yuenov.open.model.httpModel.GetCategoryEndHttpModel;
import com.yuenov.open.model.responseModel.FindIndexInfoResponse;
import com.yuenov.open.model.standard.CategoriesListItem;
import com.yuenov.open.model.standard.FindItemBookItemModel;
import com.yuenov.open.utils.UtilityBusiness;
import com.yuenov.open.utils.UtilityData;
import com.yuenov.open.utils.UtilityException;
import com.yuenov.open.utils.UtilityToasty;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.renrui.libraries.interfaces.IHttpRequestInterFace;
import com.renrui.libraries.util.UtilitySecurity;
import com.renrui.libraries.util.UtilitySecurityListener;
import com.renrui.libraries.util.mHttpClient;
import java.util.List;
import butterknife.BindView;
/**
* 完本
*/
public class CategoryEndListActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, CategoryListAdapter.IBookBlItemAdapter {
public static Intent getIntent(Context context) {
Intent intent = new Intent(context, CategoryEndListActivity.class);
return intent;
}
@BindView(R.id.srlCeList)
protected SwipeRefreshLayout srlCeList;
@BindView(R.id.rvCeList)
protected RecyclerView rvCeList;
private FindIndexInfoResponse res;
protected CategoryListAdapter adapter;
private int thisPage = 1;
private boolean isEnd = false;
@Override
protected int getLayoutId() {
return R.layout.activity_categoryend;
}
@Override
protected void initExtra() {
}
@Override
protected void initListener() {
UtilitySecurityListener.setOnRefreshListener(srlCeList, this);
}
@Override
protected void initData() {
initMyAppTitle(R.string.CategoryEndListActivity_title);
adapter = new CategoryListAdapter(null);
adapter.setOnLoadMoreListener(this, rvCeList);
rvCeList.setAdapter(adapter);
adapter.setOnItemChildClickListener(this);
adapter.setListener(this);
rvCeList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
loadData(true);
}
private void loadData(boolean isLoadHeader) {
if (isLoadHeader)
thisPage = 1;
GetCategoryEndHttpModel httpModel = new GetCategoryEndHttpModel();
httpModel.pageNum = thisPage;
httpModel.pageSize = ConstantInterFace.pageSize;
mHttpClient.Request(this, httpModel, new IHttpRequestInterFace() {
@Override
public void onStart() {
if (isLoadHeader)
srlCeList.setRefreshing(true);
}
@Override
public void onResponse(String s) {
if (!UtilityData.CheckResponseString(s)) {
adapter.loadMoreFail();
return;
}
try {
setResponse(s, isLoadHeader);
} catch (Exception ex) {
UtilityException.catchException(ex);
}
}
@Override
public void onErrorResponse(String s) {
UtilityToasty.error(s);
}
@Override
public void onFinish() {
srlCeList.setRefreshing(false);
}
});
}
private void setResponse(String s, boolean isLoadHeader) {
try {
res = mHttpClient.fromDataJson(s, FindIndexInfoResponse.class);
} catch (Exception ex) {
UtilityException.catchException(ex);
res = null;
}
if (res == null || res.list == null) {
isEnd = true;
adapter.loadMoreEnd(false);
return;
}
try {
if (isLoadHeader) {
adapter.setNewData(res.list);
} else {
adapter.addData(res.list);
}
isEnd = (adapter.getData().size() < (thisPage * ConstantInterFace.categoriesListPageSize)) || UtilitySecurity.isEmpty(res.list);
if (!UtilitySecurity.isEmpty(res.list))
thisPage++;
if (isEnd) {
adapter.loadMoreEnd(false);
} else {
adapter.loadMoreComplete();
}
} catch (Exception ex) {
adapter.loadMoreFail();
UtilityException.catchException(ex);
}
}
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
try {
CategoriesListItem item = (CategoriesListItem) adapter.getData().get(position);
Intent intent = PreviewDetailActivity.getIntent(this, item.bookId);
startActivity(intent);
} catch (Exception ex) {
UtilityException.catchException(ex);
}
}
@Override
public void onLoadMoreRequested() {
loadData(false);
}
@Override
public void onBookBlItemClick(CategoriesListItem item) {
try {
Intent intent = PreviewDetailActivity.getIntent(this, item.bookId);
startActivity(intent);
} catch (Exception ex) {
UtilityException.catchException(ex);
}
}
@Override
public void onBookBlItemAdapterShowAll(FindItemBookItemModel item) {
try {
Intent intent = CategoryEndAllListActivity.getIntent(this, item.categoryName, item.categoryId);
startActivity(intent);
} catch (Exception ex) {
UtilityException.catchException(ex);
}
}
@Override
public void onBookBlItemAdapterReplace(FindItemBookItemModel item) {
if (item == null || UtilitySecurity.isEmpty(item.bookList))
return;
UtilityBusiness.getReplaceCategoryEndBooks(this, item.categoryId, item.bookList.size(), item.page + 1, item.type, new IGetCategoryListListener() {
@Override
public void onGetCategoryListSuccess(List<CategoriesListItem> list) {
if (UtilitySecurity.isEmpty(list))
return;
try {
int size = adapter.getData().size();
for (int i = 0; i < size; i++) {
if (adapter.getData().get(i).categoryId == item.categoryId) {
adapter.getData().get(i).bookList = list;
adapter.getData().get(i).page++;
LinearLayoutManager linearManager = (LinearLayoutManager) rvCeList.getLayoutManager();
int mFirstVisibleItemPosition = linearManager.findFirstVisibleItemPosition();
int mLastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
if (i >= mFirstVisibleItemPosition && i <= mLastVisibleItemPosition) {
adapter.notifyItemChanged(i);
}
break;
}
}
} catch (Exception ex) {
UtilityException.catchException(ex);
}
}
@Override
public void onGetCategoryListLoadFail() {
}
});
}
@Override
public void onRefresh() {
loadData(true);
}
@Override
public void onBackPressed() {
mHttpClient.cancelRequests(this);
super.onBackPressed();
}
}
|
ThePythonator/SDL2-boilerplate
|
include/framework/BaseStage.hpp
|
#pragma once
#include "Graphics.hpp"
namespace Framework {
class BaseStage {
public:
BaseStage();
virtual void update(float dt) = 0;
virtual void render(Framework::Graphics& graphics) = 0;
BaseStage* next();
bool finished();
protected:
void finish(BaseStage* next);
private:
bool _finished = false;
BaseStage* _next = nullptr;
};
}
|
LevyForch/SilverKing
|
src/skfs/OpenDirWriteRequest.c
|
<reponame>LevyForch/SilverKing<gh_stars>0
// OpenDirWriteRequest.c
/////////////
// includes
#include "OpenDirWriteRequest.h"
#include "Util.h"
#include <string.h>
///////////////////
// implementation
OpenDirWriteRequest *odwr_new(OpenDirWriter *openDirWriter, OpenDir *od) {
OpenDirWriteRequest *odwr;
odwr = (OpenDirWriteRequest*)mem_alloc(1, sizeof(OpenDirWriteRequest));
odwr->openDirWriter = openDirWriter;
odwr->od = od;
return odwr;
}
void odwr_delete(OpenDirWriteRequest **odwr) {
if (odwr != NULL && *odwr != NULL) {
mem_free((void **)odwr);
} else {
fatalError("bad ptr in odwr_delete");
}
}
|
eikeschumann971/kspp
|
tools/avro2pg/avro2pg.cpp
|
<filename>tools/avro2pg/avro2pg.cpp
#include <iostream>
#include <csignal>
#include <boost/program_options.hpp>
#include <kspp/topology_builder.h>
#include <kspp/sources/avro_file_source.h>
#include <kspp/processors/flat_map.h>
#include <kspp/utils/env.h>
#include <kspp/connect/postgres/postgres_generic_avro_sink.h>
#include <kspp/processors/transform.h>
#include <kspp/utils/string_utils.h>
#include <nlohmann/json.hpp>
#include <sstream>
#define SERVICE_NAME "avro2pg"
using namespace std::chrono_literals;
using namespace kspp;
namespace fs = std::experimental::filesystem;
using json = nlohmann::json;
static bool run = true;
static void sigterm(int sig) {
run = false;
}
void assign_record_members(const kspp::generic_avro::generic_record& src, kspp::generic_avro::generic_record& dst){
for (auto i : dst.members()){
//virtual size_t schema().names() const = 0;
//virtual const std::string &nameAt(int index) const = 0;
dst.set<std::string>(i, src.get<std::string>(i));
}
}
int main(int argc, char **argv) {
FLAGS_logtostderr = 1;
google::InitGoogleLogging(argv[0]);
boost::program_options::options_description desc("options");
desc.add_options()
("help", "produce help message")
("src", boost::program_options::value<std::string>(), "src")
("postgres_host", boost::program_options::value<std::string>()->default_value(get_env_and_log("POSTGRES_HOST")), "postgres_host")
("postgres_port", boost::program_options::value<int32_t>()->default_value(5432), "postgres_port")
("postgres_user", boost::program_options::value<std::string>()->default_value(get_env_and_log("POSTGRES_USER")),"postgres_user")
("postgres_password", boost::program_options::value<std::string>()->default_value(get_env_and_log_hidden("POSTGRES_PASSWORD")),"postgres_password")
("postgres_dbname", boost::program_options::value<std::string>()->default_value(get_env_and_log("POSTGRES_DBNAME")),"postgres_dbname")
("postgres_table_name", boost::program_options::value<std::string>(), "postgres_table_name")
("postgres_max_items_in_insert", boost::program_options::value<int32_t>()->default_value(5000), "postgres_max_items_in_insert")
("postgres_warning_timeout", boost::program_options::value<int32_t>()->default_value(1000),"postgres_warning_timeout")
("keys", boost::program_options::value<std::string>(), "keys")
("character_encoding", boost::program_options::value<std::string>()->default_value("UTF8"), "character_encoding");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 0;
}
auto config = std::make_shared<kspp::cluster_config>("dummy", kspp::cluster_config::NONE);
config->load_config_from_env();
std::string src;
if (vm.count("src")) {
src = vm["src"].as<std::string>();
} else {
std::cout << "--src must be specified" << std::endl;
return 0;
}
kspp::start_offset_t start_offset = kspp::OFFSET_BEGINNING;
std::string postgres_host;
if (vm.count("postgres_host")) {
postgres_host = vm["postgres_host"].as<std::string>();
}
int postgres_port;
if (vm.count("postgres_port")) {
postgres_port = vm["postgres_port"].as<int>();
}
std::string postgres_dbname;
if (vm.count("postgres_dbname")) {
postgres_dbname = vm["postgres_dbname"].as<std::string>();
}
std::string postgres_user;
if (vm.count("postgres_user")) {
postgres_user = vm["postgres_user"].as<std::string>();
}
std::string postgres_password;
if (vm.count("postgres_password")) {
postgres_password = vm["postgres_password"].as<std::string>();
}
int postgres_max_items_in_insert;
if (vm.count("postgres_max_items_in_insert")) {
postgres_max_items_in_insert = vm["postgres_max_items_in_insert"].as<int>();
}
int postgres_warning_timeout;
if (vm.count("postgres_warning_timeout")) {
postgres_warning_timeout = vm["postgres_warning_timeout"].as<int>();
}
std::vector<std::string> keys;
if (vm.count("keys")) {
std::string s = vm["keys"].as<std::string>();
keys = parse_string_array(s);
}
std::string postgres_table_name;
if (vm.count("postgres_table_name")) {
postgres_table_name = vm["postgres_table_name"].as<std::string>();
} else {
std::cout << "--postgres_table_name must be specified" << std::endl;
return 0;
}
std::string character_encoding;
if (vm.count("character_encoding")) {
character_encoding = vm["character_encoding"].as<std::string>();
} else {
std::cout << "--character_encoding must be specified" << std::endl;
return 0;
}
bool postgres_disable_delete = false;
if (vm.count("postgres_disable_delete")) {
postgres_disable_delete = (vm["postgres_disable_delete"].as<int>() > 0);
}
std::string metrics_namespace;
if (vm.count("metrics_namespace")) {
metrics_namespace = vm["metrics_namespace"].as<std::string>();
}
config->set_producer_buffering_time(1000ms);
config->set_consumer_buffering_time(500ms);
config->validate();
config->log();
LOG(INFO) << "src : " << src;
LOG(INFO) << "start_offset : " << kspp::to_string(start_offset);
LOG(INFO) << "postgres_host : " << postgres_host;
LOG(INFO) << "postgres_port : " << postgres_port;
LOG(INFO) << "postgres_dbname : " << postgres_dbname;
LOG(INFO) << "postgres_user : " << postgres_user;
LOG(INFO) << "postgres_password : " << "[hidden]";
LOG(INFO) << "postgres_max_items_in_insert : " << postgres_max_items_in_insert;
LOG(INFO) << "keys : " << kspp::to_string(keys);
LOG(INFO) << "postgres_warning_timeout : " << postgres_warning_timeout;
LOG(INFO) << "postgres_table_name : " << postgres_table_name;
LOG(INFO) << "character_encoding : " << character_encoding;
kspp::connect::connection_params connection_params;
connection_params.host = postgres_host;
connection_params.port = postgres_port;
connection_params.user = postgres_user;
connection_params.password = <PASSWORD>;
connection_params.database_name = postgres_dbname;
auto key_schema = std::make_shared<avro::ValidSchema>();
{
json j;
j["type"] = "record";
j["name"] = "pg_keys";
j["fields"] = json::array();
for (auto i : keys) {
json column;
column["name"] = i;
column["type"] = "string";
j["fields"].push_back(column);
}
std::cout << std::endl;
std::stringstream s;
s << j.dump(4) << std::endl;
try {
avro::compileJsonSchema(s, *key_schema);
} catch (std::exception &e) {
std::cerr << "exeption parsing schema " << e.what();
return -1;
}
}
kspp::generic_avro key_datum(key_schema, -1);
LOG(INFO) << "discovering facts...";
kspp::topology_builder builder(config);
auto topology = builder.create_topology();
auto source0 = topology->create_processors<kspp::generic_avro_file_source>({0}, src);
auto transform = topology->create_processors<kspp::flat_map<void, kspp::generic_avro, kspp::generic_avro, kspp::generic_avro>>(
source0, [&key_datum](const kspp::krecord<void, kspp::generic_avro>& in, auto self) {
auto key = key_datum.mutable_record();
assign_record_members(in.value()->record(), key);
insert(self, key_datum, *in.value());
});
topology->create_sink<kspp::postgres_generic_avro_sink>(transform, postgres_table_name, connection_params, keys, character_encoding, postgres_max_items_in_insert, postgres_disable_delete);
topology->start(start_offset);
std::signal(SIGINT, sigterm);
std::signal(SIGTERM, sigterm);
std::signal(SIGPIPE, SIG_IGN);
LOG(INFO) << "status is up";
{
int64_t next_exit_check = kspp::milliseconds_since_epoch() + 10000;
while (run) {
if (topology->process(kspp::milliseconds_since_epoch()) == 0) {
std::this_thread::sleep_for(10ms);
topology->commit(false);
}
if (kspp::milliseconds_since_epoch() > next_exit_check) {
if (!topology->good()) {
LOG(ERROR) << "NODES IN ERROR STATE - EXITING";
run = false;
}
if (topology->eof()) {
LOG(ERROR) << "EOF - EXITING";
run = false;
}
next_exit_check = kspp::milliseconds_since_epoch() + 10000;
}
}
}
topology->commit(true);
topology->close();
LOG(INFO) << "status is down";
return 0;
}
|
rexlManu/ChromCloud
|
TestProgram/src/main/java/me/rexlmanu/testprogram/TestProgram.java
|
package me.rexlmanu.testprogram;
import java.io.IOException;
public final class TestProgram {
public static void main(String[] args) throws IOException {
String rawCommandsList = "docker,run,-d,-it,-v,/home/Subnode/ChromCloud/servers/1/temp:/data,-it,-e,EULA=TRUE,-e,SPIGOT_DOWNLOAD_URL=https://cdn.getbukkit.org/spigot/spigot-1.8.8-R0.1-SNAPSHOT-latest.jar,-e,TYPE=spigot,-e,VERSION=1.8,-p,25565:25565,--name,mc-1,itzg/minecraft-server";
System.out.println(rawCommandsList.replace(",", " "));
// final String[] rawList = rawCommandsList.split(",");
//
// System.out.println("-");
// for (String s : rawList) {
// System.out.println(s);
// }
// System.out.println("-");
// final Process process = new ProcessBuilder(rawList).directory(new File("/home/Subnode/ChromCloud/servers/1/temp/")).redirectErrorStream(true).start();
// final Process process = new ProcessBuilder("docker", "attach", "mc-1").directory(new File("/home/Subnode/ChromCloud/servers/1/temp/")).redirectErrorStream(true).start();
// final Process process = new ProcessBuilder("docker", "logs", "mc-1").directory(new File("/home/Subnode/ChromCloud/servers/1/temp/")).redirectErrorStream(true).start();
// DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://localhost:2375").build();
// PipedOutputStream out = new PipedOutputStream();
// PipedInputStream in = new PipedInputStream(out);
//
// dockerClient.attachContainerCmd("mc-1")
// .withStdErr(true)
// .withStdOut(true)
// .withFollowStream(true)
// .withStdIn(in)
// .exec(new Penis());
//
// out.write(("op rexlManu" + "\n").getBytes());
// out.flush();
// final Docker docker = new LocalDocker(new File("/var/run/docker.sock"));
// docker.containers().all().forEachRemaining(container -> {
// System.out.println(container.containerId());
// container.execCommand();
// });
}
// public static class Penis extends AttachContainerResultCallback {
// @Override
// public void onNext(Frame item) {
// System.out.println(new String(item.getPayload()));
// }
// }
}
|
Nels885/csd_dashboard
|
dashboard/management/commands/importexcel.py
|
import logging
from django.core.management.base import BaseCommand
from django.core.management import call_command
logger = logging.getLogger('command')
class Command(BaseCommand):
help = 'Interact with the all tables in the database'
def handle(self, *args, **options):
self.stdout.write("[IMPORT_EXCEL] Waiting...")
call_command("loadraspeedi")
call_command("programing")
# call_command("corvet")
call_command("loadsqualaetp", "--xelon_update")
call_command("importcorvet", "--squalaetp")
call_command("exportsqualaetp")
call_command("loadsqualaetp", "--relations")
self.stdout.write(self.style.SUCCESS("[IMPORT_EXCEL] Update completed."))
|
BrittonAlone/main
|
src/main/java/seedu/address/logic/commands/FindAccountCommand.java
|
<filename>src/main/java/seedu/address/logic/commands/FindAccountCommand.java
package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import java.util.List;
import seedu.address.commons.core.Messages;
import seedu.address.logic.CommandHistory;
import seedu.address.model.Model;
import seedu.address.model.account.Account;
import seedu.address.model.account.UsernameContainsKeywordsPredicate;
/**
* Finds and lists all accounts in account list whose username contains any of the argument keywords.
* Keyword matching is case insensitive.
*/
public class FindAccountCommand extends Command {
public static final String COMMAND_WORD = "findaccount";
public static final String COMMAND_ALIAS = "fAc";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all accounts whose usernames contain any of "
+ "the specified keywords (case-insensitive) and displays them as a list with index numbers.\n"
+ "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
+ "Example: " + COMMAND_WORD + " jalil kelvin";
private final UsernameContainsKeywordsPredicate predicate;
public FindAccountCommand(UsernameContainsKeywordsPredicate predicate) {
this.predicate = predicate;
}
@Override
public CommandResult execute(Model model, CommandHistory history) {
requireNonNull(model);
model.updateFilteredAccountList(predicate);
List<Account> foundAccounts = model.getFilteredAccountList();
String messageOutput = getMessageOutput(model.getFilteredAccountList().size(), foundAccounts);
return new CommandResult(messageOutput);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof FindAccountCommand // instanceof handles nulls
&& predicate.equals(((FindAccountCommand) other).predicate)); // state check
}
private String getMessageOutput (int numAccounts, List<Account> accounts) {
String messageOutput = "";
messageOutput += String.format(Messages.MESSAGE_ACCOUNTS_FOUND_OVERVIEW, numAccounts) + "\n";
messageOutput += "Accounts: \n";
int counter = 0;
for (Account account : accounts) {
counter++;
messageOutput += counter + ". "
+
account.getUsername()
+ "\n";
}
return messageOutput;
}
}
|
whwang1996/pra
|
edu/cmu/pra/model/RWRModel.java
|
package edu.cmu.pra.model;
import java.io.BufferedWriter;
import edu.cmu.lti.algorithm.container.MapID;
import edu.cmu.lti.algorithm.container.SetI;
import edu.cmu.lti.algorithm.container.VectorD;
import edu.cmu.lti.algorithm.container.VectorI;
import edu.cmu.lti.algorithm.optimization.AModel;
import edu.cmu.lti.algorithm.optimization.lbfgs.Interfaces.OptizationEval;
import edu.cmu.lti.util.file.FFile;
import edu.cmu.lti.util.run.Counter;
import edu.cmu.lti.util.system.FSystem;
import edu.cmu.lti.util.text.FString;
import edu.cmu.pra.graph.GraphWalker;
import edu.cmu.pra.graph.IGraph;
/** stuff related to the parameter*/
public class RWRModel extends AModel {
public Param p;
public IGraph graph_;
public GraphWalker walker_;
public RWRModel(GraphWalker walker) { //IGraph graph) {
this.graph_ = walker.graph_;
this.walker_ = walker;//new GraphWalker(graph);
p = new Param();
}
public VectorD getGradient(OptizationEval eva){
return null;
}
public void setParameters(double x[]){
}
public double[] getParameters(){
return null;
}
public void initWeights() {
}
// assuming each path has the format
// FieldID:relation,relation,...
public void loadModel(String model_file) {
FSystem.checkTrue(FFile.exist(model_file), "cannot find " + model_file);
//
// for (VectorS vs : FFile.enuRows(model_file, "\t", true)) {
// double weight = Double.parseDouble(vs.get(0));
// String field_path = vs.get(1);
// if (field_path.equals("bias")) continue;
// addPath(field_path).is_target_ = true;
// }
//
// loadWeights(model_file);
// //this.saveModel(model_file +".loaded", false);
// return;
}
public void clear() {
this.clearWeights();
}
public void getFeatures(Query query, BufferedWriter inspect) {
Counter.count50.stepDot();
//g.setTime(q.time);
if (inspect != null)
FFile.writeln(inspect, query.print(walker_));
query.features_.clear();
for (int field = 0; field < query.seeds_.size(); ++field) {
SetI seed = query.seeds_.get(field);
MapID dist = walker_.walkRWR(query, seed,
p.rwr_restart, p.max_steps.get(field));
query.features_.add(dist);
}
return;
}
public MapID predict(Query query) {
if (query.features_.size() == 0) getFeatures(query, null);
MapID result = query.features_.sum();
walker_.applyFilters(query, result);
return result;
}
public void predictQuery(Query query,
BufferedWriter result_writer, BufferedWriter reason_writer) {
StringBuffer result = new StringBuffer();
StringBuffer reason = reason_writer!=null? new StringBuffer() : null;
//MapID dist = predict(query);
this.predictQuery(query, result, reason);
//FString.split(fields, "\t")
synchronized(result_writer) {
FFile.writeln(result_writer, result.toString());
}
if (reason_writer!=null)
synchronized(reason_writer) {
FFile.writeln(reason_writer, reason.toString());
}
}
public void predictQuery(Query query,
StringBuffer predction, StringBuffer reasons) {
MapID result = predict(query);
//Query query = model_.parseQuery(fields);
predction.append(String.format("%s\t%d", query.name_, result.size()));
if (reasons!=null) reasons.append(query.name_).append("\n");
VectorI sorted_result = result.KeyToVecSortByValue(true);
for (int i = 0; i < sorted_result.size(); ++i) {
int id = sorted_result.get(i);
double score = result.get(id);
if (score < p.prediction_threshold) break;
String name = (query.good_.contains(id)) ?"*" : "";
name += graph_.getNodeName(id);
predction.append(String.format("\t%.3e,%s", score, name));
//
// if (reasons!=null) {
// MapID feature_score = query.features_.getRowMap(id)
// .multiply(this.feature_weights_);// param_weights_);
// reasons.append(String.format("%.3e\t%s\t", score, name));
// VectorI sorted_reason = feature_score.KeyToVecSortByAbsValue(true);
// reasons.append(feature_score.join(sorted_reason,"=", "\t", false));
// reasons.append("\n");
// }
}
}
public static class Param extends edu.cmu.lti.util.run.Param {
public Param() {
super(PRAModel.class);
parse();
}
public VectorI max_steps = new VectorI();
public String max_steps_str;
// Assume that the last column contains the targets
public int num_fields = -1;
public int num_columns = -1;
public boolean cache_RW;
public double prediction_threshold;
public double rwr_epsilon;
public double rwr_restart;
//public double min_exploration_particle;
public void parse() {
rwr_epsilon = getDouble("rwr_epsilon", 1e-5);
rwr_restart = getDouble("rwr_restart", 0.2);
max_steps_str = getString("max_steps", "3");
max_steps = VectorI.from(FString.splitVS(max_steps_str, "-"));
num_fields = max_steps.size();
num_columns=num_fields+1;
prediction_threshold = getDouble("prediction_threshold", 0.0);
cache_RW = getBoolean("cache_RW", false);
model_code_ = "M" + max_steps_str + String.format("_R%.0e", rwr_restart);
}
public String model_code_;
}
}
|
tsymiar/----
|
CommonCPlus/CommonCPlus/ice/Ice/Outgoing.h
|
// **********************************************************************
//
// Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
#ifndef ICE_OUTGOING_H
#define ICE_OUTGOING_H
#include <IceUtil/Mutex.h>
#include <IceUtil/Monitor.h>
#include <IceUtil/UniquePtr.h>
#include <Ice/RequestHandlerF.h>
#include <Ice/InstanceF.h>
#include <Ice/ConnectionIF.h>
#include <Ice/ReferenceF.h>
#include <Ice/BasicStream.h>
#include <Ice/Current.h>
#include <Ice/ObserverHelper.h>
namespace Ice
{
class LocalException;
}
namespace IceInternal
{
//
// An exception wrapper, which is used for local exceptions that
// require special retry considerations.
//
class ICE_API LocalExceptionWrapper
{
public:
LocalExceptionWrapper(const Ice::LocalException&, bool);
LocalExceptionWrapper(const LocalExceptionWrapper&);
const Ice::LocalException* get() const;
//
// If true, always repeat the request. Don't take retry settings
// or "at-most-once" guarantees into account.
//
// If false, only repeat the request if the retry settings allow
// to do so, and if "at-most-once" does not need to be guaranteed.
//
bool retry() const;
static void throwWrapper(const ::std::exception&);
private:
const LocalExceptionWrapper& operator=(const LocalExceptionWrapper&);
IceUtil::UniquePtr<Ice::LocalException> _ex;
bool _retry;
};
class ICE_API OutgoingMessageCallback : private IceUtil::noncopyable
{
public:
virtual ~OutgoingMessageCallback() { }
virtual void sent(bool) = 0;
virtual void finished(const Ice::LocalException&, bool) = 0;
};
class ICE_API Outgoing : public OutgoingMessageCallback
{
public:
Outgoing(RequestHandler*, const std::string&, Ice::OperationMode, const Ice::Context*, InvocationObserver&);
~Outgoing();
bool invoke(); // Returns true if ok, false if user exception.
void abort(const Ice::LocalException&);
virtual void sent(bool);
virtual void finished(BasicStream&);
void finished(const Ice::LocalException&, bool);
// Inlined for speed optimization.
BasicStream* os() { return &_os; }
BasicStream* startReadParams()
{
_is.startReadEncaps();
return &_is;
}
void endReadParams()
{
_is.endReadEncaps();
}
void readEmptyParams()
{
_is.skipEmptyEncaps();
}
void readParamEncaps(const Ice::Byte*& encaps, Ice::Int& sz)
{
_is.readEncaps(encaps, sz);
}
BasicStream* startWriteParams(Ice::FormatType format)
{
_os.startWriteEncaps(_encoding, format);
return &_os;
}
void endWriteParams()
{
_os.endWriteEncaps();
}
void writeEmptyParams()
{
_os.writeEmptyEncaps(_encoding);
}
void writeParamEncaps(const Ice::Byte* encaps, Ice::Int size)
{
if(size == 0)
{
_os.writeEmptyEncaps(_encoding);
}
else
{
_os.writeEncaps(encaps, size);
}
}
bool hasResponse()
{
return !_is.b.empty();
}
void throwUserException();
void attachRemoteObserver(const Ice::ConnectionInfoPtr& c, const Ice::EndpointPtr& endpt,
Ice::Int requestId, Ice::Int size)
{
_remoteObserver.attach(_observer.getRemoteObserver(c, endpt, requestId, size));
}
private:
//
// Optimization. The request handler and the reference may not be
// deleted while a stack-allocated Outgoing still holds it.
//
RequestHandler* _handler;
IceUtil::UniquePtr<Ice::LocalException> _exception;
InvocationObserver& _observer;
ObserverHelperT<Ice::Instrumentation::RemoteObserver> _remoteObserver;
enum
{
StateUnsent,
StateInProgress,
StateOK,
StateUserException,
StateLocalException,
StateFailed
} _state;
Ice::EncodingVersion _encoding;
BasicStream _is;
BasicStream _os;
bool _sent;
//
// NOTE: we use an attribute for the monitor instead of inheriting
// from the monitor template. Otherwise, the template would be
// exported from the DLL on Windows and could cause linker errors
// because of multiple definition of IceUtil::Monitor<IceUtil::Mutex>,
// see bug 1541.
//
IceUtil::Monitor<IceUtil::Mutex> _monitor;
};
class BatchOutgoing : public OutgoingMessageCallback
{
public:
BatchOutgoing(RequestHandler*, InvocationObserver&);
BatchOutgoing(Ice::ConnectionI*, Instance*, InvocationObserver&);
void invoke();
virtual void sent(bool);
virtual void finished(const Ice::LocalException&, bool);
BasicStream* os() { return &_os; }
void attachRemoteObserver(const Ice::ConnectionInfoPtr& connection, const Ice::EndpointPtr& endpt, Ice::Int sz)
{
_remoteObserver.attach(_observer.getRemoteObserver(connection, endpt, 0, sz));
}
private:
IceUtil::Monitor<IceUtil::Mutex> _monitor;
RequestHandler* _handler;
Ice::ConnectionI* _connection;
bool _sent;
IceUtil::UniquePtr<Ice::LocalException> _exception;
BasicStream _os;
InvocationObserver& _observer;
ObserverHelperT<Ice::Instrumentation::RemoteObserver> _remoteObserver;
};
}
#endif
|
RobotLocomotion/drake-python3.7
|
examples/manipulation_station/mock_station_simulation.cc
|
<filename>examples/manipulation_station/mock_station_simulation.cc
#include <limits>
#include <gflags/gflags.h>
#include "drake/common/eigen_types.h"
#include "drake/common/find_resource.h"
#include "drake/common/is_approx_equal_abstol.h"
#include "drake/examples/manipulation_station/manipulation_station.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/lcmt_iiwa_command.hpp"
#include "drake/lcmt_iiwa_status.hpp"
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"
#include "drake/manipulation/kuka_iiwa/iiwa_command_receiver.h"
#include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include "drake/math/rigid_transform.h"
#include "drake/math/rotation_matrix.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/lcm/lcm_interface_system.h"
#include "drake/systems/lcm/lcm_publisher_system.h"
#include "drake/systems/lcm/lcm_subscriber_system.h"
#include "drake/systems/primitives/matrix_gain.h"
#include "drake/systems/sensors/image_to_lcm_image_array_t.h"
namespace drake {
namespace examples {
namespace manipulation_station {
namespace {
// Runs a simulation of the manipulation station plant as a stand-alone
// simulation which mocks the network inputs and outputs of the real robot
// station. This is a useful test in the transition from a single-process
// simulation to operating on the real robot hardware.
using Eigen::VectorXd;
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
DEFINE_double(duration, std::numeric_limits<double>::infinity(),
"Simulation duration.");
DEFINE_string(setup, "manipulation_class",
"Manipulation station type to simulate. "
"Can be {manipulation_class, clutter_clearing}");
DEFINE_bool(publish_cameras, false,
"Whether to publish camera images to LCM");
int do_main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
systems::DiagramBuilder<double> builder;
// Create the "manipulation station".
auto station = builder.AddSystem<ManipulationStation>();
if (FLAGS_setup == "manipulation_class") {
station->SetupManipulationClassStation();
station->AddManipulandFromFile(
"drake/examples/manipulation_station/models/061_foam_brick.sdf",
math::RigidTransform<double>(math::RotationMatrix<double>::Identity(),
Eigen::Vector3d(0.6, 0, 0)));
} else if (FLAGS_setup == "clutter_clearing") {
station->SetupClutterClearingStation();
station->AddManipulandFromFile(
"drake/manipulation/models/ycb/sdf/003_cracker_box.sdf",
math::RigidTransform<double>(math::RollPitchYaw<double>(-1.57, 0, 3),
Eigen::Vector3d(-0.3, -0.55, 0.36)));
} else {
throw std::domain_error(
"Unrecognized station type. Options are "
"{manipulation_class, clutter_clearing}.");
}
// TODO(russt): Load sdf objects specified at the command line. Requires
// #9747.
station->Finalize();
geometry::DrakeVisualizerd::AddToBuilder(
&builder, station->GetOutputPort("query_object"));
auto lcm = builder.AddSystem<systems::lcm::LcmInterfaceSystem>();
auto iiwa_command_subscriber = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_iiwa_command>(
"IIWA_COMMAND", lcm));
auto iiwa_command =
builder.AddSystem<manipulation::kuka_iiwa::IiwaCommandReceiver>();
builder.Connect(iiwa_command_subscriber->get_output_port(),
iiwa_command->get_message_input_port());
builder.Connect(station->GetOutputPort("iiwa_position_measured"),
iiwa_command->get_position_measured_input_port());
// Pull the positions out of the state.
builder.Connect(iiwa_command->get_commanded_position_output_port(),
station->GetInputPort("iiwa_position"));
builder.Connect(iiwa_command->get_commanded_torque_output_port(),
station->GetInputPort("iiwa_feedforward_torque"));
auto iiwa_status =
builder.AddSystem<manipulation::kuka_iiwa::IiwaStatusSender>();
builder.Connect(station->GetOutputPort("iiwa_position_commanded"),
iiwa_status->get_position_commanded_input_port());
builder.Connect(station->GetOutputPort("iiwa_position_measured"),
iiwa_status->get_position_measured_input_port());
builder.Connect(station->GetOutputPort("iiwa_velocity_estimated"),
iiwa_status->get_velocity_estimated_input_port());
builder.Connect(station->GetOutputPort("iiwa_torque_commanded"),
iiwa_status->get_torque_commanded_input_port());
builder.Connect(station->GetOutputPort("iiwa_torque_measured"),
iiwa_status->get_torque_measured_input_port());
builder.Connect(station->GetOutputPort("iiwa_torque_external"),
iiwa_status->get_torque_external_input_port());
auto iiwa_status_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_iiwa_status>(
"IIWA_STATUS", lcm, 0.005 /* publish period */));
builder.Connect(iiwa_status->get_output_port(),
iiwa_status_publisher->get_input_port());
// Receive the WSG commands.
auto wsg_command_subscriber = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_schunk_wsg_command>(
"SCHUNK_WSG_COMMAND", lcm));
auto wsg_command =
builder.AddSystem<manipulation::schunk_wsg::SchunkWsgCommandReceiver>();
builder.Connect(wsg_command_subscriber->get_output_port(),
wsg_command->GetInputPort("command_message"));
builder.Connect(wsg_command->get_position_output_port(),
station->GetInputPort("wsg_position"));
builder.Connect(wsg_command->get_force_limit_output_port(),
station->GetInputPort("wsg_force_limit"));
// Publish the WSG status.
auto wsg_status =
builder.AddSystem<manipulation::schunk_wsg::SchunkWsgStatusSender>();
builder.Connect(station->GetOutputPort("wsg_state_measured"),
wsg_status->get_state_input_port());
builder.Connect(station->GetOutputPort("wsg_force_measured"),
wsg_status->get_force_input_port());
auto wsg_status_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_schunk_wsg_status>(
"SCHUNK_WSG_STATUS", lcm, 0.05 /* publish period */));
builder.Connect(wsg_status->get_output_port(0),
wsg_status_publisher->get_input_port());
// Publish the camera outputs.
if (FLAGS_publish_cameras) {
auto image_encoder = builder.AddSystem<
systems::sensors::ImageToLcmImageArrayT>();
for (const auto& camera_name : station->get_camera_names()) {
// RGB
const std::string rgb_name = "camera_" + camera_name + "_rgb_image";
const auto& rgb_output = station->GetOutputPort(rgb_name);
const auto& rgb_input =
image_encoder->DeclareImageInputPort<
systems::sensors::PixelType::kRgba8U>(rgb_name);
builder.Connect(rgb_output, rgb_input);
// Depth
const std::string depth_name = "camera_" + camera_name + "_depth_image";
const auto& depth_output = station->GetOutputPort(depth_name);
const auto& depth_input =
image_encoder->DeclareImageInputPort<
systems::sensors::PixelType::kDepth16U>(depth_name);
builder.Connect(depth_output, depth_input);
}
const double fps = 30.0;
auto image_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_image_array>(
"DRAKE_RGBD_CAMERA_IMAGES", lcm, 1.0 / fps));
builder.Connect(image_encoder->image_array_t_msg_output_port(),
image_publisher->get_input_port());
}
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
simulator.set_publish_every_time_step(false);
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.AdvanceTo(FLAGS_duration);
return 0;
}
} // namespace
} // namespace manipulation_station
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
return drake::examples::manipulation_station::do_main(argc, argv);
}
|
just-hugo/city-scrapers-det
|
city_scrapers/spiders/det_city_council.py
|
<filename>city_scrapers/spiders/det_city_council.py
import re
from city_scrapers_core.constants import CITY_COUNCIL, COMMITTEE, FORUM
from city_scrapers_core.spiders import CityScrapersSpider
from city_scrapers.mixins import DetCityMixin
class DetCityCouncilSpider(DetCityMixin, CityScrapersSpider):
name = "det_city_council"
agency = "Detroit City Council"
agency_cal_id = "296"
def parse_event_page(self, response):
# Ignore districts, president if title not sufficient
meeting = super().parse_event_page(response)
tags = self._parse_tags(response)
# Include Budget Priorities meetings
if "budget" in meeting["title"].lower():
return meeting
if any(["District" in tag for tag in tags]) or re.match(
r"Coffee|Recess|District \d{1,2}", meeting["title"], flags=re.IGNORECASE
):
return
return meeting
def _parse_description(self, response):
return ""
def _parse_classification(self, response):
title = self._parse_title(response)
if "Committee" in title:
return COMMITTEE
if "forum" in title.lower():
return FORUM
return CITY_COUNCIL
def _parse_tags(self, response):
return response.css("article.tags a::text").extract()
|
bonedaddy/spago
|
pkg/ml/ag/graph.go
|
<reponame>bonedaddy/spago
// Copyright 2019 spaGO Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ag
import (
"github.com/nlpodyssey/spago/pkg/mat"
"github.com/nlpodyssey/spago/pkg/mat/rand"
"github.com/nlpodyssey/spago/pkg/ml/ag/fn"
"log"
"sync"
"sync/atomic"
)
type Graph struct {
// to avoid data race during concurrent computations
mu sync.Mutex
// maxId is the id of the last inserted node (corresponds of len(nodes)-1)
maxId int64
// the time-step is useful to perform truncated back propagation (default 0)
curTimeStep int64
// nodes contains the list of nodes of the graph. The indices of the list are the nodes ids.
nodes []Node
//
incrementalForward bool
// whether to run the forward or backward computations distributing the workload over the available CPUs.
concurrentComputations bool
// cache of the support structures created during the last groupNodesByHeight() computation.
// Before using it you have to check if the maxId of the graph matches the maxId of the cache.
// Otherwise the cache must be invalidated and the values recalculated.
cache struct {
// the maxId when this cache was created.
maxId int64
// nodes grouped by height
nodesByHeight [][]Node
// the nodes height. The index corresponds to the node Id.
height []int
}
// randGen is the generator of random numbers
randGen *rand.LockedRand
}
type GraphOption func(*Graph)
func Rand(rand *rand.LockedRand) GraphOption {
return func(g *Graph) {
g.randGen = rand
}
}
func IncrementalForward(value bool) GraphOption {
return func(g *Graph) {
g.incrementalForward = value
}
}
// ConcurrentComputations sets whether to perform the forward and backward computations in concurrent or sequential mode.
// In the case of concurrent computation all available CPUs are exploited.
// By default, the forward is executed sequentially.
func ConcurrentComputations(value bool) GraphOption {
return func(g *Graph) {
g.concurrentComputations = value
}
}
// NewGraph returns a new initialized graph.
// It can take an optional random generator of type rand.Rand.
func NewGraph(opts ...GraphOption) *Graph {
g := &Graph{
maxId: -1,
curTimeStep: 0,
nodes: nil,
incrementalForward: true,
concurrentComputations: false,
}
for _, opt := range opts {
opt(g)
}
if g.randGen == nil {
g.randGen = rand.NewLockedRand(1) // set default random generator
}
return g
}
// Clear cleans the graph. This is a destructive operation.
// It is not mandatory to call this method, but it is strongly recommended to do so when you finish using the graph.
// The cleaning of the graph improves the memory management and therefore the efficiency of execution.
// Clear releases the matrices underlying the nodes so to reduce the need of future new time-consuming allocations.
// It is important to stress that calling g.Clean(), the "value" and "grad" of the operators nodes are freed (set to nil).
// Whoever is using the Value() or Grad() properties of a node, does so at his own risk. It is therefore recommended to
// make always a copy of the return value of Value() or Grad().
// Alternatively, you can use the convenient graph's methods g.GetCopiedValue(node) and g.GetCopiedGrad(node).
func (g *Graph) Clear() {
g.mu.Lock()
defer g.mu.Unlock()
if g.nodes == nil {
return
}
g.maxId = -1
g.curTimeStep = 0
g.clearCache()
g.releaseMemory()
g.nodes = nil
}
func (g *Graph) clearCache() {
g.cache.maxId = -1
g.cache.nodesByHeight = nil
g.cache.height = nil
}
// ClearForReuse() does the same thing as Clear(), with the difference that the graph structure i.e. how nodes are
// connected to each other, is maintained.
// This allows you to efficiently use the graph as if it were "pre-computed" (see the ForwardAll() method for this usage).
func (g *Graph) ClearForReuse() {
g.mu.Lock()
defer g.mu.Unlock()
if g.nodes == nil {
return
}
g.releaseMemory()
}
// releaseMemory clears the values and the gradients of operator nodes.
// Since the values and the gradients within the nodes are handled through a pool of dense matrices,
// releasing them allows the memory to be reused without being reallocated, improving performance.
func (g *Graph) releaseMemory() {
for _, node := range g.nodes {
if node, ok := node.(*operator); ok {
g.releaseValue(node)
g.releaseGrad(node)
}
}
}
func (g *Graph) releaseValue(node *operator) {
if node.value == nil {
return
}
mat.ReleaseDense(node.value.(*mat.Dense))
node.value = nil
}
func (g *Graph) releaseGrad(node *operator) {
node.ZeroGrad()
}
func (g *Graph) ZeroGrad() {
for _, node := range g.nodes {
node.ZeroGrad()
}
}
// NewVariable creates e returns a new node.
func (g *Graph) NewVariable(value mat.Matrix, requiresGrad bool) Node {
g.mu.Lock()
defer g.mu.Unlock()
newNode := &variable{
graph: g,
timeStep: g.curTimeStep,
id: g.newId(),
value: value,
grad: nil,
hasGrad: false,
requiresGrad: requiresGrad,
}
// the new id is sequential so this the append is fine
g.nodes = append(g.nodes, newNode)
return newNode
}
// NewScalar creates a variable node that doesn't require gradients
func (g *Graph) NewScalar(value float64) Node {
return g.NewVariable(mat.NewScalar(value), false)
}
// NewOperator creates a new operator along with its forward pass.
// Please note that operations must be performed among nodes belonging to the same graph; it panics otherwise.
func (g *Graph) NewOperator(f fn.Function, operands ...Node) Node {
for _, o := range operands {
if o.Graph() != g {
panic("ag: operations cannot be executed among nodes of different graphs. " +
"You may consider wrapping the nodes you need with NewWrap().")
}
}
var value mat.Matrix = nil
if g.incrementalForward {
value = f.Forward() // the calculation is out of the lock so it can run concurrently with other operators
}
requiresGrad := false
for _, operand := range operands {
if operand.RequiresGrad() {
requiresGrad = true
break
}
}
g.mu.Lock()
defer g.mu.Unlock()
newNode := &operator{
graph: g,
timeStep: g.curTimeStep,
id: g.newId(),
function: f,
operands: operands,
value: value,
grad: nil,
hasGrad: false,
requiresGrad: requiresGrad,
}
// the new id is sequential so this the append is fine
g.nodes = append(g.nodes, newNode)
return newNode
}
func (g *Graph) NewWrap(value GradValue) Node {
g.mu.Lock()
defer g.mu.Unlock()
newNode := &wrapper{
GradValue: value,
timeStep: g.curTimeStep,
graph: g,
id: g.newId(),
wrapGrad: true,
}
// the new id is sequential so this the append is fine
g.nodes = append(g.nodes, newNode)
return newNode
}
func (g *Graph) NewWrapNoGrad(value GradValue) Node {
g.mu.Lock()
defer g.mu.Unlock()
newNode := &wrapper{
GradValue: value,
graph: g,
timeStep: g.curTimeStep,
id: g.newId(),
wrapGrad: false,
}
// the new id is sequential so this the append is fine
g.nodes = append(g.nodes, newNode)
return newNode
}
type ForwardOption func(*forwardHandler)
// Range allows you to limit the forward computation within a time-step range.
// By default, the forward computes from the first node at time-step 0 to the last node at the current time-step.
func Range(fromTimeStep, toTimeStep int) ForwardOption {
if fromTimeStep < 0 {
log.Fatalf("ag: expected fromTimeStep equal to or greater than zero. Found %d.", fromTimeStep)
}
if toTimeStep > -1 && toTimeStep < fromTimeStep {
log.Fatalf("ag: expected toTimeStep equal to or greater than `%d` (fromTimeStep). Found `%d`.",
fromTimeStep, toTimeStep)
}
return func(f *forwardHandler) {
f.fromTimeStep = int64(fromTimeStep)
f.toTimeStep = int64(toTimeStep)
}
}
func (g *Graph) Forward(opts ...ForwardOption) {
handler := &forwardHandler{
g: g,
fromTimeStep: 0,
toTimeStep: -1, // unlimited
}
for _, opt := range opts {
opt(handler)
}
// Free the values that are about to be recalculated so that memory is not wasted
for _, node := range g.nodes {
if op, ok := node.(*operator); ok {
if op.timeStep >= handler.fromTimeStep && (handler.toTimeStep == -1 || op.timeStep <= handler.toTimeStep) {
g.releaseValue(op)
}
}
}
if g.concurrentComputations {
handler.runConcurrent()
} else {
handler.runSerial()
}
}
type BackwardOption func(*backwardHandler)
func Truncate(backSteps int) BackwardOption {
return func(f *backwardHandler) {
f.stopAtTimeStep = f.node.getTimeStep() - int64(backSteps)
}
}
func OutputGrad(grad mat.Matrix) BackwardOption {
return func(f *backwardHandler) {
f.outputGrad = grad
}
}
// Backward performs the back-propagation.
// It visits each node in reverse topological order, to propagate the gradients from the given node all the way
// back to the leaf. Note that the gradients are summed to the existing ones. Unless that's what you want, make sure
// all nodes have zero gradients.
//
// The back-propagation starts from the node's output gradients, following these mutually exclusive rules:
// a) the node has gradients (probably assigned externally via node.PropagateGrads()), use those;
// b) the output gradients are passed through the backward options, use those;
// c) the output gradients are automatically assigned by finding the derivative of the node with respect
// to the node itself (dy/dy = 1).
//
// If the optional back steps are set, a Truncated Back-Propagation Through Time is carried out, that is:
// the visit ends as soon as it is encountered a node with time-step less or equal to the number of back steps.
// The TBTT can perform without the need to recalculate the values of previous nodes (Williams and Peng, 1990).
func (g *Graph) Backward(node Node, opts ...BackwardOption) {
handler := &backwardHandler{
g: g,
node: node,
outputGrad: nil,
stopAtTimeStep: -1, // no stop
}
for _, opt := range opts {
opt(handler)
}
if !node.HasGrad() {
handler.propagateOutputGrad()
}
if g.concurrentComputations {
handler.runConcurrent()
} else {
handler.runSerial()
}
}
// BackwardAll performs full back-propagation from the last node of the graph.
// It requires the root nodes to have assigned gradients already.
func (g *Graph) BackwardAll() {
handler := &backwardHandler{
g: g,
node: g.nodes[g.maxId],
outputGrad: nil,
stopAtTimeStep: -1, // no stop
}
if g.concurrentComputations {
handler.runConcurrent()
} else {
handler.runSerial()
}
}
// GetValues returns a copy of the value of a node. If the value is nil, GetCopiedValue returns nil.
// The returned value is a copy, so it is safe to use even after the graph has been cleared calling g.Clear().
// It is important to remember that the Value() property of a Node is a weak access, as the matrix derived from
// graph's operations can be freed.
func (g *Graph) GetCopiedValue(node Node) mat.Matrix {
if node.Value() == nil {
return nil
}
return node.Value().Clone()
}
// GetValues returns a copy of the gradients of a node. If the gradients are nil, GetCopiedGrad returns nil.
// The returned value is a copy, so it is safe to use even after the graph has been cleared calling g.Clear().
// It is important to remember that the Grad() property of a Node is a weak access, as the matrix derived from
// graph's operations can be freed.
func (g *Graph) GetCopiedGrad(node Node) mat.Matrix {
if node.Grad() == nil {
return nil
}
return node.Grad().Clone()
}
// ReplaceValue
func (g *Graph) ReplaceValue(node Node, value mat.Matrix) {
if node, ok := node.(*variable); !ok {
panic("ag: invalid node. Only variables are allowed to change their value.")
} else {
node.value = value
}
}
func (g *Graph) IncTimeStep() {
atomic.AddInt64(&g.curTimeStep, 1)
}
func (g *Graph) TimeStep() int {
return int(g.curTimeStep)
}
// newId generates and returns a new incremental sequential ID.
func (g *Graph) newId() int64 {
return atomic.AddInt64(&g.maxId, 1)
}
func (g *Graph) groupNodesByHeight() [][]Node {
if g.cache.maxId == g.maxId {
return g.cache.nodesByHeight
}
groups := make([][]Node, 0, 1)
height := make([]int, len(g.nodes))
for _, node := range g.nodes {
h := 0
if node, ok := node.(*operator); ok {
for _, operand := range node.operands {
if operand, ok := operand.(*operator); ok {
if height[operand.id] >= h {
h = height[operand.id] + 1
}
}
}
}
height[node.Id()] = h
if h == len(groups) {
groups = append(groups, make([]Node, 0, 1))
}
groups[h] = append(groups[h], node)
}
// update cache and return
g.cache.maxId = g.maxId
g.cache.nodesByHeight = groups
g.cache.height = height
return groups
}
|
wushuaixing/assets-monitor-react
|
src/views/portrait-inquiry/inquiry-check.js
|
import React from 'react';
import { Modal, message } from 'antd';
import { navigate } from '@reach/router';
import { inquiryLimit } from 'api/portrait-inquiry';
const contentStr = num => React.createElement('p', { style: { fontSize: 14 } },
React.createElement('span', { style: { marginBottom: 6 } }, '点击确认,将消耗1次查询次数,返回债务人相关资产、风险等各维度信息的综合查询结果。'),
React.createElement('br', null),
React.createElement('br', null),
React.createElement('span', {}, '当前查询剩余次数:'),
React.createElement('b', { color: '#4E5566' }, ` ${num || 0} 次`));
const contentStrRemind = num => React.createElement('p', { style: { fontSize: 14 } },
React.createElement('span', { style: { marginBottom: 6 } }, '刷新后将消耗1次查询次数,并返回最新画像查询结果;'),
React.createElement('br', null),
React.createElement('br', null),
React.createElement('span', { style: { marginBottom: 6 } }, '点击取消将返回画像查询首页。'),
React.createElement('br', null),
React.createElement('br', null),
React.createElement('span', {}, '当前查询剩余次数:'),
React.createElement('b', { color: '#4E5566' }, ` ${num || 0} 次`));
export const inquiryCheck = (url, type, remind = true) => {
if (global.PORTRAIT_INQUIRY_ALLOW && type === 2) {
return inquiryLimit().then((res) => {
// console.log('查询画像的剩余次数 res ====', res);
const { portraitLimitCount, portraitLimitUseCount } = res.data;
const degree = portraitLimitCount - portraitLimitUseCount;
if (degree > 0 && remind) {
Modal.confirm({
title: '确定查询此债务人画像?',
content: contentStr(degree),
iconType: 'exclamation-circle',
className: 'message-confirm-icon',
onOk() {
if (url)navigate(url);
},
onCancel() {},
});
} else {
message.warning('画像查询次数已用完,若需获取更多查询次数请联系销售或客服!');
}
});
}
return new Promise(resolve => resolve()).then(() => {
if (url)navigate(url);
});
};
export const noneRemind = affirm => inquiryLimit().then((res) => {
if (global.PORTRAIT_INQUIRY_ALLOW) {
const { portraitLimitCount, portraitLimitUseCount } = res.data;
const degree = portraitLimitCount - portraitLimitUseCount;
// eslint-disable-next-line no-shadow
return new Promise((resolve) => {
if (affirm) {
if (degree > 0) {
Modal.confirm({
title: '刷新后将重新获取债务人画像!',
content: contentStrRemind(degree),
iconType: 'exclamation-circle',
className: 'message-confirm-icon',
onOk() {
resolve();
},
onCancel() {
navigate('/inquiry');
// eslint-disable-next-line prefer-promise-reject-errors
},
});
} else {
Modal.warning({
title: '画像查询次数已用完',
content: '若需获取更多查询次数请联系销售或客服!',
iconType: 'exclamation-circle',
className: 'message-confirm-icon',
onOk() {
navigate('/inquiry');
// eslint-disable-next-line prefer-promise-reject-errors
},
});
}
} else {
resolve();
}
});
}
return new Promise(resolve => resolve());
});
|
oleg-cherednik/json-utils
|
src/main/java/ru/olegcherednik/jackson/utils/serializers/JacksonUtilsLocalDateTimeSerializer.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 ru.olegcherednik.jackson.utils.serializers;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
/**
* @author <NAME>
* @since 02.05.2022
*/
public class JacksonUtilsLocalDateTimeSerializer extends LocalDateTimeSerializer {
private static final long serialVersionUID = 2318448753397445923L;
private final boolean useMilliseconds;
public JacksonUtilsLocalDateTimeSerializer(boolean useMilliseconds) {
this(null, useMilliseconds);
}
public JacksonUtilsLocalDateTimeSerializer(DateTimeFormatter formatter, boolean useMilliseconds) {
super(formatter);
this.useMilliseconds = useMilliseconds;
}
@Override
protected JacksonUtilsLocalDateTimeSerializer withFormat(Boolean useTimestamp,
DateTimeFormatter formatter,
JsonFormat.Shape shape) {
return new JacksonUtilsLocalDateTimeSerializer(formatter, useMilliseconds);
}
@Override
@SuppressWarnings("PMD.AvoidReassigningParameters")
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (_formatter == null) {
value = useMilliseconds ? value : value.truncatedTo(ChronoUnit.SECONDS);
}
super.serialize(value, gen, provider);
}
}
|
korenlev/calipso-cvim
|
front-end/imports/api/migrations/migrations.js
|
<gh_stars>0
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2017-2018 <NAME> (Cisco Systems), /
// <NAME> (Cisco Systems), <NAME> (Cisco Systems) and others /
// /
// All rights reserved. This program and the accompanying materials /
// are made available under the terms of the Apache License, Version 2.0 /
// which accompanies this distribution, and is available at /
// http://www.apache.org/licenses/LICENSE-2.0 /
///////////////////////////////////////////////////////////////////////////////
import { CliqueTypes } from '/imports/api/clique-types/clique-types';
Migrations.add({
version: 1,
up: () => {
console.log('migrating: add clique type constaints for env+name, env+focal_point_type');
CliqueTypes._ensureIndex({ environment: 1, name: 1 });
CliqueTypes._ensureIndex({ environment: 1, focal_point_type: 1 });
},
down: () => {
}
});
|
AndyThirtover/wb_gateway
|
WebBrickLibs/EventHandlers/tests/TestSerial.py
|
<reponame>AndyThirtover/wb_gateway
# Copyright L.P.Klyne 2013
# Licenced under 3 clause BSD licence
# $Id: TestSerial.py 2610 2008-08-11 20:08:49Z graham.klyne $
#
# Unit testing for Serial Eventhandler (Serial.py)
# See http://pyunit.sourceforge.net/pyunit.html
#
# NOTE: The local serial parts of this unittest require a serial cable with pins 2 and 3 shorted* to be available at address /dev/ttyUSB0
# *tx wired to rx so anything sent down it is recieved back, wiring must be decent otherwise there will be noise so the test will fail,
import sys, time
import unittest
from MiscLib.DomHelpers import *
from MiscLib.tests.Utils import TestTCPServer
from EventLib.Event import Event, makeEvent
from EventHandlers.BaseHandler import *
from EventHandlers.EventRouterLoad import EventRouterLoader
#import Events
from DummyRouter import *
from EventHandlers.Serial import Serial
import EventHandlers.tests.TestEventLogger as TestEventLogger
# Configuration for the tests
#
testConfigTCP = """<?xml version="1.0" encoding="utf-8"?>
<eventInterface module='EventHandlers.Serial' name='Serial'>
<serialPorts>
<serialPort id="serial-1"
port_type="tcp"
name='My TCP Serial Port'
ipAddress='127.0.0.1'
port='4747'
driver = "TestDriver"
protocol_handler = "TestPHandler"
/>
</serialPorts>
<eventtype type="internal/test/serial">
<eventsource source="serial/test/1" >
<event>
<params>
</params>
<serial cmd="send" action = "light1/on" id='serial-1' />
</event>
</eventsource>
</eventtype>
</eventInterface>
"""
testConfigLocal = """<?xml version="1.0" encoding="utf-8"?>
<eventInterface module='EventHandlers.Serial' name='Serial'>
<!-- This is -->
<serialPorts>
<serialPort id="serial-2"
type="local"
name='A local serial port'
uDevID = '/dev/ttyUSB0'
baudRate = '115200'
driver = "TestDriver"
protocol_handler = "TestPHandler"
/>
</serialPorts>
<eventtype type="internal/test/serial">
<eventsource source="serial/test/2" >
<event>
<params>
</params>
<serial cmd="write" data="65;66;67:" id='serial-2' />
</event>
</eventsource>
</eventtype>
</eventInterface>
"""
testConfigLocalAndTCP = """<?xml version="1.0" encoding="utf-8"?>
<eventInterface module='EventHandlers.Serial' name='Serial'>
<serialPorts>
<serialPort id="serial-1"
type="tcp"
name='My TCP Serial Port'
ipAddress='127.0.0.1'
port='4747'
driver = "TestDriver"
protocol_handler = "TestPHandler"
/>
<serialPort id="serial-2"
type="local"
name='A local serial port'
uDevID = '/dev/ttyUSB0'
baudRate = '115200'
driver = "TestDriver"
protocol_handler = "TestPHandler"
/>
</serialPorts>
<eventtype type="internal/test/serial">
<eventsource source="serial/test/1" >
<event>
<params>
</params>
<serial cmd="send" data="65;66;67:" id='serial-1' />
</event>
</eventsource>
</eventtype>
<eventtype type="internal/test/serial">
<eventsource source="serial/test/2" >
<event>
<params>
</params>
<serial cmd="send" data="66;67;68:" id='serial-2' />
</event>
</eventsource>
</eventtype>
</eventInterface>
"""
# Some Events we might want to send
#evtDO_0_off = makeEvent( 'http://id.webbrick.co.uk/events/webbrick/DO', 'webbrick/100/DO/0', { 'state':'0' } )
#evtDO_0_off = makeEvent( 'http://id.webbrick.co.uk/events/webbrick/DO', 'webbrick/100/DO/0', { 'state':'0' } )
class TestSerial(unittest.TestCase):
def setUp(self):
self._log = logging.getLogger( "TestEventMapper" )
self._log.debug( "\n\n-------------------------------setUp-------------------------------" )
self._log.debug( "\nInitializing dummy router" )
self._router = DummyRouter()
def tearDown(self):
self._log.debug( "\n\n-------------------------------tearDown-------------------------------" )
time.sleep(5)
def expectNevents(self, cnt ):
idx = 20
while (len(TestEventLogger._events) < cnt) and (idx > 0):
time.sleep(0.05)
idx = idx - 1
if ( len(TestEventLogger._events) != cnt):
TestEventLogger.logEvents()
self.assertEqual( len(TestEventLogger._events), cnt)
# Actual tests follow
def testConfigureTCP(self):
self._log.debug( "\n\n-------------------------------testConfigureTCP-------------------------------" )
self._log.debug( "\nInitializng TCP server" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
try:
self._log.debug( "\nInitializing eventhandler" )
testCfg = getDictFromXmlString(testConfigTCP)
self._log.debug( "testCfg %s" % testCfg )
eh = Serial(self._router)
self.assertNotEqual( eh, None)
eh.configure(testCfg['eventInterface'])
eh.start()
configuredPorts = eh.getSerialPorts()
self._log.debug( "\n\nconfigured ports are: %s" % configuredPorts )
assert(configuredPorts.has_key("serial-1"))
if configuredPorts.has_key("serial-1"):
self.assertNotEqual( configuredPorts["serial-1"], None)
eh.stop()
finally:
TCPServ.stop()
def testConfigureLocal(self):
self._log.debug( "\n\n-------------------------------testConfigureLocal-------------------------------" )
testCfg = getDictFromXmlString(testConfigLocal)
self._log.debug( "\nInitializng eventhandler" )
self._log.debug( "testCfg %s" % testCfg )
eh = Serial(self._router)
self.assertNotEqual( eh, None)
eh.configure(testCfg['eventInterface'])
eh.start()
configuredPorts = eh.getSerialPorts()
self._log.debug( "\n\nconfigured ports are: %s" % configuredPorts )
assert(configuredPorts.has_key("serial-2"))
if configuredPorts.has_key("serial-2"):
self.assertNotEqual( configuredPorts["serial-2"], None)
eh.stop()
def testConfigureLocalAndTCP(self):
self._log.debug( "\n\n-------------------------------testconfigureLocalAndTCP-------------------------------" )
self._log.debug( "\nInitializng TCP server" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
try:
self._log.debug( "\nInitializng eventhandler" )
#load the test xml that contains both a local and TCP port
testCfg = getDictFromXmlString(testConfigLocalAndTCP)
self._log.debug( "testCfg %s" % testCfg )
#initialize the eventhandler and make sure it intialized
eh = Serial(self._router)
self.assertNotEqual( eh, None)
#call the configure method to load the ports from the xml
eh.configure(testCfg['eventInterface'])
#start the eventhandler
eh.start()
#get the list of serial ports from our handler
configuredPorts = eh.getSerialPorts()
self._log.debug( "\n\nconfigured ports are: %s" % configuredPorts )
#check our list of serial ports contains the correct serial ports
assert(configuredPorts.has_key("serial-1"))
if configuredPorts.has_key("serial-1"):
self.assertNotEqual( configuredPorts["serial-1"], None)
assert(configuredPorts.has_key("serial-2"))
if configuredPorts.has_key("serial-2"):
self.assertNotEqual( configuredPorts["serial-2"], None)
eh.stop()
finally:
TCPServ.stop()
def testWriteLocal(self):
"""
Test what happens when we start a write event to a Local serial port.
"""
self._log.debug( "\n\n-------------------------------testWriteLocal-------------------------------" )
testCfg = getDictFromXmlString(testConfigLocal)
self._log.debug( "testCfg %s" % testCfg )
eh = Serial(self._router)
self.assertNotEqual( eh, None)
eh.configure(testCfg['eventInterface'])
eh.start()
testEvent = makeEvent( 'internal/test/serial', 'serial/test/2')
eh.handleEvent( testEvent )
time.sleep(2)
portlist = eh.getSerialPorts()
self._log.debug(portlist)
self.assertEqual( len(self._router._pubs), 1 )
self.assertEqual( self._router._pubs[0][1].getType(), "http://id.webbrick.co.uk/events/serial/receive" )
self.assertEqual( self._router._pubs[0][1].getSource(), "serial-2/receive" )
self.assertEqual( self._router._pubs[0][1].getPayload()['data'], "65;66;67:" )
eh.stop()
def testWriteLocalCustomPayload(self):
"""
Test what happens when we start a write event with a custom payload to a Local serial port.
"""
self._log.debug( "\n\n-------------------------------testWriteLocalCustomPayLoad-------------------------------" )
testCfg = getDictFromXmlString(testConfigLocal)
self._log.debug( "testCfg %s" % testCfg )
eh = Serial(self._router)
self.assertNotEqual( eh, None)
eh.configure(testCfg['eventInterface'])
eh.start()
testEvent = makeEvent( 'internal/test/serial', 'serial/test/2', {'cmd':'write','data':'66;67;68:','address':'serial-2'} )
eh.handleEvent( testEvent )
time.sleep(2)
portlist = eh.getSerialPorts()
self._log.debug(portlist)
self.assertEqual( len(self._router._pubs), 1 )
self.assertEqual( self._router._pubs[0][1].getType(), "http://id.webbrick.co.uk/events/serial/receive" )
self.assertEqual( self._router._pubs[0][1].getSource(), "serial-2/receive" )
self.assertEqual( self._router._pubs[0][1].getPayload()['data'], "66;67;68:" )
eh.stop()
def testWriteTCP(self):
"""
Test what happens when we start a write event to a TCP serial port
"""
self._log.debug( "\n\n-------------------------------testWriteTCP-------------------------------" )
self._log.debug( "\nInitializng TCP server" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
try:
self._log.debug( "\nInitializing serial eventhandler" )
testCfg = getDictFromXmlString(testConfigTCP)
self._log.debug( "\ntestCfg : %s" %testCfg )
eh=Serial(self._router)
self.assertNotEqual( eh, None )
eh.configure(testCfg['eventInterface'])
eh.start()
self._log.debug( "\nCreating test event :" )
testEvent = makeEvent( 'internal/test/serial', 'serial/test/1', {} )
self._log.debug( testEvent )
self._log.debug( "\nTesting eventhandler..." )
eh.handleEvent( testEvent )
time.sleep(1)
portlist = eh.getSerialPorts()
self._log.debug( "\nList of active ports : %s" %portlist )
data = TCPServ.data
self._log.debug( "\nTCP server recieved : ##%s##" %data )
assert data == "turn lights onsuccess!"
eh.stop()
finally:
TCPServ.stop()
def testWriteTCPCustomPayload(self):
"""
Test what happens when we start a write event to a TCP serial port with a custom payload
"""
self._log.debug( "\n\n-------------------------------testWriteTCPCustomPayload-------------------------------" )
self._log.debug( "\nInitializng TCP server" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
try:
self._log.debug( "\nInitializing serial eventhandler" )
testCfg = getDictFromXmlString(testConfigTCP)
self._log.debug( "\ntestCfg : %s" %testCfg )
eh=Serial(self._router)
self.assertNotEqual( eh, None )
eh.configure(testCfg['eventInterface'])
eh.start()
self._log.debug( "\nCreating test event :" )
testEvent = makeEvent( 'internal/test/serial', 'serial/test/1', {'cmd':'send','action':'HELLO','id':'serial-1'} )
self._log.debug( testEvent )
self._log.debug( "\nTesting eventhandler..." )
eh.handleEvent( testEvent )
time.sleep(1)
portlist = eh.getSerialPorts()
self._log.debug( "\nList of active ports : %s" %portlist )
data = TCPServ.data
self._log.debug( "\nTCP server recieved : ##%s##" %data )
assert data == "turn lights onsuccess!"
eh.stop()
finally :
TCPServ.stop()
time.sleep(2)
def testWriteTCPAndLocal(self):
"""
Test what happens when we start a write event to a TCP serial port and a Local one at the same time
"""
self._log.debug( "\n\n-------------------------------testWriteTCPAndLocal-------------------------------" )
self._log.debug( "\nInitializng TCP server" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
try:
self._log.debug( "\nInitializing serial eventhandler" )
testCfg = getDictFromXmlString(testConfigLocalAndTCP)
self._log.debug( "\ntestCfg : %s" %testCfg )
eh=Serial(self._router)
self.assertNotEqual( eh, None )
self._log.debug( "\n Configuring serial eventhandler" )
eh.configure(testCfg['eventInterface'])
eh.start()
self._log.debug( "\nCreating test events :" )
TCPSerialevent = makeEvent( 'internal/test/serial', 'serial/test/1', {} )
localSerialevent = makeEvent( 'internal/test/serial', 'serial/test/2', {} )
self._log.debug( "%s and %s" %(localSerialevent,TCPSerialevent) )
self._log.debug( "\nSending TCP event..." )
eh.handleEvent( TCPSerialevent )
self._log.debug( "\nSending local event..." )
eh.handleEvent( localSerialevent )
time.sleep(1)
portlist = eh.getSerialPorts()
self._log.debug( "\nList of active ports : %s" %portlist )
TCPData = TCPServ.data
self._log.debug( "\nTCP server recieved : ##%s##" %TCPData )
assert TCPData == 'ABC'
self.assertEqual( len(self._router._pubs), 1 )
self.assertEqual( self._router._pubs[0][1].getType(), "http://id.webbrick.co.uk/events/serial/receive" )
self.assertEqual( self._router._pubs[0][1].getSource(), "serial-2/receive" )
self.assertEqual( self._router._pubs[0][1].getPayload()['data'], "66;67;68:" )
self._log.debug( "\nLocal serial recieved local data ")
eh.stop()
finally :
TCPServ.stop()
time.sleep(1)
def testReadTCP(self):
"""
Test recieve callback is working correctly for serial ports
"""
self._log.debug( "\n\n-------------------------------testReadTCP-------------------------------" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
try:
self._log.debug( "\nInitializing serial eventhandler with tcp connection configured" )
testCfg = getDictFromXmlString(testConfigTCP)
eh = Serial(self._router)
self.assertNotEqual( eh, None )
eh.configure(testCfg['eventInterface'])
eh.start()
self._log.debug ( "Sending test data" )
TCPServ.send("hello\r")
time.sleep(1)
self.assertEqual( len(self._router._pubs), 1 )
self.assertEqual( self._router._pubs[0][1].getType(), "lighting/update" )
self.assertEqual( self._router._pubs[0][1].getSource(), "light1/on" )
self.assertEqual( self._router._pubs[0][1].getPayload()['lightval'], "1")
eh.stop()
finally:
TCPServ.stop()
time.sleep(1)
def testReadLocal(self):
"""
Test recieve callback is working correctly for serial ports
"""
self._log.debug( "\n\n-------------------------------testReadLocal-------------------------------" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
try:
self._log.debug( "\nInitializing serial eventhandler with tcp connection configured" )
testCfg = getDictFromXmlString(testConfigLocal)
eh = Serial(self._router)
self.assertNotEqual( eh, None )
eh.configure(testCfg['eventInterface'])
eh.start()
self._log.debug ( "Sending test data" )
portlist = eh.getSerialPorts()
portlist["serial-2"].write("hello\r")
portlist["serial-2"].write("world\r")
time.sleep(2)
self.assertEqual( len(self._router._pubs), 2 )
self.assertEqual( self._router._pubs[0][1].getType(), "http://id.webbrick.co.uk/events/serial/receive" )
self.assertEqual( self._router._pubs[0][1].getSource(), "serial-2/receive" )
self.assertEqual( self._router._pubs[0][1].getPayload()['data'], "104;101;108;108;111:" )
self.assertEqual( self._router._pubs[1][1].getType(), "http://id.webbrick.co.uk/events/serial/receive" )
self.assertEqual( self._router._pubs[1][1].getSource(), "serial-2/receive" )
self.assertEqual( self._router._pubs[1][1].getPayload()['data'], "119;111;114;108;100:" )
eh.stop()
finally:
TCPServ.stop()
time.sleep(1)
def testDisconnectRecover(self):
"""
Test recieve callback is working correctly for serial ports
"""
self._log.debug( "\n\n-------------------------------testReadTCP-------------------------------" )
TCPServ = TestTCPServer(4747)
TCPServ.start()
self._log.debug( "\nInitializing serial eventhandler with tcp connection configured" )
testCfg = getDictFromXmlString(testConfigTCP)
eh = Serial(self._router)
self.assertNotEqual( eh, None )
eh.configure(testCfg['eventInterface'])
eh.start()
self._log.debug ( "Sending test data" )
TCPServ.send("hello\r")
time.sleep(0.5)
self.assertEqual( len(self._router._pubs), 1 )
self.assertEqual( self._router._pubs[0][1].getType(), "lighting/update" )
self.assertEqual( self._router._pubs[0][1].getSource(), "light1/on" )
self.assertEqual( self._router._pubs[0][1].getPayload()['lightval'], "1")
TCPServ.stop()
time.sleep(0.5)
TCPServ = TestTCPServer(4747)
TCPServ.start()
testEvent = makeEvent( 'internal/test/serial', 'serial/test/1', {} )
self._log.debug( testEvent )
self._log.debug( "\nTesting eventhandler..." )
eh.handleEvent( testEvent )
eh.handleEvent( testEvent )
eh.handleEvent( testEvent )
eh.handleEvent( testEvent )
TCPServ.send("hello\r")
time.sleep(1)
assert TCPServ.read() == "turn lights onsuccess!turn lights onsuccess!"
self.assertEqual( len(self._router._pubs), 2 )
self.assertEqual( self._router._pubs[1][1].getType(), "lighting/update" )
self.assertEqual( self._router._pubs[1][1].getSource(), "light1/on" )
self.assertEqual( self._router._pubs[1][1].getPayload()['lightval'], "1")
time.sleep(0.5)
def testDummy(self):
return
from MiscLib import TestUtils
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" return suite of pending tests
name a single named test to be run
"""
testdict = {
"unit":
[
"testConfigureTCP",
"testWriteTCP",
"testWriteTCPCustomPayload",
"testReadTCP",
"testDisconnectRecover"
],
"component":
[
"testConfigureLocal",
"testConfigureLocalAndTCP",
"testWriteLocal",
"testWriteLocalCustomPayload",
"testWriteTCPAndLocal",
"testReadLocal"
],
"integration":
[ "testDummy"
],
"pending":
[ "testDummy"
]
}
return TestUtils.getTestSuite(TestSerial, testdict, select=select)
# Run unit tests directly from command line
if __name__ == "__main__":
TestUtils.runTests("TestSerial.log", getTestSuite, sys.argv)
|
Heasn/ms
|
src/main/java/im/cave/ms/provider/wz/MapleDataTool.java
|
package im.cave.ms.provider.wz;
import im.cave.ms.tools.StringUtil;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
public class MapleDataTool {
public static String getString(MapleData data) {
if (data.getData() instanceof Integer) {
return Integer.toString((Integer) data.getData());
}
if (data.getData() instanceof Long) {
return Long.toString(((Long) data.getData()));
}
if (data.getData() instanceof Float) {
return Float.toString((Float) data.getData());
}
if (data.getData() instanceof Double) {
return Double.toString(((Double) data.getData()));
}
if (data.getData() instanceof Short) {
return Short.toString((Short) data.getData());
}
if (data.getData() instanceof Point) {
return data.getData().toString();
}
String ret;
try {
ret = ((String) data.getData());
} catch (Exception e) {
return null;
}
return ret;
}
public static String getString(MapleData data, String def) {
if (data == null || data.getData() == null) {
return def;
} else if (data.getType() == MapleDataType.STRING || data.getData() instanceof String) {
String ret = ((String) data.getData());
ret = ret.replace("<", "<");
ret = ret.replace("&lt;", "<");
ret = ret.replace(">", ">");
return ret;
} else {
// return String.valueOf(getInt(data));
return data.getData().toString();
}
}
public static String getString(String path, MapleData data) {
return getString(data.getChildByPath(path));
}
public static String getString(String path, MapleData data, String def) {
return getString(data == null || data.getChildByPath(path) == null ? null : data.getChildByPath(path), def);
}
public static double getDouble(MapleData data) {
return (Double) data.getData();
}
public static float getFloat(MapleData data) {
return (Float) data.getData();
}
public static float getFloat(MapleData data, float def) {
if (data == null || data.getData() == null) {
return def;
} else {
return (Float) data.getData();
}
}
public static int getInt(MapleData data) {
return Integer.parseInt(data.getData().toString());
}
public static int getInt(MapleData data, int def) {
if (data == null || data.getData() == null) {
return def;
} else {
if (data.getType() == MapleDataType.STRING) {
String data_ = getString(data);
if (data_ == null || data_.isEmpty()) {
data_ = "0";
}
return Integer.parseInt(data_);
} else if (data.getType() == MapleDataType.SHORT) {
return (int) (Short) data.getData();
} else if (data.getType() == MapleDataType.DOUBLE) {
return (int) (double) data.getData();
} else {
return ((Long) data.getData()).intValue();
}
}
}
public static int getInt(String path, MapleData data) {
return getInt(data.getChildByPath(path));
}
public static short getShort(MapleData data) {
return (short) getInt(data);
}
public static int getIntConvert(MapleData data) {
if (data.getType() == MapleDataType.STRING) {
return Integer.parseInt(getString(data));
} else {
return getInt(data);
}
}
public static int getIntConvert(String path, MapleData data) {
MapleData d = data.getChildByPath(path);
if (d.getType() == MapleDataType.STRING) {
return Integer.parseInt(getString(d));
} else {
return getInt(d);
}
}
public static int getInt(String path, MapleData data, int def) {
if (data == null) {
return def;
}
return getInt(data.getChildByPath(path), def);
}
public static int getIntConvert(String path, MapleData data, int def) {
if (data == null) {
return def;
}
return getIntConvert(data.getChildByPath(path), def);
}
public static int getIntConvert(MapleData d, int def) {
if (d == null) {
return def;
}
if (d.getType() == MapleDataType.STRING) {
String dd = getString(d);
if (dd.endsWith("%")) {
dd = dd.substring(0, dd.length() - 1);
}
try {
return Integer.parseInt(dd);
} catch (NumberFormatException nfe) {
return def;
}
} else {
return getInt(d, def);
}
}
public static BufferedImage getImage(MapleData data) {
return ((MapleCanvas) data.getData()).getImage();
}
public static Point getPoint(MapleData data) {
return ((Point) data.getData());
}
public static Point getPoint(String path, MapleData data) {
return getPoint(data.getChildByPath(path));
}
public static Point getPoint(String path, MapleData data, Point def) {
MapleData pointData = data.getChildByPath(path);
if (pointData == null) {
return def;
}
return getPoint(pointData);
}
public static String getFullDataPath(MapleData data) {
String path = "";
MapleDataEntity myData = data;
while (myData != null) {
path = myData.getName() + "/" + path;
myData = myData.getParent();
}
return path.substring(0, path.length() - 1);
}
public static Map<?, ?> getAllMapleData(MapleData data) {
Map<Object, Object> ret = new HashMap<>();
for (MapleData subdata : data) {
switch (subdata.getName()) {
case "icon":
case "iconRaw":
boolean isInLink;
boolean isOutLink;
for (MapleData subdatum : subdata) {
isInLink = subdatum.getName().equals("_inlink");
isOutLink = subdatum.getName().equals("_outlink");
if (isInLink || isOutLink) {
int inlink = 0;
String[] split = subdatum.getData().toString().replace(".img", "").split("/");
for (int i = 0; i < split.length; i++) {
if ((isInLink && i == 0 || isOutLink && (i == 2 || i == 3)) && StringUtil.isNumber(split[i])) {
inlink = Integer.parseInt(split[i]);
}
}
if (inlink != 0) {
ret.put(subdatum.getName(), inlink);
}
}
}
continue;
}
ret.put(subdata.getName(), subdata.getChildren().isEmpty() ? subdata.getData() : getAllMapleData(subdata));
}
return ret;
}
}
|
miotech/KUN
|
kun-security/kun-security-common/src/main/java/com/miotech/kun/security/common/KunRole.java
|
<reponame>miotech/KUN
package com.miotech.kun.security.common;
import java.util.Set;
public interface KunRole {
Set<UserOperation> getUserOperation();
Integer rank();
String getName();
}
|
doveylovey/alipay-sdk-java
|
src/main/java/com/alipay/api/domain/KoubeiQualityTestCloudacptCheckresultSubmitModel.java
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 云验收检测结果提交
*
* @author auto create
* @since 1.0, 2016-10-26 18:05:16
*/
public class KoubeiQualityTestCloudacptCheckresultSubmitModel extends AlipayObject {
private static final long serialVersionUID = 8693141332285249948L;
/**
* 活动id
*/
@ApiField("activity_id")
private String activityId;
/**
* 付款码
*/
@ApiField("auth_code")
private String authCode;
/**
* 批次ID
*/
@ApiField("batch_id")
private String batchId;
/**
* 结束时间
*/
@ApiField("end_time")
private String endTime;
/**
* partenter id
*/
@ApiField("pid")
private String pid;
/**
* 开始时间
*/
@ApiField("start_time")
private String startTime;
/**
* user id
*/
@ApiField("uid")
private String uid;
public String getActivityId() {
return this.activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getAuthCode() {
return this.authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public String getBatchId() {
return this.batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getEndTime() {
return this.endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getPid() {
return this.pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getStartTime() {
return this.startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getUid() {
return this.uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
|
magic-lantern-studio/mle-core-dpp
|
DigitalPlayprint/runtime/common/include/mle/scenechk.h
|
<reponame>magic-lantern-studio/mle-core-dpp<filename>DigitalPlayprint/runtime/common/include/mle/scenechk.h
/** @defgroup MleDPPMaster Magic Lantern Digital Playprint Library API - Master */
/**
* @file scenechk.h
* @ingroup MleDPPMaster
*
* Magic Lantern Digital Playprint Library API.
*
* @author <NAME>
* @created September 15, 2004
*/
// COPYRIGHT_BEGIN
//
// Copyright (c) 2015-2018 Wizzer Works
//
// 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.
//
// For information concerning this header file, contact Mark S. Millard,
// of Wizzer Works at <EMAIL>.
//
// More information concerning Wizzer Works may be found at
//
// http://www.wizzerworks.com
//
// COPYRIGHT_END
#ifndef __MLE_DPP_SCENECHUNK_H_
#define __MLE_DPP_SCENECHUNK_H_
// Include Digital Playprint header files.
#include "mle/mlTypes.h"
#include "mle/Dpp.h"
/**
* @brief This class is used to create Scene Chunks for the Magic
* Lantern Digital Playprint format.
*/
class MleDppSceneChunk
{
public:
/**
* A constructor that initializes the file nane and endian format
* of the chunk file.
*
* @param filename The name of the chunk generated by the MleDppOutput class in the workprint.
* @param isLittle Indicate whether the chunk file should be formatted using the Little
* Endian byte format.
*/
MleDppSceneChunk(const char* filename, MlBoolean isLittle);
/**
* The destructor.
*/
virtual ~MleDppSceneChunk()
{
if (m_groupNames != NULL)
delete m_groupNames;
fclose(m_fp);
};
/**
* @brief Get the name of the groups.
*
* @return An inline array of strings is returned.
*/
const char* getNames(void)
{ return m_groupNames; };
/**
* @brief Get the next group name.
*
* This can be used to iterate from one string to the next.
*
* @return The next group name will be returned as a pointer to
* a character string. <b>NULL</b> is returned when it runs out of strings.
*/
const char *nextName(const char *name);
/**
* @brief Get the number of groups.
*
* @return The number of strings is returned.
*/
int countNames(void);
/**
* @brief Load the Scene Chunk
*
* This constructs an scene chunk with each group name replaced
* with its corresponding index into the chunk; it returns the address and length of the
* resolved scene chunk.
* <p>
* It is the caller's responsibility to call delete on the method result.
* </p>
*/
const MlByte *loadChunk(MlInt *length);
/**
* Override operator new.
*
* @param tSize The size, in bytes, to allocate.
*/
void* operator new(size_t tSize);
/**
* Override operator delete.
*
* @param p A pointer to the memory to delete.
*/
void operator delete(void *p);
private:
FILE * m_fp;
char * m_groupNames;
MlInt m_nameOffset;
MlInt m_nameLength;
MlBoolean m_littleEndian;
const MlByte * m_chunkRef;
const MlByte * m_chunkStart;
const MlByte * m_chunkEnd;
MlByte * m_resolvedChunkPtr;
MlByte nextChunkByte(void);
MlByte copyStreamByte(void)
{ return *m_resolvedChunkPtr++ = nextChunkByte(); };
MlInt readIndex(void);
MlInt writeIndex(MlInt index);
MlInt readInt(void);
MlInt writeInt(MlInt index);
MlInt copyIndex()
{ return writeIndex(readIndex()); };
MlInt copyInt()
{ return writeInt(readInt()); };
};
#endif /* __MLE_DPP_SCENECHUNK_H_ */
|
damianosky/Maud-X
|
src/it/unitn/ing/rista/diffr/cal/D20IntensityCalibration.java
|
/*
* @(#)D20IntensityCalibration.java created 24/07/1999 Pergine
*
* Copyright (c) 1997-1999 <NAME> All Rights Reserved.
*
* This software is the research result of <NAME> and it is
* provided as it is as confidential and proprietary information.
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with the author.
*
* THE AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. THE AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
package it.unitn.ing.rista.diffr.cal;
import it.unitn.ing.rista.diffr.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import it.unitn.ing.rista.util.*;
import it.unitn.ing.rista.awt.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* The D20IntensityCalibration is a class
*
*
* @version $Revision: 1.6 $, $Date: 2006/01/19 14:45:55 $
* @author <NAME>
* @since JDK1.1
*/
public class D20IntensityCalibration extends IntensityFileCalibration {
public D20IntensityCalibration(XRDcat aobj, String alabel) {
super(aobj, alabel);
identifier = "D20 Intensity cal";
IDlabel = "D20 Intensity cal";
}
public D20IntensityCalibration(XRDcat aobj) {
this(aobj, "Calibration file x");
}
public D20IntensityCalibration() {
identifier = "D20 Intensity cal";
IDlabel = "D20 Intensity cal";
}
public void readall() {
refreshCalibration = true;
boolean isAbilitate = isAbilitatetoRefresh;
isAbilitatetoRefresh = false;
BufferedReader reader = Misc.getReader(getFileName());
if (reader != null) {
try {
Vector angular = new Vector(0, 100);
String token = new String("");
StringTokenizer st = null;
String linedata = null;
boolean endoffile = false;
boolean found = false;
linedata = reader.readLine();
st = new StringTokenizer(linedata, "() ,\t\r\n");
token = st.nextToken();
token = st.nextToken();
datanumber = Integer.valueOf(token).intValue();
calintensity = new double[datanumber];
int i = 0;
while (i < datanumber) {
linedata = reader.readLine();
if (linedata == null) {
endoffile = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
while (st.hasMoreTokens() && i < datanumber) {
st.nextToken();
i++;
}
}
i = 0;
while (i < datanumber) {
linedata = reader.readLine();
if (linedata == null) {
endoffile = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
while (st.hasMoreTokens() && i < datanumber) {
double calibration = Double.valueOf(st.nextToken()).doubleValue();
if (calibration == 0.0)
calibration = 3.86173;
calintensity[i++] = 1.0 / calibration;
}
}
} catch (IOException e) {
System.out.println("Error in loading the data file! Try to remove this data file");
}
try {
reader.close();
} catch (IOException e) {
}
}
isAbilitatetoRefresh = isAbilitate;
notifyUpObjectChanged(this, Constants.INTENSITY_CALIBRATION);
}
public double calibrateData(DiffrDataFile datafile, double x, int index) {
if (calintensity == null) {
if (getFileName() != null && !getFileName().equals("")) {
} else
return 1.0;
}
return calintensity[index];
}
public boolean validX(DiffrDataFile datafile, double x, int index) {
if (calintensity == null) {
if (getFileName() != null && !getFileName().equals("")) {
} else
return true;
}
if (calintensity[index] >= 3.86173)
return false;
else
return true;
}
public JOptionsDialog getOptionsDialog(Frame parent) {
JOptionsDialog adialog = new JIDCOptionsD(parent, this);
return adialog;
}
class JIDCOptionsD extends JOptionsDialog {
JTextField filenameL;
public JIDCOptionsD(Frame parent, XRDcat obj) {
super(parent, obj);
principalPanel.setLayout(new BorderLayout(6, 6));
JPanel jp3 = new JPanel();
jp3.setLayout(new BorderLayout(6, 6));
JPanel jp2 = new JPanel();
jp2.setLayout(new BorderLayout(6, 6));
principalPanel.add(BorderLayout.NORTH, jp3);
JPanel jp1 = new JPanel();
jp1.setLayout(new FlowLayout(FlowLayout.LEFT, 1, 1));
jp3.add(BorderLayout.WEST, jp1);
JLabel jl1 = new JLabel("Intensity calibration File: ");
jp1.add(jl1);
jp1 = new JPanel();
jp1.setLayout(new FlowLayout(FlowLayout.RIGHT, 1, 1));
jp3.add(BorderLayout.EAST, jp1);
JButton jb = new JIconButton("Open.gif", "Browse...");
jp1.add(jb);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
browsethefile();
}
});
jp1 = new JPanel();
jp1.setLayout(new FlowLayout());
principalPanel.add(BorderLayout.CENTER, jp1);
filenameL = new JTextField(40);
filenameL.setEditable(false);
jp1.add(filenameL);
setTitle("Intensity calibration");
initParameters();
pack();
}
public void initParameters() {
filenameL.setText(getFileName());
}
public void retrieveParameters() {
}
public void browsethefile() {
String filename = loadDataFile(this);
filenameL.setText(getFileName());
}
}
}
|
tlaukkan/zigbee4java
|
zigbee-common/src/main/java/org/bubblecloud/zigbee/v3/zcl/protocol/command/rssi/location/GetLocationDataCommand.java
|
package org.bubblecloud.zigbee.v3.zcl.protocol.command.rssi.location;
import org.bubblecloud.zigbee.v3.zcl.ZclCommandMessage;
import org.bubblecloud.zigbee.v3.zcl.ZclCommand;
import org.bubblecloud.zigbee.v3.zcl.protocol.ZclCommandType;
import org.bubblecloud.zigbee.v3.zcl.protocol.ZclFieldType;
/**
* Code generated Get Location Data Command value object class.
*/
public class GetLocationDataCommand extends ZclCommand {
/**
* Header command message field.
*/
private Integer header;
/**
* Number Responses command message field.
*/
private Integer numberResponses;
/**
* Target Address command message field.
*/
private Long targetAddress;
/**
* Default constructor setting the command type field.
*/
public GetLocationDataCommand() {
this.setType(ZclCommandType.GET_LOCATION_DATA_COMMAND);
}
/**
* Constructor copying field values from command message.
* @param message the command message
*/
public GetLocationDataCommand(final ZclCommandMessage message) {
super(message);
this.header = (Integer) message.getFields().get(ZclFieldType.GET_LOCATION_DATA_COMMAND_HEADER);
this.numberResponses = (Integer) message.getFields().get(ZclFieldType.GET_LOCATION_DATA_COMMAND_NUMBER_RESPONSES);
this.targetAddress = (Long) message.getFields().get(ZclFieldType.GET_LOCATION_DATA_COMMAND_TARGET_ADDRESS);
}
@Override
public ZclCommandMessage toCommandMessage() {
final ZclCommandMessage message = super.toCommandMessage();
message.getFields().put(ZclFieldType.GET_LOCATION_DATA_COMMAND_HEADER,header);
message.getFields().put(ZclFieldType.GET_LOCATION_DATA_COMMAND_NUMBER_RESPONSES,numberResponses);
message.getFields().put(ZclFieldType.GET_LOCATION_DATA_COMMAND_TARGET_ADDRESS,targetAddress);
return message;
}
/**
* Gets Header.
* @return the Header
*/
public Integer getHeader() {
return header;
}
/**
* Sets Header.
* @param header the Header
*/
public void setHeader(final Integer header) {
this.header = header;
}
/**
* Gets Number Responses.
* @return the Number Responses
*/
public Integer getNumberResponses() {
return numberResponses;
}
/**
* Sets Number Responses.
* @param numberResponses the Number Responses
*/
public void setNumberResponses(final Integer numberResponses) {
this.numberResponses = numberResponses;
}
/**
* Gets Target Address.
* @return the Target Address
*/
public Long getTargetAddress() {
return targetAddress;
}
/**
* Sets Target Address.
* @param targetAddress the Target Address
*/
public void setTargetAddress(final Long targetAddress) {
this.targetAddress = targetAddress;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(super.toString());
builder.append(", ");
builder.append("header");
builder.append('=');
builder.append(header);
builder.append(", ");
builder.append("numberResponses");
builder.append('=');
builder.append(numberResponses);
builder.append(", ");
builder.append("targetAddress");
builder.append('=');
builder.append(targetAddress);
return builder.toString();
}
}
|
freddyz/computerscare-vcv-modules
|
src/waveblob.hpp
|
<reponame>freddyz/computerscare-vcv-modules
#pragma once
namespace rack {
namespace app {
struct Waveblob {
std::vector<Vec> trigs;
Points points;
int numPoints;
Waveblob(int n = 200) {
numPoints = n;
makeTrigs();
}
void makeTrigs() {
trigs.resize(numPoints);
float omega = 2 * M_PI / numPoints;
for (int i = 0; i < numPoints) {
numPoints.push_back(Vec(cos(omega * i), sin(omega * i)));
}
}
Points eval(float time) {
//points.
}
};
}
}
|
nilamjadhav/TypeScript
|
tests/baselines/reference/overloadOnConstDuplicateOverloads1.js
|
//// [overloadOnConstDuplicateOverloads1.ts]
function foo(a: 'hi', x: string);
function foo(a: 'hi', x: string);
function foo(a: any, x: any) {
}
function foo2(a: 'hi', x: string);
function foo2(a: 'hi', x: string);
function foo2(a: string, x: string);
function foo2(a: any, x: any) {
}
//// [overloadOnConstDuplicateOverloads1.js]
function foo(a, x) {
}
function foo2(a, x) {
}
|
fmjsjx/entrepot
|
entrepot-server/src/main/java/com/github/fmjsjx/entrepot/server/conf/WharfType.java
|
package com.github.fmjsjx.entrepot.server.conf;
import lombok.extern.slf4j.Slf4j;
/**
* Enumeration of hangar type.
*/
@Slf4j
public enum WharfType {
RAW, COOK;
public static final WharfType of(String type) {
if (type == null) {
return RAW;
}
switch (type) {
case "cook":
return COOK;
default:
log.warn("Unknown wharf type `{}`, use the default wharf type `raw` instead", type);
case "raw":
return RAW;
}
}
}
|
margaretkennedy/deephaven-core
|
DB/src/test/java/io/deephaven/db/v2/utils/RedirectionIndexLockFreeTest.java
|
<reponame>margaretkennedy/deephaven-core
/*
* Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending
*/
package io.deephaven.db.v2.utils;
import io.deephaven.db.tables.live.LiveTableMonitor;
import io.deephaven.db.v2.LiveTableTestCase;
import io.deephaven.db.v2.sources.LogicalClock;
import gnu.trove.list.array.TLongArrayList;
import org.apache.commons.lang3.mutable.MutableInt;
import java.util.Arrays;
import java.util.Random;
import static io.deephaven.base.ArrayUtil.swap;
public class RedirectionIndexLockFreeTest extends LiveTableTestCase {
private static final long oneBillion = 1000000000L;
private static final int testDurationInSeconds = 15;
public void testRedirectionIndex() throws InterruptedException {
final RedirectionIndexLockFreeImpl index = new RedirectionIndexLockFreeFactory().createRedirectionIndex(10);
index.startTrackingPrevValues();
final long initialStep = LogicalClock.DEFAULT.currentStep();
Writer writer = new Writer("writer", initialStep, index);
Reader r0 = new Reader("reader0", initialStep, index);
Reader r1 = new Reader("reader1", initialStep, index);
// Run one iteration of the writer so the prev values exist.
writer.doOneIteration();
RWBase[] participants = { writer, r0, r1 };
Thread[] threads = Arrays.stream(participants).map(Thread::new).toArray(Thread[]::new);
for (Thread thread : threads) {
thread.start();
}
System.out.printf("Test will run for %d seconds%n", testDurationInSeconds);
Thread.sleep(testDurationInSeconds * 1000);
for (RWBase rwb : participants) {
rwb.cancel();
}
for (Thread thread : threads) {
thread.join();
}
boolean failed = false;
for (RWBase rwb : participants) {
System.out.println(rwb);
failed |= rwb.hasFailed();
}
if (failed) {
fail("RedirectionIndex had some corrupt values");
}
}
private interface Cancellable {
void cancel();
}
private static abstract class RWBase implements Runnable, Cancellable {
protected final String name;
protected final long initialStep;
protected final RedirectionIndexLockFreeImpl index;
protected int numIterations;
protected volatile boolean cancelled;
protected RWBase(String name, long initialStep, RedirectionIndexLockFreeImpl index) {
this.name = name;
this.initialStep = initialStep;
this.index = index;
this.numIterations = 0;
this.cancelled = false;
}
public final void run() {
while (!cancelled) {
doOneIteration();
++numIterations;
}
}
public final void cancel() {
this.cancelled = true;
}
protected abstract void doOneIteration();
public abstract boolean hasFailed();
}
private static class Reader extends RWBase {
private int goodIdleCycles;
private int goodUpdateCycles;
private int badIdleCycles;
private int badUpdateCycles;
private int incoherentCycles;
Reader(String name, long initialStep, RedirectionIndexLockFreeImpl index) {
super(name, initialStep, index);
goodIdleCycles = 0;
goodUpdateCycles = 0;
badIdleCycles = 0;
badUpdateCycles = 0;
incoherentCycles = 0;
}
@Override
protected final void doOneIteration() {
// Figure out what step we're in and what step to read from (current or prev).
final long logicalClockStartValue = LogicalClock.DEFAULT.currentValue();
final long stepFromCycle = LogicalClock.getStep(logicalClockStartValue);
final LogicalClock.State state = LogicalClock.getState(logicalClockStartValue);
final long step = state == LogicalClock.State.Updating ? stepFromCycle - 1 : stepFromCycle;
final int keysInThisGeneration = (int)((step - initialStep) * 1000 + 1000);
final Random rng = new Random(step);
final int numKeysToInsert = rng.nextInt(keysInThisGeneration);
long[] keys = fillAndShuffle(rng, keysInThisGeneration);
final RedirectionIndexLockFreeImpl ix = index;
// Record the mismatches
final TLongArrayList mmKeys = new TLongArrayList();
final TLongArrayList mmExpect = new TLongArrayList();
final TLongArrayList mmActual = new TLongArrayList();
// Look at the map in the reverse order of the writer, just to avoid any unintended synchronization.
// These keys are expected to not exist.
for (int ii = keys.length - 1; ii >= numKeysToInsert; --ii) {
final long key = keys[ii];
final long actualValue = state == LogicalClock.State.Updating ? ix.getPrev(key) : ix.get(key);
if (actualValue != -1) {
mmKeys.add(key);
mmExpect.add(-1);
mmActual.add(actualValue);
}
}
// These keys are expected to exist
for (int ii = numKeysToInsert - 1; ii >= 0; --ii) {
final long key = keys[ii];
final long expectedValue = step * oneBillion + ii;
final long actualValue = state == LogicalClock.State.Updating ? ix.getPrev(key) : ix.get(key);
if (expectedValue != actualValue) {
mmKeys.add(key);
mmExpect.add(expectedValue);
mmActual.add(actualValue);
}
}
final long logicalClockEndValue = LogicalClock.DEFAULT.currentValue();
if (logicalClockStartValue != logicalClockEndValue) {
++incoherentCycles;
return;
}
if (mmKeys.isEmpty()) {
if (state == LogicalClock.State.Updating) {
++goodUpdateCycles;
} else {
++goodIdleCycles;
}
return;
}
if (state == LogicalClock.State.Updating) {
++badUpdateCycles;
} else {
++badIdleCycles;
}
}
@Override
public boolean hasFailed() {
return badIdleCycles != 0 || badUpdateCycles != 0;
}
@Override
public String toString() {
return String.format("--- %s: iterations: %d, good update: %d, good idle: %d, bad update: %d, bad idle: %d, incoherent (no judgment): %d ---",
name, numIterations, goodUpdateCycles, goodIdleCycles, badUpdateCycles, badIdleCycles, incoherentCycles);
}
}
private static class Writer extends RWBase {
Writer(String name, long initialStep, RedirectionIndexLockFreeImpl index) {
super(name, initialStep, index);
}
@Override
protected final void doOneIteration() {
final MutableInt keysInThisGeneration = new MutableInt();
LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> {
final long step = LogicalClock.DEFAULT.currentStep();
keysInThisGeneration.setValue((int) ((step - initialStep) * 1000 + 1000));
final Random rng = new Random(step);
final int numKeysToInsert = rng.nextInt(keysInThisGeneration.getValue());
// A bit of a waste because we only look at the first 'numKeysToInsert' keys, but that's ok.
long[] keys = fillAndShuffle(rng, keysInThisGeneration.getValue());
final RedirectionIndexLockFreeImpl ix = index;
for (int ii = 0; ii < numKeysToInsert; ++ii) {
final long key = keys[ii];
final long value = step * oneBillion + ii;
ix.put(key, value);
}
for (int ii = numKeysToInsert; ii < keys.length; ++ii) {
final long key = keys[ii];
ix.remove(key);
}
});
// waste some time doing something else
final RedirectionIndexLockFreeImpl privateIndex = new RedirectionIndexLockFreeFactory().createRedirectionIndex(10);
for (long ii = 0; ii < keysInThisGeneration.getValue() * 4; ++ii) {
privateIndex.put(ii, ii);
}
}
@Override
public String toString() {
return String.format("+++ %s: iterations: %d +++", name, numIterations);
}
public boolean hasFailed() {
return false;
}
}
private static long[] fillAndShuffle(Random rng, int length) {
long[] result = new long[length];
for (int ii = 0; ii < result.length; ++ii) {
result[ii] = ii;
}
for (int size = length; size > 1; --size) {
int target = rng.nextInt(size);
swap(result, target, size - 1);
}
return result;
}
}
|
noirhero/the_madness
|
client/system/system_movement_anim.js
|
<filename>client/system/system_movement_anim.js
// Copyright 2018 TAP, Inc. All Rights Reserved.
const SystemMovementAnim = CES.System.extend({
init: function() {
this.player_memory = {
is_first: true,
pos: glMatrix.vec3.create(),
};
this.net_player_memories = [];
},
update: function() {
const process_fn = (memory, entity) => {
const pos = entity.getComponent("Pos").pos;
const rot = entity.getComponent("Rot").rot;
const anim_comp = entity.getComponent("Anim");
if(true === memory.is_first) {
memory.is_first = false;
glMatrix.vec3.copy(memory.pos, pos);
}
else {
const dist = glMatrix.vec3.distance(memory.pos, pos);
if(1 > dist) {
anim_comp.state = "idle";
}
else {
if(memory.pos[0] > pos[0]) {
glMatrix.quat.rotateY(rot, IDENTITY_QUAT, RAD_180);
}
else if(memory.pos[0] < pos[0]){
glMatrix.quat.copy(rot, IDENTITY_QUAT);
}
anim_comp.state = "run";
glMatrix.vec3.copy(memory.pos, pos);
}
}
};
const player_memory = this.player_memory;
this.world.getEntities("Player", "Pos", "Rot", "Anim").forEach(entity => {
process_fn(player_memory, entity);
});
const net_player_memories = this.net_player_memories;
this.world.getEntities("NetPlayer", "Pos", "Rot", "Anim").forEach(entity => {
const net_player_id = entity.getComponent("NetPlayer").id;
if(!net_player_memories[net_player_id]) {
net_player_memories[net_player_id] = {
is_first: false,
pos: glMatrix.vec3.create(),
};
}
process_fn(net_player_memories[net_player_id], entity);
});
},
});
|
BlockClusterApp/homepage
|
src/routes/legal/privacy/index.js
|
<gh_stars>0
import React from 'react';
// import Layout from '../../../components/Layout';
import LegalLayout from '../components/Layout';
import Privacy from './Privacy';
async function action() {
return {
title: 'Privacy policy',
chunks: ['privacy'],
component: (
<LegalLayout>
<Privacy />
</LegalLayout>
),
};
}
export default action;
|
lesleycl/patternfly-react
|
packages/patternfly-4/react-core/src/components/Wizard/examples/FinishedStep.js
|
import React from 'react';
import PropTypes from 'prop-types';
const propTypes = {
onClose: PropTypes.func.isRequired
};
class FinishedStep extends React.Component {
constructor(props) {
super(props);
this.state = { percent: 0 };
}
tick() {
if (this.state.percent < 100) {
this.setState(prevState => ({
percent: prevState.percent + 20
}));
}
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
const { percent } = this.state;
return (
<div className="pf-l-bullseye">
<div className="pf-c-empty-state pf-m-lg">
<i className="fas fa- fa-cogs pf-c-empty-state__icon" aria-hidden="true" />
<h1 className="pf-c-title pf-m-lg">
{percent === 100 ? `Configuration Complete` : `Configuration in progress`}
</h1>
<div className="pf-c-empty-state__body">
<div className="pf-c-progress pf-m-singleline" id="progress-singleline-example">
<div className="pf-c-progress__description" id="progress-singleline-example-description" />
<div className="pf-c-progress__status" aria-hidden="true">
<span className="pf-c-progress__measure">{percent}%</span>
</div>
<div
className="pf-c-progress__bar"
role="progressbar"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow={percent}
aria-describedby="progress-singleline-example-description"
>
<div
className="pf-c-progress__indicator"
style={{
width: `${percent}%`
}}
/>
</div>
</div>
</div>
<div className="pf-c-empty-state__body">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec non pulvinar tortor. Maecenas sit amet
pellentesque velit, eu eleifend mauris.
</div>
<div className="pf-c-empty-state__secondary">
<button
className={percent === 100 ? `pf-c-button pf-m-primary` : `pf-c-button pf-m-link`}
onClick={this.props.onClose}
>
{percent === 100 ? `Close` : `Cancel`}
</button>
</div>
</div>
</div>
);
}
}
FinishedStep.propTypes = propTypes;
export default FinishedStep;
|
smartchicago/kimball
|
spec/factories/event_invitations.rb
|
require 'faker'
FactoryGirl.define do
factory :event_invitation, class: V2::EventInvitation do
title 'event title'
description 'Lorem ipsum for now'
slot_length 15
buffer 0
user
before(:create) do |event_invitation|
invitees = FactoryGirl.create_list(:person, 3)
event_invitation.invitees << invitees
event_invitation.people_ids = invitees.collect(&:id).join(',')
start_time = Time.current + 1.day
# three slots, one for each person
end_time = start_time + (15 * 3).minutes
event_invitation.date = start_time.strftime('%m/%d/%Y')
event_invitation.start_time = start_time.strftime('%H:%M')
event_invitation.end_time = end_time.strftime('%H:%M')
end
end
end
|
MateusAraujoBorges/abc
|
examples/varargs.c
|
void printf(char * format, ...);
void main() {
printf("test", 2);
}
|
Testiduk/frontend
|
static/src/javascripts/projects/common/modules/ui/accessibility-prefs.js
|
<filename>static/src/javascripts/projects/common/modules/ui/accessibility-prefs.js<gh_stars>1000+
/* We live in a rainbow of chaos. */
// ^ U WOT
import fastdom from 'fastdom';
import userPrefs from 'common/modules/user-prefs';
const FILTERS = [
'sepia',
'grayscale',
'invert',
'contrast',
'saturate',
'opacity',
];
const setFilter = (mode) => {
const body = document.body;
const value = `${mode}(100%)`;
if (body) {
Object.assign(body.style, {
'-webkit-filter': value,
filter: value,
});
}
};
const breuer = () => {
if (document.body) {
document.body.classList.add('is-breuer-mode');
}
};
const initAccessibilityPreferences = () => {
fastdom.mutate(() => {
FILTERS.forEach(filter => {
if (userPrefs.isOn(filter)) {
setFilter(filter);
}
});
});
if (userPrefs.isOn('breuerMode')) {
breuer();
}
};
export { initAccessibilityPreferences };
|
pedrohsreis/boulos
|
src/Core/External/unsw/unsw/utils/basic_maths.hpp
|
<filename>src/Core/External/unsw/unsw/utils/basic_maths.hpp
#pragma once
#include <cmath>
#include "types/Point.hpp"
#ifndef MAX
template <class T>
inline static T MAX(const T &x, const T &y) {
return (x > y ? x : y);
}
inline static float MAX(const float x, const int y) {
return (x > y ? x : y);
}
inline static float MAX(const int x, const float y) {
return (x > y ? x : y);
}
#endif
#ifndef MIN
template <class T>
inline static T MIN(const T &x, const T &y) {
return (x > y ? y : x);
}
inline static float MIN(const float x, const int y) {
return (x > y ? y : x);
}
inline static float MIN(const int x, const float y) {
return (x > y ? y : x);
}
#endif
template <class T>
inline static T ABS(const T &x) {
return (x > 0 ? x : -x);
}
template <class T>
inline static T SQUARE(const T &x) {
return x * x;
}
template <class T>
inline static T DISTANCE_SQR(const T &xA,
const T &yA,
const T &xB,
const T &yB) {
return SQUARE(xA - xB) + SQUARE(yA - yB);
}
// This is slow. The sqrt probably sucks.
inline static float DISTANCE(const float xA,
const float yA,
const float xB,
const float yB) {
return sqrt(DISTANCE_SQR(xA, yA, xB, yB));
}
template <class T>
inline static int SIGN(const T &x) {
return (x < 0 ? -1 : (x > 0) ? 1 : 0);
}
template <typename T>
inline static T crop(const T &x, const T &minimum, const T &maximum)
{
if (x < minimum) {
return minimum;
} else if (x > maximum) {
return maximum;
} else {
return x;
}
}
inline static float normaliseTheta(float theta) {
while (theta > M_PI) theta -= 2.0f*M_PI;
while (theta < -M_PI) theta += 2.0f*M_PI;
return theta;
}
inline double pointSegmentDist(Point point, Point lineStart, Point lineEnd) {
Point v;
v.x() = lineEnd.x() - lineStart.x();
v.y() = lineEnd.y() - lineStart.y();
Point w;
w.x() = point.x() - lineStart.x();
w.y() = point.y() - lineStart.y();
double c1 = w.x()*v.x() + w.y()*v.y();
if (c1 <= 0.0) {
return sqrt(w.x()*w.x() + w.y()*w.y());
}
double c2 = v.x()*v.x() + v.y()*v.y();
if (c2 <= c1) {
double dx = point.x() - lineEnd.x();
double dy = point.y() - lineEnd.y();
return sqrt(dx*dx + dy*dy);
}
double b = c1 / c2;
Point Pb;
Pb.x() = lineStart.x() + v.x()*b;
Pb.y() = lineStart.y() + v.y()*b;
double dx = point.x() - Pb.x();
double dy = point.y() - Pb.y();
return sqrt(dx*dx + dy*dy);
}
|
Diego-Zulu/leetcode_answers
|
python3/146.lru-cache.329634071.ac.py
|
#
# @lc app=leetcode id=146 lang=python3
#
# [146] LRU Cache
#
# https://leetcode.com/problems/lru-cache/description/
#
# algorithms
# Medium (31.91%)
# Likes: 5403
# Dislikes: 243
# Total Accepted: 522.3K
# Total Submissions: 1.6M
# Testcase Example: '["LRUCache","put","put","get","put","get","put","get","get","get"]\n' +
'[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]'
#
# Design and implement a data structure for Least Recently Used (LRU) cache. It
# should support the following operations: get and put.
#
# get(key) - Get the value (will always be positive) of the key if the key
# exists in the cache, otherwise return -1.
# put(key, value) - Set or insert the value if the key is not already present.
# When the cache reached its capacity, it should invalidate the least recently
# used item before inserting a new item.
#
# The cache is initialized with a positive capacity.
#
# Follow up:
# Could you do both operations in O(1) time complexity?
#
# Example:
#
#
# LRUCache cache = new LRUCache( 2 /* capacity */ );
#
# cache.put(1, 1);
# cache.put(2, 2);
# cache.get(1); // returns 1
# cache.put(3, 3); // evicts key 2
# cache.get(2); // returns -1 (not found)
# cache.put(4, 4); // evicts key 1
# cache.get(1); // returns -1 (not found)
# cache.get(3); // returns 3
# cache.get(4); // returns 4
#
#
#
#
#
# @lc code=start
class DoubleNode:
def __init__(self, k, x):
self.key = k
self.val = x
self.next = self.prev = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.used_head = DoubleNode(-1, -1)
self.used_tail = DoubleNode(-1, -1)
self.used_head.next = self.used_tail
self.used_tail.prev = self.used_head
self.used = {}
def get(self, key: int) -> int:
if key not in self.used:
return -1
n = self.used[key]
self._change_head(n)
return n.val
def _change_head(self, node):
if node.key in self.used:
node.prev.next = node.next
node.next.prev = node.prev
next_ = self.used_head.next
next_.prev = node
node.next = next_
node.prev = self.used_head
self.used_head.next = node
def _pop_tail(self):
prev = self.used_tail.prev
prev.prev.next = prev.next
prev.next.prev = prev.prev
return prev.key
def put(self, key: int, value: int) -> None:
if key in self.used:
self.capacity += 1
node = self.used[key]
node.val = value
else:
node = DoubleNode(key, value)
self._change_head(node)
self.capacity -= 1
self.used[key] = node
if self.capacity < 0:
self.capacity = 0
del self.used[self._pop_tail()]
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
# @lc code=end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.