repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
vershininds/mixture
|
app/src/main/java/com/vershininds/mixture/sample/presentation/common/dbadapter/util/DebounceHelper.java
|
<reponame>vershininds/mixture<filename>app/src/main/java/com/vershininds/mixture/sample/presentation/common/dbadapter/util/DebounceHelper.java<gh_stars>0
/*
* Copyright <NAME>. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vershininds.mixture.sample.presentation.common.dbadapter.util;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Helper to handle debounce time
* Created on 25.07.2017.
*/
public class DebounceHelper {
private final HashMap<String, Long> mDebounceMap = new HashMap<>();
private final ReentrantReadWriteLock mLock = new ReentrantReadWriteLock();
/**
* Check if time "debounceMillis" elapsed since last timer reset by call {@link #resetTime}
* or {@link #checkTimeAndResetIfElapsed(String, long)}
*
* @param tag the tag
* @param debounceMillis the debounce time for defined tag
* @return true if debounce time has been elapsed since last call, false otherwise
*/
public boolean checkTimeElapsed(String tag, long debounceMillis) {
mLock.readLock().lock();
Long lastCallMillis = this.mDebounceMap.get(tag);
mLock.readLock().unlock();
long nowMillis = System.currentTimeMillis();
return lastCallMillis == null
|| nowMillis - lastCallMillis > debounceMillis;
}
/**
* Reset timer for specific tag
*
* @param tag the tag
*/
public void resetTime(String tag){
mLock.writeLock().lock();
this.mDebounceMap.put(tag, System.currentTimeMillis());
mLock.writeLock().unlock();
}
/**
* Check if time "debounceMillis" elapsed since last timer reset by call {@link #resetTime}
* or {@link #checkTimeAndResetIfElapsed(String, long)}
*
* @param tag the tag
* @param debounceMillis the debounce time for defined tag
* @return true if debounce time has been elapsed since last call, false otherwise
*/
public boolean checkTimeAndResetIfElapsed(String tag, long debounceMillis) {
mLock.readLock().lock();
Long lastCallMillis = this.mDebounceMap.get(tag);
mLock.readLock().unlock();
long nowMillis = System.currentTimeMillis();
if(lastCallMillis == null || nowMillis - lastCallMillis > debounceMillis) {
mLock.writeLock().lock();
this.mDebounceMap.put(tag, nowMillis);
mLock.writeLock().unlock();
return true;
}
return false;
}
}
|
gridgentoo/Tarantool.Lua.Net
|
src/box/memtx_tree.cc
|
<filename>src/box/memtx_tree.cc
/*
* Copyright 2010-2015, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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
* <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 "memtx_tree.h"
#include "tuple.h"
#include "space.h"
#include "schema.h" /* space_cache_find() */
#include "errinj.h"
#include "memory.h"
#include "fiber.h"
#include <third_party/qsort_arg.h>
/* {{{ Utilities. *************************************************/
struct key_data
{
const char *key;
uint32_t part_count;
};
int
tree_index_compare(const tuple *a, const tuple *b, struct key_def *key_def)
{
int r = tuple_compare(a, b, key_def);
if (r == 0 && !key_def->opts.is_unique)
r = a < b ? -1 : a > b;
return r;
}
int
tree_index_compare_key(const tuple *a, const struct key_data *key_data,
struct key_def *key_def)
{
return tuple_compare_with_key(a, key_data->key,
key_data->part_count, key_def);
}
int tree_index_qcompare(const void* a, const void *b, void *c)
{
return tree_index_compare(*(struct tuple **)a,
*(struct tuple **)b, (struct key_def *)c);
}
/* {{{ MemtxTree Iterators ****************************************/
struct tree_iterator {
struct iterator base;
const struct bps_tree_index *tree;
struct key_def *key_def;
struct bps_tree_index_iterator bps_tree_iter;
struct key_data key_data;
};
static void
tree_iterator_free(struct iterator *iterator);
static inline struct tree_iterator *
tree_iterator(struct iterator *it)
{
assert(it->free == tree_iterator_free);
return (struct tree_iterator *) it;
}
static void
tree_iterator_free(struct iterator *iterator)
{
free(iterator);
}
static struct tuple *
tree_iterator_dummie(struct iterator *iterator)
{
(void)iterator;
return 0;
}
static struct tuple *
tree_iterator_fwd(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
tuple **res = bps_tree_index_itr_get_elem(it->tree, &it->bps_tree_iter);
if (!res)
return 0;
bps_tree_index_itr_next(it->tree, &it->bps_tree_iter);
return *res;
}
static struct tuple *
tree_iterator_bwd(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
tuple **res = bps_tree_index_itr_get_elem(it->tree, &it->bps_tree_iter);
if (!res)
return 0;
bps_tree_index_itr_prev(it->tree, &it->bps_tree_iter);
return *res;
}
static struct tuple *
tree_iterator_fwd_check_equality(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
tuple **res = bps_tree_index_itr_get_elem(it->tree, &it->bps_tree_iter);
if (!res)
return 0;
if (tree_index_compare_key(*res, &it->key_data, it->key_def) != 0) {
it->bps_tree_iter = bps_tree_index_invalid_iterator();
return 0;
}
bps_tree_index_itr_next(it->tree, &it->bps_tree_iter);
return *res;
}
static struct tuple *
tree_iterator_fwd_check_next_equality(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
tuple **res = bps_tree_index_itr_get_elem(it->tree, &it->bps_tree_iter);
if (!res)
return 0;
bps_tree_index_itr_next(it->tree, &it->bps_tree_iter);
iterator->next = tree_iterator_fwd_check_equality;
return *res;
}
static struct tuple *
tree_iterator_bwd_skip_one(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
bps_tree_index_itr_prev(it->tree, &it->bps_tree_iter);
iterator->next = tree_iterator_bwd;
return tree_iterator_bwd(iterator);
}
static struct tuple *
tree_iterator_bwd_check_equality(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
tuple **res = bps_tree_index_itr_get_elem(it->tree, &it->bps_tree_iter);
if (!res)
return 0;
if (tree_index_compare_key(*res, &it->key_data, it->key_def) != 0) {
it->bps_tree_iter = bps_tree_index_invalid_iterator();
return 0;
}
bps_tree_index_itr_prev(it->tree, &it->bps_tree_iter);
return *res;
}
static struct tuple *
tree_iterator_bwd_skip_one_check_next_equality(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
bps_tree_index_itr_prev(it->tree, &it->bps_tree_iter);
iterator->next = tree_iterator_bwd_check_equality;
return tree_iterator_bwd_check_equality(iterator);
}
/* }}} */
/* {{{ MemtxTree **********************************************************/
MemtxTree::MemtxTree(struct key_def *key_def_arg)
: MemtxIndex(key_def_arg), build_array(0), build_array_size(0),
build_array_alloc_size(0)
{
memtx_index_arena_init();
bps_tree_index_create(&tree, key_def,
memtx_index_extent_alloc,
memtx_index_extent_free, NULL);
}
MemtxTree::~MemtxTree()
{
bps_tree_index_destroy(&tree);
free(build_array);
}
size_t
MemtxTree::size() const
{
return bps_tree_index_size(&tree);
}
size_t
MemtxTree::bsize() const
{
return bps_tree_index_mem_used(&tree);
}
struct tuple *
MemtxTree::random(uint32_t rnd) const
{
struct tuple **res = bps_tree_index_random(&tree, rnd);
return res ? *res : 0;
}
struct tuple *
MemtxTree::findByKey(const char *key, uint32_t part_count) const
{
assert(key_def->opts.is_unique && part_count == key_def->part_count);
struct key_data key_data;
key_data.key = key;
key_data.part_count = part_count;
struct tuple **res = bps_tree_index_find(&tree, &key_data);
return res ? *res : 0;
}
struct tuple *
MemtxTree::replace(struct tuple *old_tuple, struct tuple *new_tuple,
enum dup_replace_mode mode)
{
uint32_t errcode;
if (new_tuple) {
struct tuple *dup_tuple = NULL;
/* Try to optimistically replace the new_tuple. */
int tree_res =
bps_tree_index_insert(&tree, new_tuple, &dup_tuple);
if (tree_res) {
tnt_raise(OutOfMemory, BPS_TREE_EXTENT_SIZE,
"MemtxTree", "replace");
}
errcode = replace_check_dup(old_tuple, dup_tuple, mode);
if (errcode) {
bps_tree_index_delete(&tree, new_tuple);
if (dup_tuple)
bps_tree_index_insert(&tree, dup_tuple, 0);
struct space *sp = space_cache_find(key_def->space_id);
tnt_raise(ClientError, errcode, index_name(this),
space_name(sp));
}
if (dup_tuple)
return dup_tuple;
}
if (old_tuple) {
bps_tree_index_delete(&tree, old_tuple);
}
return old_tuple;
}
struct iterator *
MemtxTree::allocIterator() const
{
struct tree_iterator *it = (struct tree_iterator *)
calloc(1, sizeof(*it));
if (it == NULL) {
tnt_raise(OutOfMemory, sizeof(struct tree_iterator),
"MemtxTree", "iterator");
}
it->key_def = key_def;
it->tree = &tree;
it->base.free = tree_iterator_free;
it->bps_tree_iter = bps_tree_index_invalid_iterator();
return (struct iterator *) it;
}
void
MemtxTree::initIterator(struct iterator *iterator, enum iterator_type type,
const char *key, uint32_t part_count) const
{
assert(part_count == 0 || key != NULL);
struct tree_iterator *it = tree_iterator(iterator);
if (part_count == 0) {
/*
* If no key is specified, downgrade equality
* iterators to a full range.
*/
if (type < 0 || type > ITER_GT) {
return Index::initIterator(iterator, type, key,
part_count);
}
type = iterator_type_is_reverse(type) ? ITER_LE : ITER_GE;
key = 0;
}
it->key_data.key = key;
it->key_data.part_count = part_count;
bool exact = false;
if (key == 0) {
if (iterator_type_is_reverse(type))
it->bps_tree_iter = bps_tree_index_invalid_iterator();
else
it->bps_tree_iter = bps_tree_index_itr_first(&tree);
} else {
if (type == ITER_ALL || type == ITER_EQ || type == ITER_GE || type == ITER_LT) {
it->bps_tree_iter = bps_tree_index_lower_bound(&tree, &it->key_data, &exact);
if (type == ITER_EQ && !exact) {
it->base.next = tree_iterator_dummie;
return;
}
} else { // ITER_GT, ITER_REQ, ITER_LE
it->bps_tree_iter = bps_tree_index_upper_bound(&tree, &it->key_data, &exact);
if (type == ITER_REQ && !exact) {
it->base.next = tree_iterator_dummie;
return;
}
}
}
switch (type) {
case ITER_EQ:
it->base.next = tree_iterator_fwd_check_next_equality;
break;
case ITER_REQ:
it->base.next = tree_iterator_bwd_skip_one_check_next_equality;
break;
case ITER_ALL:
case ITER_GE:
it->base.next = tree_iterator_fwd;
break;
case ITER_GT:
it->base.next = tree_iterator_fwd;
break;
case ITER_LE:
it->base.next = tree_iterator_bwd_skip_one;
break;
case ITER_LT:
it->base.next = tree_iterator_bwd_skip_one;
break;
default:
return Index::initIterator(iterator, type, key, part_count);
}
}
void
MemtxTree::beginBuild()
{
assert(bps_tree_index_size(&tree) == 0);
}
void
MemtxTree::reserve(uint32_t size_hint)
{
if (size_hint < build_array_alloc_size)
return;
build_array = (struct tuple**)
realloc(build_array, size_hint * sizeof(struct tuple *));
build_array_alloc_size = size_hint;
}
void
MemtxTree::buildNext(struct tuple *tuple)
{
if (!build_array) {
build_array = (struct tuple**)malloc(BPS_TREE_EXTENT_SIZE);
build_array_alloc_size =
BPS_TREE_EXTENT_SIZE / sizeof(struct tuple*);
}
assert(build_array_size <= build_array_alloc_size);
if (build_array_size == build_array_alloc_size) {
build_array_alloc_size = build_array_alloc_size +
build_array_alloc_size / 2;
build_array = (struct tuple**)
realloc(build_array,
build_array_alloc_size *
sizeof(struct tuple *));
}
build_array[build_array_size++] = tuple;
}
void
MemtxTree::endBuild()
{
qsort_arg(build_array, build_array_size, sizeof(struct tuple *), tree_index_qcompare, key_def);
bps_tree_index_build(&tree, build_array, build_array_size);
free(build_array);
build_array = 0;
build_array_size = 0;
build_array_alloc_size = 0;
}
/**
* Create a read view for iterator so further index modifications
* will not affect the iterator iteration.
*/
void
MemtxTree::createReadViewForIterator(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
struct bps_tree_index *tree = (struct bps_tree_index *)it->tree;
bps_tree_index_itr_freeze(tree, &it->bps_tree_iter);
}
/**
* Destroy a read view of an iterator. Must be called for iterators,
* for which createReadViewForIterator was called.
*/
void
MemtxTree::destroyReadViewForIterator(struct iterator *iterator)
{
struct tree_iterator *it = tree_iterator(iterator);
struct bps_tree_index *tree = (struct bps_tree_index *)it->tree;
bps_tree_index_itr_destroy(tree, &it->bps_tree_iter);
}
|
ZJU-Robotics-Lab/model-based-social-navigation
|
src/model_based_version/utils/log_drawer.py
|
<gh_stars>10-100
from tensorboard.backend.event_processing import event_accumulator
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
def parse_data(records, name, start_step, end_step, step_interval):
x = []
y = []
for record in records:
ea = event_accumulator.EventAccumulator(record)
ea.Reload()
average_reward = ea.scalars.Items('Reward/average_reward')
# print(len(average_reward))
first_reward = True
for reward in average_reward:
# print(reward.step)
if reward.step <= start_step and reward.step >= start_step - 5:
previous_sum = reward.step * reward.value
elif reward.step >= start_step and reward.step < end_step:# and reward.step % step_interval == 1:
current_reward = max((reward.step * reward.value - previous_sum)/(reward.step - start_step), -1)
if first_reward:
first_reward = False
for i in range(start_step, reward.step):
x.append(i-start_step)
y.append(current_reward)
if len(x) > 0 and reward.step - start_step > x[-1]:
for i in range(x[-1]+start_step+1, reward.step):
x.append(i - start_step)
y.append(y[-1])
x.append(reward.step - start_step)
y.append(current_reward)
for i in range(x[-1]+1, end_step - start_step):
x.append(i)
y.append(y[-1])
print(len(x), len(y))
print(x[-20:])
print(y[-20:])
data = pd.DataFrame({
'step': x,
'average reward': y,
'Methods': name
})
return data
if __name__ == '__main__':
single_agent = True
if not single_agent:
# parameters
start_step = 3000
end_step = 10000
step_interval = 20
# model_free_four_20
model_free_four_20 = [
'xxx/events.out.tfevents.xxx.xxx',
]
data1 = parse_data(model_free_four_20, 'Ours_w/o_20', start_step, end_step, step_interval)
# model_free_four
model_free_four = [
'xxx/events.out.tfevents.xxx.xxx',
]
data2 = parse_data(model_free_four, 'Ours_w/o_1', start_step, end_step, step_interval)
# fully_distributed_four
fully_distributed_four = [
'xxx/events.out.tfevents.xxx.xxx',
]
data3 = parse_data(fully_distributed_four, 'FDMCA', start_step, end_step, step_interval)
# mapless_navigation_four
mapless_navigation_four = [
'xxx/events.out.tfevents.xxx.xxx',
]
data4 = parse_data(mapless_navigation_four, 'MNDS', start_step, end_step, step_interval)
# model based
model_based_four = [
'xxx/events.out.tfevents.xxx.xxx',
]
data5 = parse_data(model_based_four, 'Ours', start_step, end_step, step_interval)
sns.lineplot(x='step', y='average reward', hue='Methods', data=pd.concat([data5,data2,data1,data3,data4]))
plt.savefig('result.svg')
else:
# parameters
start_step = 3000
end_step = 7000
step_interval = 20
# model_free_20
model_free_20 = [
'xxx/events.out.tfevents.xxx.xxx',
]
data1 = parse_data(model_free_20, 'Ours_w/o_20', start_step, end_step, step_interval)
# model_free
model_free = [
'xxx/events.out.tfevents.xxx.xxx',
]
data2 = parse_data(model_free, 'Ours_w/o_1', start_step, end_step, step_interval)
# fully_distributed
fully_distributed = [
'xxx/events.out.tfevents.xxx.xxx',
]
data3 = parse_data(fully_distributed, 'FDMCA', start_step, end_step, step_interval)
# mapless_navigation
mapless_navigation = [
'xxx/events.out.tfevents.xxx.xxx',
]
data4 = parse_data(mapless_navigation, 'MNDS', start_step, end_step, step_interval)
# model based
model_based = [
'xxx/events.out.tfevents.xxx.xxx',
]
data5 = parse_data(model_based, 'Ours', start_step, end_step, step_interval)
sns.lineplot(x='step', y='average reward', hue='Methods', data=pd.concat([data5,data2,data1,data3,data4]))
plt.savefig('result-single.svg')
|
Tkachenko-Serhii/wallet_project_group_1_backend
|
controllers/developer/addDev.js
|
const { Developer, schemaDeveloper } = require('../../models/developer');
const addDev = async (req, res, next) => {
try {
const { error } = schemaDeveloper.validate(req.body);
if (error) {
throw res.status(400).json(error.message);
}
const newDev = await Developer.create(req.body);
res.status(201).json(newDev);
} catch (error) {
next(error);
}
};
module.exports = addDev;
|
yarf-framework/extras
|
subdomain/subdomain.go
|
package subdomain
import (
"github.com/yarf-framework/yarf"
"strings"
)
// Subdomain middleware parses the Request URL
// and sets the subdomain value into "_subdomain" index on Context Data
type Subdomain struct {
yarf.Middleware
}
// PreDispatch parses the URL and sets the value.
func (s *Subdomain) PreDispatch(c *yarf.Context) error {
// One-liner
c.Data.Set("_subdomain", strings.Split(c.Request.Host, ".")[0])
return nil
}
|
ojhaanshu87/LeetCode
|
714_buy_and_sell_transaction_fees.py
|
<reponame>ojhaanshu87/LeetCode
"""
Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Note:
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
"""
class Solution(object):
def maxProfit(self, prices, fee):
available, pending = 0, -prices[0]
for elem in range (1, len(prices)):
available = max(available, pending + prices[elem] - fee)
pending = max(pending, available - prices[elem])
return available
|
crossmob/WinObjC
|
Frameworks/CoreFoundation/RunLoop.subproj/CFSocket.h
|
<gh_stars>1000+
// clang-format off
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/* CFSocket.h
Copyright (c) 1999-2015, Apple Inc. All rights reserved.
*/
#if !defined(__COREFOUNDATION_CFSOCKET__)
#define __COREFOUNDATION_CFSOCKET__ 1
#include <CoreFoundation/CFRunLoop.h>
#include <CoreFoundation/CFData.h>
CF_IMPLICIT_BRIDGING_ENABLED
CF_EXTERN_C_BEGIN
typedef struct CF_BRIDGED_MUTABLE_TYPE(id) __CFSocket * CFSocketRef;
/* A CFSocket contains a native socket within a structure that can
be used to read from the socket in the background and make the data
thus read available using a runloop source. The callback used for
this may be of three types, as specified by the callBackTypes
argument when creating the CFSocket.
If kCFSocketReadCallBack is used, then data will not be
automatically read, but the callback will be called when data
is available to be read, or a new child socket is waiting to be
accepted.
If kCFSocketAcceptCallBack is used, then new child sockets will be
accepted and passed to the callback, with the data argument being
a pointer to a CFSocketNativeHandle. This is usable only with
connection rendezvous sockets.
If kCFSocketDataCallBack is used, then data will be read in chunks
in the background and passed to the callback, with the data argument
being a CFDataRef.
These three types are mutually exclusive, but any one of them may
have kCFSocketConnectCallBack added to it, if the socket will be
used to connect in the background. Connect in the background occurs
if CFSocketConnectToAddress is called with a negative timeout
value, in which case the call returns immediately, and a
kCFSocketConnectCallBack is generated when the connect finishes.
In this case the data argument is either NULL, or a pointer to
an SInt32 error code if the connect failed. kCFSocketConnectCallBack
will never be sent more than once for a given socket.
The callback types may also have kCFSocketWriteCallBack added to
them, if large amounts of data are to be sent rapidly over the
socket and notification is desired when there is space in the
kernel buffers so that the socket is writable again.
With a connection-oriented socket, if the connection is broken from the
other end, then one final kCFSocketReadCallBack or kCFSocketDataCallBack
will occur. In the case of kCFSocketReadCallBack, the underlying socket
will have 0 bytes available to read. In the case of kCFSocketDataCallBack,
the data argument will be a CFDataRef of length 0.
There are socket flags that may be set to control whether callbacks of
a given type are automatically reenabled after they are triggered, and
whether the underlying native socket will be closed when the CFSocket
is invalidated. By default read, accept, and data callbacks are
automatically reenabled; write callbacks are not, and connect callbacks
may not be, since they are sent once only. Be careful about automatically
reenabling read and write callbacks, since this implies that the
callbacks will be sent repeatedly if the socket remains readable or
writable respectively. Be sure to set these flags only for callbacks
that your CFSocket actually possesses; the result of setting them for
other callback types is undefined.
Individual callbacks may also be enabled and disabled manually, whether
they are automatically reenabled or not. If they are not automatically
reenabled, then they will need to be manually reenabled when the callback
is ready to be received again (and not sooner). Even if they are
automatically reenabled, there may be occasions when it will be useful
to be able to manually disable them temporarily and then reenable them.
Be sure to enable and disable only callbacks that your CFSocket actually
possesses; the result of enabling and disabling other callback types is
undefined.
By default the underlying native socket will be closed when the CFSocket
is invalidated, but it will not be if kCFSocketCloseOnInvalidate is
turned off. This can be useful in order to destroy a CFSocket but
continue to use the underlying native socket. The CFSocket must
still be invalidated when it will no longer be used. Do not in
either case close the underlying native socket without invalidating
the CFSocket.
Addresses are stored as CFDatas containing a struct sockaddr
appropriate for the protocol family; make sure that all fields are
filled in properly when passing in an address.
*/
/* Values for CFSocketError */
typedef CF_ENUM(CFIndex, CFSocketError) {
kCFSocketSuccess = 0,
kCFSocketError = -1L,
kCFSocketTimeout = -2L
};
typedef struct {
SInt32 protocolFamily;
SInt32 socketType;
SInt32 protocol;
CFDataRef address;
} CFSocketSignature;
/* Values for CFSocketCallBackType */
typedef CF_OPTIONS(CFOptionFlags, CFSocketCallBackType) {
kCFSocketNoCallBack = 0,
kCFSocketReadCallBack = 1,
kCFSocketAcceptCallBack = 2,
kCFSocketDataCallBack = 3,
kCFSocketConnectCallBack = 4,
kCFSocketWriteCallBack = 8
};
/* Socket flags */
CF_ENUM(CFOptionFlags) {
kCFSocketAutomaticallyReenableReadCallBack = 1,
kCFSocketAutomaticallyReenableAcceptCallBack = 2,
kCFSocketAutomaticallyReenableDataCallBack = 3,
kCFSocketAutomaticallyReenableWriteCallBack = 8,
kCFSocketLeaveErrors CF_ENUM_AVAILABLE(10_5, 2_0) = 64,
kCFSocketCloseOnInvalidate = 128
};
typedef void (*CFSocketCallBack)(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info);
/* If the callback wishes to keep hold of address or data after the point that it returns, then it must copy them. */
typedef struct {
CFIndex version;
void * info;
const void *(*retain)(const void *info);
void (*release)(const void *info);
CFStringRef (*copyDescription)(const void *info);
} CFSocketContext;
#if TARGET_OS_WIN32
typedef uintptr_t CFSocketNativeHandle;
#else
typedef int CFSocketNativeHandle;
#endif
CF_EXPORT CFTypeID CFSocketGetTypeID(void);
CF_EXPORT CFSocketRef CFSocketCreate(CFAllocatorRef allocator, SInt32 protocolFamily, SInt32 socketType, SInt32 protocol, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context);
CF_EXPORT CFSocketRef CFSocketCreateWithNative(CFAllocatorRef allocator, CFSocketNativeHandle sock, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context);
CF_EXPORT CFSocketRef CFSocketCreateWithSocketSignature(CFAllocatorRef allocator, const CFSocketSignature *signature, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context);
/* CFSocketCreateWithSocketSignature() creates a socket of the requested type and binds its address (using CFSocketSetAddress()) to the requested address. If this fails, it returns NULL. */
CF_EXPORT CFSocketRef CFSocketCreateConnectedToSocketSignature(CFAllocatorRef allocator, const CFSocketSignature *signature, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext *context, CFTimeInterval timeout);
/* CFSocketCreateConnectedToSocketSignature() creates a socket suitable for connecting to the requested type and address, and connects it (using CFSocketConnectToAddress()). If this fails, it returns NULL. */
CF_EXPORT CFSocketError CFSocketSetAddress(CFSocketRef s, CFDataRef address);
CF_EXPORT CFSocketError CFSocketConnectToAddress(CFSocketRef s, CFDataRef address, CFTimeInterval timeout);
CF_EXPORT void CFSocketInvalidate(CFSocketRef s);
CF_EXPORT Boolean CFSocketIsValid(CFSocketRef s);
CF_EXPORT CFDataRef CFSocketCopyAddress(CFSocketRef s);
CF_EXPORT CFDataRef CFSocketCopyPeerAddress(CFSocketRef s);
CF_EXPORT void CFSocketGetContext(CFSocketRef s, CFSocketContext *context);
CF_EXPORT CFSocketNativeHandle CFSocketGetNative(CFSocketRef s);
CF_EXPORT CFRunLoopSourceRef CFSocketCreateRunLoopSource(CFAllocatorRef allocator, CFSocketRef s, CFIndex order);
CF_EXPORT CFOptionFlags CFSocketGetSocketFlags(CFSocketRef s);
CF_EXPORT void CFSocketSetSocketFlags(CFSocketRef s, CFOptionFlags flags);
CF_EXPORT void CFSocketDisableCallBacks(CFSocketRef s, CFOptionFlags callBackTypes);
CF_EXPORT void CFSocketEnableCallBacks(CFSocketRef s, CFOptionFlags callBackTypes);
/* For convenience, a function is provided to send data using the socket with a timeout. The timeout will be used only if the specified value is positive. The address should be left NULL if the socket is already connected. */
CF_EXPORT CFSocketError CFSocketSendData(CFSocketRef s, CFDataRef address, CFDataRef data, CFTimeInterval timeout);
/* Generic name registry functionality (CFSocketRegisterValue,
CFSocketCopyRegisteredValue) allows the registration of any property
list type. Functions specific to CFSockets (CFSocketRegisterSocketData,
CFSocketCopyRegisteredSocketData) register a CFData containing the
components of a socket signature (protocol family, socket type,
protocol, and address). In each function the nameServerSignature
may be NULL, or any component of it may be 0, to use default values
(TCP, INADDR_LOOPBACK, port as set). Name registration servers might
not allow registration with other than TCP and INADDR_LOOPBACK.
The actual address of the server responding to a query may be obtained
by using the nameServerAddress argument. This address, the address
returned by CFSocketCopyRegisteredSocketSignature, and the value
returned by CFSocketCopyRegisteredValue must (if non-null) be released
by the caller. CFSocketUnregister removes any registration associated
with the specified name.
*/
CF_EXPORT CFSocketError CFSocketRegisterValue(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef value);
CF_EXPORT CFSocketError CFSocketCopyRegisteredValue(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef *value, CFDataRef *nameServerAddress);
CF_EXPORT CFSocketError CFSocketRegisterSocketSignature(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, const CFSocketSignature *signature);
CF_EXPORT CFSocketError CFSocketCopyRegisteredSocketSignature(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFSocketSignature *signature, CFDataRef *nameServerAddress);
CF_EXPORT CFSocketError CFSocketUnregister(const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name);
CF_EXPORT void CFSocketSetDefaultNameRegistryPortNumber(UInt16 port);
CF_EXPORT UInt16 CFSocketGetDefaultNameRegistryPortNumber(void);
/* Constants used in name registry server communications */
CF_EXPORT const CFStringRef kCFSocketCommandKey;
CF_EXPORT const CFStringRef kCFSocketNameKey;
CF_EXPORT const CFStringRef kCFSocketValueKey;
CF_EXPORT const CFStringRef kCFSocketResultKey;
CF_EXPORT const CFStringRef kCFSocketErrorKey;
CF_EXPORT const CFStringRef kCFSocketRegisterCommand;
CF_EXPORT const CFStringRef kCFSocketRetrieveCommand;
CF_EXTERN_C_END
CF_IMPLICIT_BRIDGING_DISABLED
#endif /* ! __COREFOUNDATION_CFSOCKET__ */
// clang-format on
|
TanqiZhou/nimbus-jose-jwt
|
src/test/java/com/nimbusds/jose/jca/JCASupportTest.java
|
<reponame>TanqiZhou/nimbus-jose-jwt<filename>src/test/java/com/nimbusds/jose/jca/JCASupportTest.java
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.nimbusds.jose.jca;
import java.security.Provider;
import java.security.Security;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.nimbusds.jose.Algorithm;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.crypto.bc.BouncyCastleFIPSProviderSingleton;
import com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton;
/**
* JCA provider support tests.
*/
public class JCASupportTest {
@Test
public void testUnlimitedCrypto() {
String msg = "Unlimited JCE cryptography strength not supported, go to http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html";
assertTrue(msg, JCASupport.isUnlimitedStrength());
}
@Test
public void testJWSSupport_Default_Java_7() {
if (! System.getProperty("java.version").startsWith("1.7")) {
return;
}
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS256));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS512));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS256));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS512));
assertFalse(JCASupport.isSupported(JWSAlgorithm.PS512));
assertFalse(JCASupport.isSupported(JWSAlgorithm.PS256));
assertFalse(JCASupport.isSupported(JWSAlgorithm.PS384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES256));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES512));
}
@Test
public void testJWSSupport_SUN_Java_7() {
if (! System.getProperty("java.version").startsWith("1.7")) {
return;
}
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS256, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS384, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS512, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS256, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS384, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS512, Security.getProvider("SunRsaSign")));
assertFalse(JCASupport.isSupported(JWSAlgorithm.PS512, Security.getProvider("SunRsaSign")));
assertFalse(JCASupport.isSupported(JWSAlgorithm.PS256, Security.getProvider("SunRsaSign")));
assertFalse(JCASupport.isSupported(JWSAlgorithm.PS384, Security.getProvider("SunRsaSign")));
if (Security.getProvider("SunEC") != null) {
// Not supported on OpenJDK
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES256, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES384, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES512, Security.getProvider("SunEC")));
}
}
@Test
public void testJWSSupport_Default_Java_8() {
if (! System.getProperty("java.version").startsWith("1.8")) {
return;
}
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS256));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS512));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS256));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS512));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS512));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS256));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES256));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES384));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES512));
}
@Test
public void testJWSSupport_SUN_Java_8() {
if (! System.getProperty("java.version").startsWith("1.8")) {
return;
}
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS256, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS384, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS512, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS256, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS384, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS512, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS512, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS256, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS384, Security.getProvider("SunRsaSign")));
if (Security.getProvider("SunEC") != null) {
// Not supported on OpenJDK
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES256, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES384, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES512, Security.getProvider("SunEC")));
}
}
@Test
public void testJWSSupport_BC() {
Provider bc = BouncyCastleProviderSingleton.getInstance();
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS512, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS512, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS512, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES512, bc));
}
// To run the test without class loading clashes disable the optional
// plain BC provider in pom.xml
// @Test
public void testJWSSupport_BC_FIPS() {
Provider bc = BouncyCastleFIPSProviderSingleton.getInstance();
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.HS512, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.RS512, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.PS512, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES256, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES384, bc));
assertTrue(JCASupport.isSupported(JWSAlgorithm.ES512, bc));
}
@Test
public void testJWESupport_Default_Java_7() {
if (! System.getProperty("java.version").startsWith("1.7")) {
return;
}
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA1_5));
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA_OAEP));
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA_OAEP_256));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A128KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A192KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A256KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.PBES2_HS256_A128KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.PBES2_HS384_A192KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.PBES2_HS512_A256KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A128KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A192KW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A256KW));
assertFalse(JCASupport.isSupported(JWEAlgorithm.A128GCMKW));
assertFalse(JCASupport.isSupported(JWEAlgorithm.A192GCMKW));
assertFalse(JCASupport.isSupported(JWEAlgorithm.A256GCMKW));
assertTrue(JCASupport.isSupported(JWEAlgorithm.DIR));
}
@Test
public void testJWESupport_SUN_Java_7() {
if (! System.getProperty("java.version").startsWith("1.7")) {
return;
}
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA1_5, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA_OAEP, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA_OAEP_256, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A128KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A192KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A256KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.PBES2_HS256_A128KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.PBES2_HS384_A192KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.PBES2_HS512_A256KW, Security.getProvider("SunJCE")));
if (Security.getProvider("SunEC") != null) {
// Not supported on OpenJDK
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A128KW, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A192KW, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A256KW, Security.getProvider("SunEC")));
}
assertFalse(JCASupport.isSupported(JWEAlgorithm.A128GCMKW, Security.getProvider("SUN")));
assertFalse(JCASupport.isSupported(JWEAlgorithm.A192GCMKW, Security.getProvider("SUN")));
assertFalse(JCASupport.isSupported(JWEAlgorithm.A256GCMKW, Security.getProvider("SUN")));
assertTrue(JCASupport.isSupported(JWEAlgorithm.DIR, Security.getProvider("SUN")));
}
@Test
public void testJWESupport_BC() {
Provider bc = BouncyCastleProviderSingleton.getInstance();
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA1_5, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA_OAEP, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.RSA_OAEP_256, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A128KW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A192KW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A256KW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A128KW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A192KW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.ECDH_ES_A256KW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A128GCMKW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A192GCMKW, bc));
assertTrue(JCASupport.isSupported(JWEAlgorithm.A256GCMKW, bc));
}
@Test
public void testEncryptionMethodSupport_Default_Java_7() {
if (! System.getProperty("java.version").startsWith("1.7")) {
return;
}
assertTrue(JCASupport.isSupported(EncryptionMethod.A128CBC_HS256));
assertTrue(JCASupport.isSupported(EncryptionMethod.A192CBC_HS384));
assertTrue(JCASupport.isSupported(EncryptionMethod.A256CBC_HS512));
assertFalse(JCASupport.isSupported(EncryptionMethod.A128GCM));
assertFalse(JCASupport.isSupported(EncryptionMethod.A192GCM));
assertFalse(JCASupport.isSupported(EncryptionMethod.A256GCM));
}
@Test
public void testEncryptionMethodSupport_SUN_Java_7() {
if (! System.getProperty("java.version").startsWith("1.7")) {
return;
}
assertTrue(JCASupport.isSupported(EncryptionMethod.A128CBC_HS256, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(EncryptionMethod.A192CBC_HS384, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported(EncryptionMethod.A256CBC_HS512, Security.getProvider("SunJCE")));
assertFalse(JCASupport.isSupported(EncryptionMethod.A128GCM, Security.getProvider("SunJCE")));
assertFalse(JCASupport.isSupported(EncryptionMethod.A192GCM, Security.getProvider("SunJCE")));
assertFalse(JCASupport.isSupported(EncryptionMethod.A256GCM, Security.getProvider("SunJCE")));
}
@Test
public void testEncryptionMethodSupport_BC() {
Provider bc = BouncyCastleProviderSingleton.getInstance();
assertTrue(JCASupport.isSupported(EncryptionMethod.A128CBC_HS256, bc));
assertTrue(JCASupport.isSupported(EncryptionMethod.A192CBC_HS384, bc));
assertTrue(JCASupport.isSupported(EncryptionMethod.A256CBC_HS512, bc));
assertTrue(JCASupport.isSupported(EncryptionMethod.A128GCM, bc));
assertTrue(JCASupport.isSupported(EncryptionMethod.A192GCM, bc));
assertTrue(JCASupport.isSupported(EncryptionMethod.A256GCM, bc));
}
@Test
public void testAlgNoneAlwaysSupported() {
assertTrue(JCASupport.isSupported(new JWSAlgorithm("none")));
}
@Test
public void testJOSEAlgorithmSupport_Default_Java_8() {
if (! System.getProperty("java.version").startsWith("1.8")) {
return;
}
// JWS
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.HS256));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.HS384));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.HS512));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.RS256));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.RS384));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.RS512));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.PS512));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.PS256));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.PS384));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.ES256));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.ES384));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.ES512));
// JWE alg
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.RSA1_5));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.RSA_OAEP));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.RSA_OAEP_256));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A128KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A192KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A256KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.PBES2_HS256_A128KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.PBES2_HS384_A192KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.PBES2_HS512_A256KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES_A128KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES_A192KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES_A256KW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A128GCMKW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A192GCMKW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A256GCMKW));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.DIR));
// JWE enc
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A128CBC_HS256));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A192CBC_HS384));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A256CBC_HS512));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A128GCM));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A192GCM));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A256GCM));
}
@Test
public void testJOSEAlgorithmSupport_SUN_Java8() {
if (! System.getProperty("java.version").startsWith("1.8")) {
return;
}
// JWS
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.HS256, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.HS384, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.HS512, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.RS256, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.RS384, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.RS512, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.PS512, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.PS256, Security.getProvider("SunRsaSign")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.PS384, Security.getProvider("SunRsaSign")));
if (Security.getProvider("SunEC") != null) {
// Not supported on OpenJDK
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.ES256, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.ES384, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported((Algorithm) JWSAlgorithm.ES512, Security.getProvider("SunEC")));
}
// JWE alg
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.RSA1_5, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.RSA_OAEP, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.RSA_OAEP_256, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A128KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A192KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.A256KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.PBES2_HS256_A128KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.PBES2_HS384_A192KW, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.PBES2_HS512_A256KW, Security.getProvider("SunJCE")));
if (Security.getProvider("SunEC") != null) {
// Not supported on OpenJDK
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES_A128KW, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES_A192KW, Security.getProvider("SunEC")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.ECDH_ES_A256KW, Security.getProvider("SunEC")));
}
assertFalse(JCASupport.isSupported((Algorithm) JWEAlgorithm.A128GCMKW, Security.getProvider("SUN")));
assertFalse(JCASupport.isSupported((Algorithm) JWEAlgorithm.A192GCMKW, Security.getProvider("SUN")));
assertFalse(JCASupport.isSupported((Algorithm) JWEAlgorithm.A256GCMKW, Security.getProvider("SUN")));
assertTrue(JCASupport.isSupported((Algorithm) JWEAlgorithm.DIR, Security.getProvider("SUN")));
// JWE enc
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A128CBC_HS256, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A192CBC_HS384, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A256CBC_HS512, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A128GCM, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A192GCM, Security.getProvider("SunJCE")));
assertTrue(JCASupport.isSupported((Algorithm) EncryptionMethod.A256GCM, Security.getProvider("SunJCE")));
}
}
|
wall72/JavaCoreFramework
|
jcf-ui/jcf-sua/src/main/java/jcf/sua/ux/flex/exception/MciExceptionTranslator.java
|
package jcf.sua.ux.flex.exception;
import jcf.sua.mvc.MciRequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.flex.core.ExceptionTranslator;
import org.springframework.util.StringUtils;
import flex.messaging.MessageException;
public class MciExceptionTranslator implements ExceptionTranslator {
@Autowired(required = false)
private MessageSourceAccessor messageSourceAccessor;
public boolean handles(Class<?> arg0) {
return true;
}
public MessageException translate(Throwable t) {
if(!MciRequestContextHolder.get().isMciRequest()){
return null;
}
String message = t.getMessage();
MessageException messageException = null;
if(messageSourceAccessor != null){
try{
String remoteMessage = messageSourceAccessor.getMessage(message);
messageException = buildRemoteMassage(message,remoteMessage,t);
}catch (Exception NoSuchMessageException) {
if (StringUtils.hasText(message)) {
messageException = buildRemoteMassage("",message,t);
}else{
messageException = buildRemoteMassage("","",t);
}
}
}
return messageException;
}
private MessageException buildRemoteMassage(String code, String message, Throwable t){
MessageException messageException = new MessageException(message, t);
messageException.setCode(code);
messageException.setDetails(message);
return messageException;
}
}
|
hatbui345/yng-fishjoy
|
old/data_server/src/buzz/buzz_change.js
|
////////////////////////////////////////////////////////////
// 实物兑换订单相关接口的业务逻辑
////////////////////////////////////////////////////////////
//==============================================================================
// import
//==============================================================================
//------------------------------------------------------------------------------
// 工具
//------------------------------------------------------------------------------
var _ = require('underscore');
var CstError = require('./cst/buzz_cst_error');
var ERROR_OBJ = CstError.ERROR_OBJ;
var CommonUtil = require('./CommonUtil');
var ObjUtil = require('./ObjUtil');
var BuzzUtil = require('../utils/BuzzUtil');
//------------------------------------------------------------------------------
// POJO
//------------------------------------------------------------------------------
// var Reward = require('./pojo/Reward');
//------------------------------------------------------------------------------
// 业务
//------------------------------------------------------------------------------
// var buzz_reward = require('./buzz_reward');
//------------------------------------------------------------------------------
// 缓存(Cache)
//------------------------------------------------------------------------------
var CacheChange = require('./cache/CacheChange');
//------------------------------------------------------------------------------
// 配置表
//------------------------------------------------------------------------------
//==============================================================================
// const
//==============================================================================
var DEBUG = 0;
var ERROR = 1;
var TAG = "【buzz_change】";
//==============================================================================
// public
//==============================================================================
//------------------------------------------------------------------------------
// definition
//------------------------------------------------------------------------------
exports.modifyOrders = modifyOrders;
//------------------------------------------------------------------------------
// implement
//------------------------------------------------------------------------------
/**
* 运营管理——修改配置.
*/
function modifyOrders(req, dataObj, cb) {
const FUNC = TAG + "modifyCfgs() --- ";
//----------------------------------
if (!lPrepare(dataObj)) return;
_modifyOrders(req, dataObj, cb);
function lPrepare(input) {
return BuzzUtil.checkParams(input, ['op', 'orderid'], "【buzz_change】", cb);
}
}
//==============================================================================
// private
//==============================================================================
/**
* 修改订单状态
*/
function _modifyOrders(req, dataObj, cb) {
const FUNC = TAG + "_modifyOrders() --- ";
//----------------------------------
var op = dataObj.op;
var orderid = dataObj.orderid;
var way = dataObj.way;
var thingnum = dataObj.thingnum;
var status = dataObj.status;
console.log(FUNC + "op:", op);
console.log(FUNC + "orderid:", orderid);
console.log(FUNC + "way:", way);
console.log(FUNC + "thingnum:", thingnum);
console.log(FUNC + "status:", status);
if ("status" == op) {
CacheChange.updateStatus(req, orderid, status);
}
else if ("way" == op) {
CacheChange.updateWay(req, orderid, way, thingnum);
}
cb(null, CacheChange.getStatusByOrderId(orderid));
}
|
coin3d/smallchange
|
lib/SmallChange/nodes/SmShadowText2.h
|
#ifndef SMALLCHANGE_SOSHADOWTEXT2_H
#define SMALLCHANGE_SOSHADOWTEXT2_H
#include <Inventor/nodes/SoSubNode.h>
#include <Inventor/nodes/SoText2.h>
#include <Inventor/fields/SoMFString.h>
#include <Inventor/fields/SoSFFloat.h>
#include <Inventor/fields/SoSFEnum.h>
#include <Inventor/fields/SoSFVec2f.h>
#include <SmallChange/basic.h>
class SmShadowText2P;
class SMALLCHANGE_DLL_API SmShadowText2 : public SoText2 {
typedef SoShape inherited;
SO_NODE_HEADER(ShadowText2);
public:
static void initClass(void);
SmShadowText2(void);
enum Justification {
LEFT = 1,
RIGHT,
CENTER
};
SoSFVec2f pixelOffset;
virtual void GLRender(SoGLRenderAction * action);
protected:
virtual ~SmShadowText2();
private:
class SmShadowText2P * pimpl;
friend class SmShadowText2P;
};
#endif // !SMALLCHANGE_SOSHADOWTEXT2_H
|
paulobrizolara/geometric-escape
|
core/src/org/example/game/physics/proximitydetector/ProximityFilter.java
|
<reponame>paulobrizolara/geometric-escape
package org.example.game.physics.proximitydetector;
import com.badlogic.gdx.physics.box2d.Fixture;
public interface ProximityFilter{
public boolean acceptFixture(Fixture fixture);
}
|
antonleliuk/spring-social-skypeBot
|
botFramework/src/main/java/org/springframework/social/botframework/api/data/cards/CardImage.java
|
<gh_stars>0
package org.springframework.social.botframework.api.data.cards;
/**
* @author <NAME>
*/
public class CardImage {
/**
* Description of the image. You should include the description to support accessibility.
*/
private String alt;
/**
* A CardAction object that specifies the action to perform if the user taps or clicks the image.
*/
private CardAction tap;
/**
* URL to the source of the image or the base64 binary of the image (for example, data:image/png;base64,iVBORw0KGgo...).
*/
private String url;
public CardImage alt(String alt){
this.alt = alt;
return this;
}
public CardImage tap(CardAction tap){
this.tap = tap;
return this;
}
public CardImage url(String url){
this.url = url;
return this;
}
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
}
public CardAction getTap() {
return tap;
}
public void setTap(CardAction tap) {
this.tap = tap;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
paulkefer/cardioid
|
tools/mpi_comm_test/test.cc
|
<reponame>paulkefer/cardioid
#include <cstdlib>
#include <iostream>
#include <mpi.h>
#include <vector>
#include <set>
#include "CommTable.hh"
using namespace std;
#define timebase(x) asm volatile ("mftb %0" : "=r"(x) : )
#include "HaloExchange.hh"
//number of neighbors to talk to
const int Nneighbor=20;
//number of doubles to send per node
const int MessageSize = 70;
//variation range
const int VarRange = 37;
//locality range
const int LocalRange = 3;
#define RANDOM
extern "C"{
uint32_t coord_list(int *myid, int *totN, int* mapping);
}
int Nnode;
int main(int argc, char** argv)
{
uint64_t t1,t2,t3,t4;
int npes, mype;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD, &npes);
MPI_Comm_rank(MPI_COMM_WORLD, &mype);
//get my ID
int myID=mype;
int sum;
Nnode=npes;
assert(Nnode > Nneighbor);
//randomize
srand((myID+3213)*2627);
set<int> sendTask_s;
vector<int> sendOffset;
//assign nodes
#ifdef RANDOM
while(sendTask_s.size()<Nneighbor)
{
sendTask_s.insert((rand()%(Nnode-1) +1+ myID )%Nnode);
}
vector<int> sendTask(sendTask_s.begin(),sendTask_s.end());
#else
int* mapping = new int[Nnode*5];
int myid_spi;
int totN_spi;
int dist;
vector<int> sendTask;
coord_list(&myid_spi,&totN_spi,mapping);
// cout << "mpi_rank=" << mype << " spi_rank=" << myid_spi << endl;
// cout << "mpi_totN=" << npes << " spi_totN=" << totN_spi << endl;
for(int ii=0;ii<totN_spi;ii++)
{
dist = abs(mapping[myid_spi*5+0] - mapping[ii*5+0]) +
abs(mapping[myid_spi*5+1] - mapping[ii*5+1]) +
abs(mapping[myid_spi*5+2] - mapping[ii*5+2]) +
abs(mapping[myid_spi*5+3] - mapping[ii*5+3]) +
abs(mapping[myid_spi*5+4] - mapping[ii*5+4]) ;
if (dist==0)
{
assert(ii==myid_spi);
continue;
}
if ( dist <= LocalRange ) sendTask.push_back(ii);
cout << dist << " ";
}
cout << endl;
assert(sendTask.size() >= Nneighbor);
while(sendTask.size() > Nneighbor )
{
sendTask.erase(sendTask.begin()+rand()%sendTask.size());
}
assert(sendTask.size() == Nneighbor);
delete [] mapping;
#endif
cout << "my dest is :";
for(int ii=0 ; ii < sendTask.size() ; ++ii )
cout << sendTask[ii] << " ";
cout<<endl;
sum=0;
for(int ii=0 ; ii < sendTask.size() ; ++ii )
{
sendOffset.push_back(sum);
int new_size=rand()%VarRange + MessageSize;
new_size -= new_size%4; //why align by 4?
sum+=new_size;
}
sendOffset.push_back(sum);
//create sendMap
vector<int> sendMap;
sendMap.resize(sum);
cout<<"my total send size is " << sum << " doubles" << endl;
for(int ii=0;ii<sendMap.size();ii++) sendMap[ii]=ii;
//create Data
vector<double> Data;
for(int ii=0;ii<sum;ii++) Data.push_back(mype*1000+ii);
int nLocal = sum;
//create commTable
CommTable my_cmt(sendTask,sendOffset,MPI_COMM_WORLD);
// my_cmt.dump_put();
//create Halo Exchange for mpi
mpi_HaloExchange<double> mpi_HE(sendMap,&my_cmt);
mpi_HE.execute(Data,nLocal);
// mpi_HE.complete();
// cout << "========== mpi buff============" << endl;
// mpi_HE.dump_recv_buf();
cout<<"my total recv size is " << my_cmt.recvSize() << " doubles" << endl;
spi_HaloExchange<double> spi_HE(sendMap,&my_cmt);
int diff_detect=0;
t3=0;
spi_HE.set_recv_buf(0);
for(int jj=0;jj<10;jj++) //iterate 10 times
{
spi_HE.set_recv_buf((jj+1)%2);
for(int ii=0;ii<Data.size();ii++) Data[ii]=rand();
mpi_HE.move2Buf(Data);
mpi_HE.set_recv_buf(Data,nLocal);
spi_HE.barrier();
// MPI_Barrier(MPI_COMM_WORLD);
timebase(t1);
mpi_HE.execute2();
mpi_HE.complete();
timebase(t2);
t3+=t2-t1;
// spi_HE.dump_recv_buf();
spi_HE.move2Buf(Data);
spi_HE.execute(Data,nLocal);
spi_HE.complete();
diff_detect=0;
for(int ii=0;ii<my_cmt.recvSize();ii++)
{
if(spi_HE.get_recv_buf_()[ii] != mpi_HE.get_recv_buf_()[ii])
{
cout << "diff at " << ii << ":" << spi_HE.get_recv_buf_()[ii] - mpi_HE.get_recv_buf_()[ii] << endl;
diff_detect = 1;
}
}
if(diff_detect !=0 ) exit(-1);
}
cout << " total time = " << (double)t3/10.0/1600.0 << " us : " ;
cout << (double)mpi_HE.t5/10.0/1600 << " " << (double)mpi_HE.t6/10.0/1600 << " " << (double)mpi_HE.t7/10.0/1600 << endl;
MPI_Finalize();
return diff_detect;
}
|
rishabh9785/HackerrankProblems
|
Implementation/GameOfThrones.java
|
<reponame>rishabh9785/HackerrankProblems<filename>Implementation/GameOfThrones.java
import java.util.*;
import javax.swing.plaf.synth.SynthSpinnerUI;
public class GameOfThrones {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String s=new String();
s=sc.next();
int freq[]=new int[26];
for(int i=0;i<s.length();i++) {
freq[s.charAt(i)-97]++;
}
int count1=0;
int count2=0;
int count3=0;
for(int i=0;i<26;i++) {
if(freq[i]%2!=0 && freq[i]!=1) {
count1++;
}
else if(freq[i]%2!=0 && freq[i]==1) {
count2++;
}
else if(freq[i]%2==0) {
count3++;
}
}
if(count1==1 && count2==0 || count2==1) {
System.out.println("YES");
}
else if(count1>1 ||count2>1) {
System.out.println("NO");
}
else {
System.out.println("YES");
}
}
}
|
ThisIsanAlt/AlternativeBot
|
cogs/meta.py
|
<reponame>ThisIsanAlt/AlternativeBot<gh_stars>1-10
import discord
import asyncio
from discord.ext import commands, tasks
from discord.ext.commands.cooldowns import BucketType
import random
class Meta(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def dev_update(self, ctx):
await ctx.channel.purge(limit = 1)
await ctx.send(f''' > **AlternativeBot Version 0.1.12**
>
> **New stuff:**
> - `/rockpaperscissors`is finally complete! Challenge all of your friends and **defeat them all.**
> - `/mute` is done! Use `/bindmuterole` to automatically create a `Muted` role, or pass in your own role to use your own!
> - `/lock` is also done! Quickly lock your channels down in case of a raid!
> - Logging is finally complete! Use `/togglelogging` and begin tracking your server's moderation actions!
>
> **In progress:**
> -
''')
#help command
'''@commands.cooldown(1, 3, BucketType.user)
@commands.command(ignore_extra=True)
async def help(self, ctx, info=None):
if not info:
embed = discord.Embed(title='AlternativeBot Help and Documentation', description='Categories. Do /help [category] to get more info.\
\nThis message will be deleted in 60 seconds.', colour=ctx.author.color)
embed.add_field(name='Fun', value='Some fun commands for you to use!')
embed.add_field(name='Meta', value='Bot-related and user-related commands. Includes /whois, /about, and /bugreport.')
embed.add_field(name='Moderation', value='These commands empower the moderation team. Rest assured, I won\'t do what the user can\'t.')
embed.add_field(name='Logging', value='Track what your moderators are doing with these commands!')
embed.set_footer(text=f'(optional) [required] | Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send (embed=embed, delete_after=60)
elif info.lower()=='fun':
embed = discord.Embed(title='AlternativeBot Help and Documentation', description='Here are some fun commands for you to use!\
\nThis message will be deleted in 60 seconds.', colour=ctx.author.color)
embed.add_field(name='/8ball (question)', value='Ask the magic 8ball a question!')
embed.add_field(name='/slap [person]', value='Slap someone.')
embed.add_field(name='/hug [person]', value='Hug someone.')
embed.add_field(name='/fight [person]', value='Fight someone.')
embed.add_field(name='/rockpaperscissors [person]', value='Challenge someone to a rock paper scissors challenge! \
(Must have DMs open)')
embed.set_footer(text=f'(optional) [required] | Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send (embed=embed, delete_after=60)
elif info.lower()=='meta':
embed = discord.Embed(title='AlternativeBot Help and Documentation', description='Meta commands. Concerns more of the geeky side of the userbase.\
\nThis message will be deleted in 60 seconds.', colour=ctx.author.color)
embed.add_field(name='/about', value='Get information about the bot!')
embed.add_field(name='/ping', value='Check the ping of the bot to the Discord API.')
embed.add_field(name='/whois (person)', value='Get info on a member in the server.')
embed.add_field(name= '/membercount', value='Get the amount of members in the server.')
embed.add_field(name='/bugreport (description)', value='Report a bug!')
embed.add_field(name='~~/suggest (suggestion)~~', value='**Command is currently unavailable.** ~~Suggest something for the bot!~~')
embed.set_footer(text=f'(optional) [required] | Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send (embed=embed, delete_after=60)
elif info.lower() in ['mod', 'moderation']:
embed = discord.Embed(title='AlternativeBot Help and Documentation', description='Moderation commands.\nThis message will be deleted in 60 seconds.', colour=ctx.author.colour)
embed.add_field(name='/purge (no. of messages)', value='Purge messages. Number of messages defaults to 5. Requires manage messages permission.')
embed.add_field(name='/kick [member] (reason)', value='Kick a member. Reason defaults to "no reason". Requires kick members permission.')
embed.add_field(name='/ban [member/user id] (reason)', value='Permanently ban a member. Reason defaults to "no reason". Requires ban members permission.')
embed.add_field(name='/unban [user id : int] (reason)', value='Unban a user. Reason defaults to "no reason". Requires ban members permission.')
embed.add_field(name='/mute [user] (reason)', value='Permanently mute a user. Reason defaults to "no reason". Requires manage roles permission.')
embed.add_field(name='/unmute [user] (reason)', value='Unmute a user. Reason defaults to "no reason". Requires manage roles permission')
embed.add_field(name='/bindmuterole (role)', value='Bind a mute role to a server. \
This role will be used for muting users. If a role isnt specified, one will be created automatically. Requires manage roles permission.')
embed.add_field(name='/unbindmuterole', value='Delete this server\'s mute role. `/mute` will no longer work. Requires manage roles permission.')
embed.add_field(name='/lock', value='Lock the channel the command was run in. All users will be barred from speaking. Requires manage channels permission.')
embed.add_field(name='/unlock', value='Unlock the channel the command was run in. The previous channel overwrites will be restored. Requires manage channels permission.')
embed.add_field(name='/role [member]', value='Give a member the selected role. Requires manage roles permission.')
embed.add_field(name='/unrole [member]', value='Remove the selected role from a member. Requires manage roles permission.')
embed.set_footer(text=f'(optional) [required] | Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send (embed=embed, delete_after=60)
elif info.lower()=='logging':
embed = discord.Embed(title='AlternativeBot Help and Documentation', description='Logging commands.\nThis message will be deleted in 60 seconds.', colour=ctx.author.colour)
embed.add_field(name='/togglelogging', value='Returns a menu to toggle specific logging events. Requires manage servers permission.')
embed.add_field(name='/bindloggingchannel [channel]', value='Bind a logging channel to the server. Requires manage channels permission.')
embed.set_footer(text=f'(optional) [required] | Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
else:
await ctx.send('That\'s not a valid field!')'''
@commands.command()
async def acceptbug(self, ctx, userid, bug_number, *, description):
if ctx.author.id == 4<PASSWORD>:
userid1 = int(userid)
user = self.bot.get_user(userid1)
await user.send(f'Your bug report {bug_number} has been approved!')
channel = self.bot.get_channel(702605147402010654)
embed = discord.Embed(title='AlternativeBot Bug Report', color=ctx.author.color, timestamp=ctx.message.created_at)
embed.add_field(name='Description:', value=description)
embed.add_field(name='Bug ID:', value=bug_number)
embed.set_footer(text=f'Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await channel.send(embed=embed)
@commands.command()
async def declinebug(self, ctx, userid, bug_number):
if ctx.author.id == <PASSWORD>:
userid1 = int(userid)
user = self.bot.get_user(userid1)
await user.send(f'Your bug report {bug_number} has been declined.')
@commands.command()
async def bugreport(self, ctx, *, description=None):
bug_number = random.randint(0,500)
user = self.bot.get_user(447119084627427351)
if description != None:
await ctx.send(f'Your bug has been reported!')
embed=discord.Embed(title='AlternativeBot Bug Report', color=ctx.author.color, timestamp=ctx.message.created_at)
embed.add_field(name='Description:', value=description)
embed.add_field(name='Reported By', value=ctx.author.mention)
embed.add_field(name='Bug ID:', value=bug_number)
embed.set_footer(text=f'Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
await user.send(embed=embed)
else:
await ctx.send('**Bug report wizard**\n\nFollow the prompts and answer them!')
await ctx.send('What\'s the description of the bug?')
def check(message : discord.Message) -> bool:
return message.author == ctx.author
try:
description = await self.bot.wait_for('message', timeout = 60, check=check)
except asyncio.TimeoutError:
await ctx.send('You took too long to respond!')
else:
await ctx.send(f'''Your bug has been reported!''')
embed=discord.Embed(title='AlternativeBot bug report', color=ctx.author.color, timestamp=ctx.message.created_at)
embed.add_field(name='Description:', value=description.content)
embed.add_field(name='Reported By', value=ctx.author.mention)
embed.add_field(name='Bug ID:', value=bug_number)
embed.set_footer(text=f'Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
await user.send(embed=embed)
@commands.guild_only()
@commands.command()
async def membercount(self, ctx):
await ctx.send(f'{ctx.guild.name} currently has {ctx.guild.member_count} members!')
@commands.command()
async def suggest(self, ctx, *, suggestion = None):
user = self.bot.get_user(447119084627427351)
if suggestion != None:
await ctx.send(f'Thanks for your suggestion!')
embed=discord.Embed(title='AlternativeBot Suggestion Form', color=ctx.author.color, timestamp=ctx.message.created_at)
embed.add_field(name='Suggestion', value=suggestion)
embed.add_field(name='Suggested by', value=ctx.author.mention)
embed.set_footer(text=f'Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
await user.send(embed=embed)
else:
await ctx.send('**Suggestion wizard**\n\nFollow the prompts and answer them!')
await ctx.send('What would you like to suggest?')
def check(message : discord.Message) -> bool:
return message.author == ctx.author
try:
description = await self.bot.wait_for('message', timeout = 60, check=check)
except asyncio.TimeoutError:
await ctx.send('You took too long to respond!')
else:
await ctx.send(f'Thanks for your suggestion!')
embed=discord.Embed(title='AlternativeBot Suggestion Form', color=ctx.author.color, timestamp=ctx.message.created_at)
embed.add_field(name='Suggestion', value=description.content)
embed.add_field(name='Suggested by', value=ctx.author.mention)
embed.set_footer(text=f'Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
await user.send(embed=embed)
#ping command
@commands.command()
async def ping(self, ctx):
await ctx.send(f':ping_pong: Pong! {round(self.bot.latency * 1000)}ms')
#about command
@commands.command()
async def about(self, ctx):
embed = discord.Embed(title='About the bot', colour=ctx.author.color)
embed.add_field(name='Developer', value = 'ThisIsanAlt#3043')
embed.add_field(name='Server invite', value = 'https://discord.gg/33utPs9')
embed.add_field(name='Programming Language and library', value='Python 3.8.5, discord.py version 1.5.0')
embed.set_footer(text=f'Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
await ctx.send (embed=embed)
#whois command
@commands.guild_only()
@commands.command()
async def whois(self, ctx, *, member: discord.Member = None):
member = ctx.author if not member else member
roles = [role for role in member.roles]
embed = discord.Embed (color=member.color, timestamp=ctx.message.created_at)
embed.set_author(name=f'User info on {member}')
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(text=f'Requested by {ctx.author} | Support: https://discord.gg/33utPs9', icon_url=ctx.author.avatar_url)
embed.add_field(name='Discord ID:', value=member.id)
value1 = 'None' if member.display_name == member.name else member.display_name
embed.add_field(name='Nickname:', value=value1)
embed.add_field(name='Created at:', value=member.created_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(name='Joined at:', value=member.joined_at.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
embed.add_field(
name=f'Roles: ({len(roles)})',
value=' '.join(role.mention for role in roles),
)
embed.add_field(name='Top Role:', value=member.top_role.mention)
bot_status = 'Yes' if member.bot else 'No'
embed.add_field(name='Am I a bot:', value=bot_status)
if member.premium_since != None:
embed.add_field(name='Boosting since:', value=member.premium_since.strftime('%a, %#d %B %Y, %I:%M %p UTC'))
await ctx.send(embed=embed)
@commands.command()
async def invite(self, ctx):
await ctx.send ('Invite me using this invite link! ')
def setup(bot):
bot.add_cog(Meta(bot))
|
dsofowote/KW-Tool
|
keywordTool/pubfiles/src/code/oms/124645/default.js
|
<reponame>dsofowote/KW-Tool
integration.meta = {
"sectionID" : "124645",
"siteName" : "<NAME>",
"publisher" : "oms",
"platform" : "desktop"
};
integration.testParams = {};
integration.params = {
'mf_siteId' : '706249',
"plr_UseCreativeSettings" : true,
"plr_ContentW" : 960,
"plr_ContentType" : "PAGESKINEXPRESS",
"plr_PageAlignment" : "center",
"plr_UseFullVersion" : true,
"plr_HideElementsByID" : "[id^=adcloud_], [id^=google_ads_], [id=uAd_]",
"plr_HideElementsByClass" : "",
'plr_BarneyThresholdClicks' : 4,
'plr_BarneyThresholdRate' : 1
};
integration.on("adCallResult", function(e) {
if (e.data.hasSkin) {
$("#container_border").css({
"padding" : "0",
"max-width" : "950px"
});
$("#inhalte_superbanner").css({
"height" : "auto",
"text-align" : "center",
"margin-top" : "10px"
});
}
});
integration.on("adServed", function(e) {
$(".ism-frame").parent().css({
"z-index" : "1000"
});
});
|
farhanzeb95/react
|
src/components/searchBar/SearchBar.js
|
<filename>src/components/searchBar/SearchBar.js
import React from 'react'
import Select from 'react-select'
import {
addCategory,
setSearchQuery,
handleFetchSearchResults
} from '../../actions/search'
import { connect } from 'react-redux'
class SearchBar extends React.Component {
constructor(props) {
super(props)
this.state = {
categories: [
{ label: "All"},
{ label: "Book"},
{ label: "Furniture"},
{ label: "Electronics"},
{ label: "School Supplies"},
{ label: "Other"}
]
}
}
searchBarStyle ={
width: "600",
display: "flex",
justifyContent: "space-between",
alignItems: "center"
}
handleDropDownChange = (category) => {
this.props.dispatch(addCategory(category.label))
}
handleSubmit = (e) => {
e.preventDefault()
this.props.dispatch(handleFetchSearchResults(
this.props.searchQuery,
this.props.category
))
}
handleSearchQueryChange = (e) => {
this.props.dispatch(setSearchQuery(e.target.value))
}
render() {
return(
<div className="row" style={this.searchBarStyle}>
<div>
<form onSubmit={this.handleSubmit}>
<div className="input-group"
style = {{
marginLeft: "65px",
"display":"flex",
"height": "inherit"
}}>
<div style={{
width: "160px"}}>
<Select
style={{boxShadow: 'none !important'}}
value={{label: this.props.category}}
options={this.state.categories}
onChange={this.handleDropDownChange}
/>
</div>
<input
style={{
borderRadius: "0",
height: "38px",
width: "350px",
}}
value = {this.props.searchQuery}
className="form-control col-lg-6"
type="text"
width= "800px"
aria-label="Search"
placeholder="Gator Search..."
onChange={this.handleSearchQueryChange}
/>
<span className="input-group-btn" >
<button
className="btn btn-light"
type="submit"
style={{
// borderRadius: "5px",
height: "38px",
marginLeft: "-3px",
color: "white",
backgroundColor: "#7851a9"
}}>
<span className="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
</span>
</div>
</form>
</div>
</div>
)
}
}
const mapStateToProps = ({search}) => {
const {searchQuery, category} = search
return {
searchQuery,
category
}
}
export default connect(mapStateToProps)(SearchBar)
|
AlexRogalskiy/DevArtifacts
|
master/autotools-book-files/autotools/book/flaim-ch8-10/flaim/src/fdbremov.cpp
|
<reponame>AlexRogalskiy/DevArtifacts
//-------------------------------------------------------------------------
// Desc: Delete a database.
// Tabs: 3
//
// Copyright (c) 2001-2003, 2005-2007 Novell, Inc. All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version 2.1
// of the License.
//
// This library 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
// Library Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, contact Novell, Inc.
//
// To contact Novell about this file by physical or electronic mail,
// you may find current contact information at www.novell.com.
//
// $Id$
//------------------------------------------------------------------------------
#include "flaimsys.h"
/*******************************************************************************
Desc: Removes a database, including roll-forward log files, if requested.
*******************************************************************************/
FLMEXP RCODE FLMAPI FlmDbRemove(
const char * pszDbName,
const char * pszDataDir,
const char * pszRflDir,
FLMBOOL bRemoveRflFiles)
{
RCODE rc = FERR_OK;
IF_FileHdl * pFileHdl = NULL;
FLMBYTE * pucBuffer = NULL;
FLMUINT uiFileNumber;
FILE_HDR FileHdr;
FLMUINT uiVersionNum;
char * pszTmpName = NULL;
char * pszRflDirName;
char * pszDataName;
char * pszBaseName;
char szPrefix[ F_FILENAME_SIZE];
char * pszExt;
char * pszDataExt;
IF_DirHdl * pDirHdl = NULL;
// Cannot handle empty database name.
if( !pszDbName || !(*pszDbName))
{
rc = RC_SET( FERR_IO_INVALID_PATH);
goto Exit;
}
// Allocate memory, so as to not consume stack.
if( RC_BAD( rc = f_alloc( F_PATH_MAX_SIZE * 3 + F_FILENAME_SIZE,
&pszTmpName)))
{
goto Exit;
}
pszRflDirName = pszTmpName + F_PATH_MAX_SIZE;
pszDataName = pszRflDirName + F_PATH_MAX_SIZE;
pszBaseName = pszDataName + F_PATH_MAX_SIZE;
// First make sure we have closed this database and gotten rid of
// it from our internal memory tables - in case it had been open.
if (RC_BAD( rc = FlmConfig( FLM_CLOSE_FILE, (void *)pszDbName,
(void *)pszDataDir)))
{
goto Exit;
}
gv_FlmSysData.pFileHdlCache->closeUnusedFiles();
// Open the file so we can get the log header.
if( RC_BAD( rc = gv_FlmSysData.pFileSystem->openFile(
pszDbName, gv_FlmSysData.uiFileOpenFlags, &pFileHdl)))
{
goto Exit;
}
// Allocate a buffer for reading the header stuff.
if( RC_BAD( rc = f_allocAlignedBuffer( 2048, &pucBuffer)))
{
goto Exit;
}
// Read the header to get the low and high RFL log
// file numbers.
if (RC_BAD( flmReadAndVerifyHdrInfo( NULL, pFileHdl,
pucBuffer, &FileHdr, NULL, NULL)))
{
uiVersionNum = FLM_CUR_FILE_FORMAT_VER_NUM;
}
else
{
uiVersionNum = FileHdr.uiVersionNum;
}
// Close the file.
pFileHdl->Release();
pFileHdl = NULL;
if (pszDataDir && *pszDataDir)
{
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->pathReduce(
pszDbName, pszDataName, pszBaseName)))
{
goto Exit;
}
f_strcpy( pszDataName, pszDataDir);
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->pathAppend(
pszDataName, pszBaseName)))
{
goto Exit;
}
}
else
{
f_strcpy( pszDataName, pszDbName);
}
f_strcpy( pszTmpName, pszDbName);
// Start deleting files, beginning with the main DB file.
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->deleteFile( pszDbName)))
{
if (rc == FERR_IO_PATH_NOT_FOUND || rc == FERR_IO_INVALID_PATH)
{
rc = FERR_OK;
}
else
{
goto Exit;
}
}
// Find where the extension of the database name is
pszExt = pszTmpName + f_strlen( pszTmpName) - 1;
pszDataExt = pszDataName + f_strlen( pszDataName) - 1;
while (pszExt != pszTmpName && *pszExt != '.')
{
pszExt--;
// Both the db name and data name have the same
// base name, so we can decrement pszDataExt
// at the same time we decrement pszExt.
pszDataExt--;
}
if (*pszExt != '.')
{
pszExt = pszTmpName + f_strlen( pszTmpName);
pszDataExt = pszDataName + f_strlen( pszDataName);
}
// Delete the .lck file, if any
f_strcpy( pszExt, ".lck");
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->deleteFile( pszTmpName)))
{
if (rc == FERR_IO_PATH_NOT_FOUND || rc == FERR_IO_INVALID_PATH)
{
rc = FERR_OK;
}
else
{
goto Exit;
}
}
// Delete block (data) files.
uiFileNumber = 1;
for (;;)
{
F_SuperFileClient::bldSuperFileExtension(
uiVersionNum, uiFileNumber, pszDataExt);
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->deleteFile( pszDataName)))
{
if (rc == FERR_IO_PATH_NOT_FOUND || rc == FERR_IO_INVALID_PATH)
{
rc = FERR_OK;
break;
}
else
{
goto Exit;
}
}
if (uiFileNumber == MAX_DATA_BLOCK_FILE_NUMBER( uiVersionNum))
{
break;
}
uiFileNumber++;
}
// Delete rollback log files.
uiFileNumber = FIRST_LOG_BLOCK_FILE_NUMBER( uiVersionNum);
for (;;)
{
F_SuperFileClient::bldSuperFileExtension(
uiVersionNum, uiFileNumber, pszExt);
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->deleteFile( pszTmpName)))
{
if (rc == FERR_IO_PATH_NOT_FOUND || rc == FERR_IO_INVALID_PATH)
{
rc = FERR_OK;
break;
}
else
{
goto Exit;
}
}
if (uiFileNumber == MAX_LOG_BLOCK_FILE_NUMBER( uiVersionNum))
{
break;
}
uiFileNumber++;
}
if (bRemoveRflFiles)
{
// Delete roll-forward log files.
if (uiVersionNum < FLM_FILE_FORMAT_VER_4_3)
{
// For pre-4.3 versions, only need to delete one RFL file.
if (RC_BAD( rc = rflGetFileName( uiVersionNum, pszDbName,
pszRflDir, 1, pszTmpName)))
{
goto Exit;
}
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->deleteFile( pszTmpName)))
{
if (rc == FERR_IO_PATH_NOT_FOUND || rc == FERR_IO_INVALID_PATH)
{
rc = FERR_OK;
}
else
{
goto Exit;
}
}
}
else
{
FLMBOOL bCanDeleteDir;
// For 4.3 and greater, need to scan the RFL directory for
// RFL files.
if (RC_BAD( rc = rflGetDirAndPrefix( uiVersionNum,
pszDbName, pszRflDir, pszRflDirName, szPrefix)))
{
goto Exit;
}
// See if the directory exists. If not, we are done.
if (!gv_FlmSysData.pFileSystem->isDir( pszRflDirName))
{
goto Exit; // Should return FERR_OK
}
// Open the directory and scan for RFL files.
// NOTE: DO NOT just call RemoveDir. There may be other
// things in the directory that we do not want to delete.
// Look specifically for files that match our expected
// name format for RFL files.
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->openDir( pszRflDirName,
"*", &pDirHdl)))
{
goto Exit;
}
// Assume that we can delete the directory. This will only
// be set to FALSE if we can't delete all of the files in
// the directory - i.e., some don't look like RFL log files.
bCanDeleteDir = TRUE;
for (;;)
{
if (RC_BAD( rc = pDirHdl->next()))
{
if (rc == FERR_IO_NO_MORE_FILES)
{
rc = FERR_OK;
break;
}
else
{
goto Exit;
}
}
pDirHdl->currentItemPath( pszTmpName);
if (pDirHdl->currentItemIsDir())
{
bCanDeleteDir = FALSE;
}
else if (!rflGetFileNum( uiVersionNum,
szPrefix, pszTmpName, &uiFileNumber))
{
bCanDeleteDir = FALSE;
}
else
{
if( RC_BAD( rc =
gv_FlmSysData.pFileSystem->deleteFile( pszTmpName)))
{
if (rc == FERR_IO_PATH_NOT_FOUND ||
rc == FERR_IO_INVALID_PATH)
{
rc = FERR_OK;
}
else
{
goto Exit;
}
}
}
}
// Attempt to delete the directory - if allowed.
if (bCanDeleteDir)
{
// Need to release the directory handle so the
// directory will be closed when we try to delete it
// below.
if (pDirHdl)
{
pDirHdl->Release();
pDirHdl = NULL;
}
if (RC_BAD( rc = gv_FlmSysData.pFileSystem->removeDir(
pszRflDirName)))
{
if (rc == FERR_IO_PATH_NOT_FOUND || rc == FERR_IO_INVALID_PATH)
{
rc = FERR_OK;
}
goto Exit;
}
}
}
}
Exit:
if( pszTmpName)
{
f_free( &pszTmpName);
}
if( pFileHdl)
{
pFileHdl->Release();
}
if( pucBuffer)
{
f_freeAlignedBuffer( &pucBuffer);
}
if( pDirHdl)
{
pDirHdl->Release();
}
return( rc);
}
|
ardaerlik/SpacePongGame
|
spacePong/src/frame/home/SettingsFrame.java
|
package frame.home;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import frame.home.panel.*;
public class SettingsFrame extends JFrame {
private JPanel contentPane;
private CreditsButtonsPanel creditsButtonsPanel;
private SettingsPanel settingsPanel;
public SettingsFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(100, 100, 1024, 768);
contentPane = new JPanel();
setContentPane(contentPane);
layoutManager();
}
private void layoutManager() {
settingsPanel = new SettingsPanel(this);
creditsButtonsPanel = new CreditsButtonsPanel(this);
SpringLayout springLayout = new SpringLayout();
contentPane.setLayout(springLayout);
springLayout.putConstraint(SpringLayout.NORTH, settingsPanel, 0, SpringLayout.NORTH, contentPane);
springLayout.putConstraint(SpringLayout.SOUTH, settingsPanel, 623, SpringLayout.NORTH, contentPane);
springLayout.putConstraint(SpringLayout.WEST, settingsPanel, 0, SpringLayout.WEST, contentPane);
springLayout.putConstraint(SpringLayout.EAST, settingsPanel, 1024, SpringLayout.WEST, contentPane);
springLayout.putConstraint(SpringLayout.NORTH, creditsButtonsPanel, 623, SpringLayout.NORTH, contentPane);
springLayout.putConstraint(SpringLayout.SOUTH, creditsButtonsPanel, 768, SpringLayout.NORTH, contentPane);
springLayout.putConstraint(SpringLayout.WEST, creditsButtonsPanel, 0, SpringLayout.WEST, contentPane);
springLayout.putConstraint(SpringLayout.EAST, creditsButtonsPanel, 1024, SpringLayout.WEST, contentPane);
settingsPanel.setBackground(new Color(40, 40, 40));
creditsButtonsPanel.setBackground(new Color(235, 219, 178));
contentPane.add(settingsPanel);
contentPane.add(creditsButtonsPanel);
}
}
|
jessy1092/explore-africa
|
src/pages/ContactUsPage/index.js
|
<gh_stars>1-10
import React from 'react';
import IndexMenu from '../../components/IndexMenu';
import CategoryMenu from '../../components/CategoryMenu';
import styles from './index.css';
export default React.createClass({
componentDidMount() {
$('#category-menu').hide();
},
render() {
return (
<div>
<div className="fixed-top-menu">
<IndexMenu />
<CategoryMenu />
</div>
<div style={{paddingTop: '180px'}}>
<div className="ui two column stackable grid">
<div className="seven wide column">
<div className={styles.contactUsBox}>
<div className="ui two column grid">
<div className="ten wide column">
<div className={styles.contactUsBoxTitle}>
聯絡我們
</div>
</div>
<div className="column">
</div>
</div>
<div className={styles.contactUsBoxInner}>
<div className={styles.contactUsBoxContent}>
如果想要可以即時和我們展開討論,請追蹤我們的粉絲團,掌握最新動態。
</div>
<a href="https://www.facebook.com/wowafrica.tw/" target="_blank">
<img src="/images/rb_facebook.png" style={{width: '50px', margin: '3px'}}/>
</a>
<div className={styles.contactUsBoxContent}>
或者可以填寫聯絡表單,我們會以 Email 和您聯繫!
</div>
</div>
</div>
</div>
<div className="column">
<div id={styles.contactForm} className="ui large form">
<div className="eleven wide field">
<label>稱謂</label>
<input id="nameInput" type="text"/>
</div>
<div className="eleven wide field">
<label>Email</label>
<input id="emailInput" type="text"/>
</div>
<div className="eleven wide field">
<label>內容</label>
<textarea id="contentInput"/>
</div>
<div className="ui error message">
oops! 現在有些問題,請稍候再試
</div>
<div className="ui grid">
<div className="nine wide column"/>
<div className="two wide column">
<div id={styles.submitBtn} onClick={this._onSubBtnClick} className="ui submit button" style={{}}>
發送
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
},
_onSubBtnClick(e) {
$(`#${styles.contactForm}`).removeClass('error');
$(`#${styles.submitBtn}`).removeClass('button').addClass('loading button');
let request = $.ajax({
url: 'https://script.google.com/macros/s/AKfycbyYVbtEdw0FcLSUUJmADYqN9P523HcmQL1MjmnUqvCdruUNkwvs/exec',
type: 'post',
data: {
'稱謂': $('#nameInput')[0].value,
'Email': $('#emailInput')[0].value,
'內容': $('#contentInput')[0].value
}
})
.done(function(data) {
$(`#${styles.submitBtn}`).text('完成!');
})
.fail(function(data) {
$(`#${styles.contactForm}`).addClass('error');
})
.always(function() {
$(`#${styles.submitBtn}`).removeClass('loading button').addClass('button');
});
}
});
|
Semicheche/foa_frappe_docker
|
frappe-bench/apps/erpnext/erpnext/patches/v8_1/add_hsn_sac_codes.py
|
<reponame>Semicheche/foa_frappe_docker
import frappe
from erpnext.regional.india.setup import setup
def execute():
company = frappe.get_all('Company', filters = {'country': 'India'})
if not company:
return
# call setup for india
setup(patch=True)
|
EmileSonneveld/maproef1819-emile
|
iPlasma_decompiled/decompiled_result/src/lrg/memoria/importer/mcc/loader/DefaultVariableVisitor.java
|
/* */ package lrg.memoria.importer.mcc.loader;
/* */ import java.util.HashMap;
/* */ import java.util.Map;
/* */ import java.util.Set;
/* */ import lrg.memoria.core.Attribute;
/* */ import lrg.memoria.core.Class;
/* */ import lrg.memoria.core.File;
/* */ import lrg.memoria.core.Function;
/* */ import lrg.memoria.core.FunctionBody;
/* */ import lrg.memoria.core.GlobalVariable;
/* */ import lrg.memoria.core.LocalVariable;
/* */ import lrg.memoria.core.Location;
/* */ import lrg.memoria.core.Namespace;
/* */ import lrg.memoria.core.Package;
/* */ import lrg.memoria.core.Parameter;
/* */ import lrg.memoria.core.UnnamedNamespace;
/* */ import lrg.memoria.core.Variable;
/* */
/* */ public class DefaultVariableVisitor extends DefaultVisitorRoot implements VariableVisitor {
/* */ private Integer varId;
/* */ private Location location;
/* */ private String varName;
/* */ private int accessMode;
/* */ private boolean isStatic;
/* */ private boolean isConst;
/* 26 */ private HashMap<Integer, GlobalVariable> refersToMap = new HashMap(); private Type type; private String kindOf; private DataAbstraction typeScope; private Package packageScope; private Namespace namespaceScope; private Integer bodyScopeId; private Integer refersToVariable;
/* */ private File currentFile;
/* */
/* */ public void setId(Integer id) {
/* 30 */ this.varId = id;
/* 31 */ this.accessMode = 0;
/* */ }
/* */
/* */ public void setFileName(String fileFullName) {
/* 35 */ if (!fileFullName.equals("NULL")) {
/* 36 */ this.currentFile = Loader.getInstance().getFileByName(fileFullName);
/* 37 */ this.location = new Location(this.currentFile);
/* */ } else {
/* 39 */ this.location = new Location(File.getUnknownFile());
/* */ }
/* */ }
/* */
/* 43 */ public void setDeclarationLine(Integer declarationLine) { this.location.setStartLine(declarationLine.intValue()); }
/* */
/* */
/* */ public void setVariableName(String variableName) {
/* 47 */ if (variableName.indexOf("NO_NAME") >= 0) {
/* 48 */ this.varName = "";
/* */ } else {
/* 50 */ this.varName = variableName;
/* */ }
/* */ }
/* */
/* 54 */ public void setKindOf(String kindOf) { this.kindOf = kindOf; }
/* */
/* */
/* */ public void setTypeId(String tId) {
/* 58 */ if (tId.indexOf("<ERROR>") >= 0 || tId.indexOf("<NO_ONE>") >= 0) {
/* 59 */ this.type = Class.getUnknownClass();
/* */ } else {
/* 61 */ int temp = Integer.parseInt(tId);
/* 62 */ this.type = Loader.getInstance().getType(new Integer(temp));
/* 63 */ if (this.type == null) {
/* 64 */ this.type = Class.getUnknownClass();
/* */ }
/* */ }
/* */ }
/* */
/* */ public void setAccess(String access) {
/* 70 */ if (access.indexOf("public") >= 0)
/* 71 */ this.accessMode = 1;
/* 72 */ if (access.indexOf("private") >= 0)
/* 73 */ this.accessMode = 4;
/* 74 */ if (access.indexOf("protected") >= 0)
/* 75 */ this.accessMode = 2;
/* */ }
/* */
/* */ public void setClassId(String cId) {
/* 79 */ if (cId.indexOf("<ERROR>") >= 0 || cId.indexOf("NULL") >= 0) {
/* 80 */ this.typeScope = Class.getUnknownClass();
/* */ } else {
/* 82 */ int temp = Integer.parseInt(cId);
/* 83 */ this.typeScope = (DataAbstraction)Loader.getInstance().getType(new Integer(temp));
/* */ }
/* */ }
/* */
/* */ public void setBodyId(String bId) {
/* 88 */ if (bId.indexOf("<ERROR>") >= 0 || bId.indexOf("NULL") >= 0) {
/* 89 */ this.bodyScopeId = new Integer(-1);
/* */ } else {
/* 91 */ this.bodyScopeId = new Integer(bId);
/* */ }
/* */ }
/* */
/* */ public void setPackageId(String pId) {
/* 96 */ if (pId.indexOf("NULL") < 0) {
/* 97 */ int temp = Integer.parseInt(pId);
/* 98 */ this.packageScope = Loader.getInstance().getPackage(new Integer(temp));
/* */ }
/* 100 */ if (this.packageScope == null)
/* 101 */ this.packageScope = Package.getUnknownPackage();
/* */ }
/* */
/* */ public void setNamespaceId(String namespaceId) {
/* 105 */ if (namespaceId.indexOf("<NO_ONE>") >= 0) {
/* 106 */ this.namespaceScope = Namespace.getAnonymousNamespace();
/* */ return;
/* */ }
/* 109 */ if (namespaceId.indexOf("<ERROR>") < 0 && namespaceId.indexOf("NULL") < 0) {
/* 110 */ int temp = Integer.parseInt(namespaceId);
/* 111 */ this.namespaceScope = Loader.getInstance().getNamespace(new Integer(temp));
/* */ }
/* 113 */ if (this.namespaceScope == null)
/* 114 */ this.namespaceScope = Namespace.getUnknownNamespace();
/* */ }
/* */
/* */ public void setIsStatic(Integer isSt) {
/* 118 */ if (isSt.intValue() == 1) {
/* 119 */ this.isStatic = true;
/* */ } else {
/* 121 */ this.isStatic = false;
/* */ }
/* */ }
/* */ public void setIsConst(Integer isCt) {
/* 125 */ if (isCt.intValue() == 1) {
/* 126 */ this.isConst = true;
/* */ } else {
/* 128 */ this.isConst = false;
/* */ }
/* */ }
/* */ public void setRefersTo(String refersTo) {
/* 132 */ if (refersTo.indexOf("<ERROR>") >= 0 || refersTo.indexOf("NULL") >= 0 ||
/* 133 */ refersTo.indexOf("<NOT_INIT>") >= 0 || refersTo.indexOf("<NO_ONE>") >= 0) {
/* 134 */ this.refersToVariable = new Integer(0);
/* */ } else {
/* 136 */ this.refersToVariable = new Integer(refersTo);
/* */ }
/* */ }
/* */
/* */
/* */ public void addVariable() {
/* 142 */ Variable var = null;
/* 143 */ if (this.kindOf.equals("global"))
/* 144 */ var = addGlobalVariable();
/* 145 */ if (this.kindOf.equals("attribute"))
/* 146 */ var = addAttribute();
/* 147 */ if (this.kindOf.equals("parameter"))
/* 148 */ Parameter parameter = addParameter();
/* 149 */ if (this.kindOf.equals("local"))
/* 150 */ var = addLocalVariable();
/* 151 */ var.setLocation(this.location);
/* 152 */ var.setType(this.type);
/* 153 */ if (this.isConst)
/* 154 */ var.setFinal();
/* 155 */ if (this.refersToVariable.intValue() > 0) {
/* 156 */ assert var instanceof GlobalVariable : "ERROR: The variable that refers an extern variable should be global !";
/* 157 */ if (var instanceof GlobalVariable)
/* 158 */ this.refersToMap.put(this.refersToVariable, (GlobalVariable)var);
/* */ }
/* 160 */ var.setStatute(1);
/* 161 */ Loader.getInstance().addVariable(this.varId, var);
/* */ }
/* */
/* */ public void variablesEOF() {
/* 165 */ Set<Map.Entry<Integer, GlobalVariable>> keys = this.refersToMap.entrySet();
/* */
/* */
/* 168 */ for (Map.Entry<Integer, GlobalVariable> key : keys) {
/* 169 */ Integer refersToID = (Integer)key.getKey();
/* 170 */ GlobalVariable var = (GlobalVariable)key.getValue();
/* 171 */ GlobalVariable refersTo = (GlobalVariable)Loader.getInstance().getVariable(refersToID);
/* 172 */ var.setRefersTo(refersTo);
/* */ }
/* */ }
/* */
/* */ private Variable addGlobalVariable() {
/* 177 */ GlobalVariable gv = new GlobalVariable(this.varName);
/* 178 */ if (this.isStatic) {
/* 179 */ UnnamedNamespace unsp = Loader.getInstance().getUnnamedNamespace(this.currentFile.getFullName());
/* 180 */ gv.setScope(unsp);
/* 181 */ unsp.addGlobalVariable(gv);
/* */ } else {
/* 183 */ gv.setScope(this.namespaceScope);
/* 184 */ this.namespaceScope.addGlobalVariable(gv);
/* */ }
/* 186 */ gv.setPackage(this.packageScope);
/* 187 */ this.packageScope.addGlobalVariable(gv);
/* 188 */ if (this.isStatic)
/* 189 */ gv.setStatic();
/* 190 */ return gv;
/* */ }
/* */
/* */ private Variable addLocalVariable() {
/* 194 */ LocalVariable lv = new LocalVariable(this.varName);
/* 195 */ FunctionBody fb = Loader.getInstance().getBody(this.bodyScopeId);
/* 196 */ if (lv == null || fb == null) return lv;
/* */
/* 198 */ fb.addLocalVar(lv);
/* 199 */ lv.setScope(fb.getCodeStripe());
/* 200 */ if (this.isStatic)
/* 201 */ lv.setStatic();
/* 202 */ return lv;
/* */ }
/* */
/* */ private Variable addAttribute() {
/* 206 */ Attribute attr = new Attribute(this.varName);
/* 207 */ attr.setScope(this.typeScope);
/* 208 */ this.typeScope.addAttribute(attr);
/* 209 */ assert this.accessMode != 0 : "Error: could not identify the access mode for attribute *" + attr.getFullName() + "*";
/* 210 */ attr.setAccessMode(this.accessMode);
/* 211 */ if (this.isStatic)
/* 212 */ attr.setStatic();
/* 213 */ return attr;
/* */ }
/* */
/* */ private Parameter addParameter() {
/* 217 */ Parameter par = new Parameter(this.varName);
/* 218 */ FunctionBody fb = Loader.getInstance().getBody(this.bodyScopeId);
/* 219 */ if (fb == null) return par;
/* 220 */ Function func = fb.getScope();
/* 221 */ if (func == null) return par;
/* 222 */ func.addParameter(par);
/* 223 */ par.setScope(func);
/* 224 */ return par;
/* */ }
/* */ }
/* Location: C:\Users\emill\Dropbox\slimmerWorden\2018-2019-Semester2\THESIS\iPlasma6\tools\iPlasma\memoria.jar!\lrg\memoria\importer\mcc\loader\DefaultVariableVisitor.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 1.0.7
*/
|
ursomniac/skytour
|
skytour/skytour/apps/session/pdf_pages/utils.py
|
from ...utils.format import to_sex, to_hm, to_dm, to_time
def show_object_table(obj, p, y, instance, xoff=0):
app = obj['apparent']
obs = obj['observe']
p.drawString(50, y, obj['name'])
p.drawString(120+xoff, y, 'in '+obs['constellation']['abbr'])
p.drawString(150+xoff, y, to_hm(app['equ']['ra']))
p.drawString(195+xoff, y, to_dm(app['equ']['dec']))
p.drawString(230+xoff, y, f"{app['distance']['au']:5.2f}")
p.drawString(260+xoff, y, f"{to_time(app['distance']['light_time'])}")
p.drawString(300+xoff, y, f"{obs['apparent_magnitude']:5.2f}")
if instance.last_observed is not None:
p.drawString(330+xoff, y, instance.last_observed.strftime('%Y-%m-%d'))
y -= 12
return p, y
def show_table_header(p, y, xoff=0):
p.setFont('Helvetica-Bold', 9)
p.drawString(50, y, 'NAME')
p.drawString(120+xoff, y, 'CON.')
p.drawString(150+xoff, y, 'R.A.')
p.drawString(195+xoff, y, 'DEC.')
p.drawString(230+xoff, y, 'DIST')
p.drawString(260+xoff, y, 'L.T.')
p.drawString(300+xoff, y, 'MAG')
p.drawString(330+xoff, y, 'LAST OBS.')
y -= 15
p.setFont('Helvetica', 8)
return p, y
def do_line(p, x, y, l, dy=15):
p.drawString(x, y, l)
y -= dy
return p, y
|
EmanuelHerrendorf/mapping-core
|
src/pointvisualization/Circle.h
|
<gh_stars>0
#ifndef POINTVISUALIZATION_CIRCLE_H_
#define POINTVISUALIZATION_CIRCLE_H_
#include <vector>
#include <memory>
#include <cmath>
#include <string>
#include <sstream>
#include <map>
#include <numeric>
#include <algorithm>
#include "Coordinate.h"
namespace pv {
/**
* A circle cluster consisting of a center, a radius and a number of points.
* The radius calculates of the minimum radius and the number of points (cluster).
*/
class Circle {
public:
/**
* This class represents a numeric attribute value aggregation.
*/
class NumericAttribute {
public:
/**
* Construct a NumericAttribute using the initialValue for the average of cardinality one.
* @param initialValue
*/
NumericAttribute(double initialValue);
/**
* Merge this attribute with another one, specifying weights
* @param other the other attribute
* @return a new numeric attribute
*/
NumericAttribute merge(
const NumericAttribute& other,
unsigned int thisWeight,
unsigned int otherWeight
) const;
/**
* Return the average of the numeric attribute regarding the circle assignement.
* @return the average
*/
double getAverage() const;
/**
* Return the variance of the numeric attribute regarding the circle assignment.
* @return the variance
*/
double getVariance() const;
private:
double average;
double averageOfSquared;
};
/**
* This dictionary allows efficient storage of strings and maps them to numbers.
*/
class TextDictionary {
public:
std::string getTextForKey(std::size_t key) const;
std::size_t getKeyForText(std::string& text);
private:
std::map<std::string, std::size_t> textResolutionMap;
std::vector<std::string> keyResolutionMap;
};
/**
* Attributes that are shared among each circle
*/
class CommonAttributes {
public:
/**
* Create common attributes
* @param circleMinRadius
* @param epsilonDistance
* @return a common attributes instance
*/
CommonAttributes(double circleMinRadius, double epsilonDistance);
/**
* @return the minimum radius
*/
double getCircleMinRadius() const;
/**
* @return the epsilon distance
*/
double getEpsilonDistance() const;
/**
* @return a reference to the text dictionary
*/
Circle::TextDictionary& getTextDictionary();
private:
double CIRCLE_MIN_RADIUS;
double EPSILON_DISTANCE;
Circle::TextDictionary textDictionary;
};
/**
* This class represents a textual attribute value aggregation.
*/
class TextAttribute {
public:
/**
* Construct a TextAttribute using an initial value.
* @param initialValue
* @param textResolutionMap
*/
TextAttribute(
std::string initialValue,
Coordinate coordinate,
Circle::CommonAttributes& commonAttributes
);
/**
* Merge this attribute with another one, specifying weights
* @param other the other attribute
* @return a new text attribute
*/
TextAttribute merge(
const TextAttribute& other,
const Coordinate& center
) const;
/**
* Get the text values of this attribute.
* @return a list of text values
*/
std::vector<std::string> getTexts() const;
private:
/**
* This constructor is used for merge operations.
* @param textDictionary
* @return an empty text attribute
*/
TextAttribute(
Circle::TextDictionary& textDictionary
);
Circle::TextDictionary& textDictionary;
std::vector<std::size_t> textKeys;
std::vector<Coordinate> coordinates;
static std::size_t maximumTextArrayLength;
};
/**
* Constructs a circle given a coordinate center, a minimum radius and an epsilon distance.
* @param circleMinRadius Minimum radius independent of the number of points.
* @param epsilonDistance Minimum distance between two points.
*/
Circle(Coordinate center, CommonAttributes& commonAttributes);
/**
* Constructs a circle given a coordinate center, a minimum radius and an epsilon distance.
* @param center
* @param commonAttributes
* @param textAttributes
* @param numericAttributes
*/
Circle(
Coordinate center,
CommonAttributes& commonAttributes,
std::map<std::string, TextAttribute> textAttributes,
std::map<std::string, NumericAttribute> numericAttributes
);
/**
* Merge this circle with another one and construct a new one.
* @param other
* @return merged circle
*/
Circle merge(Circle& other) const;
/**
* @return center
*/
Coordinate getCenter() const;
/**
* @return x
*/
double getX() const;
/**
* @return y
*/
double getY() const;
/**
* @return radius
*/
double getRadius() const;
/**
* @return number of points
*/
int getNumberOfPoints() const;
/**
* Checks for intersection of this circle with another one.
* (Takes epsilonDistance into account.)
* @return true if circle intersect, false else.
*/
bool intersects(Circle& circle) const;
const std::map<std::string, NumericAttribute> getNumericAttributes() const;
const std::map<std::string, TextAttribute> getTextAttributes() const;
/**
* String representation of circle.
*/
std::string to_string() const;
private:
/**
* Constructs a circle given a coordinate center, a minimum radius and an epsilon distance.
* @param circleMinRadius Minimum radius independent of the number of points.
* @param epsilonDistance Minimum distance between two points.
* @param numberOfPoints Number of points in the cluster.
*/
Circle(Coordinate center, CommonAttributes& commonAttributes, unsigned int numberOfPoints);
Coordinate center;
double radius;
CommonAttributes& commonAttributes;
unsigned int numberOfPoints;
double calculateRadius(int numberOfPoints) const;
std::map<std::string, NumericAttribute> numericAttributes;
std::map<std::string, TextAttribute> textAttributes;
};
}
#endif /* POINTVISUALIZATION_CIRCLE_H_ */
|
Kiri23/DECE-Backend-Project
|
inicio/urls.py
|
<reponame>Kiri23/DECE-Backend-Project
from django.urls import path
from . import views
urlpatterns = [
path('', views.inicio.as_view(), name='inicio'),
path('ajax/listaDeCurso', views.obtenerCategoriaFromAjax, name='ajax_cursos'),
]
|
raymondng76/sgnlp
|
sgnlp/models/rst_pointer/config.py
|
from transformers import PretrainedConfig
class RstPointerSegmenterConfig(PretrainedConfig):
"""
This is the configuration class to store the configuration of a
:class:`~sgnlp.models.rst_pointer.modeling.RstPointerSegmenterModel`.
It is used to instantiate a discourse segmenter pointer network according to the specified arguments, defining the
model architecture.
Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model
outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information.
Args:
word_dim (:obj:`int`, defaults to 1024): Word embedding dimension size.
hidden_dim (:obj:`int`, defaults to 64): Hidden dimension zie.
dropout_prob (:obj:`float`, defaults to 0.2): Dropout probability.
use_bilstm (:obj:`bool`, defaults to :obj:`True`): Whether to use bilstm layer.
num_rnn_layers (:obj:`int`, defaults to 6): Number of RNN layers.
rnn_type (:obj:`str`, defaults to "GRU"): RNN type. Supported choices: ["LSTM", "GRU"].
is_batch_norm (:obj:`bool`, defaults to True): Whether to use batch normalization.
elmo_size (:obj:`bool`, defaults to "Large"): Elmo size. Supported choices: ["Large", "Medium", "Small"].
Example::
from sgnlp.models.rst_pointer import RstPointerSegmenterConfig
# Initialize with default values
config = RstPointerSegmenterConfig()
"""
def __init__(
self,
word_dim=1024,
hidden_dim=64,
dropout_prob=0.2,
use_bilstm=True,
num_rnn_layers=6,
rnn_type="GRU",
is_batch_norm=True,
elmo_size="Large",
**kwargs):
super().__init__(**kwargs)
self.word_dim = word_dim
self.hidden_dim = hidden_dim
self.dropout_prob = dropout_prob
self.use_bilstm = use_bilstm
self.num_rnn_layers = num_rnn_layers
self.rnn_type = rnn_type
self.is_batch_norm = is_batch_norm
self.elmo_size = elmo_size
class RstPointerParserConfig(PretrainedConfig):
"""
This is the configuration class to store the configuration of a
:class:`~sgnlp.models.rst_pointer.modeling.RstPointerParserModel`.
It is used to instantiate a discourse parser pointer network according to the specified arguments, defining the
model architecture.
Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model
outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information.
Args:
word_dim (:obj:`int`, defaults to 1024): Word dimension size.
hidden_size (:obj:`int`, defaults to 64): Hidden dimension size.
decoder_input_size (:obj:`int`, defaults to 64): Decoder input size.
atten_model: (:obj:`str`, defaults to "Dotproduct"):
Attention type. Supported choices: ["Dotproduct", "Biaffine"].
classifier_input_size (:obj:`int`, defaults to 64): Classifier input size.
classifier_hidden_size (:obj:`int`, defaults to 64): Classifier hidden size.
highorder (:obj:`bool`, defaults to False): Whether to incorporate higher order information.
classes_label (:obj:`int`, defaults to 39): Number of classes to predict for.
classifier_bias (:obj:`bool`, defaults to True): Whether to use bias for classifier.
rnn_layers (:obj:`int`, defaults to 6): Number of RNN layers.
dropout_e (:obj:`float`, defaults to 0.33): Dropout rate for encoder layer.
dropout_d (:obj:`float`, defaults to 0.5): Dropout rate for decoder layer.
dropout_c (:obj:`float`, defaults to 0.5): Dropout rate for classifier layer.
elmo_size (:obj:`bool`, defaults to "Large"): Elmo size. Supported choices: ["Large", "Medium", "Small"].
Example::
from sgnlp.models.rst_pointer import RstPointerParserConfig
# Initialize with default values
config = RstPointerParserConfig()
"""
def __init__(
self,
word_dim=1024,
hidden_size=64,
decoder_input_size=64,
atten_model='Dotproduct',
classifier_input_size=64,
classifier_hidden_size=64,
highorder=False,
classes_label=39,
classifier_bias=True,
rnn_layers=6,
dropout_e=0.33,
dropout_d=0.5,
dropout_c=0.5,
elmo_size="Large",
**kwargs):
super().__init__(**kwargs)
self.word_dim = word_dim
self.hidden_size = hidden_size
self.decoder_input_size = decoder_input_size
self.atten_model = atten_model
self.classifier_input_size = classifier_input_size
self.classifier_hidden_size = classifier_hidden_size
self.highorder = highorder
self.classes_label = classes_label
self.classifier_bias = classifier_bias
self.rnn_layers = rnn_layers
self.dropout_e = dropout_e
self.dropout_d = dropout_d
self.dropout_c = dropout_c
self.elmo_size = elmo_size
|
Accelerator404/Algorithm-Demonstration
|
PAT/PAT Advanced/c++/1128.cpp
|
<reponame>Accelerator404/Algorithm-Demonstration
#include <iostream>
#include <vector>
using namespace std;
//PAT Advanced Level 1128 N Queens Puzzle
int main() {
int K;
cin >> K;
for (int i = 0; i < K; ++i) {
int N;
cin >> N;
vector<int> row(N);
bool isSolution = true;
for (int j = 0; j < N; ++j) {
cin >> row[j];
for (int k = 0; k < j; ++k) {
if(row[j] == row[k] || abs(row[j]-row[k]) == abs(j-k)){
isSolution = false;
break;
}
}
}
if(isSolution)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
|
Wildrimak/bootcamp-01-template-casa-do-codigo
|
src/main/java/br/com/zup/casadocodigo/api/controllers/EstadoController.java
|
package br.com.zup.casadocodigo.api.controllers;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import br.com.zup.casadocodigo.api.dtos.requests.EstadoRequest;
import br.com.zup.casadocodigo.domain.models.Estado;
@RestController
@RequestMapping("/estados")
public class EstadoController {
@PersistenceContext
private EntityManager manager;
@Transactional
@PostMapping // 1
public ResponseEntity<?> cadastrarEstado(@Valid @RequestBody EstadoRequest request,
UriComponentsBuilder uriComponentsBuilder) {
// 2
Estado estado = request.toModel(manager);
manager.persist(estado);
return ResponseEntity.created(uriComponentsBuilder.path("/estados/{id}").buildAndExpand(estado.getId()).toUri())
.body(estado);
}
}
|
JChanceHud/fuel-js
|
packages/wallet/src/test/index.js
|
<gh_stars>0
const { test, utils } = require('@fuel-js/environment');
const ethers = require('ethers');
const fuel = require('../index');
module.exports = test('wallet', async t => {
try {
const seedPhraseWallet = new ethers.Wallet.createRandom();
const walletMnumonic = new fuel.Wallet(null, {
network: 'rinkeby',
privateKey: seedPhraseWallet,
});
t.equal(seedPhraseWallet.address, seedPhraseWallet.address, 'seed phrase wallet');
await walletMnumonic.faucet();
await walletMnumonic.transfer(1, seedPhraseWallet.address, 500, {
sync: false,
});
walletMnumonic.off();
await walletMnumonic.db.close();
const walletA = new fuel.Wallet(null, {
network: 'rinkeby',
});
await walletA.sync();
t.equal(walletA.address, walletA.key.address, 'address');
t.equal(walletA.network.name, 'rinkeby', 'network');
t.equalBig(await walletA.balance(0), 0, 'balance ether');
await walletA.sync();
t.equalBig(await walletA.balance(1), 0, 'balance token');
await walletA.faucet();
t.equalBig(await walletA.balance(1), utils.parseEther('1000'), 'balance token');
const tokenAddr = await walletA._token(1);
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('1000'), 'balance token address');
t.equalBig(await walletA.balance(tokenAddr, {
sync: false,
}), utils.parseEther('1000'), 'balance no sync');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('1000'), 'balance no sync id');
t.catch(walletA.transfer(1, walletA.address, utils.parseEther('0')), 'invalid amount');
t.catch(walletA.transfer(2, walletA.address, utils.parseEther('100')), 'invalid token');
t.ok(await walletA.transfer(1, walletA.address, utils.parseEther('1000')), 'transfer full to self');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('1000'), 'balance no sync id');
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('1000'), 'balance token address');
t.ok(await walletA.transfer(tokenAddr, walletA.address, utils.parseEther('1000')), 'transfer full to self');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('1000'), 'balance no sync id');
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('1000'), 'balance token address');
t.ok(await walletA.transfer(tokenAddr, walletA.address, utils.parseEther('500')), 'transfer 500 to self');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('1000'), 'balance no sync id');
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('1000'), 'balance token address');
t.ok(await walletA.transfer(tokenAddr, utils.emptyAddress, utils.parseEther('1')), 'transfer 1 to null');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('999'), 'balance no sync id');
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('999'), 'balance token address');
t.ok(await walletA.transfer(tokenAddr, utils.emptyAddress, utils.parseEther('100')), 'transfer 1 to null');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('899'), 'balance no sync id');
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('899'), 'balance token address');
t.ok(await walletA.transfer(tokenAddr, utils.emptyAddress, utils.parseEther('1')), 'transfer 1 to null');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('898'), 'balance no sync id');
t.ok(await walletA.transfer(tokenAddr, utils.emptyAddress, utils.parseEther('1')), 'transfer 1 to null');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('897'), 'balance no sync id');
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('897'), 'balance token address sync');
const returnTransfer = await walletA.transfer(tokenAddr, walletA.address, utils.parseEther('1'), {
return: '0xdeafbeef',
});
t.ok(returnTransfer, 'transfer 1 to null');
t.equalBig(await walletA.balance(1, {
sync: false,
}), utils.parseEther('897'), 'balance no sync id');
t.equalBig(await walletA.balance(tokenAddr), utils.parseEther('897'), 'balance token address sync');
walletA.off();
await walletA.db.close();
} catch (testError) { console.error(testError); }
});
|
julian-blaschke/inkme
|
inkme-web-app/lib/firebase/queries.js
|
<filename>inkme-web-app/lib/firebase/queries.js
import { firebase } from "@/firebase/index";
export async function getArtistByUsername(username) {
if (!username) return;
const db = firebase.firestore();
//TODO: make checks for provided arg `username`
const doc = db.collection("artists").doc(username);
const artist = await doc.get();
if (!artist.exists) return;
return { ...artist.data(), username: doc.id };
}
export async function getInvites(shop) {
const db = firebase.firestore();
const docs = await db.collection("shops").doc(shop).collection("invites").get();
const invites = docs.docs.map((doc) => doc.data());
return invites;
}
export function ARTIST(username) {
if (!username) return;
const db = firebase.firestore();
return db.collection("artists").doc(username);
}
export function ALL_ARTISTS(username) {
const db = firebase.firestore();
if (!username) return;
return db
.collection("artists")
.where(firebase.firestore.FieldPath.documentId(), ">=", username)
.where(firebase.firestore.FieldPath.documentId(), "<=", username + "\uf8ff");
}
export function SHOP_ARTISTS(usernames) {
const db = firebase.firestore();
if (!usernames) return;
return db.collection("usernames").where(firebase.firestore.FieldPath.documentId(), "in", usernames);
}
export function ALL_SHOPS(name) {
const db = firebase.firestore();
if (!name) return;
return db
.collection("shops")
.where(firebase.firestore.FieldPath.documentId(), ">=", name)
.where(firebase.firestore.FieldPath.documentId(), "<=", name + "\uf8ff");
}
export function MY_SHOPS(username) {
const db = firebase.firestore();
if (!username) return;
return db.collection("shops").where("artists", "array-contains", username);
}
export function SHOP(name) {
const db = firebase.firestore();
if (!name) return;
return db.collection("shops").doc(name);
}
export function ALL_INVITES(shop) {
const db = firebase.firestore();
if (!shop) return;
return db.collection("shops").doc(shop).collection("invites");
}
export function MY_INVITES(username) {
const db = firebase.firestore();
if (!username) return;
return db.collectionGroup("invites").where("artist", "==", username).where("status", "==", "pending");
}
export function ALL_GUEST_SPOTS(shop) {
const db = firebase.firestore();
if (!shop) return;
return db.collection("shops").doc(shop).collection("guestspots");
}
export function MY_GUEST_SPOTS(username) {
const db = firebase.firestore();
if (!username) return;
return db.collectionGroup("guestspots").where("artist", "==", username);
}
|
Avix101/blade
|
server/models/GameResult.js
|
<filename>server/models/GameResult.js
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
let GameResultModel = {};
// Construct a game results schema (stores ids and scores)
const GameResultSchema = new mongoose.Schema({
player1Id: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
player2Id: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
winner: {
type: String,
required: true,
},
player1Score: {
type: Number,
set: num => Math.floor(num),
min: 0,
max: 1000,
},
player2Score: {
type: Number,
set: num => Math.floor(num),
min: 0,
max: 1000,
},
player1Privacy: {
type: Boolean,
required: true,
},
player2Privacy: {
type: Boolean,
required: true,
},
meta: {
type: Object,
required: true,
},
createdDate: {
type: Date,
default: Date.now,
},
});
// A static function that finds all games that a player (account) was involved in
GameResultSchema.statics.findAllGamesFor = (id, callback) => {
const search = {
$or: [
{ player1Id: id },
{ player2Id: id },
],
};
GameResultModel.find(search, callback);
};
// A static function that searches for a given number of games that fit the search criteria
GameResultSchema.statics.searchForGames = (id, startDate, endDate, limit, callback) => {
const search = {};
// Include an id to search for if requested
if (id) {
search.$or = [
{ player1Id: id },
{ player2Id: id },
];
}
// Include a start and end date if specified
if (startDate && endDate) {
search.createdDate = {
$gte: startDate.toISOString(),
$lte: endDate.toISOString(),
};
}
// Return public games only
search.player1Privacy = false;
search.player2Privacy = false;
GameResultModel.find(search, callback).sort({ createdDate: -1 }).limit(limit);
};
// A static function that searches for a GameResult by its id
GameResultSchema.statics.findById = (id, callback) => {
const search = {
_id: id,
};
return GameResultModel.findOne(search, callback);
};
GameResultModel = mongoose.model('GameResult', GameResultSchema);
module.exports.GameResultModel = GameResultModel;
module.exports.GameResultSchema = GameResultSchema;
|
pplante/droidtowers
|
tools/proguard/src/proguard/classfile/visitor/ClassCleaner.java
|
/*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2011 <NAME> (<EMAIL>)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.visitor;
import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.attribute.annotation.*;
import proguard.classfile.attribute.annotation.visitor.*;
import proguard.classfile.attribute.preverification.*;
import proguard.classfile.attribute.preverification.visitor.*;
import proguard.classfile.attribute.visitor.*;
import proguard.classfile.constant.Constant;
import proguard.classfile.constant.visitor.ConstantVisitor;
import proguard.classfile.util.SimplifiedVisitor;
/**
* This <code>ClassVisitor</code> removes all visitor information of the
* classes it visits.
*
* @author <NAME>
*/
public class ClassCleaner
extends SimplifiedVisitor
implements ClassVisitor,
ConstantVisitor,
MemberVisitor,
AttributeVisitor,
ExceptionInfoVisitor,
InnerClassesInfoVisitor,
StackMapFrameVisitor,
VerificationTypeVisitor,
AnnotationVisitor,
ElementValueVisitor
{
// Implementations for ClassVisitor.
public void visitProgramClass(ProgramClass programClass)
{
clean(programClass);
programClass.constantPoolEntriesAccept(this);
programClass.fieldsAccept(this);
programClass.methodsAccept(this);
programClass.attributesAccept(this);
}
public void visitLibraryClass(LibraryClass libraryClass)
{
clean(libraryClass);
libraryClass.fieldsAccept(this);
libraryClass.methodsAccept(this);
}
// Implementations for ConstantVisitor.
public void visitAnyConstant(Clazz clazz, Constant constant)
{
clean(constant);
}
// Implementations for MemberVisitor.
public void visitProgramMember(ProgramClass programClass, ProgramMember programMember)
{
clean(programMember);
programMember.attributesAccept(programClass, this);
}
public void visitLibraryMember(LibraryClass libraryClass, LibraryMember libraryMember)
{
clean(libraryMember);
}
// Implementations for AttributeVisitor.
public void visitAnyAttribute(Clazz clazz, Attribute attribute)
{
clean(attribute);
}
public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
{
clean(innerClassesAttribute);
innerClassesAttribute.innerClassEntriesAccept(clazz, this);
}
public void visitExceptionsAttribute(Clazz clazz, Method method, ExceptionsAttribute exceptionsAttribute)
{
clean(exceptionsAttribute);
exceptionsAttribute.exceptionEntriesAccept((ProgramClass)clazz, this);
}
public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
{
clean(codeAttribute);
codeAttribute.exceptionsAccept(clazz, method, this);
codeAttribute.attributesAccept(clazz, method, this);
}
public void visitStackMapAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapAttribute stackMapAttribute)
{
clean(stackMapAttribute);
stackMapAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
}
public void visitStackMapTableAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute, StackMapTableAttribute stackMapTableAttribute)
{
clean(stackMapTableAttribute);
stackMapTableAttribute.stackMapFramesAccept(clazz, method, codeAttribute, this);
}
public void visitAnyAnnotationsAttribute(Clazz clazz, AnnotationsAttribute annotationsAttribute)
{
clean(annotationsAttribute);
annotationsAttribute.annotationsAccept(clazz, this);
}
public void visitAnyParameterAnnotationsAttribute(Clazz clazz, Method method, ParameterAnnotationsAttribute parameterAnnotationsAttribute)
{
clean(parameterAnnotationsAttribute);
parameterAnnotationsAttribute.annotationsAccept(clazz, method, this);
}
public void visitAnnotationDefaultAttribute(Clazz clazz, Method method, AnnotationDefaultAttribute annotationDefaultAttribute)
{
clean(annotationDefaultAttribute);
annotationDefaultAttribute.defaultValueAccept(clazz, this);
}
// Implementations for InnerClassesInfoVisitor.
public void visitInnerClassesInfo(Clazz clazz, InnerClassesInfo innerClassesInfo)
{
clean(innerClassesInfo);
}
// Implementations for ExceptionInfoVisitor.
public void visitExceptionInfo(Clazz clazz, Method method, CodeAttribute codeAttribute, ExceptionInfo exceptionInfo)
{
clean(exceptionInfo);
}
// Implementations for StackMapFrameVisitor.
public void visitSameZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameZeroFrame sameZeroFrame)
{
clean(sameZeroFrame);
}
public void visitSameOneFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SameOneFrame sameOneFrame)
{
clean(sameOneFrame);
sameOneFrame.stackItemAccept(clazz, method, codeAttribute, offset, this);
}
public void visitLessZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LessZeroFrame lessZeroFrame)
{
clean(lessZeroFrame);
}
public void visitMoreZeroFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, MoreZeroFrame moreZeroFrame)
{
clean(moreZeroFrame);
moreZeroFrame.additionalVariablesAccept(clazz, method, codeAttribute, offset, this);
}
public void visitFullFrame(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, FullFrame fullFrame)
{
clean(fullFrame);
fullFrame.variablesAccept(clazz, method, codeAttribute, offset, this);
fullFrame.stackAccept(clazz, method, codeAttribute, offset, this);
}
// Implementations for VerificationTypeVisitor.
public void visitAnyVerificationType(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationType verificationType)
{
clean(verificationType);
}
// Implementations for AnnotationVisitor.
public void visitAnnotation(Clazz clazz, Annotation annotation)
{
clean(annotation);
annotation.elementValuesAccept(clazz, this);
}
// Implementations for ElementValueVisitor.
public void visitAnyElementValue(Clazz clazz, Annotation annotation, ElementValue elementValue)
{
clean(elementValue);
}
public void visitAnnotationElementValue(Clazz clazz, Annotation annotation, AnnotationElementValue annotationElementValue)
{
clean(annotationElementValue);
annotationElementValue.annotationAccept(clazz, this);
}
public void visitArrayElementValue(Clazz clazz, Annotation annotation, ArrayElementValue arrayElementValue)
{
clean(arrayElementValue);
}
// Small utility methods.
private void clean(VisitorAccepter visitorAccepter)
{
visitorAccepter.setVisitorInfo(null);
}
}
|
jerryzhenleicai/Streams
|
source/providers/Zip.h
|
<reponame>jerryzhenleicai/Streams
#ifndef SCHEINERMAN_STREAM_PROVIDERS_ZIP_H
#define SCHEINERMAN_STREAM_PROVIDERS_ZIP_H
#include "StreamProvider.h"
#include <tuple>
#include <type_traits>
namespace stream {
namespace provider {
namespace detail {
template<typename L, typename R>
struct ZipperImpl {
using Type = std::tuple<L, R>;
static Type zip(L&& a, R&& b) {
return std::make_tuple<L, R>(std::move(a), std::move(b));
}
};
template<typename L, typename... RArgs>
struct ZipperImpl<L, std::tuple<RArgs...>> {
using Type = std::tuple<L, RArgs...>;
static Type zip(L&& a, std::tuple<RArgs...>&& b) {
return std::tuple_cat(std::make_tuple<L>(std::move(a)), std::move(b));
}
};
template<typename... LArgs, typename R>
struct ZipperImpl<std::tuple<LArgs...>, R> {
using Type = std::tuple<LArgs..., R>;
static Type zip(std::tuple<LArgs...>&& a, R&& b) {
return std::tuple_cat(std::move(a), std::make_tuple<R>(std::move(b)));
}
};
template<typename... LArgs, typename... RArgs>
struct ZipperImpl<std::tuple<LArgs...>, std::tuple<RArgs...>> {
using Type = std::tuple<LArgs..., RArgs...>;
static Type zip(std::tuple<LArgs...>&& a, std::tuple<RArgs...>&& b) {
return std::tuple_cat(std::move(a), std::move(b));
}
};
struct Zipper {
template<typename L, typename R>
auto operator() (L&& left, R&& right) {
using Left = typename std::decay<L>::type;
using Right = typename std::decay<R>::type;
return detail::ZipperImpl<Left, Right>::zip(std::forward<Left>(left),
std::forward<Right>(right));
}
};
} /* namespace detail */
template<typename L, typename R, typename Function>
class Zip : public StreamProvider<std::result_of_t<Function(L&&, R&&)>> {
public:
using ValueType = std::result_of_t<Function(L&&, R&&)>;
Zip(StreamProviderPtr<L> left_source,
StreamProviderPtr<R> right_source,
Function&& zipper)
: left_source_(std::move(left_source)),
right_source_(std::move(right_source)),
zipper_(zipper) {}
std::shared_ptr<ValueType> get() override {
return current_;
}
bool advance_impl() override {
if(left_source_->advance() && right_source_->advance()) {
current_ = std::make_shared<ValueType>(
zipper_(std::move(*left_source_->get()),
std::move(*right_source_->get())));
return true;
}
current_.reset();
return false;
}
PrintInfo print(std::ostream& os, int indent) const override {
this->print_indent(os, indent);
os << "Zip:\n";
return left_source_->print(os, indent + 1)
+ right_source_->print(os, indent + 1);
}
private:
StreamProviderPtr<L> left_source_;
StreamProviderPtr<R> right_source_;
std::shared_ptr<ValueType> current_;
Function zipper_;
};
} /* namespace provider */
} /* namespace stream */
#endif
|
Kvalifik/kvalifik
|
src/Components/ServicesBlock/index.js
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import ServiceList from './ServiceList'
import ServicePreview from './ServicePreview'
import Skewer from 'Components/Shared/Skewer'
import Container from 'Components/Shared/Container'
import Button from 'Components/Shared/Button'
import Padder from 'Components/Shared/Padder'
import theme from 'utils/theme'
const Content = styled.div`
padding: ${props => props.theme.spacing(2)};
`
const ButtonWrapper = styled.div`
display: flex;
flex-direction: column;
flex-wrap: nowrap;
align-items: center;
margin-top: ${props => props.theme.spacing(5)};
text-align: center;
`
class ServicesBlock extends Component {
isMobile () {
let isMobile
try {
isMobile = !!window && window.innerWidth < parseInt(theme.breakpoints.md)
} catch (e) {
isMobile = false
}
return isMobile
}
constructor (props) {
super(props)
this.state = {
selected: this.isMobile() ? -1 : 0,
isMobile: this.isMobile(),
selectedEl: null
}
}
componentDidUpdate (prevProps, prevState) {
if (prevState.selected !== this.state.selected) {
const topY = this.state.selectedEl.getBoundingClientRect().top
const scrollY = window.scrollY
if (topY < 0) {
window.scrollTo(0, scrollY + topY - 16)
}
}
}
handleSelect (ev, next) {
this.setState({
selected: next === this.state.selected /* if already selected */
? this.state.isMobile ? -1 : next /* set to nothing if mobile and next on desktop */
: next, /* otherwise go to next */
selectedEl: ev.currentTarget
})
}
render () {
const {
bgColor,
services,
buttonLink,
sideText,
toolboxPage
} = this.props
const {
selected
} = this.state
const toolboxUrl = toolboxPage ? toolboxPage.url : ''
return (
<Skewer
bgColor={bgColor || 'transparent'}
layer={1200}
>
<Padder padding={theme.spacing(10)}>
<Container sideText={sideText}>
<Content>
<ServiceList
services={services}
selected={selected}
onSelect={this.handleSelect.bind(this)}
renderPreview={(service) => (
<ServicePreview
service={service}
toolboxUrl={toolboxUrl}
/>
)}
/>
{buttonLink && (
<ButtonWrapper>
<Button
to={buttonLink.path}
type="link"
isExternal={buttonLink.isExternal}
bgColor={theme.hexToRgba(theme.palette.light, 0.2)}
color={theme.palette.light}
>
{buttonLink.name}
</Button>
</ButtonWrapper>
)}
</Content>
</Container>
</Padder>
</Skewer>
)
}
}
ServicesBlock.propTypes = {
bgColor: PropTypes.string,
sideText: PropTypes.string,
services: PropTypes.array,
buttonLink: PropTypes.shape({
path: PropTypes.string,
name: PropTypes.string,
isExternal: PropTypes.bool
}),
toolboxPage: PropTypes.shape({
url: PropTypes.string
})
}
export default ServicesBlock
|
tinochinamora/iw_imdb
|
accls/RBM/SysCV/InstVerify/RBM.ConfInst/vWrapper.cpp
|
<gh_stars>1-10
// verification wrapper
#include "model_RBM_class.hpp"
#include "subfun_cppUpdateFun_data.cpp"
#include "subfun_cppUpdateFun_data_out.cpp"
#include "subfun_cppUpdateFun_done.cpp"
#include "subfun_cppUpdateFun_init_done.cpp"
#include "subfun_cppUpdateFun_num_hidden.cpp"
#include "subfun_cppUpdateFun_num_loops.cpp"
#include "subfun_cppUpdateFun_num_movies.cpp"
#include "subfun_cppUpdateFun_num_testusers.cpp"
#include "subfun_cppUpdateFun_num_users.cpp"
#include "subfun_cppUpdateFun_num_visible.cpp"
#include "subfun_cppUpdateFun_rd_complete.cpp"
#include "subfun_cppUpdateFun_rd_granted.cpp"
#include "subfun_cppUpdateFun_rd_index.cpp"
#include "subfun_cppUpdateFun_rd_length.cpp"
#include "subfun_cppUpdateFun_rd_request.cpp"
#include "subfun_cppUpdateFun_wr_complete.cpp"
#include "subfun_cppUpdateFun_wr_granted.cpp"
#include "subfun_cppUpdateFun_wr_index.cpp"
#include "subfun_cppUpdateFun_wr_length.cpp"
#include "subfun_cppUpdateFun_wr_request.cpp"
#include "subfun_update.cpp"
model_RBM GM;
#include "verifyExample.cpp"
rbm IMPL;
int main() {
// call function
IMPL.config();
return 0;
}
|
rosecodym/space-boundary-tool
|
src/Core/src/nef_polygon_face.h
|
#pragma once
#include "precompiled.h"
#include "polygon_with_holes_2.h"
namespace geometry_2d {
namespace nef_polygons {
class face {
private:
const nef_polygon_2::Explorer * e;
nef_polygon_2::Explorer::Face_const_iterator f;
boost::optional<polygon_2> outer() const;
public:
face(const nef_polygon_2::Explorer & explorer, nef_polygon_2::Explorer::Face_const_iterator iter)
: e(&explorer), f(iter)
{ }
boost::optional<polygon_with_holes_2> to_pwh() const;
std::string to_string() const;
boost::optional<polygon_2> to_simple_polygon() const;
NT outer_regular_area() const;
};
} // namespace nef_polygons
} // namespace geometry_2d
|
imperialCHEPI/healthgps
|
source/HealthGPS.Tests/Core.UnivariateSummary.Test.cpp
|
#include "pch.h"
#include <optional>
#include "HealthGPS.Core\univariate_summary.h"
TEST(TestCore_UnivariateSummary, CreateEmptyWithoutName)
{
using namespace hgps::core;
auto init_empty = UnivariateSummary();
ASSERT_TRUE(init_empty.is_empty());
EXPECT_EQ("Untitled", init_empty.name());
EXPECT_TRUE(std::isnan(init_empty.min()));
EXPECT_TRUE(std::isnan(init_empty.max()));
EXPECT_EQ(0, init_empty.count_valid());
EXPECT_EQ(0, init_empty.count_null());
EXPECT_EQ(0, init_empty.count_total());
}
TEST(TestCore_UnivariateSummary, CreateEmptyWithName)
{
using namespace hgps::core;
auto init_name = UnivariateSummary("Test");
ASSERT_TRUE(init_name.is_empty());
EXPECT_EQ("Test", init_name.name());
EXPECT_TRUE(std::isnan(init_name.min()));
EXPECT_TRUE(std::isnan(init_name.max()));
EXPECT_EQ(0, init_name.count_valid());
EXPECT_EQ(0, init_name.count_null());
EXPECT_EQ(0, init_name.count_total());
}
TEST(TestCore_UnivariateSummary, CreateFullFromVectorWithoutName)
{
using namespace hgps::core;
auto data = std::vector<double>{ 1.0, 2.0, 3.0, 4.0, 5.0 };
auto init_vector = UnivariateSummary(data);
ASSERT_FALSE(init_vector.is_empty());
ASSERT_EQ("Untitled", init_vector.name());
ASSERT_EQ(data.size(), init_vector.count_valid());
ASSERT_EQ(0, init_vector.count_null());
ASSERT_EQ(data.size(), init_vector.count_total());
EXPECT_FALSE(std::isnan(init_vector.min()));
EXPECT_FALSE(std::isnan(init_vector.max()));
}
TEST(TestCore_UnivariateSummary, CreateFullFromVectorWithName)
{
using namespace hgps::core;
auto data = std::vector<double>{ 1.0, 2.0, 3.0, 4.0, 5.0 };
auto init_full = UnivariateSummary("Test", data);
ASSERT_FALSE(init_full.is_empty());
ASSERT_EQ("Test", init_full.name());
ASSERT_EQ(data.size(), init_full.count_valid());
ASSERT_EQ(0, init_full.count_null());
ASSERT_EQ(data.size(), init_full.count_total());
EXPECT_FALSE(std::isnan(init_full.min()));
EXPECT_FALSE(std::isnan(init_full.max()));
}
TEST(TestCore_UnivariateSummary, CreateFullFromListWithName)
{
using namespace hgps::core;
auto data = std::vector<double>{ 1.0, 2.0, 3.0, 4.0, 5.0 };
auto init_list = UnivariateSummary("Test", { 1.0, 2.0, 3.0, 4.0, 5.0 });
ASSERT_FALSE(init_list.is_empty());
ASSERT_EQ("Test", init_list.name());
ASSERT_EQ(data.size(), init_list.count_valid());
ASSERT_EQ(0, init_list.count_null());
ASSERT_EQ(data.size(), init_list.count_total());
EXPECT_FALSE(std::isnan(init_list.min()));
EXPECT_FALSE(std::isnan(init_list.max()));
}
TEST(TestCore_UnivariateSummary, CreateFullValues)
{
using namespace hgps::core;
auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 };
// min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness
auto expected = std::vector<double>{
0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238,
-0.533980927444051, 0.172868169857032 };
auto tolerance = 1e-10;
auto summary = UnivariateSummary("Test", data);
ASSERT_EQ("Test", summary.name());
ASSERT_FALSE(summary.is_empty());
ASSERT_EQ(0, summary.count_null());
ASSERT_EQ(data.size(), summary.count_valid());
ASSERT_EQ(data.size(), summary.count_total());
ASSERT_DOUBLE_EQ(expected[0], summary.min());
ASSERT_DOUBLE_EQ(expected[1], summary.max());
ASSERT_DOUBLE_EQ(expected[2], summary.range());
ASSERT_DOUBLE_EQ(expected[3], summary.sum());
ASSERT_DOUBLE_EQ(expected[4], summary.average());
EXPECT_NEAR(expected[5], summary.variance(), tolerance);
EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance);
EXPECT_NEAR(expected[7], summary.std_error(), tolerance);
EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance);
EXPECT_NEAR(expected[9], summary.skewness(), tolerance);
}
TEST(TestCore_UnivariateSummary, AppendOneValues)
{
using namespace hgps::core;
auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 };
// min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness
auto expected = std::vector<double>{
0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238,
-0.533980927444051, 0.172868169857032 };
auto tolerance = 1e-10;
auto summary = UnivariateSummary("Test");
for (auto& v : data) {
summary.append(v);
}
ASSERT_EQ("Test", summary.name());
ASSERT_FALSE(summary.is_empty());
ASSERT_EQ(0, summary.count_null());
ASSERT_EQ(data.size(), summary.count_valid());
ASSERT_EQ(data.size(), summary.count_total());
ASSERT_DOUBLE_EQ(expected[0], summary.min());
ASSERT_DOUBLE_EQ(expected[1], summary.max());
ASSERT_DOUBLE_EQ(expected[2], summary.range());
ASSERT_DOUBLE_EQ(expected[3], summary.sum());
ASSERT_DOUBLE_EQ(expected[4], summary.average());
EXPECT_NEAR(expected[5], summary.variance(), tolerance);
EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance);
EXPECT_NEAR(expected[7], summary.std_error(), tolerance);
EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance);
EXPECT_NEAR(expected[9], summary.skewness(), tolerance);
}
TEST(TestCore_UnivariateSummary, AppendRangeValues)
{
using namespace hgps::core;
auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 };
// min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness
auto expected = std::vector<double>{
0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238,
-0.533980927444051, 0.172868169857032 };
auto tolerance = 1e-10;
auto summary = UnivariateSummary("Test");
summary.append(data);
ASSERT_EQ("Test", summary.name());
ASSERT_FALSE(summary.is_empty());
ASSERT_EQ(0, summary.count_null());
ASSERT_EQ(data.size(), summary.count_valid());
ASSERT_EQ(data.size(), summary.count_total());
ASSERT_DOUBLE_EQ(expected[0], summary.min());
ASSERT_DOUBLE_EQ(expected[1], summary.max());
ASSERT_DOUBLE_EQ(expected[2], summary.range());
ASSERT_DOUBLE_EQ(expected[3], summary.sum());
ASSERT_DOUBLE_EQ(expected[4], summary.average());
EXPECT_NEAR(expected[5], summary.variance(), tolerance);
EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance);
EXPECT_NEAR(expected[7], summary.std_error(), tolerance);
EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance);
EXPECT_NEAR(expected[9], summary.skewness(), tolerance);
}
TEST(TestCore_UnivariateSummary, AppendNullValues)
{
using namespace hgps::core;
auto data = std::vector<double>{ 3.4, 0.5, 2.5, 12.6, 5.7, 8.3, 10.2, 15.8, 7.3, 9.7 };
// min, max, range, sum, average, variance, std_dev, std_error, kurtosis, skewness
auto expected = std::vector<double>{
0.5, 15.8, 15.3, 76.0, 7.6, 22.4066666666667, 4.73356806929685, 1.49688565584238,
-0.533980927444051, 0.172868169857032 };
auto tolerance = 1e-10;
auto summary = UnivariateSummary("Test", data);
auto null_count = 4;
auto null_value = std::optional<double>();
summary.append_null();
summary.append_null(2);
summary.append(null_value);
auto report = summary.to_string();
ASSERT_TRUE(report.size() > 1);
ASSERT_EQ("Test", summary.name());
ASSERT_FALSE(summary.is_empty());
ASSERT_EQ(null_count, summary.count_null());
ASSERT_EQ(data.size(), summary.count_valid());
ASSERT_EQ(data.size()+ null_count, summary.count_total());
ASSERT_DOUBLE_EQ(expected[0], summary.min());
ASSERT_DOUBLE_EQ(expected[1], summary.max());
ASSERT_DOUBLE_EQ(expected[2], summary.range());
ASSERT_DOUBLE_EQ(expected[3], summary.sum());
ASSERT_DOUBLE_EQ(expected[4], summary.average());
EXPECT_NEAR(expected[5], summary.variance(), tolerance);
EXPECT_NEAR(expected[6], summary.std_deviation(), tolerance);
EXPECT_NEAR(expected[7], summary.std_error(), tolerance);
EXPECT_NEAR(expected[8], summary.kurtosis(), tolerance);
EXPECT_NEAR(expected[9], summary.skewness(), tolerance);
}
|
amitkumarj441/QNET
|
src/qnet/algebra/core/indexed_operations.py
|
"""Base classes for indexed operations (sums and products)"""
from abc import ABCMeta
from .abstract_algebra import Expression, Operation
from .exceptions import InfiniteSumError
from ..pattern_matching import wc
from ...utils.indices import (
IdxSym, IndexRangeBase, SymbolicLabelBase, yield_from_ranges, )
__all__ = ["IndexedSum"]
class IndexedSum(Operation, metaclass=ABCMeta):
"""Base class for indexed sums"""
_expanded_cls = None # must be set by subclasses
_expand_limit = 1000
def __init__(self, term, *ranges):
self._term = term
self.ranges = tuple(ranges)
for r in self.ranges:
if not isinstance(r, IndexRangeBase):
# We need this type check to that we can use attr.astuple below
raise TypeError(
"Every range must be an instance of IndexRangeBase")
index_symbols = set([r.index_symbol for r in ranges])
if len(index_symbols) != len(self.ranges):
raise ValueError(
"ranges %s must have distinct index_symbols" % repr(ranges))
super().__init__(term, ranges=ranges)
@property
def term(self):
return self._term
@property
def operands(self):
return (self._term, )
@property
def args(self):
return tuple([self._term, *self.ranges])
@property
def variables(self):
"""List of the dummy (index) variable symbols
See also :property:`bound_symbols` for a set of the same symbols
"""
return [r.index_symbol for r in self.ranges]
@property
def bound_symbols(self):
"""Set of bound variables, i.e. the index variable symbols
See also :property:`variables` for an ordered list of the same symbols
"""
return set(self.variables)
@property
def free_symbols(self):
"""Set of all free symbols"""
return set([
sym for sym in self.term.free_symbols
if sym not in self.bound_symbols])
@property
def kwargs(self):
return {}
@property
def terms(self):
"""Iterator over the terms of the sum
Yield from the (possibly) infinite list of terms of the indexed sum, if
the sum was written out explicitly. Each yielded term in an instance of
:class:`.Expression`
"""
from qnet.algebra.core.scalar_algebra import ScalarValue
for mapping in yield_from_ranges(self.ranges):
term = self.term.substitute(mapping)
if isinstance(term, ScalarValue._val_types):
term = ScalarValue.create(term)
assert isinstance(term, Expression)
yield term
def __len__(self):
length = 1
for ind_range in self.ranges:
try:
length *= len(ind_range)
except TypeError:
raise InfiniteSumError(
"Cannot determine length from non-finite ranges")
return length
def doit(
self, classes=None, recursive=True, indices=None, max_terms=None,
**kwargs):
"""Write out the indexed sum explicitly
If `classes` is None or :class:`IndexedSum` is in `classes`,
(partially) write out the indexed sum in to an explicit sum of terms.
If `recursive` is True, write out each of the new sum's summands by
calling its :meth:`doit` method.
Args:
classes (None or list): see :meth:`.Expression.doit`
recursive (bool): see :meth:`.Expression.doit`
indices (list): List of :class:`IdxSym` indices for which the sum
should be expanded. If `indices` is a subset of the indices
over which the sum runs, it will be partially expanded. If not
given, expand the sum completely
max_terms (int): Number of terms after which to truncate the sum.
This is particularly useful for infinite sums. If not given,
expand all terms of the sum. Cannot be combined with `indices`
kwargs: keyword arguments for recursive calls to
:meth:`doit`. See :meth:`.Expression.doit`
"""
return super().doit(
classes, recursive, indices=indices, max_terms=max_terms, **kwargs)
def _doit(self, **kwargs):
indices = kwargs.get('indices', None)
max_terms = kwargs.get('max_terms', None)
if indices is None:
return self._doit_full(max_terms=max_terms)
else:
if max_terms is not None:
raise ValueError(
"max_terms is incompatible with summing over specific "
"indices")
return self._doit_over_indices(indices)
def _doit_full(self, max_terms=None):
res = None
if max_terms is None:
len(self) # side-effect: raise InfiniteSumError
else:
if max_terms > self._expand_limit:
raise ValueError(
"max_terms = %s must be smaller than the limit %s"
% (max_terms, self._expand_limit))
for i, term in enumerate(self.terms):
if max_terms is not None:
if i >= max_terms:
break
if res is None:
res = term
else:
res += term
if i > self._expand_limit:
raise InfiniteSumError(
"Cannot expand %s: more than %s terms"
% (self, self._expand_limit))
return res
def _doit_over_indices(self, indices):
if len(indices) == 0:
return self
ind_sym, *indices = indices
if not isinstance(ind_sym, IdxSym):
ind_sym = IdxSym(ind_sym)
selected_range = None
other_ranges = []
for index_range in self.ranges:
if index_range.index_symbol == ind_sym:
selected_range = index_range
else:
other_ranges.append(index_range)
if selected_range is None:
return self
res_term = None
for i, mapping in enumerate(selected_range.iter()):
res_summand = self.term.substitute(mapping)
if res_term is None:
res_term = res_summand
else:
res_term += res_summand
if i > self._expand_limit:
raise InfiniteSumError(
"Cannot expand %s: more than %s terms"
% (self, self._expand_limit))
if len(other_ranges) == 0:
res = res_term
else:
res = self.__class__.create(res_term, *other_ranges)
res = res._doit_over_indices(indices=indices)
return res
def make_disjunct_indices(self, *others):
"""Return a copy with modified indices to ensure disjunct indices with
`others`.
Each element in `others` may be an index symbol (:class:`.IdxSym`),
a index-range object (:class:`.IndexRangeBase`) or list of index-range
objects, or an indexed operation (something with a ``ranges`` attribute)
Each index symbol is primed until it does not match any index symbol in
`others`.
"""
new = self
other_index_symbols = set()
for other in others:
try:
if isinstance(other, IdxSym):
other_index_symbols.add(other)
elif isinstance(other, IndexRangeBase):
other_index_symbols.add(other.index_symbol)
elif hasattr(other, 'ranges'):
other_index_symbols.update(
[r.index_symbol for r in other.ranges])
else:
other_index_symbols.update(
[r.index_symbol for r in other])
except AttributeError:
raise ValueError(
"Each element of other must be an an instance of IdxSym, "
"IndexRangeBase, an object with a `ranges` attribute "
"with a list of IndexRangeBase instances, or a list of"
"IndexRangeBase objects.")
for r in self.ranges:
index_symbol = r.index_symbol
modified = False
while index_symbol in other_index_symbols:
modified = True
index_symbol = index_symbol.incr_primed()
if modified:
new = new._substitute(
{r.index_symbol: index_symbol}, safe=True)
return new
def __mul__(self, other):
if isinstance(other, IndexedSum):
other = other.make_disjunct_indices(self)
new_ranges = self.ranges + other.ranges
return self.__class__.create(self.term * other.term, *new_ranges)
try:
return super().__mul__(other)
except AttributeError:
return NotImplemented
def __rmul__(self, other):
if isinstance(other, IndexedSum):
self = self.make_disjunct_indices(other)
new_ranges = other.ranges + self.ranges
return self.__class__.create(other.term * self.term, *new_ranges)
try:
return super().__rmul__(other)
except AttributeError:
return NotImplemented
|
jfnavarro/old_python_courses
|
ML.1/src/lab2.py
|
'''
Created on Sep 29, 2011
@author: jfn
'''
#!/usr/bin/env python
from cvxopt.solvers import qp
from cvxopt.base import matrix
import numpy as np,pylab,random, math
from numpy import linalg
def linear_kernel(x, y):
k=0
for i in range(len(x)):
k+=(x[i]*y[i])
return k+1
def polynomial_kernel(x, y, p=3):
k=0
for i in range(len(x)):
k=k+(x[i]*y[i])
return pow((k+1),p)
def gaussian_kernel(x, y, sigma=2.0,a=0):
sigma=2
for i in range(len(x)):
a=a+(x[i]-y[i])*(x[i]-y[i])
k=np.exp(-a/(2*sigma*sigma))
return k
def sigmoid_kernel(x, y, b=0.05, delta=-0.05):
c=0
for i in range(len(x)):
c=c+(b*x[i]*y[i])
k=math.tanh(c-delta)
return k
def ind(alpha,point):
X2 = 0
for i in range(0,len(alpha)):
X2 = X2 + (alpha[i][0] * alpha[i][1][2] * linear_kernel(point,(alpha[i][1][0],alpha[i][1][1])))
return X2
classA = [(random.normalvariate(-1.5, 1),
random.normalvariate(0.5, 1),
1.0)
for i in range(5)] + \
[(random.normalvariate(1.5, 1),
random.normalvariate(0.5, 1),
1.0)
for i in range(5)]
classB = [(random.normalvariate(0.0, 0.5),
random.normalvariate(-0.5, 0.5),
-1.0)
for i in range(10)]
#classA = [(-3,3,1),(-3,2,1),(-2,3,1),(-2,2,1)]
#classB = [(3,-3,-1),(3,-2,-1),(2,-3,-1),(2,-2,-1)]
data = classA + classB
random.shuffle(data)
size = len(data)
pylab.hold(True)
pylab.plot([p[0] for p in classA],
[p[1] for p in classA],
'bo')
pylab.plot([p[0] for p in classB],
[p[1] for p in classB],
'ro')
P = np.ones(shape=(size,size)) # P[i][j] = K(x[i],x[j])
#G = np.zeros(shape=(size,size)) # 1 in diagonal and 0 in the rest
#h = np.zeros(shape=(size,1)) ## all 0
#q = np.ones(shape=(size,1)) # all -1
Q=-1.0*matrix(1.0, (size,1),'d')
G = matrix(0.0, (size,size),'d')
G[::size+1] = -1.0
H = matrix(0.0, (size,1),'d')
#for i in xrange(len(q)):
# q[i] = q[i] * -1
#
#for i in range(0,size):
# for j in range(0,size):
# if(i == j):
# G[i][j] = 1
for i in range(0,size):
for j in range(0,size):
kernel = linear_kernel(data[i][0:2],data[j][0:2])
P[i][j] = (data[i][2] * data[j][2] * kernel)
P=matrix(P, (size,size),'d')
r = qp(P, Q, G, H)
alpha = list (r['x'])
C = list()
for i in range(len(alpha)):
if alpha[i] >= 1e-5:
C.append((alpha[i],data[i]))
print alpha
xrange = np.arange(-4,4,0.05)
yrange = np.arange(-4,4,0.05)
grid = matrix([[ind(C,(x,y))
for x in yrange]
for y in xrange])
pylab.hold(True)
pylab.contour(xrange, yrange, grid,
(-1.0, 0.0, 1.0),
colors = ('red', 'black', 'blue'),
linewidths = (1, 3, 1))
pylab.show()
|
prasadus92/news-app
|
src/main/java/com/upday/news/service/impl/AuthorServiceImpl.java
|
<filename>src/main/java/com/upday/news/service/impl/AuthorServiceImpl.java<gh_stars>1-10
package com.upday.news.service.impl;
import com.upday.news.dao.Article;
import com.upday.news.dao.Author;
import com.upday.news.dto.ArticleDto;
import com.upday.news.dto.AuthorDto;
import com.upday.news.dto.mapper.ArticleMapper;
import com.upday.news.dto.mapper.AuthorMapper;
import com.upday.news.repository.ArticleRepository;
import com.upday.news.repository.AuthorRepository;
import com.upday.news.service.AuthorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component("authorService")
public class AuthorServiceImpl implements AuthorService {
private final Logger log = LoggerFactory.getLogger(AuthorServiceImpl.class);
@Autowired
private AuthorRepository authorRepository;
@Autowired
private AuthorMapper authorMapper;
@Autowired
private ArticleRepository articleRepository;
@Autowired
private ArticleMapper articleMapper;
public AuthorServiceImpl(final AuthorRepository authorRepository,
final AuthorMapper authorMapper,
final ArticleRepository articleRepository,
final ArticleMapper articleMapper) {
this.authorRepository = authorRepository;
this.authorMapper = authorMapper;
this.articleRepository = articleRepository;
this.articleMapper = articleMapper;
}
@Override
public AuthorDto createAuthor(AuthorDto authorDto) {
Author author = authorMapper.toEntity(authorDto);
author = authorRepository.save(author);
AuthorDto result = authorMapper.toDto(author);
return result;
}
@Override
public AuthorDto updateAuthor(AuthorDto authorDto) {
Author author = authorMapper.toEntity(authorDto);
author = authorRepository.save(author);
AuthorDto result = authorMapper.toDto(author);
return result;
}
@Override
public List<AuthorDto> getAllAuthors() {
List<Author> authors = authorRepository.findAll();
return authorMapper.toDto(authors);
}
@Override
public AuthorDto getAuthor(Long id) {
Optional<Author> author = authorRepository.findById(id);
if(author.isPresent()){
AuthorDto authorDto = authorMapper.toDto(author.get());
return authorDto;
}
return null;
}
@Override
public void deleteAuthor(Long id) {
authorRepository.deleteById(id);
}
@Override
public List<ArticleDto> getArticlesByAuthor(Long id) {
List<Article> articles = articleRepository.findByAuthor(id);
List<ArticleDto> articlesDto = articleMapper.toDto(articles);
return articlesDto;
}
}
|
artem-bayandin/udemy-react
|
udemy-react-guide/src/containers/App/App.js
|
import React, { useState } from 'react'
import styles from './App.module.css'
import PeopleList from '../../components/People/PeopleList/PeopleList'
import Cockpit from '../../components/Cockpit/Cockpit'
import MultipleAdjacentElements from '../../components/Custom/MultipleAdjacent/MultipleAdjacentElements'
import Auxilliary from '../../hoc/Auxilliary/Auxilliary'
import WithClass from '../../hoc/WithClass/WithClass'
import AuthContext from '../../context/auth-context'
const App = props => {
const initialState = {
people: [
{ id: 1, name: 'Bob', age: 18 },
{ id: 2, name: 'John', age: 33 },
{ id: 3, name: 'Daddy', age: 65 },
{ id: 4, name: 'Diana', age: 21 },
{ id: 5, name: 'Mary', age: 25 }
]
}
const [peopleState, setPeople] = useState(initialState)
const addAgeToAll = () => {
setPeople(prevState => {
return { people: [...prevState.people.map(p => { return { ...p, age: p.age + 1 } })] }
})
}
const makeOneOlderHandler = (event, id) => {
let target = event.currentTarget;
setPeople(prevState => {
return { people: [...prevState.people.map(p => { return p.id === id ? { ...p, age: p.age + 1 } : p })] }
})
}
const nameChangedHandler = (event, id) => {
let target = event.currentTarget;
setPeople(prevState => {
return { people: [...prevState.people.map(p => { return p.id === id ? { ...p, name: target.value } : p })] }
})
}
const deletePersonById = (id) => {
setPeople(prevState => {
return { people: [...prevState.people.filter(p => p.id !== id)] }
})
}
const [viewPeople, setViewPeople] = useState(false)
const [authenticated, setAuthenticated] = useState(false)
const loginHandler = () => setAuthenticated(prevState => !prevState)
return (
<WithClass classes={styles.app}>
<AuthContext.Provider value={{authenticated: authenticated, login: loginHandler}}>
<Cockpit
title={props.title}
setPeople={() => setPeople(initialState)}
addAgeToAll={addAgeToAll}
setViewPeople={() => setViewPeople(prevState => !prevState)}
peopleCount={peopleState.people.length}
login={loginHandler}
/>
{
viewPeople &&
<PeopleList
people={peopleState.people}
makeOneOlderHandler={makeOneOlderHandler}
nameChangedHandler={nameChangedHandler}
deletePersonById={deletePersonById}
/>
}
</AuthContext.Provider>
<div>
<Auxilliary>
<MultipleAdjacentElements />
</Auxilliary>
</div>
</WithClass>
)
}
export default App
|
learningtcc/dubbox
|
dubbo-transactiontree/src/main/java/com/alibaba/dubbo/transactiontree/api/Transaction.java
|
package com.alibaba.dubbo.transactiontree.api;
import java.util.List;
/**
*
* @author fuhaining
*/
public interface Transaction {
Xid getXid();
void setXid(Xid xid);
TransactionType getTransactionType();
void setTransactionType(TransactionType transactionType);
TransactionStatus getTransactionStatus();
void setTransactionStatus(TransactionStatus transactionStatus);
List<Participant> getParticipantList();
void addParticipant(Participant participant);
void begin();
void commit();
void rollback();
void recovery();
// void setRollbackOnly();
void setCreatedTime();
long getCreatedTime();
void setUpdateTime();
long getUpdateTime();
int incrRecoveryNum();
int getRecoveryNum();
}
|
ehardy/graphql-schema-registry
|
webpack.config.js
|
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const config = (env) => ({
output: {
path: path.resolve('./dist/assets'),
filename: '[name].js',
libraryTarget: 'umd',
chunkFilename: '[name].[contenthash].js',
crossOriginLoading: 'anonymous',
pathinfo: true,
},
module: {
rules: [
{
test: /.jsx?$/,
use: {
loader: 'babel-loader',
},
include: [path.resolve(__dirname, './client')],
},
{
test: /\.(png|jpg|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
{
test: /\.(p|post)?css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.json'],
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css?v=[contenthash]',
}),
],
});
function createConfigDev(name, entry) {
return {
mode: 'development',
name,
entry: {
[name]: [
`webpack-hot-middleware/client?path=/__webpack_hmr&reload=true&name=${name}`,
entry,
],
},
stats: 'minimal',
devtool: 'eval-cheap-source-map',
plugins: [new webpack.HotModuleReplacementPlugin()],
};
}
function createConfigProd(name, entry) {
return {
mode: 'production',
entry: {
[name]: [entry],
},
optimization: {
namedModules: true,
namedChunks: true,
minimizer: [
new TerserPlugin({
parallel: true,
sourceMap: false,
}),
],
},
plugins: [new OptimizeCssAssetsPlugin()],
};
}
const standalone = {
dev: createConfigDev(
'management-ui-standalone',
'./client/entry-standalone.jsx'
),
prod: createConfigProd(
'management-ui-standalone',
'./client/entry-standalone.jsx'
),
};
module.exports = (env) => [
merge(
config(env),
env && env.production ? standalone.prod : standalone.dev
),
];
|
shrutiparabgoogle/registry
|
server/registry/names/spec_revision.go
|
<gh_stars>10-100
// Copyright 2020 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package names
import (
"fmt"
"regexp"
)
var specRevisionRegexp = regexp.MustCompile(fmt.Sprintf("^projects/%s/locations/%s/apis/%s/versions/%s/specs/%s@%s$", identifier, Location, identifier, identifier, identifier, revisionTag))
// SpecRevision represents a resource name for an API spec revision.
type SpecRevision struct {
ProjectID string
ApiID string
VersionID string
SpecID string
RevisionID string
}
// Spec returns the parent spec for this resource.
func (s SpecRevision) Spec() Spec {
return Spec{
ProjectID: s.ProjectID,
ApiID: s.ApiID,
VersionID: s.VersionID,
SpecID: s.SpecID,
}
}
func (s SpecRevision) String() string {
return normalize(fmt.Sprintf("projects/%s/locations/%s/apis/%s/versions/%s/specs/%s@%s",
s.ProjectID, Location, s.ApiID, s.VersionID, s.SpecID, s.RevisionID))
}
// ParseSpecRevision parses the name of a spec.
func ParseSpecRevision(name string) (SpecRevision, error) {
if !specRevisionRegexp.MatchString(name) {
return SpecRevision{}, fmt.Errorf("invalid spec revision name %q: must match %q", name, specRevisionRegexp)
}
m := specRevisionRegexp.FindStringSubmatch(name)
revision := SpecRevision{
ProjectID: m[1],
ApiID: m[2],
VersionID: m[3],
SpecID: m[4],
RevisionID: m[5],
}
return revision, nil
}
|
lodenos/libft
|
src/_string/test/test-_strncat.c
|
<gh_stars>0
#include "_string.h"
void test_strncat() {}
|
nnadams/mage
|
Mage.Sets/src/mage/cards/t/TwoHeadedGiant.java
|
<reponame>nnadams/mage<filename>Mage.Sets/src/mage/cards/t/TwoHeadedGiant.java
package mage.cards.t;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.keyword.DoubleStrikeAbility;
import mage.abilities.keyword.MenaceAbility;
import mage.constants.SubType;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Outcome;
import mage.game.Game;
import mage.players.Player;
/**
*
* @author TheElk801
*/
public final class TwoHeadedGiant extends CardImpl {
public TwoHeadedGiant(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{R}{R}");
this.subtype.add(SubType.GIANT);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Whenever Two-Headed Giant attacks, flip two coins. If both coins come up heads, Two-Headed Giant gains double strike until end of turn. If both coins come up tails, Two-Headed Giant gains menace until end of turn.
this.addAbility(new AttacksTriggeredAbility(new TwoHeadedGiantEffect(), false));
}
private TwoHeadedGiant(final TwoHeadedGiant card) {
super(card);
}
@Override
public TwoHeadedGiant copy() {
return new TwoHeadedGiant(this);
}
}
class TwoHeadedGiantEffect extends OneShotEffect {
public TwoHeadedGiantEffect() {
super(Outcome.Benefit);
this.staticText = "flip two coins. If both coins come up heads, {this} gains double strike until end of turn."
+ " If both coins come up tails, {this} gains menace until end of turn";
}
public TwoHeadedGiantEffect(final TwoHeadedGiantEffect effect) {
super(effect);
}
@Override
public TwoHeadedGiantEffect copy() {
return new TwoHeadedGiantEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player player = game.getPlayer(source.getControllerId());
if (player == null) {
return false;
}
boolean head1 = player.flipCoin(source, game, false);
boolean head2 = player.flipCoin(source, game, false);
if (head1 == head2) {
if (head1) {
game.addEffect(new GainAbilitySourceEffect(DoubleStrikeAbility.getInstance(), Duration.EndOfTurn), source);
} else {
game.addEffect(new GainAbilitySourceEffect(new MenaceAbility(), Duration.EndOfTurn), source);
}
}
return true;
}
}
|
Glost/db_nets_renew_plugin
|
root/prj/sol/projects/renew2.5source/renew2.5/src/Gui/src/de/renew/gui/NetInstanceBuilder.java
|
<gh_stars>0
package de.renew.gui;
import de.renew.application.NoSimulationException;
import de.renew.application.SimulatorPlugin;
import de.renew.formalism.FormalismPlugin;
import de.renew.shadow.ShadowCompilerFactory;
import de.renew.shadow.ShadowNetSystem;
import de.renew.shadow.SyntaxException;
import java.awt.EventQueue;
/**
* @author <NAME>
*
* This static helper class allows to instantiate nets from arbitrary
* net drawings (<code>CPNDrawing</code>) at runtime.
*/
public class NetInstanceBuilder {
public static org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger(NetInstanceBuilder.class);
/**
* This method generates a new ShadowNet for the given CPN drawing and registers it with
* the running simulation. If the name is "untitled" the request is kindly ignored. Old nets with
* the same name are not removed from the simulation, but newly instantiated nets use the
* new CPN drawing. The current default compiler is used to compile the net.
*
* @param cpnd
* The CPNDrawing to instantiate
*/
public static void buildInstanceFromDrawing(CPNDrawing cpnd) {
buildInstanceFromDrawing(cpnd,
FormalismPlugin.getCurrent().getCompiler());
}
/**
* This method generates a new ShadowNet for the given CPN drawing and registers it with
* the running simulation. If the name is "untitled" the request is kindly ignored. Old nets with
* the same name are not removed from the simulation, but newly instantiated nets use the
* new CPN drawing. The used formalism can be specified by the formalismName parameter
*
* @param cpnd
* The CPNDrawing to instantiate
* @param formalismName
* The name of the formalism as registered with the formalims plugin
*/
public static void buildInstanceFromDrawing(CPNDrawing cpnd,
String formalismName) {
FormalismPlugin fp = FormalismPlugin.getCurrent();
buildInstanceFromDrawing(cpnd,
fp.getCompilerFactoryByName(formalismName));
}
/**
* This method generates a new ShadowNet for the given CPN drawing and registers it with
* the running simulation. If the name is "untitled" the request is kindly ignored. Old nets with
* the same name are not removed from the simulation, but newly instantiated nets use the
* new CPN drawing. The used formalism can be specified by the compilerFactory parameter
*
* @param cpnd
* The CPNDrawing to instantiate
* @param compilerFactory
* A ShadowCompilerFactory object that will be used to compile the given net
*/
public static void buildInstanceFromDrawing(CPNDrawing cpnd,
ShadowCompilerFactory compilerFactory) {
if (!cpnd.getName().equals("untitled")) {
ShadowNetSystem sns = new ShadowNetSystem(compilerFactory);
cpnd.buildShadow(sns);
SimulatorPlugin simulatorPlugin = SimulatorPlugin.getCurrent();
try {
simulatorPlugin.insertNets(sns);
} catch (NoSimulationException e) {
logger.error("Simulation was terminated befor the new net has been initialized");
} catch (final SyntaxException e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
GuiPlugin.getCurrent()
.processSyntaxException(FigureExceptionFactory
.createFigureException(e),
true);
}
});
}
}
}
}
|
martinx/martinxus-foursquared
|
main/src/com/joelapenna/foursquare/parsers/CategoryParser.java
|
/**
* Copyright 2010 <NAME>
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.util.IconUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Log;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @date March 6, 2010
* @author <NAME> (<EMAIL>)
* @param <T>
*/
public class CategoryParser extends AbstractParser<Category> {
private static final Logger LOG = Logger.getLogger(StatsParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public Category parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
Category category = new Category();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
if ("id".equals(name)) {
category.setId(parser.nextText());
} else if ("fullpathname".equals(name)) {
category.setFullPathName(parser.nextText());
} else if ("nodename".equals(name)) {
category.setNodeName(parser.nextText());
} else if ("iconurl".equals(name)) {
// TODO: Remove this once api v2 allows icon request.
String iconUrl = parser.nextText();
if (IconUtils.get().getRequestHighDensityIcons()) {
iconUrl = iconUrl.replace(".png", "_64.png");
}
category.setIconUrl(iconUrl);
} else if ("categories".equals(name)) {
category.setChildCategories(new GroupParser(new CategoryParser()).parse(parser));
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return category;
}
}
|
cantona/NT6
|
nitan/kungfu/class/huashan/zhanglao.h
|
// by Lonely
int accept_fight(object ob)
{
object obj, me = this_object();
int my_max_qi=query("max_qi", me);
if( query("qi", me)*100/my_max_qi <= 80 )
{
call_out("checking1", 1, me, ob);
return 0;
}
remove_call_out("checking1");
call_out("checking1", 1, me, ob);
return 1;
}
int accept_kill(object ob)
{
object obj, me = this_object();
if( query("id", me) == "ailao" && obj=present("gaolao",environment(me)) )
{
command("say 好傢伙,竟想謀害老夫!師弟,準備雙刀合壁!");
obj->kill_ob(ob);
}
if( query("id", me) == "gaolao" && obj=present("ailao",environment(me)) )
{
command("say 師兄,準備雙刀合壁超渡這傢伙!");
obj->kill_ob(ob);
}
remove_call_out("checking2");
call_out("checking2", 1, me, obj, ob);
return 1;
}
int checking1(object me, object ob)
{
object obj;
if( me->is_fighting() && me->is_killing() && !query_temp("hebi", me) )
{
if( query("id", me) == "gaolao" && obj=present("ailao",environment(me)) )
obj->kill_ob(ob);
if( query("id", me) == "ailao" && obj=present("ailao",environment(me)) )
obj->kill_ob(ob);
call_out("checking2", 1, me, obj, ob);
}
else if (me->is_fighting())
{
call_out("checking1", 1, me, ob);
}
return 1;
}
int checking2(object me, object obj, object ob)
{
if (me->is_fighting())
{
if (objectp(obj) && !obj->is_fighting())
{
obj->kill_ob(ob);
}
if( !query_temp("hebi", me) )
{
if( query("id", me) == "gaolao" )
command("perform hebi ai");
if( query("id", me) == "ailao" )
command("perform hebi gao");
}
call_out("checking2", 1, me, obj, ob);
}
return 1;
}
int accept_object(object me, object obj)
{
object ob = this_player();
int r;
if (r = ::accept_object(me, obj))
return r;
if (me->is_fighting())
return notify_fail("渾帳!你沒見我正忙着嗎?\n");
if( query("id", obj) != "zixiapaper" )
return 0;
if( query("huashan/yin-jue", ob)>1 )
{
remove_call_out("ask_why");
call_out("ask_why", 1, obj, ob);
return 1;
}
if( query("family/family_name", ob) != "華山派" )
{
remove_call_out("thank_other");
call_out("thank_other", 1, me, obj, ob);
}
else
{
remove_call_out("thank_huashan");
call_out("thank_huashan", 1, obj, ob);
}
return 1;
}
int ask_why(object obj, object ob)
{
object me = this_object();
message_vision("$N皺着眉頭對$n説道:咦!你不是已閉關靜修過了嗎?\n", me, ob);
command("say 紫霞遺頁交給我保管也好,你還有甚麼事嗎?");
destruct(obj);
return 1;
}
int thank_other(object me, object obj, object ob)
{
message_vision("$N失聲叫道:啊!這竟是本派遺失多年的紫霞遺頁!這。。。本派真是無以為報。\n", me);
command("say 請受老朽代表華山一脈向" + RANK_D->query_respect(ob) + "至意。");
command("bow");
message_vision("$N説完便飛身離去。\n", me);
destruct(obj);
destruct(me);
return 1;
}
int thank_huashan(object obj, object ob)
{
object ob1, me = this_object();
message_vision("$N失聲叫道:啊!這竟是本派遺失多年的紫霞遺頁!\n", me);
if( query("id", me) == "gaolao" && ob1=present("ailao",environment(me)) )
{
command("say 讓我和師哥商量商量,你便在此等着吧。");
message_vision("$N將矮老者拉到一旁細説了一番,只見矮老者臉色變了幾變,兩人低頭沉思着。\n", me);
me = ob1;
}
else if( query("id", me) == "ailao" && present("gaolao",environment(me)) )
{
command("say 讓我和師弟商量商量,你便在此等着吧。");
message_vision("$N將高老者拉到一旁細説了一番。高老者聽罷臉色變了幾變,兩人低頭沉思着。\n", me);
}
else
{
command("say 讓我仔細研究此箋,你便在此等着吧。");
message_vision("$N説完後便獨自走到一旁坐下,全神貫注地研讀起着紫霞遺頁來。\n", me);
}
remove_call_out("open_room");
call_out("open_room", 5, me, ob, obj);
return 1;
}
int open_room(object me, object ob, object obj)
{
message_vision("$N走了過來,向$n凝視了一陣。\n", me, ob);
command("say 你既能找回紫霞遺頁,實在是為本派立了個大功。華山有幸了! ");
if (file_name(environment(me)) != "/d/huashan/chaoyang")
{
command("say 你快回華山去吧,把喜訊告訴大夥兒!");
message_vision("$N説完便飛身離去。\n", me);
destruct(obj);
if (objectp(me))
destruct(me);
}
else
{
command("say 好!我便為你護法。你安心在密室裏閉關修練玄功吧。");
message_vision("$N將紫霞遺頁交還給$n。\n", me, ob);
message_vision("接着$N轉身向牆上一處一按一掀,牆壁正中轟隆隆響了一陣,露出一道門來。\n", me);
command("say 唉!數十年來我始終鑽研不透密室裏的用處,原來還有這個祕密。");
command("say 好好利用密室裏的東西,小心別把練功的步驟搞錯了!");
obj->move(ob);
message_vision("$N走入了門內,石門便緩緩關閉起來。\n", ob);
ob->move("/d/huashan/stair");
}
return 1;
}
|
sajalguptajft/cobbzilla-wizard
|
wizard-common/src/main/java/org/cobbzilla/wizard/client/script/ApiInnerScript.java
|
package org.cobbzilla.wizard.client.script;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.jknack.handlebars.Handlebars;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.cobbzilla.util.handlebars.HandlebarsUtil;
import org.cobbzilla.util.javascript.JsEngine;
import java.util.*;
import static org.cobbzilla.util.daemon.ZillaRuntime.empty;
import static org.cobbzilla.util.json.JsonUtil.json;
@Slf4j
public class ApiInnerScript {
@Getter @Setter private ApiScript parent;
@Getter @Setter private ApiInnerScriptRunMode runMode = ApiInnerScriptRunMode.fail_fast;
@Getter @Setter private Map<String, String> params;
public boolean hasParams () { return !empty(params); }
public void setParam(String name, String value) {
if (params == null) params = new HashMap<>();
params.put(name, value);
}
@Getter @Setter private char paramStartDelim = '[';
@Getter @Setter private char paramEndDelim = ']';
@Getter @Setter private Map<String, String> iterate;
public boolean hasIterate () { return !empty(iterate); }
public void setIterate(String name, String value) {
if (iterate == null) iterate = new HashMap<>();
iterate.put(name, value);
}
@Getter @Setter private ApiScript[] scripts;
public boolean hasScripts () { return !empty(scripts); }
public List<ApiScript> getAllScripts (JsEngine js, Handlebars handlebars, Map<String, Object> ctx) {
if (!hasScripts()) {
log.warn("getAllScripts: no scripts!");
return Collections.emptyList();
}
final List<ApiScript> all = new ArrayList<>();
if (hasParams()) {
for (Map.Entry<String, String> param : getParams().entrySet()) {
ctx.put(param.getKey(), js.evaluate(param.getValue(), ctx));
}
}
if (hasIterate()) {
final Map<String, String> iterations = new HashMap<>(getIterate());
applyIterations(js, handlebars, ctx, iterations, all);
} else {
all.addAll(buildScripts(handlebars, ctx));
}
return all;
}
private void applyIterations(JsEngine js, Handlebars handlebars, Map<String, Object> ctx, Map<String, String> iterations, List<ApiScript> scripts) {
if (empty(iterations)) {
scripts.addAll(buildScripts(handlebars, ctx));
return;
}
final Map<String, Object> ctxCopy = new HashMap<>(ctx);
final Iterator<Map.Entry<String, String>> iter = iterations.entrySet().iterator();
final Map.Entry<String, String> entry = iter.next();
iter.remove();
final Object var = js.evaluate(entry.getValue(), ctxCopy);
if (empty(var)) {
log.warn("applyIterations: var "+entry.getValue()+" evaluated to something empty: "+var);
} else {
final List<Object> resolved = new ArrayList<>();
if (var.getClass().isArray()) {
resolved.addAll(Arrays.asList((Object[]) var));
} else if (var instanceof Collection) {
resolved.addAll((Collection<?>) var);
} else {
resolved.add(var);
}
for (Object value : resolved) {
ctxCopy.put(entry.getKey(), value);
applyIterations(js, handlebars, ctxCopy, iterations, scripts);
}
}
}
private List<ApiScript> buildScripts(Handlebars handlebars, Map<String, Object> ctx) {
final List<ApiScript> scripts = new ArrayList<>();
for (ApiScript script : getCopyOfScripts()) {
HandlebarsUtil.applyReflectively(handlebars, script, ctx, paramStartDelim, paramEndDelim);
scripts.add(script);
}
return scripts;
}
@JsonIgnore private ApiScript[] getCopyOfScripts() { return json(json(getScripts()), ApiScript[].class); }
}
|
xxg1413/oneflow
|
oneflow/core/job/critical_section_desc.h
|
<gh_stars>1-10
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ONEFLOW_CORE_JOB_CRITICAL_SECTION_DESC_H_
#define ONEFLOW_CORE_JOB_CRITICAL_SECTION_DESC_H_
#include "oneflow/core/common/util.h"
#include "oneflow/core/common/protobuf.h"
#include "oneflow/core/common/data_type.h"
#include "oneflow/core/job/critical_section.pb.h"
namespace oneflow {
class CriticalSectionDesc final {
public:
OF_DISALLOW_COPY_AND_MOVE(CriticalSectionDesc);
~CriticalSectionDesc() = default;
void AddCriticalSection(std::unique_ptr<CriticalSection>&&);
void Done();
size_t CriticalSectionNum() const { return critical_sections_.size(); }
const CriticalSection& GetCriticalSection(int64_t) const;
CriticalSection* MutCriticalSection(int64_t) const;
const std::vector<int64_t>& CriticalSectionIds4JobId(int64_t) const;
void DumpCriticalSectionId2IntersectinIds(PbRpf<Int64List>* id2id_list) const;
const std::vector<int64_t>& job_id2total_job_critical_section_id() const {
return job_id2total_job_critical_section_id_;
}
private:
friend class Global<CriticalSectionDesc>;
CriticalSectionDesc() : inited_(false) {}
void UpdateJobId2CriticalSectionIds();
void UpdateJobId2TotalJobCriticalSectionId();
void UpdateCriticalSectionIds2IntersectingIds();
bool inited_;
std::vector<std::unique_ptr<CriticalSection>> critical_sections_;
std::vector<std::vector<int64_t>> job_id2critical_section_ids_;
std::vector<int64_t> job_id2total_job_critical_section_id_;
std::vector<HashSet<int64_t>> critical_section_id2intersecting_ids_;
};
} // namespace oneflow
#endif // ONEFLOW_CORE_JOB_CRITICAL_SECTION_DESC_H_
|
AgentMervin/operating-system
|
weenix/user/usr/bin/spin.c
|
/*
* Spins.
*/
int main(int argc, char **argv)
{
while (1);
return 0;
}
|
deg-commerce/salesforce-commerce-cloud-libraries
|
test/unit/lodash/isNil.test.js
|
<gh_stars>10-100
var assert = require('assert');
var { falsey } = require('../helpers/stubs');
var args = require('../helpers/args');
var isNil = require('../../../cartridges/lodash/isNil');
var map = require('../../../cartridges/lodash/map');
var _ = require('../../../cartridges/lodash/wrapperLodash');
var slice = Array.prototype.slice;
describe('isNil', function () {
it('should return `true` for nullish values', function () {
assert.strictEqual(isNil(null), true);
assert.strictEqual(isNil(), true);
assert.strictEqual(isNil(undefined), true);
});
it('should return `false` for non-nullish values', function () {
var expected = map(falsey, function (value) {
return value == null;
});
var actual = map(falsey, function (value, index) {
return index ? isNil(value) : isNil();
});
assert.deepStrictEqual(actual, expected);
assert.strictEqual(isNil(args), false);
assert.strictEqual(isNil([1, 2, 3]), false);
assert.strictEqual(isNil(true), false);
assert.strictEqual(isNil(new Date()), false);
assert.strictEqual(isNil(new Error()), false);
assert.strictEqual(isNil(_), false);
assert.strictEqual(isNil(slice), false);
assert.strictEqual(isNil({ 'a': 1 }), false);
assert.strictEqual(isNil(1), false);
assert.strictEqual(isNil(/x/), false);
assert.strictEqual(isNil('a'), false);
});
});
|
einsundnull/Conjugator-Software
|
KonjugateGermanVerbs/src/strings/LoadedVerbs.java
|
<filename>KonjugateGermanVerbs/src/strings/LoadedVerbs.java
package strings;
import java.util.ArrayList;
import conjugate.ConjugateRegularVerbs;
import filters.Filters;
public class LoadedVerbs {
public static String completeText = "";
public static ArrayList<Integer> endingsPresIDArray = new ArrayList<Integer>();
private static ArrayList<Integer> endingsPretIDArray = new ArrayList<Integer>();
private static ArrayList<Integer> endingsPerfIDArray = new ArrayList<Integer>();
private static ArrayList<Integer> endingsImpIDArray = new ArrayList<Integer>();
public static ArrayList<String[]> printArray = new ArrayList<String[]>();
public static ArrayList<String> printArrayList = new ArrayList<String>();
public static ArrayList<String> infinitiveArray = new ArrayList<String>();
public static String prs1SG = new String();
public static String prs2SG = new String();
public static String prs3SG = new String();
public static String prs1PL = new String();
public static String prs2PL = new String();
public static String prs3PL = new String();
public static String prät1SG = new String();
public static String prät2SG = new String();
public static String prät3SG = new String();
public static String prät1PL = new String();
public static String prät2PL = new String();
public static String prät3PL = new String();
public static String partI = new String();
public static String partII = new String();
public static String impI = new String();
public static String impII = new String();
public static String impIII = new String();
public static ArrayList<String> prs1SG_Irreg = new ArrayList<String>();;
public static ArrayList<String> prs2SG_Irreg = new ArrayList<String>();;
public static ArrayList<String> prs3SG_Irreg = new ArrayList<String>();;
public static ArrayList<String> prs1PL_Irreg = new ArrayList<String>();;
public static ArrayList<String> prs2PL_Irreg = new ArrayList<String>();;
public static ArrayList<String> prs3PL_Irreg = new ArrayList<String>();;
public static ArrayList<String> prät1SG_Irreg = new ArrayList<String>();;
public static ArrayList<String> prät2SG_Irreg = new ArrayList<String>();;
public static ArrayList<String> prät3SG_Irreg = new ArrayList<String>();;
public static ArrayList<String> prät1PL_Irreg = new ArrayList<String>();;
public static ArrayList<String> prät2PL_Irreg = new ArrayList<String>();;
public static ArrayList<String> prät3PL_Irreg = new ArrayList<String>();;
public static ArrayList<String> partI_Irreg = new ArrayList<String>();;
public static ArrayList<String> partII_Irreg = new ArrayList<String>();;
public static ArrayList<String> impI_Irreg = new ArrayList<String>();;
public static ArrayList<String> impII_Irreg = new ArrayList<String>();;
public static ArrayList<String> impIII_Irreg = new ArrayList<String>();
public static ArrayList<String> sylVerbArray = new ArrayList<String>();
public static void writeSingleRowOfVerbs() {
// infinitiveArray.add(ConjugateRegularVerbs.infinitiveWord);
prs1SG = ConjugateRegularVerbs.presens.get(0);
prs2SG = ConjugateRegularVerbs.presens.get(1);
prs3SG = ConjugateRegularVerbs.presens.get(2);
prs1PL = ConjugateRegularVerbs.presens.get(3);
prs2PL = ConjugateRegularVerbs.presens.get(4);
prs3PL = ConjugateRegularVerbs.presens.get(5);
prät1SG = ConjugateRegularVerbs.preteritum.get(0);
prät2SG = ConjugateRegularVerbs.preteritum.get(1);
prät3SG = ConjugateRegularVerbs.preteritum.get(2);
prät1PL = ConjugateRegularVerbs.preteritum.get(3);
prät2PL = ConjugateRegularVerbs.preteritum.get(4);
prät3PL = ConjugateRegularVerbs.preteritum.get(5);
partI = ConjugateRegularVerbs.partiI;
partII = ConjugateRegularVerbs.partiII;
impI = ConjugateRegularVerbs.imperative.get(0);
impII = ConjugateRegularVerbs.imperative.get(1);
impIII = ConjugateRegularVerbs.imperative.get(2);
// endingsPresIDArray.add(ConjugateRegularVerbs.endingListPresensID);
// endingsPretIDArray.add(ConjugateRegularVerbs.endingListPräteritumID);
// endingsPerfIDArray.add(ConjugateRegularVerbs.endingListePerfektID);
// endingsImpIDArray.add(ConjugateRegularVerbs.endingListImperativeID);
}
public static void createPrintArray(boolean showVerbType, int i) {
String row = "";
String newLine = "\n";
String verbType = "" + Filters.verbIsIrregular;
String verbTypeTab = "\t";
int prsID = ConjugateRegularVerbs.endingListPresensID;
int pretID = ConjugateRegularVerbs.endingListPräteritumID;
int perfID = ConjugateRegularVerbs.endingListePerfektID;
int impID = ConjugateRegularVerbs.endingListImperativeID;
// printArrayList.clear();
// printArray.clear();
if (!showVerbType) {
verbType = "";
verbTypeTab = "";
}
if (i == infinitiveArray.size() - 2) {
newLine = "";
}
row = infinitiveArray.get(i) + "\t" + prs1SG + "\t" + prs2SG + "\t" + prs3SG + "\t" + prs1PL + "\t" + prs2PL + "\t" + prs3PL + "\t" + prät1SG + "\t" + prät2SG + "\t"
+ prät3SG + "\t" + prät1PL + "\t" + prät2PL + "\t" + prät3PL + "\t" + partI + "\t" + partII + "\t" + impI + "\t" + impII + "\t" + impIII + "\t" + prsID + "\t"
+ pretID + "\t" + perfID + "\t" + impID + verbTypeTab + verbType + newLine;
printArrayList.add(row);
// String[] rowArray = { infinitiveArray.get(i), "", prs1SG, "", prs2SG, "", prs3SG, "", prs1PL, "", prs2PL, "", prs3PL, "", prät1SG, "", prät2SG, "",
// prät3SG, "", prät1PL, "", prät2PL, "", prät3PL, "", partI, "", partII, "", impI, "", impII, "", impIII};
// printArray.add(rowArray);
completeText = completeText + row;
}
public static void convertPrintArrayToSingelString() {
// for (int i = 0; i < printArray.size(); i++) {
//// completeText = completeText + printArray.get(i);
// }
}
}
|
HenryPajuri/teemaderegister-Companies-addTopic2
|
teemaderegister-be/src/constants/query.js
|
exports.subKeys = {
topics: [
'registered',
'available',
'defended'
],
supervisors: [
'supervised',
'all'
]
}
exports.columnKeys = {
topics: [
'author',
'accepted',
'defended',
'registered',
'title',
'types'
],
supervisors: [
'available',
'defended',
'defendedLastYear',
'registered',
'supervisor'
]
}
exports.orderTypes = [
'ascend',
'descend'
]
|
kltm/bbop-js
|
lib/bbop/widget/search_box.js
|
<reponame>kltm/bbop-js
/*
* Package: search_box.js
*
* Namespace: bbop.widget.search_box
*
* BBOP object to draw various UI elements that have to do with
* autocompletion.
*
* This is a completely self-contained UI and manager.
*/
if ( typeof bbop == "undefined" ){ var bbop = {}; }
if ( typeof bbop.widget == "undefined" ){ bbop.widget = {}; }
/*
* Constructor: search_box
*
* Contructor for the bbop.widget.search_box object.
*
* This is a specialized (and widgetized) subclass of
* <bbop.golr.manager.jquery>.
*
* The function for the callback argument should either accept a
* JSONized solr document representing the selected item or null
* (nothing found).
*
* While everything in the argument hash is technically optional,
* there are probably some fields that you'll want to fill out to make
* things work decently. The options for the argument hash are:
*
* fill_p - whether or not to fill the input with the val on select (default true)
* label_template - string template for dropdown, can use any document field
* value_template - string template for selected, can use any document field
* additional_results_class - class to add to the pop-up autocomplete ul tag when there are more results than are shown in the results
* minimum_length - wait for this many characters to start (default 3)
* list_select_callback - function takes a json solr doc on dropdown selection
*
* To get a better idea on how to use the templates, see the demo page
* at http://cdn.berkeleybop.org/jsapi/bbop-js/demo/index.html and
* read the documentation for <bbop.template>.
*
* Arguments:
* golr_loc - string url to GOlr server;
* golr_conf_obj - a <bbop.golr.conf> object
* interface_id - string id of the element to build on
* in_argument_hash - *[optional]* optional hash of optional arguments
*
* Returns:
* this object
*/
bbop.widget.search_box = function(golr_loc,
golr_conf_obj,
interface_id,
in_argument_hash){
bbop.golr.manager.jquery.call(this, golr_loc, golr_conf_obj);
this._is_a = 'bbop.widget.search_box';
// Aliases.
var anchor = this;
var loop = bbop.core.each;
// Per-UI logger.
var logger = new bbop.logger();
logger.DEBUG = true;
function ll(str){ logger.kvetch('W (auto): ' + str); }
// Our argument default hash.
var default_hash =
{
'fill_p': true,
'label_template': '{{id}}',
'value_template': '{{id}}',
'additional_results_class': '',
'minimum_length': 3, // wait for three characters or more
'list_select_callback': function(){}
};
var folding_hash = in_argument_hash || {};
var arg_hash = bbop.core.fold(default_hash, folding_hash);
// There should be a string interface_id argument.
this._interface_id = interface_id;
this._fill_p = arg_hash['fill_p'];
this._list_select_callback = arg_hash['list_select_callback'];
var label_tt = new bbop.template(arg_hash['label_template']);
var value_tt = new bbop.template(arg_hash['value_template']);
var ar_class = arg_hash['additional_results_class'];
var minlen = arg_hash['minimum_length'];
// The document return counts. Need tri-state here since 0 is a
// legit return.
var result_count = null;
var return_count = null;
// The all-important argument hash. See:
// http://jqueryui.com/demos/autocomplete/#method-widget
var auto_args = {
minLength: minlen,
// Function for a successful data hit.
// The data getter, which is making it all more complicated
// than it needs to be...we need to close around those
// callback hooks so we have to do it inplace here.
source: function(request_data, response_hook) {
anchor.jq_vars['success'] = function(json_data){
var retlist = [];
var resp = new bbop.golr.response(json_data);
// Reset the last return; remember: tri-state.
result_count = null;
return_count = null;
if( resp.success() ){
// Get best shot at document counts.
result_count = resp.total_documents();
return_count = resp.documents().length;
loop(resp.documents(),
function(doc){
// First, try and pull what we can out of our
var lbl = label_tt.fill(doc);
// Now the same thing for the return/value.
var val = value_tt.fill(doc);
// Add the discovered items to the return
// save.
var item = {
'label': lbl,
'value': val,
'document': doc
};
retlist.push(item);
});
}
response_hook(retlist);
};
// Get the selected term into the manager and fire.
//anchor.set_query(request_data.term);
anchor.set_comfy_query(request_data.term);
anchor.JQ.ajax(anchor.get_query_url(), anchor.jq_vars);
},
// What to do when an element is selected.
select: function(event, ui){
// Prevent default selection input filling action (from
// jQuery UI) when non-default marked.
if( ! anchor._fill_p ){
event.preventDefault();
}
var doc_to_apply = null;
if( ui.item ){
doc_to_apply = ui.item.document;
}
// Only do the callback if it is defined.
if( doc_to_apply &&
bbop.core.is_defined(anchor._list_select_callback) ){
anchor._list_select_callback(doc_to_apply);
}
},
// What to do when a search is completed.
response: function(event, ui){
// if( result_count != null && return_count != null ){ // possible
// if( result_count > return_count ){
// //console.log('incomplete listing');
// var item = {
// 'label': '...',
// 'value': null,
// 'document': null
// };
// ui.content.push(item);
// }else{
// //console.log('complete listing');
// }
// }
}
};
// Set the ball rolling (attach jQuery autocomplete to doc).
var jac = jQuery('#' + anchor._interface_id).autocomplete(auto_args);
// Add our render override.
// Extension point to get the additional
jac.data('ui-autocomplete')._renderMenu = function(ul, items){
// Allow standard menu construction delegation.
var anchor = this;
loop(items, function(item){
anchor._renderItemData(ul, item);
});
// Add a special class to the UL if there are results that
// are not shown.
if( ar_class && ar_class != '' ){
jQuery(ul).removeClass(ar_class); // default no
if( result_count != null && return_count != null ){ // possible
console.log('res_c: ' + result_count);
console.log('ret_c: ' + return_count);
if( result_count > return_count ){
// If
jQuery(ul).addClass(ar_class);
}
}
}
};
/*
* Function: destroy
*
* Remove the autocomplete and functionality from the DOM.
*
* Arguments:
* n/a
*
* Returns:
* n/a
*/
this.destroy = function(){
jQuery('#' + anchor._interface_id).autocomplete('destroy');
};
/*
* Function: content
*
* Get the current text contents of the search box.
*
* Arguments:
* n/a
*
* Returns:
* string
*/
this.content = function(){
return jQuery('#' + anchor._interface_id).val();
};
};
bbop.core.extend(bbop.widget.search_box, bbop.golr.manager.jquery);
|
BernardJeremy/nibbler
|
Allegro/Fruit.hpp
|
//
// Fruit.hpp for nibbler in /home/bernar_w/Projet/Nibbler/core
//
// Made by bernar_w
// Login <<EMAIL>>
//
// Started on Wed Mar 12 10:41:55 2014 bernar_w
// Last update Thu Apr 3 08:28:06 2014 <NAME>
//
#ifndef FRUIT_HPP_
# define FRUIT_HPP_
#include <exception>
#include <string>
#include <iostream>
#include <cstdlib>
class Fruit
{
public:
Fruit(int X, int Y, int value);
int getX() const;
int getY() const;
int getValue() const;
void setX(int nb);
void setY(int nb);
void setValue(int nb);
bool isFruit(int X, int Y) const;
~Fruit() {}
private:
int _x;
int _y;
int _value;
};
#endif /* !FRUIT_HPP_ */
|
ArpanMittal/myOLTP
|
src/com/oltpbenchmark/benchmarks/tpcc/TPCCState.java
|
<reponame>ArpanMittal/myOLTP<filename>src/com/oltpbenchmark/benchmarks/tpcc/TPCCState.java
package com.oltpbenchmark.benchmarks.tpcc;
import java.util.Map;
public class TPCCState {
int numberOfNewOrderRows;
int numberOfHistoryRows;
int numberOfOrderRows;
int numberOfOrderLineRows;
Map<Integer, Double> w_ytd_map;
Map<Integer, Integer> d_next_o_id_map;
Map<Integer, Double> d_ytd_map;
@Override
public boolean equals(Object otherObject) {
if (!(otherObject instanceof TPCCState)) return false;
TPCCState other = (TPCCState) otherObject;
boolean e = true;
if (numberOfHistoryRows != other.numberOfHistoryRows) {
System.out.println("Number of History rows not match, this="+numberOfHistoryRows+
", other="+other.numberOfHistoryRows);
e = false;
}
if (numberOfNewOrderRows != other.numberOfNewOrderRows) {
System.out.println("Number of NewOrder rows not match, this="+numberOfNewOrderRows+
", other="+other.numberOfNewOrderRows);
e = false;
}
if (numberOfOrderLineRows != other.numberOfOrderLineRows) {
System.out.println("Number of OrderLine rows not match, this="+numberOfOrderLineRows+
", other="+other.numberOfOrderLineRows);
e = false;
}
if (numberOfOrderRows != other.numberOfOrderRows) {
System.out.println("Number of Order rows not match, this="+numberOfOrderRows+
", other="+other.numberOfOrderRows);
e = false;
}
for (Integer w_id: w_ytd_map.keySet()) {
double val_this = w_ytd_map.get(w_id);
double val_other = other.w_ytd_map.get(w_id);
if (val_this != val_other) {
System.out.println("WAREHOUSE not match, w_id="+w_id+", this="+val_this+", other="+val_other);
e = false;
}
}
for (Integer d_id: d_next_o_id_map.keySet()) {
int val_this = d_next_o_id_map.get(d_id);
int val_other = other.d_next_o_id_map.get(d_id);
if (val_this != val_other) {
System.out.println("DISTRICT not match, d_id="+d_id+", this="+val_this+", other="+val_other);
e = false;
}
}
for (Integer d_id: d_next_o_id_map.keySet()) {
double val_this = d_next_o_id_map.get(d_id);
double val_other = other.d_next_o_id_map.get(d_id);
if (val_this != val_other) {
System.out.println("DISTRICT not match, d_id="+d_id+", this="+val_this+", other="+val_other);
e = false;
}
}
return e;
}
}
|
Kir4Kun/cloudserver
|
lib/api/apiUtils/object/expirationHeaders.js
|
const { supportedLifecycleRules } = require('arsenal').constants;
const { LifecycleConfiguration } = require('arsenal').models;
const {
LifecycleDateTime,
LifecycleUtils,
} = require('arsenal').s3middleware.lifecycleHelpers;
// moves lifecycle transition deadlines 1 day earlier, mostly for testing
const transitionOneDayEarlier = process.env.TRANSITION_ONE_DAY_EARLIER === 'true';
// moves lifecycle expiration deadlines 1 day earlier, mostly for testing
const expireOneDayEarlier = process.env.EXPIRE_ONE_DAY_EARLIER === 'true';
const lifecycleDateTime = new LifecycleDateTime({
transitionOneDayEarlier,
expireOneDayEarlier,
});
const lifecycleUtils = new LifecycleUtils(supportedLifecycleRules, lifecycleDateTime);
const oneDay = 24 * 60 * 60 * 1000; // Milliseconds in a day.
function calculateDate(objDate, expDays, datetime) {
return new Date(datetime.getTimestamp(objDate) + expDays * oneDay);
}
function formatExpirationHeader(date, id) {
return `expiry-date="${date}", rule-id="${encodeURIComponent(id)}"`;
}
// format: x-amz-expiration: expiry-date="Fri, 21 Dec 2012 00:00:00 GMT", rule-id="id"
const AMZ_EXP_HEADER = 'x-amz-expiration';
// format: x-amz-abort-date: "Fri, 21 Dec 2012 00:00:00 GMT"
const AMZ_ABORT_DATE_HEADER = 'x-amz-abort-date';
// format: x-amz-abort-rule-id: "rule id"
const AMZ_ABORT_ID_HEADER = 'x-amz-abort-rule-id';
function _generateExpHeadersObjects(rules, params, datetime) {
const tags = {
TagSet: Object.keys(params.tags)
.map(key => ({ Key: key, Value: params.tags[key] })),
};
const objectInfo = { Key: params.key };
const filteredRules = lifecycleUtils.filterRules(rules, objectInfo, tags);
const applicable = lifecycleUtils.getApplicableRules(filteredRules, objectInfo, datetime);
if (applicable.Expiration) {
const rule = applicable.Expiration;
if (rule.Days === undefined && rule.Date === undefined) {
return {};
}
if (rule.Date) {
return {
[AMZ_EXP_HEADER]: formatExpirationHeader(rule.Date, rule.ID),
};
}
const date = calculateDate(params.date, rule.Days, datetime);
return {
[AMZ_EXP_HEADER]: formatExpirationHeader(date.toUTCString(), rule.ID),
};
}
return {};
}
function _generateExpHeadresMPU(rules, params, datetime) {
const noTags = { TagSet: [] };
const objectInfo = { Key: params.key };
const filteredRules = lifecycleUtils.filterRules(rules, objectInfo, noTags);
const applicable = lifecycleUtils.getApplicableRules(filteredRules, {}, datetime);
if (applicable.AbortIncompleteMultipartUpload) {
const rule = applicable.AbortIncompleteMultipartUpload;
const date = calculateDate(
params.date,
rule.DaysAfterInitiation,
datetime
);
return {
[AMZ_ABORT_ID_HEADER]: encodeURIComponent(rule.ID),
[AMZ_ABORT_DATE_HEADER]: date.toUTCString(),
};
}
return {};
}
/**
* generate response expiration headers
* @param {object} params - params
* @param {LifecycleDateTime} datetime - lifecycle datetime object
* @returns {object} - expiration response headers
*/
function generateExpirationHeaders(params, datetime) {
const { lifecycleConfig, objectParams, mpuParams, isVersionedReq } = params;
if (!lifecycleConfig || isVersionedReq) {
return {};
}
const lcfg = LifecycleConfiguration.getConfigJson(lifecycleConfig);
if (objectParams) {
return _generateExpHeadersObjects(lcfg.Rules, objectParams, datetime);
}
if (mpuParams) {
return _generateExpHeadresMPU(lcfg.Rules, mpuParams, datetime);
}
return {};
}
/**
* set response expiration headers to target header object
* @param {object} headers - target header object
* @param {object} params - params
* @returns {undefined}
*/
function setExpirationHeaders(headers, params) {
const expHeaders = generateExpirationHeaders(params, lifecycleDateTime);
Object.assign(headers, expHeaders);
}
module.exports = {
lifecycleDateTime,
generateExpirationHeaders,
setExpirationHeaders,
};
|
heeyoung2da/Giffticon
|
src/main/java/com/ncncn/service/PsnlQustService.java
|
package com.ncncn.service;
import java.util.List;
import com.ncncn.domain.CsPsnlQustVO;
import com.ncncn.domain.pagination.CsCriteria;
public interface PsnlQustService {
//1:1문의 등록
void register(CsPsnlQustVO qna);
//ajax CsPsnlQustVO 가져오기
CsPsnlQustVO get(int id);
//관리자 답변 및 수정
boolean modify(CsPsnlQustVO qna);
//사용자 문의 수정
boolean modifyFromUser(CsPsnlQustVO qna);
//1:1문의 삭제
boolean remove(int id);
//관리자 1:1문의 가져오기
List<CsPsnlQustVO> getList(CsCriteria cri);
//사용자 1:1문의 가져오기
List<CsPsnlQustVO> getListPsnlQust(CsCriteria cri, int userId);
//관리자 total
int getTotal(CsCriteria cri);
//사용자 total
int getTotalPsnlQust(CsCriteria cri, int userId);
//답변대기 통계를 위한 count
int countHaveNoAns();
}
|
Jp-caillet/Euterpe-Front
|
src/components/radio/index.js
|
<gh_stars>0
import React, { Component } from 'react'
import ReactPlayer from 'react-player'
import { CircleSlider } from 'react-circle-slider'
import { connect } from 'react-redux'
import { Timer } from 'react-soundplayer/components'
import Modal from 'react-modal'
import axios from 'axios'
import openSocket from 'socket.io-client'
class Radio extends Component {
constructor(props) {
super(props)
this.state = {
duration: null,
secondsElapsed: null,
pourcent: 0,
value: 20,
prevValue: 20,
volumesong: 0.2,
url: '',
thumbnailUrl: '',
timerCurrent: 0,
modalIsOpen: false,
urlSend: '',
musiqueName: '',
like: false,
dislike: false,
id: '',
messages: [],
messageInput: ''
}
this.socket = openSocket('http://localhost:4000')
this.onDuration = this.onDuration.bind(this)
this.onProgress = this.onProgress.bind(this)
this.handleChange = this.handleChange.bind(this)
this.onChange = this.onChange.bind(this)
this.onEnded = this.onEnded.bind(this)
this.onLoad = this.onLoad.bind(this)
this.openModal = this.openModal.bind(this)
this.closeModal = this.closeModal.bind(this)
this.handleInputChange = this.handleInputChange.bind(this)
this.like = this.like.bind(this)
this.dislike = this.dislike.bind(this)
this.chatAdd = this.chatAdd.bind(this)
this.onLoad()
}
componentDidUpdate() {
const { messages } = this.state
const { match } = this.props
this.socket.on(match.params.id, (message) => {
const returnValue = messages
returnValue.push(
<div className="chat dark">
<p>
{message.user}
{' '}
:
{' '}
{message.mess}
</p>
<span className="time-left">
{message.heure}
:
{message.minute}
</span>
</div>
)
this.setState({ messages: returnValue })
})
}
onDuration(duration) {
this.setState({ duration })
}
onProgress(progress) {
const { duration } = this.state
if (!duration) {
// Sadly we don't have the duration yet so we can't do anything
return
}
// progress.played is the fraction of the video that has been played
// so multiply with duration to get number of seconds elapsed
const secondsElapsed = progress.played * duration
const pourcent = secondsElapsed / duration * 100
this.setState({ pourcent })
this.setState({ secondsElapsed })
}
onLoad() {
const { match, auth } = this.props
axios.post('http://localhost:4000/music/show', { radio: match.params.id, token: <PASSWORD>.token })
.then((resp) => {
const { duration } = resp.data
const { url } = resp.data
const { thumbnailUrl } = resp.data
const { started } = resp.data
const { like } = resp.data
const { dislike } = resp.data
const { id } = resp.data
const toto = new Date(started)
const date = new Date()
const seconds = (date.getTime() / 1000) - (toto.getTime() / 1000)
const timerCurrent = seconds - 10
this.setState({ duration })
this.setState({ url })
this.setState({ thumbnailUrl })
this.setState({ timerCurrent })
this.setState({ like })
this.setState({ dislike })
this.setState({ id })
this.setState({ musiqueName: resp.data.title })
}).catch((error) => {
console.log(error)
})
}
onEnded() {
const { match, auth } = this.props
axios.post('http://localhost:4000/music/show', { radio: match.params.id, token: auth.token })
.then((resp) => {
const { duration } = resp.data
const { url } = resp.data
const { thumbnailUrl } = resp.data
const { started } = resp.data
const { like } = resp.data
const { dislike } = resp.data
const { id } = resp.data
const toto = new Date(started)
const date = new Date()
const seconds = (date.getTime() / 1000) - (toto.getTime() / 1000)
const timerCurrent = seconds - 10
this.setState({ duration })
this.setState({ url })
this.setState({ thumbnailUrl })
this.setState({ timerCurrent })
this.setState({ like })
this.setState({ dislike })
this.setState({ id })
this.setState({ musiqueName: resp.data.title })
}).catch((error) => {
console.log(error)
})
}
onChange() {
let { value } = this.state
const { prevValue } = this.state
if (value === 0) {
value = prevValue
this.setState({ value })
} else {
value = 0
this.setState({ value })
}
const volumesong = value / 100
this.setState({ volumesong })
}
handleChange(value) {
this.setState({ value })
const prevValue = value
const volumesong = value / 100
this.setState({ volumesong })
this.setState({ prevValue })
}
openModal() {
this.setState({ modalIsOpen: true })
}
closeModal() {
const { urlSend } = this.state
const { match } = this.props
axios.post('http://localhost:4000/music/create', { nameRadio: match.params.id, url: urlSend })
.then((resp) => {
console.log(resp.data)
})
this.setState({ modalIsOpen: false })
}
handleInputChange(event) {
this.setState({ [event.target.name]: event.target.value })
}
like() {
const { like, id, dislike } = this.state
const { auth: { loggedIn, token } } = this.props
if (loggedIn) {
if (like) {
this.setState({ like: false })
} else {
this.setState({ like: true })
}
this.setState({ dislike: false })
axios.post('http://localhost:4000/music/like', { musicId: id, token })
if (dislike) {
axios.post('http://localhost:4000/music/dislike', { musicId: id, token })
}
}
}
dislike() {
const { like, id, dislike } = this.state
const { auth: { loggedIn, token } } = this.props
if (loggedIn) {
if (dislike) {
this.setState({ dislike: false })
} else {
this.setState({ dislike: true })
}
this.setState({ like: false })
axios.post('http://localhost:4000/music/dislike', { musicId: id, token })
if (like) {
axios.post('http://localhost:4000/music/like', { musicId: id, token })
}
}
}
chatAdd() {
const { messageInput } = this.state
const { auth, match } = this.props
const messagetosend = `${match.params.id}&/${auth.login}&/${messageInput}`
this.socket.emit('message', messagetosend)
}
render() {
const {
secondsElapsed,
pourcent,
duration,
value,
volumesong,
url,
thumbnailUrl,
timerCurrent,
modalIsOpen,
urlSend,
musiqueName,
like,
dislike,
messages,
messageInput
} = this.state
const divStyle = {
width: `${pourcent}%`
}
const customStyles = {
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
width: '600px',
transform: 'translate(-50%, -50%)'
}
}
let buttonLike
if (like) {
buttonLike = <img className="addImg" src="../src/img/like-done.png" alt="Logo" />
} else {
buttonLike = <img className="addImg" src="../src/img/like.png" alt="Logo" />
}
let buttonDislike
if (dislike) {
buttonDislike = <img className="addImg" src="../src/img/dislike-done.png" alt="Logo" />
} else {
buttonDislike = <img className="addImg" src="../src/img/dislike.png" alt="Logo" />
}
const { auth: { loggedIn }, match } = this.props
let addSongPermiss
if (loggedIn) {
addSongPermiss = (
<button style={{ outline: 'none', backgroundColor: 'Transparent' }} className="buttonAddImg" type="button" onClick={this.openModal}>
<img className="addImg" src="../src/img/cross-white.png" alt="test" />
</button>
)
} else {
addSongPermiss = (
<button style={{ outline: 'none', backgroundColor: 'Transparent' }} className="buttonAddImg" type="button">
<div className="tooltip">
<img className="addImg" src="../src/img/cross-white.png" alt="test" />
<span className="tooltiptext">veuillez vous connecter</span>
</div>
</button>
)
}
let iconVolume
if (value !== 0) {
iconVolume = <img src="../src/img/unmute.png" alt="Logo" />
} else {
iconVolume = <img src="../src/img/mute.png" alt="Logo" />
}
const createUrl = `${url}&t=${timerCurrent}s`
return (
<div style={{
backgroundImage: 'radial-gradient(circle at top left,#524333, black)',
marginLeft: '150px', /* Same as the width of the sidenav */
fontSize: '28px', /* Increased text to enable scrolling */
padding: '0px 10px',
height: '91%',
position: 'fixed',
width: '100%'
}}
>
<div id="gauche">
<img className="imageEvent" src={thumbnailUrl} alt="Logo" />
<div className="title">{musiqueName}</div>
<div className="radioName">
{ `( ${match.params.id} )` }
</div>
<div className="radioName">
<button
style={{ outline: 'none', backgroundColor: 'Transparent', marginRight: '10px' }}
className="buttonAddImg"
type="button"
onClick={this.like}
>
{ buttonLike }
</button>
<button
style={{ outline: 'none', backgroundColor: 'Transparent' }}
className="buttonAddImg"
type="button"
onClick={this.dislike}
>
{ buttonDislike }
</button>
</div>
</div>
<div id="droite">
<div className="chatBox">
<div className="chatscrool">
{ messages.map(item => (
<div key={item}>
{ item }
</div>
))}
</div>
<div>
<input
className="inputChat"
type="text"
placeholder="Your message.."
name="messageInput"
value={messageInput}
onChange={this.handleInputChange}
/>
<button
style={{ outline: 'none', backgroundColor: 'Transparent', marginLeft: '75%' }}
className="buttonAddImg"
type="submit"
>
<img className="buttonSend" src="../src/img/send.png" alt="Logo" onClick={this.chatAdd} />
</button>
</div>
</div>
</div>
<div className="footer">
<div className="center-footer">
<ReactPlayer
className="react-player"
url={createUrl}
volume={volumesong}
onDuration={this.onDuration}
onProgress={this.onProgress}
onEnded={this.onEnded}
playing
hidden
/>
<div className="timerblock">
<button type="button" className="viewMore" style={{ outline: 'none', marginLeft: '7%' }} onClick={this.onChange}>{iconVolume}</button>
<div className="CircleSlider">
<CircleSlider
className="CircleSlider"
circleWidth={5}
knobRadius={10}
size={80}
value={value}
progressWidth={5}
showPercentage={true}
showTooltip={true}
tooltipSize={14}
onChange={this.handleChange}
/>
</div>
<div id="progressbar">
<div style={divStyle} />
</div>
<Timer className="timer" duration={duration} currentTime={secondsElapsed} />
{addSongPermiss}
</div>
</div>
</div>
<div>
<Modal
isOpen={modalIsOpen}
onAfterOpen={this.afterOpenModal}
onRequestClose={this.closeModal}
ariaHideApp={false}
style={customStyles}
contentLabel="Example Modal"
>
<form onSubmit={this.closeModal}>
<input
className="inputUrl"
type="text"
name="urlSend"
placeholder="ajouter un lien youtube"
value={urlSend}
onChange={this.handleInputChange}
/>
<button type="button">send</button>
</form>
</Modal>
</div>
</div>
)
}
}
export default connect(state => state)(Radio)
|
andrey-yemelyanov/competitive-programming
|
cp-book/ch4/sssp/_00383_ShippingRoutes.java
|
<gh_stars>0
package helvidios.cp.ch4.sssp;
import java.util.*;
import static java.lang.Math.*;
public class _00383_ShippingRoutes{
public static void main(String[] args){
String data = "2\n" +
"6 7 5\n" +
"AA CC QR FF DD AB\n" +
"AA CC\n" +
"CC QR\n" +
"DD CC\n" +
"AA DD\n" +
"AA AB\n" +
"DD QR\n" +
"AB DD\n" +
"5 AA AB\n" +
"14 DD CC\n" +
"1 CC DD\n" +
"2 AA FF\n" +
"13 AB QR\n" +
"3 0 1\n" +
"AA BB CC\n" +
"5 AA CC";
String data2 = "10\n" +
"3 1 10\n" +
"OO HW KT\n" +
"KT OO\n" +
"11 OO KT\n" +
"9 HW OO\n" +
"9 HW KT\n" +
"8 HW OO\n" +
"7 KT HW\n" +
"14 HW KT\n" +
"4 KT OO\n" +
"16 HW OO\n" +
"6 OO KT\n" +
"1 HW OO\n" +
"29 216 1\n" +
"DU IM HI RO WX KF KD MV HJ MC NC FD UG RT HX BU MI TB QW NL XV AD SH MU XW XB UQ NV TG\n" +
"BU FD\n" +
"UG HX\n" +
"XB HX\n" +
"NC NV\n" +
"MC HI\n" +
"RT MV\n" +
"SH MV\n" +
"DU WX\n" +
"RT UQ\n" +
"SH KF\n" +
"NC RO\n" +
"HX DU\n" +
"XV TB\n" +
"KD DU\n" +
"MC KF\n" +
"TG XB\n" +
"DU BU\n" +
"NL RO\n" +
"MV XB\n" +
"HI RT\n" +
"IM XW\n" +
"KD TG\n" +
"KD NC\n" +
"XV UG\n" +
"MV HI\n" +
"UG IM\n" +
"NV NL\n" +
"XB TB\n" +
"BU NV\n" +
"HJ MU\n" +
"QW XW\n" +
"HI BU\n" +
"XV RT\n" +
"FD HI\n" +
"HX KF\n" +
"UQ NV\n" +
"MI DU\n" +
"XB KD\n" +
"MU HX\n" +
"QW FD\n" +
"KD HJ\n" +
"QW HI\n" +
"UG NL\n" +
"WX QW\n" +
"NV MU\n" +
"UQ RO\n" +
"NC KF\n" +
"FD MV\n" +
"BU MU\n" +
"NL IM\n" +
"DU MV\n" +
"DU QW\n" +
"BU KD\n" +
"DU RO\n" +
"KD MC\n" +
"WX HJ\n" +
"IM BU\n" +
"XB QW\n" +
"UG AD\n" +
"TG MV\n" +
"HJ KF\n" +
"TB HI\n" +
"NC IM\n" +
"XB MC\n" +
"HX HI\n" +
"SH XW\n" +
"NL XB\n" +
"TG XW\n" +
"UQ HI\n" +
"NL NC\n" +
"TB NC\n" +
"HI XV\n" +
"MC QW\n" +
"WX FD\n" +
"IM RT\n" +
"NV AD\n" +
"AD TB\n" +
"UQ KF\n" +
"MI MV\n" +
"TB NL\n" +
"WX TB\n" +
"NV UG\n" +
"XV BU\n" +
"NC XW\n" +
"NC XV\n" +
"AD KD\n" +
"IM TG\n" +
"MU QW\n" +
"HJ NL\n" +
"WX RT\n" +
"HX UQ\n" +
"XW MC\n" +
"TB IM\n" +
"QW KD\n" +
"KF RT\n" +
"MI RT\n" +
"TB RO\n" +
"RO WX\n" +
"MU UQ\n" +
"HJ XW\n" +
"XB RO\n" +
"BU XW\n" +
"RO TG\n" +
"FD RT\n" +
"NL KD\n" +
"BU QW\n" +
"MU RO\n" +
"MI UQ\n" +
"XB WX\n" +
"KF IM\n" +
"RO NV\n" +
"MV HX\n" +
"UQ SH\n" +
"MI NV\n" +
"QW NL\n" +
"UG QW\n" +
"DU UQ\n" +
"DU NL\n" +
"QW NC\n" +
"RO MI\n" +
"IM HI\n" +
"TG HJ\n" +
"MI NL\n" +
"TB BU\n" +
"KD TB\n" +
"MC HX\n" +
"TB UQ\n" +
"TG HI\n" +
"WX SH\n" +
"AD XB\n" +
"NV TB\n" +
"XV MU\n" +
"KF FD\n" +
"UQ UG\n" +
"HJ NC\n" +
"FD DU\n" +
"AD HX\n" +
"AD IM\n" +
"NV MC\n" +
"MU IM\n" +
"SH AD\n" +
"UG WX\n" +
"UG MC\n" +
"HI WX\n" +
"KF RO\n" +
"HX FD\n" +
"XW XB\n" +
"HX XW\n" +
"MV XW\n" +
"NC MI\n" +
"FD HJ\n" +
"HX KD\n" +
"XW XV\n" +
"TB MC\n" +
"MC BU\n" +
"XW UG\n" +
"KD XW\n" +
"HI MU\n" +
"MV KF\n" +
"RO UG\n" +
"MV MU\n" +
"TB SH\n" +
"WX AD\n" +
"DU KF\n" +
"TB UG\n" +
"TG WX\n" +
"NC MC\n" +
"NC HI\n" +
"RT SH\n" +
"RO RT\n" +
"IM SH\n" +
"IM HJ\n" +
"HX RT\n" +
"KD NV\n" +
"SH UG\n" +
"HJ TB\n" +
"WX IM\n" +
"TB KF\n" +
"KD RT\n" +
"HI KF\n" +
"NC MU\n" +
"XW KF\n" +
"FD XV\n" +
"XB DU\n" +
"MU XW\n" +
"HJ AD\n" +
"UQ XW\n" +
"RT DU\n" +
"NL MU\n" +
"RT NV\n" +
"AD HI\n" +
"IM MC\n" +
"NC DU\n" +
"NV FD\n" +
"RT UG\n" +
"MI XV\n" +
"MI XW\n" +
"BU MI\n" +
"XW FD\n" +
"RT TB\n" +
"QW HX\n" +
"NL FD\n" +
"MV NL\n" +
"SH MI\n" +
"UG TG\n" +
"UQ XB\n" +
"QW MV\n" +
"KD UG\n" +
"NV XB\n" +
"MU KF\n" +
"NL UQ\n" +
"DU AD\n" +
"TB TG\n" +
"XB MU\n" +
"DU NV\n" +
"MC MU\n" +
"9 QW IM\n" +
"4 3 6\n" +
"WG VQ ID XM\n" +
"XM ID\n" +
"XM VQ\n" +
"ID VQ\n" +
"2 VQ XM\n" +
"17 WG ID\n" +
"7 XM VQ\n" +
"18 ID VQ\n" +
"2 WG VQ\n" +
"15 WG XM\n" +
"4 6 3\n" +
"SP KD EF WH\n" +
"KD EF\n" +
"WH EF\n" +
"KD WH\n" +
"SP EF\n" +
"SP KD\n" +
"WH SP\n" +
"4 KD SP\n" +
"12 SP EF\n" +
"7 KD SP\n" +
"3 2 7\n" +
"XJ XY ZV\n" +
"ZV XJ\n" +
"XJ XY\n" +
"6 XY XJ\n" +
"9 XY ZV\n" +
"20 XY XJ\n" +
"10 XJ XY\n" +
"18 ZV XJ\n" +
"6 ZV XY\n" +
"14 XJ ZV\n" +
"10 29 4\n" +
"AT AS NU ZY HQ KM LT MW ET EO\n" +
"MW ZY\n" +
"NU ET\n" +
"AT KM\n" +
"NU AT\n" +
"MW AT\n" +
"NU MW\n" +
"EO AS\n" +
"MW AS\n" +
"HQ ZY\n" +
"KM ET\n" +
"LT AS\n" +
"KM LT\n" +
"AS KM\n" +
"ET LT\n" +
"LT ZY\n" +
"AT LT\n" +
"MW HQ\n" +
"HQ KM\n" +
"EO MW\n" +
"MW KM\n" +
"NU HQ\n" +
"KM NU\n" +
"ZY AT\n" +
"EO LT\n" +
"NU AS\n" +
"EO ET\n" +
"ET AS\n" +
"HQ LT\n" +
"ET ZY\n" +
"7 AS HQ\n" +
"12 NU KM\n" +
"5 AT AS\n" +
"11 NU LT\n" +
"4 5 4\n" +
"OK AD ZX XO\n" +
"OK ZX\n" +
"AD ZX\n" +
"AD OK\n" +
"XO OK\n" +
"XO AD\n" +
"4 XO AD\n" +
"4 AD OK\n" +
"14 OK ZX\n" +
"10 ZX AD\n" +
"14 58 10\n" +
"MU YA PY FS EE SN JK ZB BI BZ IM WI GK LT\n" +
"ZB IM\n" +
"IM WI\n" +
"MU ZB\n" +
"GK BI\n" +
"MU LT\n" +
"JK MU\n" +
"BZ BI\n" +
"PY MU\n" +
"WI JK\n" +
"LT JK\n" +
"YA IM\n" +
"JK GK\n" +
"EE YA\n" +
"WI YA\n" +
"GK YA\n" +
"JK YA\n" +
"FS PY\n" +
"IM SN\n" +
"IM LT\n" +
"BI MU\n" +
"BI JK\n" +
"YA BI\n" +
"BZ YA\n" +
"BI FS\n" +
"YA MU\n" +
"SN PY\n" +
"LT EE\n" +
"BZ EE\n" +
"YA FS\n" +
"ZB EE\n" +
"PY ZB\n" +
"WI EE\n" +
"BZ SN\n" +
"GK PY\n" +
"FS JK\n" +
"GK IM\n" +
"PY EE\n" +
"IM MU\n" +
"BZ IM\n" +
"YA ZB\n" +
"IM PY\n" +
"IM FS\n" +
"YA SN\n" +
"GK LT\n" +
"MU GK\n" +
"BI LT\n" +
"FS GK\n" +
"BI SN\n" +
"JK SN\n" +
"BI WI\n" +
"GK SN\n" +
"IM JK\n" +
"JK BZ\n" +
"WI FS\n" +
"EE MU\n" +
"IM EE\n" +
"ZB SN\n" +
"SN FS\n" +
"9 MU YA\n" +
"9 PY IM\n" +
"1 JK IM\n" +
"9 BZ YA\n" +
"9 JK ZB\n" +
"10 BZ WI\n" +
"7 EE MU\n" +
"7 BI MU\n" +
"7 GK LT\n" +
"1 LT GK\n" +
"25 171 0\n" +
"YU FE NN ZA LZ DK OP CH GX IL EB BT RL BI PH SK SC AO QD JF UY QN UE UQ GP\n" +
"BT QD\n" +
"GX IL\n" +
"RL FE\n" +
"EB OP\n" +
"EB NN\n" +
"CH YU\n" +
"AO QN\n" +
"RL AO\n" +
"OP QN\n" +
"SC FE\n" +
"IL QD\n" +
"PH NN\n" +
"GP UE\n" +
"NN JF\n" +
"BT QN\n" +
"BT GX\n" +
"RL BT\n" +
"JF QD\n" +
"UQ ZA\n" +
"UQ UY\n" +
"QN ZA\n" +
"IL UY\n" +
"AO DK\n" +
"GX DK\n" +
"GX AO\n" +
"FE QD\n" +
"NN SK\n" +
"OP BI\n" +
"QD ZA\n" +
"GP QD\n" +
"UE EB\n" +
"LZ AO\n" +
"CH OP\n" +
"GX RL\n" +
"FE SK\n" +
"CH NN\n" +
"PH YU\n" +
"YU AO\n" +
"PH FE\n" +
"QD DK\n" +
"BT JF\n" +
"EB YU\n" +
"UE UY\n" +
"UQ DK\n" +
"BI NN\n" +
"GP UY\n" +
"QN IL\n" +
"NN IL\n" +
"UE PH\n" +
"SK ZA\n" +
"QN UQ\n" +
"CH QN\n" +
"GP UQ\n" +
"GX UQ\n" +
"ZA FE\n" +
"GX SK\n" +
"AO ZA\n" +
"BT UQ\n" +
"SK BT\n" +
"CH AO\n" +
"BI BT\n" +
"EB ZA\n" +
"AO IL\n" +
"EB GX\n" +
"LZ UE\n" +
"LZ IL\n" +
"BI GP\n" +
"GP LZ\n" +
"NN YU\n" +
"SC AO\n" +
"YU SK\n" +
"UE FE\n" +
"OP AO\n" +
"PH BI\n" +
"OP YU\n" +
"ZA GP\n" +
"GP CH\n" +
"UE YU\n" +
"UE NN\n" +
"UQ EB\n" +
"NN UY\n" +
"DK IL\n" +
"SC GX\n" +
"OP FE\n" +
"DK QN\n" +
"QD PH\n" +
"NN GX\n" +
"UQ RL\n" +
"CH BI\n" +
"ZA UY\n" +
"LZ DK\n" +
"SK OP\n" +
"SC GP\n" +
"RL EB\n" +
"JF SC\n" +
"OP UY\n" +
"BI IL\n" +
"UY AO\n" +
"UY LZ\n" +
"DK UE\n" +
"QN BI\n" +
"GP QN\n" +
"NN RL\n" +
"EB FE\n" +
"QD NN\n" +
"EB CH\n" +
"UQ JF\n" +
"UE QD\n" +
"IL FE\n" +
"ZA RL\n" +
"IL CH\n" +
"PH BT\n" +
"FE JF\n" +
"YU UY\n" +
"UE QN\n" +
"IL ZA\n" +
"EB BI\n" +
"NN LZ\n" +
"UY SC\n" +
"PH SC\n" +
"OP LZ\n" +
"OP DK\n" +
"QN GX\n" +
"IL OP\n" +
"QN SC\n" +
"DK SC\n" +
"FE BI\n" +
"SC LZ\n" +
"QD GX\n" +
"EB AO\n" +
"YU GX\n" +
"RL QD\n" +
"EB GP\n" +
"BT ZA\n" +
"JF UE\n" +
"BI SK\n" +
"IL SK\n" +
"NN GP\n" +
"AO BT\n" +
"AO UE\n" +
"UQ IL\n" +
"QD UQ\n" +
"FE UY\n" +
"UQ CH\n" +
"JF YU\n" +
"LZ ZA\n" +
"FE QN\n" +
"ZA GX\n" +
"YU QD\n" +
"NN ZA\n" +
"OP JF\n" +
"UY EB\n" +
"BT YU\n" +
"YU GP\n" +
"LZ BT\n" +
"UE IL\n" +
"BT DK\n" +
"FE LZ\n" +
"SC RL\n" +
"RL CH\n" +
"UE GX\n" +
"FE GX\n" +
"EB SK\n" +
"SK LZ\n" +
"UY PH\n" +
"ZA BI\n" +
"SC IL\n" +
"NN SC\n" +
"DK ZA\n" +
"GP OP\n" +
"DK NN\n" +
"22 218 4\n" +
"CK YE VN HH OS FK GQ QY TU KX WK NR WF MB SF PG CA AA WI WE VM ER\n" +
"ER KX\n" +
"CA SF\n" +
"MB NR\n" +
"VM OS\n" +
"VN CK\n" +
"VM YE\n" +
"WF PG\n" +
"WI MB\n" +
"AA ER\n" +
"CA YE\n" +
"WI WE\n" +
"AA CK\n" +
"CA WE\n" +
"WI VM\n" +
"YE VN\n" +
"WE WF\n" +
"YE OS\n" +
"GQ CK\n" +
"MB CA\n" +
"TU MB\n" +
"CK YE\n" +
"WF ER\n" +
"KX WI\n" +
"CA TU\n" +
"WE VN\n" +
"AA CA\n" +
"WF YE\n" +
"VM VN\n" +
"VM NR\n" +
"OS TU\n" +
"WI SF\n" +
"WK ER\n" +
"PG NR\n" +
"WE YE\n" +
"YE TU\n" +
"WI CK\n" +
"CK TU\n" +
"SF NR\n" +
"VM HH\n" +
"OS QY\n" +
"SF GQ\n" +
"OS GQ\n" +
"HH FK\n" +
"ER NR\n" +
"QY WK\n" +
"CA WI\n" +
"VN KX\n" +
"OS WF\n" +
"ER VN\n" +
"HH KX\n" +
"PG TU\n" +
"VN SF\n" +
"WF NR\n" +
"OS VN\n" +
"FK AA\n" +
"MB SF\n" +
"QY WF\n" +
"QY CA\n" +
"AA HH\n" +
"WK YE\n" +
"PG WK\n" +
"YE ER\n" +
"TU WF\n" +
"WF CA\n" +
"TU KX\n" +
"KX QY\n" +
"SF FK\n" +
"YE MB\n" +
"GQ QY\n" +
"WK VM\n" +
"KX YE\n" +
"HH NR\n" +
"GQ VN\n" +
"CK SF\n" +
"NR CK\n" +
"PG ER\n" +
"CA KX\n" +
"HH CK\n" +
"KX FK\n" +
"VM WE\n" +
"TU NR\n" +
"WE CK\n" +
"CA FK\n" +
"VN NR\n" +
"WI PG\n" +
"FK WF\n" +
"WI OS\n" +
"ER HH\n" +
"TU SF\n" +
"FK VN\n" +
"AA WK\n" +
"HH WK\n" +
"PG GQ\n" +
"QY NR\n" +
"QY VN\n" +
"SF PG\n" +
"HH VN\n" +
"WK WI\n" +
"GQ WK\n" +
"YE WI\n" +
"TU AA\n" +
"PG YE\n" +
"VN WK\n" +
"SF YE\n" +
"MB WF\n" +
"GQ WI\n" +
"WK OS\n" +
"VM PG\n" +
"TU HH\n" +
"VM AA\n" +
"CK VM\n" +
"VM TU\n" +
"AA YE\n" +
"MB OS\n" +
"CA ER\n" +
"WK FK\n" +
"PG KX\n" +
"WK CA\n" +
"NR AA\n" +
"AA GQ\n" +
"QY WE\n" +
"AA OS\n" +
"HH WF\n" +
"CA PG\n" +
"MB GQ\n" +
"ER OS\n" +
"ER FK\n" +
"YE GQ\n" +
"FK GQ\n" +
"SF WF\n" +
"MB WK\n" +
"WE FK\n" +
"KX GQ\n" +
"WE PG\n" +
"CA CK\n" +
"WI NR\n" +
"TU VN\n" +
"CK OS\n" +
"AA WI\n" +
"WI TU\n" +
"WK KX\n" +
"VM FK\n" +
"AA QY\n" +
"FK WI\n" +
"QY TU\n" +
"YE NR\n" +
"OS PG\n" +
"WF CK\n" +
"WK NR\n" +
"VN CA\n" +
"FK TU\n" +
"SF AA\n" +
"WF GQ\n" +
"FK OS\n" +
"HH SF\n" +
"ER VM\n" +
"KX NR\n" +
"WF WI\n" +
"WK SF\n" +
"GQ NR\n" +
"HH WI\n" +
"MB QY\n" +
"QY HH\n" +
"SF ER\n" +
"MB CK\n" +
"MB VM\n" +
"VM GQ\n" +
"TU WK\n" +
"KX MB\n" +
"FK PG\n" +
"NR WE\n" +
"CK QY\n" +
"PG VN\n" +
"CK KX\n" +
"PG MB\n" +
"TU WE\n" +
"PG HH\n" +
"CK PG\n" +
"KX VM\n" +
"CK WK\n" +
"CA OS\n" +
"GQ CA\n" +
"FK YE\n" +
"WI VN\n" +
"QY WI\n" +
"WE MB\n" +
"WF AA\n" +
"ER WI\n" +
"WF VM\n" +
"CA NR\n" +
"WK WE\n" +
"QY VM\n" +
"HH MB\n" +
"KX WF\n" +
"QY PG\n" +
"CA HH\n" +
"GQ HH\n" +
"HH OS\n" +
"GQ ER\n" +
"HH YE\n" +
"ER WE\n" +
"OS SF\n" +
"NR FK\n" +
"CA VM\n" +
"MB VN\n" +
"OS WE\n" +
"AA MB\n" +
"WE SF\n" +
"GQ TU\n" +
"WE GQ\n" +
"KX AA\n" +
"CK ER\n" +
"CK FK\n" +
"FK QY\n" +
"QY ER\n" +
"MB FK\n" +
"SF KX\n" +
"WE AA\n" +
"8 FK TU\n" +
"5 KX WK\n" +
"15 WF FK\n" +
"7 KX VM\n";
Scanner s = new Scanner(data2);
int nTests = s.nextInt();
System.out.println("SHIPPING ROUTES OUTPUT");
for(int i = 0; i < nTests; i++){
System.out.printf("\nDATA SET %d\n\n", i + 1);
int nWarehouses = s.nextInt();
int nLegs = s.nextInt();
int nRequests = s.nextInt();
Map<String, Integer> map = new HashMap<>();
Map<Integer, List<Integer>> graph = new HashMap<>();
for(int j = 0; j < nWarehouses; j++){
map.put(s.next(), j);
graph.put(j, new ArrayList<>());
}
for(int j = 0; j < nLegs; j++){
String w1 = s.next();
String w2 = s.next();
graph.get(map.get(w1)).add(map.get(w2));
graph.get(map.get(w2)).add(map.get(w1));
}
for(int j = 0; j < nRequests; j++){
int shipmentSize = s.nextInt();
String source = s.next();
String destination = s.next();
bfs(graph, map.get(source));
int minCost = shipmentSize * dist[map.get(destination)] * 100;
if(minCost < 0) System.out.println("NO SHIPMENT POSSIBLE");
else System.out.printf("$%d\n", minCost);
}
}
System.out.println("\nEND OF OUTPUT");
}
static void getPath(int source, int target, List<Integer> path){
if(source == target){
path.add(source);
return;
}
getPath(source, parent[target], path);
path.add(target);
}
static final int INF = -1;
static int[] dist;
static int[] parent;
static void bfs(Map<Integer, List<Integer>> graph, int source){
dist = new int[graph.keySet().size()];
for(int i = 0; i < dist.length; i++){
dist[i] = INF;
}
dist[source] = 0;
parent = new int[graph.keySet().size()];
Queue<Integer> q = new LinkedList<>();
q.add(source);
while(!q.isEmpty()){
int u = q.remove();
for(int neighbor : graph.get(u)){
if(dist[neighbor] == INF){
dist[neighbor] = dist[u] + 1;
parent[neighbor] = u;
q.add(neighbor);
}
}
}
}
}
|
olegkotovich/jenkins-build-monitor-plugin
|
src/test/java/com/smartcodeltd/jenkinsci/plugins/buildmonitor_acceptance/utils/Typograph.java
|
package com.smartcodeltd.jenkinsci.plugins.buildmonitor_acceptance.utils;
/**
* @author <NAME>
*/
public class Typograph {
public static String deCamelCase(String camelCasedString) {
return camelCasedString.replaceAll(
String.format("%s|%s|%s",
"(?<=[A-Z])(?=[A-Z][a-z])",
"(?<=[^A-Z])(?=[A-Z])",
"(?<=[A-Za-z])(?=[^A-Za-z])"
),
" "
);
}
public static String de_snake_case(String snake_cased_string) {
return snake_cased_string.replaceAll("_", " ");
}
}
|
echopen/PRJ-medtec_androidapp
|
android-app/app/src/main/java/com/echopen/asso/echopen/probe_communication/commands/RequestForTestPatternCommand.java
|
package com.echopen.asso.echopen.probe_communication.commands;
public class RequestForTestPatternCommand extends Request {
private PatternType mPatternType;
private int mFrameInterval; //in micro seconds
private int mLinePerFrame;
private int mLineInterval; //in micro seconds
private int mSamplesPerLine;
private int mBitsPerSample;
public RequestForTestPatternCommand(PatternType iPatternType, int iFrameInterval, int iLinePerFrame, int iLineInterval, int iSamplesPerLine, int iBitsPerSample){
mCommand = CommandType.REQUEST_FOR_TEST_PATTERN;
mSize = 8;
mPatternType = iPatternType;
mFrameInterval = iFrameInterval;
mLinePerFrame = iLinePerFrame;
mLineInterval = iLineInterval;
mSamplesPerLine = iSamplesPerLine;
mBitsPerSample = iBitsPerSample;
}
public PatternType getPatternType(){
return mPatternType;
}
public int getFrameInterval(){
return mFrameInterval;
}
public int getLinePerFrame(){
return mLinePerFrame;
}
public int getLineInterval(){
return mLineInterval;
}
public int getSamplesPerLine(){
return mSamplesPerLine;
}
public int getBitsPerSample(){
return mBitsPerSample;
}
}
|
gnarrf95/libjayc
|
src/jproc/jproc_signal.c
|
<reponame>gnarrf95/libjayc
/**
* @file jproc_signal.c
* @author <NAME> (https://github.com/gnarrf95)
*
* @brief Implements signal functionality for jproc.
*
* @date 2020-10-01
* @copyright Copyright (c) 2020 by <NAME>
*
*/
#include <jayc/jproc.h>
#include <stdlib.h>
#include <stdbool.h>
#include <signal.h>
typedef struct __jproc_signal_handlerStruct
{
jproc_signal_handler_t handler;
void *ctx;
} jproc_signal_handlerStruct_t;
static jproc_signal_handlerStruct_t jproc_signal_handlers[32] = { { NULL, NULL } };
static void jproc_signalHandler(int signum);
//------------------------------------------------------------------------------
//
int jproc_signal_setHandler(int signal_number, jproc_signal_handler_t handler, void *ctx)
{
if(signal_number >= 32 || signal_number < 0)
{
return false;
}
jproc_signal_handlers[signal_number].handler = handler;
jproc_signal_handlers[signal_number].ctx = ctx;
signal(signal_number, jproc_signalHandler);
return true;
}
//------------------------------------------------------------------------------
//
void jproc_signalHandler(int signum)
{
if(signum >= 32 || signum < 0)
{
return;
}
if(jproc_signal_handlers[signum].handler)
{
jproc_signal_handlers[signum].handler(signum, jproc_signal_handlers[signum].ctx);
}
}
|
wecatch/app-turbo
|
setup.py
|
from setuptools import setup, find_packages
import sys
import os
version = __import__('turbo').version
install_requires = [
]
for k in ['pymongo', 'requests', 'redis', 'docopt', 'jinja2']:
try:
_m = __import__(k)
except ImportError:
if k == 'pymongo':
k = 'pymongo>=3.2'
install_requires.append(k)
kwargs = {}
readme_path = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(readme_path, 'README.rst')) as f:
kwargs['long_description'] = f.read()
if sys.version_info < (2, 7):
install_requires.append('unittest2')
install_requires.append('tornado<=4.3.0')
install_requires.append('futures')
elif sys.version_info > (2, 7) and sys.version_info < (2, 7, 9):
install_requires.append('tornado<5.0.0')
elif sys.version_info >= (2, 7, 9) and sys.version_info < (3, 5, 2):
install_requires.append('tornado<6.0.0')
elif sys.version_info >= (3, 5, 2):
install_requires.append('tornado>=6.0.0')
setup(
name="turbo",
version=version,
author="Wecatch.me",
author_email="<EMAIL>",
url="http://github.com/wecatch/app-turbo",
license="http://www.apache.org/licenses/LICENSE-2.0",
description="turbo is a web framework for fast web development based in tornado, mongodb, redis",
keywords='web framework tornado mongodb',
packages=find_packages(),
install_requires=install_requires,
scripts=['turbo/bin/turbo-admin'],
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
**kwargs
)
|
akjava/akjava_gwtlib
|
src/com/akjava/gwt/html5/client/media/OscillatorNode.java
|
<filename>src/com/akjava/gwt/html5/client/media/OscillatorNode.java
package com.akjava.gwt.html5.client.media;
import com.google.gwt.core.client.JavaScriptObject;
public class OscillatorNode extends JavaScriptObject{
protected OscillatorNode(){}
public final native String getType()/*-{
return this.type;
}-*/;
public final native void setType(String param)/*-{
this.type=param;
}-*/;
public final native Frequency getFrequency()/*-{
return this.frequency;
}-*/;
public final native void start(double start)/*-{
this.start(start);
}-*/;
public final native void stop()/*-{
this.stop();
}-*/;
}
|
the-h-team/ClansPro
|
ClansPro/src/main/java/com/github/sanctum/clans/construct/impl/SimpleEntry.java
|
package com.github.sanctum.clans.construct.impl;
import java.util.Map;
public class SimpleEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
public SimpleEntry(K k, V v) {
this.key = k;
this.value = v;
}
@Override
public K getKey() {
return this.key;
}
@Override
public V getValue() {
return this.value;
}
@Override
public V setValue(V value) {
this.value = value;
return value;
}
}
|
LarsImNetz/microservice-sentences
|
server/src/test/java/org/lla_private/rest/satz/TestNothing.java
|
<reponame>LarsImNetz/microservice-sentences
package org.lla_private.rest.satz;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.lla_private.rest.json.mapper.IObjectMapperService;
import org.lla_private.rest.satz.Nothing;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TestNothing {
@Mock
private IObjectMapperService objectMapperService;
private Nothing nothingSUT;
@Before
public void setUp() {
nothingSUT = new Nothing(objectMapperService);
}
@Test
public void testSatzDoNothing() {
// Weil wir am ende der Funktion den objectMapperService verwenden, müssen wir diesen Mocken
Mockito.when(objectMapperService.createJsonString(Mockito.any())).thenReturn("a json string");
String satz = "Dies ist ein Satz";
String response = nothingSUT.satzDoNothing(satz);
Assert.assertNotNull(response);
Assert.assertEquals("a json string", response);
}
}
|
Brikwerk/learn2learn
|
learn2learn/optim/transforms/__init__.py
|
<gh_stars>1000+
#!/usr/bin/env python3
"""
Optimization transforms are special modules that take gradients as inputs
and output model updates.
Transforms are usually parameterized, and those parameters can be learned by
gradient descent, allow you to learn optimization functions from data.
"""
from .module_transform import ModuleTransform, ReshapedTransform
from .kronecker_transform import KroneckerTransform
from .transform_dictionary import TransformDictionary
from .metacurvature_transform import MetaCurvatureTransform
|
dr-chase-g3ka1/Progtech_Korny_beadando
|
src/main/java/model/item/weapons/gunpowder/AbstractWeaponModSocket.java
|
<filename>src/main/java/model/item/weapons/gunpowder/AbstractWeaponModSocket.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 model.item.weapons.gunpowder;
/**
*
* @author Dr.Chase
*/
public abstract class AbstractWeaponModSocket {
WeaponModTypeEnum typeOfMod;
private boolean isThereAMod;
GunTypeEnum gunType;
}
|
jaouahbi/VampPlugins
|
marsyas-vamp/marsyas/src/marsyas/marsystems/MidiFileSynthSource.cpp
|
/*
** Copyright (C) 1998-2010 <NAME> <<EMAIL>>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "../common_source.h"
#include "MidiFileSynthSource.h"
using std::ostringstream;
using namespace Marsyas;
MidiFileSynthSource::MidiFileSynthSource(mrs_string name):MarSystem("MidiFileSynthSource",name)
{
addControls();
nChannels_ = 0;
size_ = 0;
}
MidiFileSynthSource::~MidiFileSynthSource()
{
}
MarSystem*
MidiFileSynthSource::clone() const
{
return new MidiFileSynthSource(*this);
}
MidiFileSynthSource::MidiFileSynthSource(const MidiFileSynthSource& a):MarSystem(a)
{
filename_ = a.filename_;
nChannels_ = a.nChannels_;
size_ = a.size_;
ctrl_filename_ = getctrl("mrs_string/filename");
ctrl_numActiveNotes_ = getctrl("mrs_natural/numActiveNotes");
ctrl_nChannels_ = getctrl("mrs_natural/nChannels");
ctrl_pos_ = getctrl("mrs_natural/pos");
ctrl_hasData_ = getctrl("mrs_bool/hasData");
ctrl_start_ = getctrl("mrs_real/start");
ctrl_end_ = getctrl("mrs_real/end");
ctrl_winSize_ = getctrl("mrs_natural/winSize");
ctrl_sigNewTextWin_ = getctrl("mrs_bool/sigNewTextWin");
ctrl_newTextWin_ = getctrl("mrs_bool/newTextWin");
ctrl_size_ = getctrl("mrs_natural/size");
}
void
MidiFileSynthSource::addControls()
{
addctrl("mrs_string/filename", "", ctrl_filename_);
setctrlState("mrs_string/filename", true);
addctrl("mrs_natural/numActiveNotes", 0, ctrl_numActiveNotes_);
addctrl("mrs_natural/nChannels", 0, ctrl_nChannels_);
addctrl("mrs_natural/pos", 0, ctrl_pos_);
addctrl("mrs_bool/hasData", true, ctrl_hasData_);
addctrl("mrs_real/start", 0.0, ctrl_start_);
addctrl("mrs_real/end", 0.0, ctrl_end_);
addctrl("mrs_natural/winSize", MRS_DEFAULT_SLICE_NSAMPLES, ctrl_winSize_);
ctrl_winSize_->setState(true);
addctrl("mrs_bool/sigNewTextWin", true, ctrl_sigNewTextWin_);
ctrl_sigNewTextWin_->setState(true);
addctrl("mrs_bool/newTextWin", false, ctrl_newTextWin_);
ctrl_newTextWin_->setState(true);
addctrl("mrs_natural/size", 0, ctrl_size_);
}
void
MidiFileSynthSource::myUpdate(MarControlPtr sender)
{
(void) sender; //suppress warning of unused parameter(s)
MRSDIAG("MidiFileSynthSource::myUpdate");
MATLAB_PUT(ctrl_winSize_->to<mrs_natural>(), "winSize");
MATLAB_PUT(inSamples_, "hopSize");
mrs_bool sigNewTextWin = ctrl_sigNewTextWin_->to<mrs_bool>();
MATLAB_PUT((mrs_natural)sigNewTextWin, "sigNewTextWin");
//in case texture windows are set from the outside...
if(!sigNewTextWin)
{
if(ctrl_newTextWin_->isTrue())
{
//get number of playing notes in texture window
mrs_natural numActiveNotes;
MATLAB_GET("numActiveNotes", numActiveNotes);
ctrl_numActiveNotes_->setValue(numActiveNotes);
MATLAB_EVAL("textWinStart = textWinEnd+1;textWinEnd = endPos2;");
//reset MATLAB
//MATLAB_EVAL("numActiveNotes = 0;");
//reset control
ctrl_newTextWin_->setValue(false, NOUPDATE);
}
}
if(filename_ != ctrl_filename_->to<mrs_string>())
{
filename_ = ctrl_filename_->to<mrs_string>();
MATLAB_PUT(filename_, "filename");
MATLAB_PUT(israte_, "fs");
MATLAB_PUT(ctrl_start_->to<mrs_real>(), "startSeg");
MATLAB_PUT(ctrl_end_->to<mrs_real>(), "endSeg");
//Synthesize MIDI file to audio
MATLAB_EVAL("synthetizeMIDI;");
MATLAB_GET("numChannels", nChannels_);
ctrl_nChannels_->setValue(nChannels_, NOUPDATE);
MATLAB_GET("audioLength", size_); //in samples
ctrl_size_->setValue(size_, NOUPDATE);
ctrl_pos_->setValue(0, NOUPDATE);
if(size_>0)
ctrl_hasData_->setValue(true, NOUPDATE);
else
ctrl_hasData_->setValue(false, NOUPDATE);
}
ctrl_onSamples_->setValue(ctrl_inSamples_, NOUPDATE);
ctrl_onObservations_->setValue(1, NOUPDATE);
ctrl_osrate_->setValue(ctrl_israte_, NOUPDATE);
ctrl_onObsNames_->setValue("MIDIaudio", NOUPDATE);
}
void
MidiFileSynthSource::myProcess(realvec& in, realvec &out)
{
(void) in;
if(size_ == 0)
return;
mrs_natural pos = ctrl_pos_->to<mrs_natural>();
//detect end of file
if(pos > size_)
{
out.setval(0.0);//fill with silence
if(!ctrl_hasData_->isTrue())
return;
ctrl_hasData_->setValue(false);
//flush last texture window
if(ctrl_sigNewTextWin_->isTrue())
{
mrs_natural numActiveNotes;
MATLAB_GET("numActiveNotes", numActiveNotes);
ctrl_numActiveNotes_->setValue(numActiveNotes);
ctrl_newTextWin_->setValue(true, NOUPDATE);
}
return;
}
MATLAB_PUT(pos+1, "pos");//MATLAB uses indexes in the range [1,...]
MATLAB_EVAL("computeAudioFrame;");
MATLAB_GET("audioFrame", out);
ctrl_pos_->setValue(pos+onSamples_);
//check if this audio frame is the last one in the current texture window:
//if it is, then signal a new texture window
if(ctrl_sigNewTextWin_->isTrue())
{
mrs_natural newTextWin = 0;
MATLAB_GET("newTextWin", newTextWin);
if(newTextWin!=0)//if true...
{
mrs_natural numActiveNotes;
MATLAB_GET("numActiveNotes", numActiveNotes);
ctrl_numActiveNotes_->setValue(numActiveNotes);
//MATLAB_EVAL("numActiveNotes = 0;"); //reset
}
ctrl_newTextWin_->setValue(newTextWin!=0, NOUPDATE);
}
}
|
mmore500/dishtiny
|
include/dish2/introspection/get_num_running_log_live_cardinal_updates.hpp
|
#pragma once
#ifndef DISH2_INTROSPECTION_GET_NUM_RUNNING_LOG_LIVE_CARDINAL_UPDATES_HPP_INCLUDE
#define DISH2_INTROSPECTION_GET_NUM_RUNNING_LOG_LIVE_CARDINAL_UPDATES_HPP_INCLUDE
#include "../config/running_log_duration_in_updates.hpp"
#include "count_live_cardinals.hpp"
#include "get_num_running_log_updates.hpp"
namespace dish2 {
template< typename Spec >
size_t get_num_running_log_live_cardinal_updates(
const dish2::ThreadWorld<Spec>& world
) {
const size_t num_log_updates = dish2::get_num_running_log_updates<Spec>( world );
const size_t num_live_cardinal_updates
= num_log_updates * dish2::count_live_cardinals<Spec>( world );
return num_live_cardinal_updates;
}
} // namespace dish2
#endif // #ifndef DISH2_INTROSPECTION_GET_NUM_RUNNING_LOG_LIVE_CARDINAL_UPDATES_HPP_INCLUDE
|
rwatson/chromium-capsicum
|
chrome/browser/notifications/notification.h
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_H_
#define CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_H_
#include <string>
#include "base/basictypes.h"
#include "chrome/browser/notifications/notification_object_proxy.h"
#include "googleurl/src/gurl.h"
// Representation of an notification to be shown to the user. All
// notifications at this level are HTML, although they may be
// data: URLs representing simple text+icon notifications.
class Notification {
public:
Notification(const GURL& origin_url, const GURL& content_url,
const std::wstring& display_source,
NotificationObjectProxy* proxy)
: origin_url_(origin_url),
content_url_(content_url),
display_source_(display_source),
proxy_(proxy) {
}
Notification(const Notification& notification)
: origin_url_(notification.origin_url()),
content_url_(notification.content_url()),
display_source_(notification.display_source()),
proxy_(notification.proxy()) {
}
// The URL (may be data:) containing the contents for the notification.
const GURL& content_url() const { return content_url_; }
// The origin URL of the script which requested the notification.
const GURL& origin_url() const { return origin_url_; }
// A display string for the source of the notification.
const std::wstring& display_source() const { return display_source_; }
void Display() const { proxy()->Display(); }
void Error() const { proxy()->Error(); }
void Close(bool by_user) const { proxy()->Close(by_user); }
bool IsSame(const Notification& other) const {
return (*proxy_).IsSame(*(other.proxy()));
}
private:
NotificationObjectProxy* proxy() const { return proxy_.get(); }
// The Origin of the page/worker which created this notification.
GURL origin_url_;
// The URL of the HTML content of the toast (may be a data: URL for simple
// string-based notifications).
GURL content_url_;
// The display string for the source of the notification. Could be
// the same as origin_url_, or the name of an extension.
std::wstring display_source_;
// A proxy object that allows access back to the JavaScript object that
// represents the notification, for firing events.
scoped_refptr<NotificationObjectProxy> proxy_;
// Disallow assign. Copy constructor written above.
void operator=(const Notification&);
};
#endif // CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_H_
|
nanusefue/CAP2-1
|
cap2/pipeline/databases/kraken2_db.py
|
<filename>cap2/pipeline/databases/kraken2_db.py
import luigi
from os.path import join, abspath, dirname
from glob import glob
import subprocess
from ..config import PipelineConfig
from ..utils.conda import CondaPackage
from ..utils.cap_task import CapDbTask
DB_DATE = '2020-06-01'
'cap2/databases/2020-06-08/taxa_kraken2/db_download_flag',
class Kraken2DBDataDown(CapDbTask):
config_filename = luigi.Parameter()
cores = luigi.IntParameter(default=1)
MODULE_VERSION = 'v0.1.0'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pkg = CondaPackage(
package="kraken2",
executable="kraken2",
channel="bioconda",
env="CAP_v2_kraken2",
config_filename=self.config_filename,
)
self.config = PipelineConfig(self.config_filename)
self.libraries = [
'archaea', 'bacteria', 'plasmid', 'viral', 'fungi', 'protozoa', 'human'
]
self.kraken_db_dir = 'taxa_kraken2'
self.download_libs = True
def tool_version(self):
return self.run_cmd(f'{self.pkg.bin} --version').stderr.decode('utf-8')
def requires(self):
return [self.pkg]
@classmethod
def _module_name(cls):
return 'kraken2_taxa_db_down'
@classmethod
def dependencies(cls):
return ['kraken2', DB_DATE]
@property
def kraken2_db(self):
return join(self.config.db_dir, self.kraken_db_dir)
def output(self):
download_flag = luigi.LocalTarget(join(self.kraken2_db, 'db_download_flag'))
download_flag.makedirs()
return {'flag': download_flag}
def run(self):
if self.config.db_mode == PipelineConfig.DB_MODE_BUILD:
if self.download_libs:
self.download_kraken2_db()
open(self.output()['flag'].path, 'w').close()
def download_kraken2_db(self):
cmd = f'{self.pkg.bin}-build --use-ftp --download-taxonomy --db {self.kraken2_db}'
self.run_cmd(cmd)
for library in self.libraries:
cmd = (
f'PATH=$PATH:{dirname(abspath(self.pkg.bin))} '
f'{self.pkg.bin}-build '
f'--use-ftp '
f'--download-library {library} '
f'--db {self.kraken2_db}'
)
self.run_cmd(cmd)
class Kraken2DB(CapDbTask):
config_filename = luigi.Parameter()
cores = luigi.IntParameter(default=1)
MODULE_VERSION = 'v0.1.0'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pkg = CondaPackage(
package="kraken2",
executable="kraken2",
channel="bioconda",
env="CAP_v2_kraken2",
config_filename=self.config_filename,
)
self.download_task = Kraken2DBDataDown(
config_filename=self.config_filename,
cores=self.cores,
)
self.config = PipelineConfig(self.config_filename)
self.db_size = 120 * (1000 ** 3) # 120 GB
def requires(self):
return self.pkg, self.download_task
@classmethod
def _module_name(cls):
return 'kraken2_taxa_db'
@classmethod
def dependencies(cls):
return ['kraken2', DB_DATE, Kraken2DBDataDown]
@property
def kraken2_db(self):
return self.download_task.kraken2_db
def output(self):
db_taxa = luigi.LocalTarget(join(self.kraken2_db, 'hash.k2d'))
db_taxa.makedirs()
return {'kraken2_db_taxa': db_taxa}
def run(self):
if self.config.db_mode == PipelineConfig.DB_MODE_BUILD:
self.build_kraken2_db()
else:
self.download_kraken2_db_from_s3()
def build_kraken2_db(self):
cmd = (
f'{self.pkg.bin}-build '
'--build '
f'--max-db-size {self.db_size} '
f'--db {self.kraken2_db}'
)
self.run_cmd(cmd)
def download_kraken2_db_from_s3(self):
paths = [
'cap2/databases/2020-06-08/taxa_kraken2/hash.k2d',
'cap2/databases/2020-06-08/taxa_kraken2/opts.k2d',
'cap2/databases/2020-06-08/taxa_kraken2/seqid2taxid.map',
'cap2/databases/2020-06-08/taxa_kraken2/taxo.k2d',
'cap2/databases/2020-06-08/taxa_kraken2/unmapped.txt',
]
for path in paths:
cmd = (
'wget '
f'--directory-prefix={dirname(self.output()["kraken2_db_taxa"].path)} '
f'https://s3.wasabisys.com/metasub-microbiome/{path} '
)
self.run_cmd(cmd)
class BrakenKraken2DB(CapDbTask):
config_filename = luigi.Parameter()
cores = luigi.IntParameter(default=1)
MODULE_VERSION = 'v0.1.0'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pkg = CondaPackage(
package="bracken==2.6.0",
executable="bracken",
channel="bioconda",
env="CAP_v2_bracken_kraken2",
config_filename=self.config_filename,
)
self.kraken2_db_task = Kraken2DB(
config_filename=self.config_filename,
cores=self.cores,
)
self.config = PipelineConfig(self.config_filename)
self.read_lengths = [75, 100, 125, 150, 175, 200, 225, 250]
def requires(self):
return self.pkg, self.kraken2_db_task
@classmethod
def _module_name(cls):
return 'bracken_kraken2_taxa_db'
@classmethod
def dependencies(cls):
return ['bracken', DB_DATE, Kraken2DB]
@property
def kraken2_db(self):
return self.kraken2_db_task.kraken2_db
def output(self):
out = {}
for rlen in self.read_lengths:
out[f'bracken_kraken2_db_{rlen}'] = luigi.LocalTarget(join(
self.kraken2_db, f'database{rlen}mers.kmer_distrib'
))
return out
def get_index(self, length):
for index_len in sorted(self.read_lengths, reverse=True):
if length > index_len:
break
# index_len is now the largest index shorter than length or the smallest
return index_len, self.output()[f'bracken_kraken2_db_{index_len}']
def run(self):
if self.config.db_mode == PipelineConfig.DB_MODE_BUILD:
for rlen in self.read_lengths:
self.build_bracken_db(rlen)
else:
self.download_bracken_db_from_s3()
def build_bracken_db(self, read_len):
cmd = (
f'PATH=${{PATH}}:{dirname(abspath(self.pkg.bin))} '
f'{self.pkg.bin}-build '
f'-d {self.kraken2_db} '
f'-t {self.cores} '
f'-k 35 '
f'-l {read_len} '
f'-x {dirname(abspath(self.kraken2_db_task.pkg.bin))}/ '
'; '
f'test -e {self.kraken2_db}/database{read_len}mers.kmer_distrib'
)
self.run_cmd(cmd)
def download_bracken_db_from_s3(self):
paths = [
'cap2/databases/2020-06-08/taxa_kraken2/database100mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database100mers.kraken',
'cap2/databases/2020-06-08/taxa_kraken2/database125mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database125mers.kraken',
'cap2/databases/2020-06-08/taxa_kraken2/database150mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database150mers.kraken',
'cap2/databases/2020-06-08/taxa_kraken2/database175mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database175mers.kraken',
'cap2/databases/2020-06-08/taxa_kraken2/database200mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database200mers.kraken',
'cap2/databases/2020-06-08/taxa_kraken2/database225mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database225mers.kraken',
'cap2/databases/2020-06-08/taxa_kraken2/database250mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database250mers.kraken',
'cap2/databases/2020-06-08/taxa_kraken2/database75mers.kmer_distrib',
'cap2/databases/2020-06-08/taxa_kraken2/database75mers.kraken',
]
for path in paths:
cmd = (
'wget '
f'--directory-prefix={dirname(self.output()["bracken_kraken2_db_150"].path)} '
f'https://s3.wasabisys.com/metasub-microbiome/{path} '
)
self.run_cmd(cmd)
|
NikolayIT/BelotGameEngine
|
etc/Other implementations/belote-android/src/belote/logic/play/strategy/NullPlayCardStrategy.java
|
/*
* Copyright (c) <NAME> 2008-2014. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the source code must retain
* the above copyright notice and the following disclaimer.
*
* This software is provided "AS IS," without a warranty of any kind.
*/
package belote.logic.play.strategy;
import belote.bean.Game;
import belote.bean.Player;
import belote.bean.pack.card.Card;
import belote.logic.play.strategy.automat.methods.NullPlayMethod;
import belote.logic.play.strategy.validators.NullValidator;
/**
* NullPlayCardStrategy class.
* @author <NAME>
*/
public class NullPlayCardStrategy extends BasePlayStrategy {
/**
* Constructor.
* @param game belote game instance.
*/
public NullPlayCardStrategy(final Game game) {
super(game, new NullValidator(game), new NullPlayMethod(game));
}
/**
* Returns next attack player.
* @param attack the trick attack card.
* @return next attack player.
*/
protected Player getNextAttackPlayer(final Card attack) {
return null;
}
}
|
windystrife/UnrealEngine_NVIDIAGameWork
|
Engine/Source/Developer/AutomationDriver/Private/Locators/SlateWidgetLocatorByDelegate.h
|
<gh_stars>1-10
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "LocateBy.h"
class IElementLocator;
class FSlateWidgetLocatorByDelegateFactory
{
public:
static TSharedRef<IElementLocator, ESPMode::ThreadSafe> Create(
const FLocateSlateWidgetElementDelegate& Delegate);
static TSharedRef<IElementLocator, ESPMode::ThreadSafe> Create(
const FLocateSlateWidgetPathElementDelegate& Delegate);
};
|
seakers/daphne-brain
|
AT/views.py
|
import json
import threading
import redis
from rest_framework.response import Response
from rest_framework.views import APIView
from AT.automated_at_routines.at_routine import anomaly_treatment_routine
from AT.automated_at_routines.hub_routine import hub_routine
from AT.simulator_thread.simulator_routine_by_false_eclss import simulate_by_dummy_eclss
from AT.simulator_thread.simulator_routine_by_real_eclss import handle_eclss_update
from AT.neo4j_queries.query_functions import diagnose_symptoms_by_intersection_with_anomaly, \
retrieve_figures_from_procedure, retrieve_references_from_procedure, retrieve_reference_links_from_procedure
from AT.neo4j_queries.query_functions import retrieve_all_anomalies
from AT.neo4j_queries.query_functions import retrieve_procedures_fTitle_from_anomaly
from AT.neo4j_queries.query_functions import retrieve_fancy_steps_from_procedure
from AT.neo4j_queries.query_functions import retrieve_objective_from_procedure
from AT.neo4j_queries.query_functions import retrieve_equipment_from_procedure
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from auth_API.helpers import get_or_create_user_information
# THREADS + QUEUES
import AT.global_objects as global_obj
def check_threads_status():
hub_is_alive = global_obj.hub_thread.is_alive()
sEclss_is_alive = global_obj.sEclss_thread.is_alive()
sim_is_alive_one = global_obj.simulator_threads[0].is_alive()
sim_is_alive_two = global_obj.simulator_threads[1].is_alive()
sim_is_alive_three = global_obj.simulator_threads[2].is_alive()
sim_is_alive_four = global_obj.simulator_threads[3].is_alive()
sEclss_at_is_alive = global_obj.sEclss_at_thread.is_alive()
sim_at_is_alive_one = global_obj.simulator_at_threads[0].is_alive()
sim_at_is_alive_two = global_obj.simulator_at_threads[1].is_alive()
sim_at_is_alive_three = global_obj.simulator_at_threads[2].is_alive()
sim_at_is_alive_four = global_obj.simulator_at_threads[3].is_alive()
# Check if all the treads are in a healthy status. Display a message according to the result.
if hub_is_alive and sEclss_is_alive and sim_is_alive_one and sim_is_alive_two and sim_is_alive_three \
and sim_is_alive_four and sEclss_at_is_alive and sim_at_is_alive_one and sim_at_is_alive_two \
and sim_at_is_alive_three and sim_at_is_alive_four:
print('**********\nAll AT threads started successfully.\n**********')
else:
print('**********')
if not hub_is_alive:
print('Hub thread start failure.')
if not sEclss_is_alive:
print('sEclss thread start failure.')
if not sim_is_alive_one:
print('Simulator thread 1 start failure.')
if not sim_is_alive_two:
print('Simulator thread 2 start failure.')
if not sim_is_alive_three:
print('Simulator thread 3 start failure.')
if not sim_is_alive_four:
print('Simulator thread 4 start failure.')
if not sEclss_at_is_alive:
print('Anomaly treatment thread for sEclss start failure.')
if not sim_at_is_alive_one:
print('Anomaly treatment thread 1 for the simulator thread start failure.')
if not sim_at_is_alive_two:
print('Anomaly treatment thread 2 for the simulator thread start failure.')
if not sim_at_is_alive_three:
print('Anomaly treatment thread 3 for the simulator thread start failure.')
if not sim_at_is_alive_four:
print('Anomaly treatment thread 4 for the simulator thread start failure.')
print('**********')
return
def convert_threshold_tag_to_neo4j_relationship(threshold_tag):
relationship = ''
if threshold_tag == 'LowerWarningLimit' or threshold_tag == 'LowerCautionLimit':
relationship = 'Exceeds_LowerCautionLimit'
elif threshold_tag == 'UpperWarningLimit' or threshold_tag == 'UpperCautionLimit':
relationship = 'Exceeds_UpperCautionLimit'
else:
print('Invalid threshold tag')
raise
return relationship
class SeclssFeed(APIView):
def post(self, request):
if 'habitatStatus' in request.data:
parameters_data = request.data['habitatStatus']
parsed_sensor_data = json.loads(parameters_data)
if global_obj.sEclss_thread is not None \
and global_obj.sEclss_thread.is_alive() \
and global_obj.sEclss_thread.name == "Real Telemetry Thread":
global_obj.server_to_sEclss_queue.put(
{'type': 'sensor_data', 'content': parsed_sensor_data['Parameters']})
return Response(parsed_sensor_data)
else:
print(request.data)
print(request.headers)
print('ERROR retrieving the sensor data from the Lab simulator')
return Response({
"status": "error",
"message": "ERROR retrieving the sensor data from the Lab simulator"
})
class HeraFeed(APIView):
def post(self, request):
# habitatStatus
if 'habitatStatus' in request.data:
parameters_data = request.data['habitatStatus']
parsed_sensor_data = json.loads(parameters_data)
if global_obj.hera_thread is not None \
and global_obj.hera_thread.is_alive() \
and global_obj.hera_thread.name == "Hera Telemetry Thread":
global_obj.server_to_hera_queue.put(
{'type': 'sensor_data', 'content': parsed_sensor_data['Parameters']})
return Response(parsed_sensor_data)
else:
print(request.data)
print(request.headers)
print('ERROR retrieving the sensor data from the Hera simulator')
return Response({
"status": "error",
"message": "ERROR retrieving the sensor data from the Hera simulator"
})
class RequestDiagnosis(APIView):
def post(self, request):
# Retrieve the symptoms list from the request
symptoms_list = json.loads(request.data['symptomsList'])
# Parse the symptoms list to meet the neo4j query function requirements
parsed_symptoms_list = []
for item in symptoms_list:
threshold_tag = item['threshold_tag']
relationship = convert_threshold_tag_to_neo4j_relationship(threshold_tag)
symptom = {'measurement': item['measurement'],
'display_name': item['display_name'],
'relationship': relationship}
parsed_symptoms_list.append(symptom)
# Query the neo4j graph (do not delete first line until second one is tested)
# diagnosis_list = diagnose_symptoms_by_subset_of_anomaly(parsed_symptoms_list)
diagnosis_list = diagnose_symptoms_by_intersection_with_anomaly(parsed_symptoms_list)
# Build the diagnosis report and send it to the frontend
diagnosis_report = {'symptoms_list': symptoms_list, 'diagnosis_list': diagnosis_list}
return Response(diagnosis_report)
class LoadAllAnomalies(APIView):
def post(self, request):
# Query the neo4j graph
anomaly_list = retrieve_all_anomalies()
return Response(anomaly_list)
class RetrieveProcedureFromAnomaly(APIView):
def post(self, request):
# Retrieve the anomaly name list from the request
anomaly_name = json.loads(request.data['anomaly_name'])
# Obtain all the procedures related to the anomaly
procedure_names = retrieve_procedures_fTitle_from_anomaly(anomaly_name)
return Response(procedure_names)
class RetrieveInfoFromProcedure(APIView):
def post(self, request):
# Retrieve the procedure name from the request
procedure_name = json.loads(request.data['procedure_name'])
# Query the neo4j to retrieve the procedure information
steps_list = retrieve_fancy_steps_from_procedure(procedure_name)
objective = retrieve_objective_from_procedure(procedure_name)
equipment = retrieve_equipment_from_procedure(procedure_name)
references = retrieve_references_from_procedure(procedure_name)
referenceLinks = retrieve_reference_links_from_procedure(procedure_name)
figures = retrieve_figures_from_procedure(procedure_name)
checkable_steps = 0
checkable_steps_list = []
for step in steps_list:
if step['depth'] > 0:
checkable_steps += 1
checkable_steps_list.append(step)
# Build the output dictionary
info = {
'procedureStepsList': steps_list,
'checkableSteps': checkable_steps,
'procedureObjective': objective,
'procedureEquipment': equipment,
'procedureReferences': references,
'procedureReferenceLinks': referenceLinks,
'procedureFigures': figures,
'checkableStepsList': checkable_steps_list,
}
return Response(info)
class TutorialStatus(APIView):
def post(self, request):
user_info = get_or_create_user_information(request.session, request.user, 'AT')
at_context = user_info.atcontext
seen_tutorial = at_context.seen_tutorial
return Response({'seen_tutorial': seen_tutorial})
class CompleteTutorial(APIView):
def post(self, request):
user_info = get_or_create_user_information(request.session, request.user, 'AT')
at_context = user_info.atcontext
seen_tutorial = at_context.seen_tutorial
seen_tutorial = not seen_tutorial
user_info.atcontext.seen_tutorial = seen_tutorial
user_info.atcontext.save()
return Response()
|
mattclegg/silverstripe-framework
|
thirdparty/tinymce/plugins/emotions/langs/it_dlg.js
|
tinyMCE.addI18n('it.emotions_dlg',{
title:"Inserisci faccina",
desc:"Faccina",
cool:"Fico",
cry:"Piango",
embarassed:"Imbarazzato",
foot_in_mouth:"Piede in bocca",
frown:"Triste",
innocent:"Santarellino",
kiss:"Bacio",
laughing:"Risatona",
money_mouth:"Bocca danarosa",
sealed:"Bocca sigillata",
smile:"Sorridente",
surprised:"Sorpreso",
tongue_out:"Linguaccia",
undecided:"Indeciso",
wink:"Occhiolino",
yell:"Arrabbiato"
});
|
pmwheatley/dfterm2
|
pointerpath.cc
|
#include "slot_dfglue.hpp"
#ifndef _WIN32
#error "Windows-only source file."
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <psapi.h>
#include <iostream>
#include "logger.hpp"
using namespace dfterm;
using namespace std;
using namespace trankesbel;
using namespace std;
PointerPath::PointerPath()
{
last_used_module = (HANDLE) 0;
num_modules = 0;
reported_error = false;
needs_search = true;
}
void PointerPath::reset()
{
address.clear();
module.clear();
search_address.clear();
needs_search = true;
}
void PointerPath::pushAddress(ptrdiff_t offset, string module)
{
address.push_back(offset);
this->module.push_back(module);
search_address.push_back(pair<SearchAddress, ptrdiff_t>(SearchAddress(), 0));
needs_search = true;
}
void PointerPath::pushSearchAddress(SearchAddress sa, string module, ptrdiff_t end_offset)
{
address.push_back(0);
this->module.push_back(module);
search_address.push_back(pair<SearchAddress, ptrdiff_t>(sa, end_offset));
needs_search = true;
}
void PointerPath::enumModules(HANDLE df_handle)
{
last_used_module = df_handle;
num_modules = 0;
EnumProcessModules(df_handle, modules, 1000 * sizeof(HMODULE), &num_modules);
num_modules /= sizeof(HMODULE);
module_addresses.clear();
int i1;
WCHAR namebuf[1000];
namebuf[999] = 0;
for (i1 = 0; i1 < num_modules; ++i1)
{
MODULEINFO mi;
int length = GetModuleBaseNameW(df_handle, modules[i1], namebuf, 999);
if (!GetModuleInformation(df_handle, modules[i1], &mi, sizeof(mi)))
continue;
if (length > 0)
module_addresses.insert(pair<string, pair<ptrdiff_t, ptrdiff_t> >(TO_UTF8(namebuf, length), pair<ptrdiff_t, ptrdiff_t>((ptrdiff_t) mi.lpBaseOfDll, (ptrdiff_t) mi.SizeOfImage)));
}
}
ptrdiff_t PointerPath::searchAddress(HANDLE df_handle, SearchAddress sa, ptrdiff_t baseaddress, ptrdiff_t size)
{
ptrdiff_t search_size = sa.getSize();
if (!search_size) return 0;
ptrdiff_t i1, i2;
char buf[4096];
for (i1 = baseaddress; i1 < baseaddress+size; i1 += 4096)
{
ReadProcessMemory(df_handle, (LPCVOID) i1, buf, 4096, NULL);
for (i2 = 0; i2 < 4096 - search_size + 1; i2 += 4)
{
if (sa.compareMemory(&buf[i2]))
return i1 + i2;
}
}
return 0;
}
ptrdiff_t PointerPath::getFinalAddress(HANDLE df_handle)
{
if (df_handle != last_used_module)
enumModules(df_handle);
ptrdiff_t fa = 0;
ptrdiff_t module_offset;
map<string, pair<ptrdiff_t, ptrdiff_t> >::iterator i2;
int i1, len = address.size();
for (i1 = 0; i1 < len; ++i1)
{
if (needs_search && search_address[i1].first.getSize() > 0 && module[i1].size() > 0)
{
if ( (i2 = module_addresses.find(module[i1])) != module_addresses.end())
{
address[i1] = searchAddress(df_handle, search_address[i1].first, i2->second.first, i2->second.second) + search_address[i1].second;
}
module_offset = 0;
module_addresses.erase(module[i1]);
}
else if ( (i2 = module_addresses.find(module[i1])) != module_addresses.end())
module_offset = i2->second.first;
else
module_offset = 0;
if (i1 == 0)
{
fa = address[i1] + module_offset;
continue;
}
ptrdiff_t fa_target = 0;
if (!ReadProcessMemory(df_handle, (LPCVOID) (fa + address[i1] + module_offset), &fa_target, sizeof(ptrdiff_t), NULL))
{
DWORD err = GetLastError();
/* If we have a wrong address or something, it's likely this error will repeat, repeat and repeat.
Therefore, we limit it to once per class instance. */
if (!reported_error)
{ LOG(Error, "Pointerpathing: ReadProcessMemory() failed in address " << (LPCVOID) (fa + address[i1] + module_offset) << " with GetLastError() == " << err << ". (This error will be reported only once for this PointerPath -class.)"); }
reported_error = true;
}
else if (!reported_path)
{ LOG(Note, "Pointerpathing: Read process memory from address " << (LPCVOID) (fa + address[i1] + module_offset) << ". Got address " << (LPCVOID) fa_target << ". (Path will be reported only once per PointerPath -class)"); }
fa = fa_target;
}
needs_search = false;
reported_path = true;
return fa;
}
|
1418014113git/syhz-fronted
|
src/api/caseCade.js
|
<reponame>1418014113git/syhz-fronted
import request from '@/utils/request'
const ModuleName = process.env.SYHZ_MODULE
export function getAJList(para) {
return request({
url: ModuleName + 'xscbfxaj',
method: 'get',
params: para
})
}
export function getCPList(para) {
return request({
url: ModuleName + 'xscbfxcp',
method: 'get',
params: para
})
}
export function getPSList(para) {
return request({
url: ModuleName + 'xscbfxps',
method: 'get',
params: para
})
}
export function getQBBean(para) {
return request({
url: ModuleName + 'qbxsjbxx/' + para.id,
method: 'get'
})
}
|
shiimizu/zig
|
lib/libc/mingw/math/tanhl.c
|
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#include "cephes_mconf.h"
#ifndef _SET_ERRNO
#define _SET_ERRNO(x)
#endif
#ifdef UNK
static uLD P[] = {
{ { -6.8473739392677100872869E-5L } },
{ { -9.5658283111794641589011E-1L } },
{ { -8.4053568599672284488465E1L } },
{ { -1.3080425704712825945553E3L } }
};
static uLD Q[] = {
{ { 9.6259501838840336946872E1L } },
{ { 1.8218117903645559060232E3L } },
{ { 3.9241277114138477845780E3L } }
};
#endif
#ifdef IBMPC
static uLD P[] = {
{ { 0xd2a4,0x1b0c,0x8f15,0x8f99,0xbff1, 0, 0, 0 } },
{ { 0x5959,0x9111,0x9cc7,0xf4e2,0xbffe, 0, 0, 0 } },
{ { 0xb576,0xef5e,0x6d57,0xa81b,0xc005, 0, 0, 0 } },
{ { 0xe3be,0xbfbd,0x5cbc,0xa381,0xc009, 0, 0, 0 } }
};
static uLD Q[] = {
{ { 0x687f,0xce24,0xdd6c,0xc084,0x4005, 0, 0, 0 } },
{ { 0x3793,0xc95f,0xfa2f,0xe3b9,0x4009, 0, 0, 0 } },
{ { 0xd5a2,0x1f9c,0x0b1b,0xf542,0x400a, 0, 0, 0 } }
};
#endif
#ifdef MIEEE
static uLD P[] = {
{ { 0xbff10000,0x8f998f15,0x1b0cd2a4, 0 } },
{ { 0xbffe0000,0xf4e29cc7,0x91115959, 0 } },
{ { 0xc0050000,0xa81b6d57,0xef5eb576, 0 } },
{ { 0xc0090000,0xa3815cbc,0xbfbde3be, 0 } }
};
static uLD Q[] = {
{ { 0x40050000,0xc084dd6c,0xce24687f, 0 } },
{ { 0x40090000,0xe3b9fa2f,0xc95f3793, 0 } },
{ { 0x400a0000,0xf5420b1b,0x1f9cd5a2, 0 } }
};
#endif
long double tanhl(long double x)
{
long double s, z;
#ifdef MINUSZERO
if (x == 0.0L)
return (x);
#endif
if (isnanl(x))
{
_SET_ERRNO (EDOM);
return x;
}
z = fabsl(x);
if (z > 0.5L * MAXLOGL)
{
_SET_ERRNO (ERANGE);
if (x > 0)
return (1.0L);
else
return (-1.0L);
}
if (z >= 0.625L)
{
s = expl(2.0*z);
z = 1.0L - 2.0/(s + 1.0L);
if (x < 0)
z = -z;
}
else
{
s = x * x;
z = polevll( s, P, 3 )/p1evll(s, Q, 3);
z = x * s * z;
z = x + z;
}
return (z);
}
|
augustinebest/app
|
init-script/scripts/3.0.9100.js
|
const { find, update } = require('../util/db');
const scheduledCollection = 'scheduledevents';
async function run() {
const events = await find(scheduledCollection, {
recurring: { $exists: false },
interval: { $exists: false },
});
for (let i = 0; i < events.length; i++) {
const event = events[i];
await update(
scheduledCollection,
{ _id: event._id },
{ recurring: false, interval: null }
);
}
}
module.exports = run;
|
punithmadaiahkumar/try-django
|
Lib/site-packages/pylint/pyreverse/printer.py
|
<filename>Lib/site-packages/pylint/pyreverse/printer.py
# Copyright (c) 2021 <NAME> <<EMAIL>>
# Copyright (c) 2021 <NAME> <<EMAIL>>
# Copyright (c) 2021 <NAME> <<EMAIL>>
# Copyright (c) 2021 <NAME> <<EMAIL>>
# Copyright (c) 2021 <NAME> <<EMAIL>>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
"""
Base class defining the interface for a printer.
"""
from abc import ABC, abstractmethod
from enum import Enum
from typing import List, NamedTuple, Optional
from astroid import nodes
from pylint.pyreverse.utils import get_annotation_label
class NodeType(Enum):
CLASS = "class"
INTERFACE = "interface"
PACKAGE = "package"
class EdgeType(Enum):
INHERITS = "inherits"
IMPLEMENTS = "implements"
ASSOCIATION = "association"
USES = "uses"
class Layout(Enum):
LEFT_TO_RIGHT = "LR"
RIGHT_TO_LEFT = "RL"
TOP_TO_BOTTOM = "TB"
BOTTOM_TO_TOP = "BT"
class NodeProperties(NamedTuple):
label: str
attrs: Optional[List[str]] = None
methods: Optional[List[nodes.FunctionDef]] = None
color: Optional[str] = None
fontcolor: Optional[str] = None
class Printer(ABC):
"""Base class defining the interface for a printer"""
def __init__(
self,
title: str,
layout: Optional[Layout] = None,
use_automatic_namespace: Optional[bool] = None,
) -> None:
self.title: str = title
self.layout = layout
self.use_automatic_namespace = use_automatic_namespace
self.lines: List[str] = []
self._indent = ""
self._open_graph()
def _inc_indent(self) -> None:
"""increment indentation"""
self._indent += " "
def _dec_indent(self) -> None:
"""decrement indentation"""
self._indent = self._indent[:-2]
@abstractmethod
def _open_graph(self) -> None:
"""Emit the header lines, i.e. all boilerplate code that defines things like layout etc."""
def emit(self, line: str, force_newline: Optional[bool] = True) -> None:
if force_newline and not line.endswith("\n"):
line += "\n"
self.lines.append(self._indent + line)
@abstractmethod
def emit_node(
self,
name: str,
type_: NodeType,
properties: Optional[NodeProperties] = None,
) -> None:
"""Create a new node. Nodes can be classes, packages, participants etc."""
@abstractmethod
def emit_edge(
self,
from_node: str,
to_node: str,
type_: EdgeType,
label: Optional[str] = None,
) -> None:
"""Create an edge from one node to another to display relationships."""
@staticmethod
def _get_method_arguments(method: nodes.FunctionDef) -> List[str]:
if method.args.args:
arguments: List[nodes.AssignName] = [
arg for arg in method.args.args if arg.name != "self"
]
else:
arguments = []
annotations = dict(zip(arguments, method.args.annotations[1:]))
for arg in arguments:
annotation_label = ""
ann = annotations.get(arg)
if ann:
annotation_label = get_annotation_label(ann)
annotations[arg] = annotation_label
return [
f"{arg.name}: {ann}" if ann else f"{arg.name}"
for arg, ann in annotations.items()
]
def generate(self, outputfile: str) -> None:
"""Generate and save the final outputfile."""
self._close_graph()
with open(outputfile, "w", encoding="utf-8") as outfile:
outfile.writelines(self.lines)
@abstractmethod
def _close_graph(self) -> None:
"""Emit the lines needed to properly close the graph."""
|
oriolhub/ghubber
|
containers/Profile/index.js
|
<filename>containers/Profile/index.js
// @author <NAME> <<EMAIL>> https://github.com/ovr
// @flow
export { default as Profile } from './Profile';
|
piotrj/administer
|
lib/administer/fields/field_builder.rb
|
module Administer
module Fields
class FieldBuilder
@@registered_classes = SuperclassHash.new
class << self
def register_class(klass, &block)
@@registered_classes[klass] = block
end
end
def build_fields_for(fields)
fields.map do |field|
field_for(field)
end
end
def field_for(object)
block = @@registered_classes[object.class]
raise "FieldBuilder has no class registered #{object.class}" unless block
block.call(object)
end
end
end
end
|
tiankafei/java
|
tiankafei-code-tool/tiankafei-redis/src/main/java/org/tiankafei/redis/service/impl/ValueOperationsServiceImpl.java
|
<reponame>tiankafei/java
package org.tiankafei.redis.service.impl;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.tiankafei.redis.service.IValueOperationsService;
/**
* @author tiankafei
*/
@Service
public class ValueOperationsServiceImpl<K, V> implements IValueOperationsService<K, V> {
@Autowired
private ValueOperations<K, V> valueOperations;
@Resource
private RedisTemplate redisTemplate;
@Override
public <K> Boolean hasKey(K key) {
return redisTemplate.hasKey(key);
}
@Override
public <K> Boolean delete(K key) {
return redisTemplate.delete(key);
}
@Override
public void set(K key, V value) {
valueOperations.set(key, value);
}
@Override
public void set(K key, V value, long timeout, TimeUnit unit) {
valueOperations.set(key, value, timeout, unit);
}
@Override
public Boolean setIfAbsent(K key, V value) {
return valueOperations.setIfAbsent(key, value);
}
@Override
public Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit) {
return valueOperations.setIfAbsent(key, value, timeout, unit);
}
@Override
public Boolean setIfPresent(K key, V value) {
return valueOperations.setIfPresent(key, value);
}
@Override
public Boolean setIfPresent(K key, V value, long timeout, TimeUnit unit) {
return valueOperations.setIfPresent(key, value, timeout, unit);
}
@Override
public void multiSet(Map<? extends K, ? extends V> map) {
valueOperations.multiSet(map);
}
@Override
public Boolean multiSetIfAbsent(Map<? extends K, ? extends V> map) {
return valueOperations.multiSetIfAbsent(map);
}
@Override
public V get(Object key) {
return valueOperations.get(key);
}
@Override
public V getAndSet(K key, V value) {
return valueOperations.getAndSet(key, value);
}
@Override
public List<V> multiGet(Collection<K> keys) {
return valueOperations.multiGet(keys);
}
@Override
public Long increment(K key) {
return valueOperations.increment(key);
}
@Override
public Long increment(K key, long delta) {
return valueOperations.increment(key, delta);
}
@Override
public Double increment(K key, double delta) {
return valueOperations.increment(key, delta);
}
@Override
public Long decrement(K key) {
return valueOperations.decrement(key);
}
@Override
public Long decrement(K key, long delta) {
return valueOperations.decrement(key, delta);
}
@Override
public Integer append(K key, String value) {
return valueOperations.append(key, value);
}
@Override
public String get(K key, long start, long end) {
return valueOperations.get(key, start, end);
}
@Override
public void set(K key, V value, long offset) {
valueOperations.set(key, value, offset);
}
@Override
public Long size(K key) {
return valueOperations.size(key);
}
@Override
public Boolean setBit(K key, long offset, boolean value) {
return valueOperations.setBit(key, offset, value);
}
@Override
public Boolean getBit(K key, long offset) {
return valueOperations.getBit(key, offset);
}
@Override
public List<Long> bitField(K key, BitFieldSubCommands subCommands) {
return valueOperations.bitField(key, subCommands);
}
@Override
public RedisOperations<K, V> getOperations() {
return valueOperations.getOperations();
}
}
|
evrythng/evrythng.js
|
src/entity/Place.js
|
<filename>src/entity/Place.js
import Entity from './Entity'
import Resource from '../resource/Resource'
const path = '/places'
/**
* Represents a Place entity object.
*
* @extends Entity
*/
export default class Place extends Entity {
/**
* Return simple resource factory for Places.
*
* @static
* @return {{place: Function}}
*/
static resourceFactory () {
return {
place: Resource.factoryFor(Place, path)
}
}
}
|
jituancaiyun/openapi-java-sdk
|
src/main/java/com/shinemo/openapi/client/dto/AccessTokenDTO.java
|
/*
* (C) Copyright 2015-2017 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
*
* 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.
*
* Contributors:
* <EMAIL> (夜色)
*/
package com.shinemo.openapi.client.dto;
import java.io.Serializable;
/**
* Created by ohun on 2017/3/22.
*
* @author <EMAIL> (夜色)
*/
public final class AccessTokenDTO implements Serializable {
private String accessToken;
private Long expireTime;
private String jsapiTicket;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getJsapiTicket() {
return jsapiTicket;
}
public void setJsapiTicket(String jsapiTicket) {
this.jsapiTicket = jsapiTicket;
}
public Long getExpireTime() {
return expireTime;
}
public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}
public boolean expired() {
return (System.currentTimeMillis() - expireTime) >= 0;
}
@Override
public String toString() {
return "AccessTokenDTO{" +
"accessToken='" + accessToken + '\'' +
", expireTime=" + expireTime +
", jsapiTicket='" + jsapiTicket + '\'' +
'}';
}
}
|
bjoernalbers/faxomat
|
spec/factories/users.rb
|
<reponame>bjoernalbers/faxomat
FactoryGirl.define do
factory :user do
username { Faker::Internet.user_name }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
title { Faker::Name.prefix }
can_release_reports true
factory :authorized_user
factory :unauthorized_user do
can_release_reports false
end
end
end
|
marcosppastor/MSV146
|
tools/src/client/inventory/MaplePet.java
|
/*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 <NAME> <<EMAIL>>
<NAME> <<EMAIL>>
<NAME> <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package client.inventory;
import client.inventory.Item;
import com.mysql.jdbc.Statement;
import java.awt.Point;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import tools.DatabaseConnection;
import server.MapleItemInformationProvider;
import server.movement.AbsoluteLifeMovement;
import server.movement.LifeMovement;
import server.movement.LifeMovementFragment;
/**
*
* @author Matze
*/
public class MaplePet extends Item {
private String name;
private int uniqueid;
private int closeness = 0;
private byte level = 1;
private int fullness = 100;
private int Fh;
private Point pos;
private int stance;
private boolean summoned;
private byte summonedpet = 0;
private MaplePet(int id, byte position, int uniqueid) {
super(id, position, (short) 1);
this.uniqueid = uniqueid;
}
public static MaplePet loadFromDb(int itemid, byte position, int petid) {
try {
MaplePet ret = new MaplePet(itemid, position, petid);
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT name, level, closeness, fullness, summoned FROM pets WHERE petid = ?"); // Get pet details..
ps.setInt(1, petid);
ResultSet rs = ps.executeQuery();
rs.next();
ret.setName(rs.getString("name"));
ret.setCloseness(Math.min(rs.getInt("closeness"), 30000));
ret.setLevel((byte) Math.min(rs.getByte("level"), 30));
ret.setFullness(Math.min(rs.getInt("fullness"), 100));
ret.setSummoned(rs.getInt("summoned") == 1);
rs.close();
ps.close();
return ret;
} catch (SQLException e) {
return null;
}
}
public void saveToDb() {
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE pets SET name = ?, level = ?, closeness = ?, fullness = ?, summoned = ? WHERE petid = ?");
ps.setString(1, getName());
ps.setInt(2, getLevel());
ps.setInt(3, getCloseness());
ps.setInt(4, getFullness());
ps.setInt(5, isSummoned() ? 1 : 0);
ps.setInt(6, getUniqueId());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
}
}
public static int createPet(int itemid) {
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("INSERT INTO pets (name, level, closeness, fullness, summoned) VALUES (?, 1, 0, 100, 0)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, MapleItemInformationProvider.getInstance().getName(itemid));
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
int ret = -1;
if (rs.next()) {
ret = rs.getInt(1);
}
rs.close();
ps.close();
return ret;
} catch (SQLException e) {
return -1;
}
}
public static int createPet(int itemid, byte level, int closeness, int fullness) {
try {
PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("INSERT INTO pets (name, level, closeness, fullness, summoned) VALUES (?, ?, ?, ?, 0)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, MapleItemInformationProvider.getInstance().getName(itemid));
ps.setByte(2, level);
ps.setInt(3, closeness);
ps.setInt(4, fullness);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
int ret = -1;
if (rs.next()) {
ret = rs.getInt(1);
rs.close();
ps.close();
}
return ret;
} catch (SQLException e) {
return -1;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getUniqueId() {
return uniqueid;
}
public void setUniqueId(int id) {
this.uniqueid = id;
}
public int getCloseness() {
return closeness;
}
public void setCloseness(int closeness) {
this.closeness = closeness;
}
public void gainCloseness(int x) {
this.closeness += x;
}
public byte getLevel() {
return level;
}
public void setLevel(byte level) {
this.level = level;
}
public int getFullness() {
return fullness;
}
public void setFullness(int fullness) {
this.fullness = fullness;
}
public int getFh() {
return Fh;
}
public void setFh(int Fh) {
this.Fh = Fh;
}
public Point getPos() {
return pos;
}
public void setPos(Point pos) {
this.pos = pos;
}
public int getStance() {
return stance;
}
public void setStance(int stance) {
this.stance = stance;
}
public boolean isSummoned() {
return summoned;
}
public void setSummoned(boolean yes) {
this.summoned = yes;
}
public boolean canConsume(int itemId) {
for (int petId : MapleItemInformationProvider.getInstance().petsCanConsume(itemId)) {
if (petId == this.getItemId()) {
return true;
}
}
return false;
}
public void updatePosition(List<LifeMovementFragment> movement) {
for (LifeMovementFragment move : movement) {
if (move instanceof LifeMovement) {
if (move instanceof AbsoluteLifeMovement) {
this.setPos(((LifeMovement) move).getPosition());
}
this.setStance(((LifeMovement) move).getNewstate());
}
}
}
public final boolean getSummoned() {
return summonedpet > 0;
}
}
|
prikarna/NanoOS
|
Src/Service.h
|
/*
* File : Service.h
* Remark : Service parameter and function definition
*
*/
#ifndef SERVICE_H
#define SERVICE_H
#include "Thread.h"
#define SVC_MAX_PARAMS 8
struct _SVC_PARAM {
UINT32_T Index;
UINT32_T ReturnValue;
UINT32_T Reserved2;
UINT32_T Reserved3;
UINT32_T R12;
UINT32_T LR;
UINT32_T PC;
UINT32_T PSR;
UINT32_T Params[SVC_MAX_PARAMS];
}__attribute__((packed));
typedef struct _SVC_PARAM SVC_PARAM, *PSVC_PARAM;
typedef void (* SERVICE_CALL_TYPE)(void);
void SvcZero();
void SvcGetOSVersion();
void SvcGetOSName();
void SvcGetSystemClock();
void SvcReserved();
void SvcDebugCharOut();
void SvcIsUsbSerReady();
void SvcWriteUsbSer();
void SvcReadUsbSer();
void SvcCancelReadUsbSer();
void SvcCreateThread();
void SvcTerminateThread();
void SvcExitThread();
void SvcGetThreadReturnValue();
void SvcGetThreadStatus();
void SvcGetCurrentThreadId();
void SvcSleep();
void SvcSuspendThread();
void SvcResumeThread();
void SvcWaitForObject();
void SvcSwitchToNextThread();
void SvcCreateEvent();
void SvcSetEvent();
void SvcResetEvent();
void SvcCloseEvent();
void SvcSetTerminationHandler();
void SvcGetFaultAddress();
void SvcGetLastFault();
void SvcSetLastError();
void SvcGetLastError();
void SvcSetIntHandler();
//void SvcSetUsbIntHandler();
void SvcLoadConfig();
void SvcSaveConfig();
void SvcLockFlash();
void SvcUnlockFlash();
void SvcEraseFlash();
void SvcProgramFlash();
void SvcAcquireSpinLock();
void SvcReleaseSpinLock();
void SvcSystemReset();
void SvcSetProbe();
void SvcResetProbe();
#endif // End of SERVICE_H
|
spookandpuff/islay
|
lib/islay.rb
|
<reponame>spookandpuff/islay
require 'rails-observers'
require 'cells'
require 'cells-rails'
require 'hamlit'
require 'cells-hamlit'
require 'compass-rails' # This is temporary. By rights this needs to go into the assets group
require 'sass-rails'
require 'jquery-rails'
require 'devise'
require 'devise_invitable'
require 'cancancan'
require 'simple_form'
require 'pg'
require 'pg_search'
require 'friendly_id'
require 'fog-aws'
require 'girl_friday'
require 'mime/types'
require 'streamio-ffmpeg'
require 'zipruby'
require 'jsonify-rails'
require 'kaminari'
require 'rmagick'
require 'rdiscount'
require 'acts_as_list'
require 'draper'
require 'premailer'
require "core_ext/active_record/querying"
require "islay/engines"
require "islay/engine"
require "islay/core_ext"
require "islay/coercion"
require "islay/form_builder"
require "islay/active_record"
require "islay/positioning"
require "islay/publishable"
require "islay/metadata"
require "islay/taggable"
require "islay/query"
require "islay/configuration"
require "islay/extensions"
require "islay/navigation"
require "islay/pages"
require "islay/resourceful_controller"
require "islay/sprockets"
require "islay/routing_mapper_helpers"
module Islay
end
|
nrgxtra/fundamentals
|
lists advanced exerscise/03. next version.py
|
new_version = int(''.join(input().split('.'))) + 1
new_version = '.'.join(str(new_version))
print(new_version)
|
mythoss/midpoint
|
infra/test-util/src/main/java/com/evolveum/midpoint/test/util/TestReportUtil.java
|
<filename>infra/test-util/src/main/java/com/evolveum/midpoint/test/util/TestReportUtil.java
/*
* Copyright (C) 2010-2020 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.test.util;
import static com.evolveum.midpoint.schema.statistics.AbstractStatisticsPrinter.Format.RAW;
import static com.evolveum.midpoint.schema.statistics.AbstractStatisticsPrinter.SortBy.NAME;
import static com.evolveum.midpoint.schema.statistics.AbstractStatisticsPrinter.SortBy.TIME;
import com.evolveum.midpoint.schema.statistics.*;
import com.evolveum.midpoint.tools.testng.TestMonitor;
import com.evolveum.midpoint.tools.testng.TestReportSection;
import com.evolveum.midpoint.util.statistics.OperationsPerformanceMonitor;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
public class TestReportUtil {
/**
* Adds global performance information as a report section to the {@link TestMonitor}.
* Does not clear the data, do not forget to call clearing in the right life-cycle method.
*/
public static void reportGlobalPerfData(TestMonitor testMonitor) {
OperationsPerformanceInformationType performanceInformation =
OperationsPerformanceInformationUtil.toOperationsPerformanceInformationType(
OperationsPerformanceMonitor.INSTANCE.getGlobalPerformanceInformation());
OperationsPerformanceInformationPrinter printer = new OperationsPerformanceInformationPrinter(performanceInformation,
new AbstractStatisticsPrinter.Options(RAW, TIME), null, null, false);
addPrinterData(testMonitor, "globalPerformanceInformation", printer);
}
private static void addPrinterData(TestMonitor testMonitor, String sectionName, AbstractStatisticsPrinter<?> printer) {
printer.prepare();
Data data = printer.getData();
Formatting formatting = printer.getFormatting();
TestReportSection section = testMonitor.addReportSection(sectionName)
.withColumns(formatting.getColumnLabels().toArray(new String[0]));
data.getRawDataStream().forEach(section::addRow);
}
/**
* Adds operation performance for a given task to the {@link TestMonitor}.
*/
public static void reportTaskOperationPerformance(TestMonitor testMonitor, String label,
TaskType task, Integer iterations, Integer seconds) {
OperationsPerformanceInformationType performanceInformationFromTask =
task.getOperationStats() != null ? task.getOperationStats().getOperationsPerformanceInformation() : null;
OperationsPerformanceInformationType performanceInformation = performanceInformationFromTask != null ?
performanceInformationFromTask : new OperationsPerformanceInformationType();
OperationsPerformanceInformationPrinter printer = new OperationsPerformanceInformationPrinter(performanceInformation,
new AbstractStatisticsPrinter.Options(RAW, TIME), iterations, seconds, false);
addPrinterData(testMonitor, label + ":operationPerformance", printer);
}
/**
* Adds repository performance for a given task to the {@link TestMonitor}.
*/
public static void reportTaskRepositoryPerformance(TestMonitor testMonitor, String label,
TaskType task, Integer iterations, Integer seconds) {
RepositoryPerformanceInformationType performanceInformationFromTask =
task.getOperationStats() != null ? task.getOperationStats().getRepositoryPerformanceInformation() : null;
RepositoryPerformanceInformationType performanceInformation = performanceInformationFromTask != null ?
performanceInformationFromTask : new RepositoryPerformanceInformationType();
RepositoryPerformanceInformationPrinter printer = new RepositoryPerformanceInformationPrinter(performanceInformation,
new AbstractStatisticsPrinter.Options(RAW, NAME), iterations, seconds);
addPrinterData(testMonitor, label + ":repositoryPerformance", printer);
}
/**
* Adds caches performance for a given task to the {@link TestMonitor}.
*/
public static void reportTaskCachesPerformance(TestMonitor testMonitor, String label, TaskType task) {
CachesPerformanceInformationType performanceInformationFromTask =
task.getOperationStats() != null ? task.getOperationStats().getCachesPerformanceInformation() : null;
CachesPerformanceInformationType performanceInformation = performanceInformationFromTask != null ?
performanceInformationFromTask : new CachesPerformanceInformationType();
CachePerformanceInformationPrinter printer = new CachePerformanceInformationPrinter(performanceInformation,
new AbstractStatisticsPrinter.Options(RAW, NAME));
addPrinterData(testMonitor, label + ":cachePerformance", printer);
}
/**
* Adds provisioning operations statistics for a given task to the {@link TestMonitor}.
*/
public static void reportTaskProvisioningStatistics(TestMonitor testMonitor, String label, TaskType task) {
EnvironmentalPerformanceInformationType envPerformanceInformationFromTask =
task.getOperationStats() != null ? task.getOperationStats().getEnvironmentalPerformanceInformation() : null;
ProvisioningStatisticsType provisioningStatisticsFromTask = envPerformanceInformationFromTask != null ?
envPerformanceInformationFromTask.getProvisioningStatistics() : null;
ProvisioningStatisticsType provisioningStatistics = provisioningStatisticsFromTask != null ?
provisioningStatisticsFromTask : new ProvisioningStatisticsType();
ProvisioningStatisticsPrinter printer = new ProvisioningStatisticsPrinter(provisioningStatistics,
new AbstractStatisticsPrinter.Options(RAW, NAME));
addPrinterData(testMonitor, label + ":provisioningStatistics", printer);
}
}
|
gabrieldiaz94/RAS-Baxter-Interface
|
baxter_ras_interface/scripts/script_validacion.py
|
<reponame>gabrieldiaz94/RAS-Baxter-Interface
#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String,Int32MultiArray
from geometry_msgs.msg import Twist
from jp_baxtertry1.srv import *
global fin
fin=0
def talker():
while not rospy.is_shutdown():
global Acabe,fin
mover = rospy.Publisher('/Validacion_script', Int32MultiArray, queue_size=40)
Guardar_Archivo = rospy.Publisher('guardardatos', Twist, queue_size=36)
datosaguardar=Twist()
rospy.init_node('Obra', anonymous=True)
auxiliar_service = rospy.ServiceProxy("auxiliar_service", auxiliar)
rospy.wait_for_service('auxiliar_service')
response = auxiliar_service.call(auxiliarRequest())
rate = rospy.Rate(0.2) # 10hz
datos=Int32MultiArray()
print "ACABE",response.acabe
if response.fin==2:
fin=0
while response.acabe==0:
rospy.wait_for_service('auxiliar_service')
response = auxiliar_service.call(auxiliarRequest())
if fin==0:
datos.data=[0,0,1,1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,1]
rospy.loginfo(datos)
mover.publish(datos)
fin=1
datosaguardar.linear.x=2
Guardar_Archivo.publish(datosaguardar)
break
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
|
lizeidsness/minimalist
|
app/@esri/calcite-components/dist/collection/components/calcite-icon/calcite-icon.stories.js
|
<reponame>lizeidsness/minimalist
import {withKnobs, select, boolean} from "@storybook/addon-knobs";
import {
darkBackground,
iconNames,
parseReadme
} from "../../../.storybook/helpers";
import readme from "./readme.md";
const notes = parseReadme(readme);
export default {
title: "Icon",
decorators: [withKnobs],
parameters: { notes }
};
export const simple = () =>
`<calcite-icon icon="${select(
"icon",
iconNames,
iconNames[0]
)}" scale="${select("size", ["s", "m", "l"], "m")}" filled="${boolean(
"filled",
false
)}"></calcite-icon>`;
export const RTL = () =>
`<calcite-icon dir="rtl" icon="arrowBoldLeft" mirror="${boolean(
"mirror",
false
)}"></calcite-icon>`;
export const darkMode = () =>
`<calcite-icon dir="rtl" icon="${select(
"icon",
iconNames,
iconNames[0]
)}" theme="dark"></calcite-icon>`;
darkMode.story = {
parameters: {
backgrounds: darkBackground
}
};
|
DmitryPogrebnoy/LARCmaCS
|
macsCommon/util/gvector.h
|
<reponame>DmitryPogrebnoy/LARCmaCS
//========================================================================
// This software is free: you can redistribute it and/or modify
// it under the terms of the GNU General Public License Version 3,
// as published by the Free Software Foundation.
//
// This software 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
// Version 3 in the file COPYING that came with this distribution.
// If not, see <http://www.gnu.org/licenses/>.
//========================================================================
/*!
\file gvector.h
\brief Simple vector class for 2D and 3D vectors
\author <NAME> <<EMAIL>>, (C) 2004
*/
//========================================================================
#ifndef __GVECTOR_H__
#define __GVECTOR_H__
#include <math.h>
#include "util.h"
#define V3COMP(p) p.x,p.y,p.z
#define V2COMP(p) p.x,p.y
namespace GVector {
//=====================================================================//
// Vector3D Class
//=====================================================================//
#define EPSILON (1.0E-10)
template <class num>
class vector3d{
public:
num x,y,z;
vector3d()
{}
vector3d(num nx,num ny,num nz)
{x=nx; y=ny; z=nz;}
void set(num nx,num ny,num nz)
{x=nx; y=ny; z=nz;}
void setAll(num nx)
{x=y=z=nx;}
void set(vector3d<num> p)
{x=p.x; y=p.y; z=p.z;}
void zero()
{x=y=z=0;}
vector3d<num> &operator=(const vector3d<num> p)
{set(p); return(*this);}
/// element accessor
num &operator[](int idx)
{return(((num*)this)[idx]);}
const num &operator[](int idx) const
{return(((num*)this)[idx]);}
num length() const MustUseResult;
num sqlength() const MustUseResult;
vector3d<num> norm() const MustUseResult;
vector3d<num> norm(const num len) const MustUseResult;
void normalize();
bool nonzero() const MustUseResult
{return(x!=0 || y!=0 || z!=0);}
num dot(const vector3d<num> p) const MustUseResult;
vector3d<num> cross(const vector3d<num> p) const MustUseResult;
vector3d<num> &operator+=(const vector3d<num> p);
vector3d<num> &operator-=(const vector3d<num> p);
vector3d<num> &operator*=(const vector3d<num> p);
vector3d<num> &operator/=(const vector3d<num> p);
vector3d<num> operator+(const vector3d<num> p) const;
vector3d<num> operator-(const vector3d<num> p) const;
vector3d<num> operator*(const vector3d<num> p) const;
vector3d<num> operator/(const vector3d<num> p) const;
vector3d<num> operator*(num f) const;
vector3d<num> operator/(num f) const;
vector3d<num> &operator*=(num f);
vector3d<num> &operator/=(num f);
vector3d<num> operator-() const;
bool operator==(const vector3d<num> p) const;
bool operator!=(const vector3d<num> p) const;
bool operator< (const vector3d<num> p) const;
bool operator> (const vector3d<num> p) const;
bool operator<=(const vector3d<num> p) const;
bool operator>=(const vector3d<num> p) const;
vector3d<num> rotate(const vector3d<num> r,const double a) const;
vector3d<num> rotate_x(const double a) const;
vector3d<num> rotate_y(const double a) const;
vector3d<num> rotate_z(const double a) const;
//double shortest_angle(const vector3d<num> a,const vector3d<num> b);
//vector3d<num> shortest_axis(const vector3d<num> a,const vector3d<num> b);
bool finite() const MustUseResult
{return(::finite(x) && ::finite(y) && ::finite(z));}
void take_min(const vector3d<num> p);
void take_max(const vector3d<num> p);
};
template <class num>
num vector3d<num>::length() const
{
return(sqrt(x*x + y*y + z*z));
}
template <class num>
num vector3d<num>::sqlength() const
{
return(x*x + y*y + z*z);
}
template <class num>
vector3d<num> vector3d<num>::norm() const
{
vector3d<num> p;
num l;
l = sqrt(x*x + y*y + z*z);
p.x = x / l;
p.y = y / l;
p.z = z / l;
return(p);
}
template <class num>
vector3d<num> vector3d<num>::norm(const num len) const
{
vector3d<num> p;
num f;
f = len / sqrt(x*x + y*y + z*z);
p.x = x * f;
p.y = y * f;
p.z = z * f;
return(p);
}
template <class num>
void vector3d<num>::normalize()
{
num l;
l = sqrt(x*x + y*y + z*z);
x /= l;
y /= l;
z /= l;
}
template <class num>
num vector3d<num>::dot(const vector3d<num> p) const
{
return(x*p.x + y*p.y + z*p.z);
}
template <class num>
num dot(const vector3d<num> a,const vector3d<num> b)
{
return(a.x*b.x + a.y*b.y + a.z*b.z);
}
template <class num>
num absdot(const vector3d<num> a,const vector3d<num> b)
{
return(fabs(a.x*b.x) + fabs(a.y*b.y) + fabs(a.z*b.z));
}
template <class num>
vector3d<num> vector3d<num>::cross(const vector3d<num> p) const
{
vector3d<num> r;
// right handed
r.x = y*p.z - z*p.y;
r.y = z*p.x - x*p.z;
r.z = x*p.y - y*p.x;
return(r);
}
template <class num>
vector3d<num> cross(const vector3d<num> a,const vector3d<num> b)
{
vector3d<num> r;
// right handed
r.x = a.y*b.z - a.z*b.y;
r.y = a.z*b.x - a.x*b.z;
r.z = a.x*b.y - a.y*b.x;
return(r);
}
#define VECTOR3D_EQUAL_BINARY_OPERATOR(opr) \
template <class num> \
vector3d<num> &vector3d<num>::operator opr (const vector3d<num> p) \
{ \
x = x opr p.x; \
y = y opr p.y; \
z = z opr p.z; \
return(*this); \
}
VECTOR3D_EQUAL_BINARY_OPERATOR(+=)
VECTOR3D_EQUAL_BINARY_OPERATOR(-=)
VECTOR3D_EQUAL_BINARY_OPERATOR(*=)
VECTOR3D_EQUAL_BINARY_OPERATOR(/=)
#define VECTOR3D_BINARY_OPERATOR(opr) \
template <class num> \
vector3d<num> vector3d<num>::operator opr (const vector3d<num> p) const \
{ \
vector3d<num> r; \
r.x = x opr p.x; \
r.y = y opr p.y; \
r.z = z opr p.z; \
return(r); \
}
VECTOR3D_BINARY_OPERATOR(+)
VECTOR3D_BINARY_OPERATOR(-)
VECTOR3D_BINARY_OPERATOR(*)
VECTOR3D_BINARY_OPERATOR(/)
#define VECTOR3D_SCALAR_OPERATOR(opr) \
template <class num> \
vector3d<num> vector3d<num>::operator opr (const num f) const \
{ \
vector3d<num> r; \
r.x = x opr f; \
r.y = y opr f; \
r.z = z opr f; \
return(r); \
}
VECTOR3D_SCALAR_OPERATOR(*)
VECTOR3D_SCALAR_OPERATOR(/)
#define VECTOR3D_EQUAL_SCALAR_OPERATOR(opr) \
template <class num> \
vector3d<num> &vector3d<num>::operator opr (num f) \
{ \
x = x opr f; \
y = y opr f; \
z = z opr f; \
return(*this); \
}
VECTOR3D_EQUAL_SCALAR_OPERATOR(*=)
VECTOR3D_EQUAL_SCALAR_OPERATOR(/=)
#define VECTOR3D_LOGIC_OPERATOR(opr,combine) \
template <class num> \
bool vector3d<num>::operator opr (const vector3d<num> p) const \
{ \
return((x opr p.x) combine \
(y opr p.y) combine \
(z opr p.z)); \
}
VECTOR3D_LOGIC_OPERATOR(==,&&)
VECTOR3D_LOGIC_OPERATOR(!=,||)
VECTOR3D_LOGIC_OPERATOR(< ,&&)
VECTOR3D_LOGIC_OPERATOR(> ,&&)
VECTOR3D_LOGIC_OPERATOR(<=,&&)
VECTOR3D_LOGIC_OPERATOR(>=,&&)
template <class num>
vector3d<num> vector3d<num>::operator-() const
{
vector3d<num> r;
r.x = -x;
r.y = -y;
r.z = -z;
return(r);
}
template <class num1,class num2>
vector3d<num2> operator*(num1 f,const vector3d<num2> &a)
{
vector3d<num2> r;
r.x = f * a.x;
r.y = f * a.y;
r.z = f * a.z;
return(r);
}
template <class num>
inline vector3d<num> abs(vector3d<num> a)
{
a.x = ::fabs(a.x);
a.y = ::fabs(a.y);
a.z = ::fabs(a.z);
return(a);
}
template <class num>
inline vector3d<num> min(vector3d<num> a,vector3d<num> b)
{
vector3d<num> v;
v.x = ::min(a.x,b.x);
v.y = ::min(a.y,b.y);
v.z = ::min(a.z,b.z);
return(v);
}
template <class num>
inline vector3d<num> max(vector3d<num> a,vector3d<num> b)
{
vector3d<num> v;
v.x = ::max(a.x,b.x);
v.y = ::max(a.y,b.y);
v.z = ::max(a.z,b.z);
return(v);
}
template <class num>
inline vector3d<num> bound(vector3d<num> v,num low,num high)
{
v.x = ::bound(v.x,low,high);
v.y = ::bound(v.y,low,high);
v.z = ::bound(v.z,low,high);
return(v);
}
// returns point rotated around axis <r> by <a> radians (right handed)
template <class num>
vector3d<num> vector3d<num>::rotate(const vector3d<num> r,const double a) const
{
vector3d<num> q;
double s,c,t;
s = sin(a);
c = cos(a);
t = 1 - c;
q.x = (t * r.x * r.x + c ) * x
+ (t * r.x * r.y - s * r.z) * y
+ (t * r.x * r.z + s * r.y) * z;
q.y = (t * r.y * r.x + s * r.z) * x
+ (t * r.y * r.y + c ) * y
+ (t * r.y * r.z - s * r.x) * z;
q.z = (t * r.z * r.x - s * r.y) * x
+ (t * r.z * r.y + s * r.x) * y
+ (t * r.z * r.z + c ) * z;
return(q);
}
// returns point rotated around X axis by <a> radians (right handed)
template <class num>
vector3d<num> vector3d<num>::rotate_x(const double a) const
{
vector3d<num> q;
double s,c;
s = sin(a);
c = cos(a);
q.x = x;
q.y = c*y + -s*z;
q.z = s*y + c*z;
return(q);
}
// returns point rotated around Y axis by <a> radians (right handed)
template <class num>
vector3d<num> vector3d<num>::rotate_y(const double a) const
{
vector3d<num> q;
double s,c;
s = sin(a);
c = cos(a);
q.x = c*x + s*z;
q.y = y;
q.z = -s*x + c*z;
return(q);
}
// returns point rotated around Z axis by <a> radians (right handed)
template <class num>
vector3d<num> vector3d<num>::rotate_z(const double a) const
{
vector3d<num> q;
double s,c;
s = sin(a);
c = cos(a);
q.x = c*x + -s*y;
q.y = s*x + c*y;
q.z = z;
return(q);
}
template <class num>
double shortest_angle(const vector3d<num> a,const vector3d<num> b) {
return(acos(std::max(-1.0,std::min(1.0,dot(a,b)/(a.length()*b.length())))));
}
template <class num>
vector3d<num> shortest_axis(const vector3d<num> a,const vector3d<num> b) {
return(cross(a,b).norm());
}
// set the vector to the minimum of its components and p's components
template <class num>
void vector3d<num>::take_min(const vector3d<num> p)
{
if(p.x < x) x = p.x;
if(p.y < y) y = p.y;
if(p.z < z) z = p.z;
}
// set the vector to the maximum of its components and p's components
template <class num>
void vector3d<num>::take_max(const vector3d<num> p)
{
if(p.x > x) x = p.x;
if(p.y > y) y = p.y;
if(p.z > z) z = p.z;
}
// returns distance between two points
template <class num>
num dist(const vector3d<num> a,const vector3d<num> b)
{
num dx,dy,dz;
dx = a.x - b.x;
dy = a.y - b.y;
dz = a.z - b.z;
return(sqrt(dx*dx + dy*dy + dz*dz));
}
template <class num>
inline num distance(const vector3d<num> a,const vector3d<num> b)
{
return(dist(a,b));
}
// returns square of distance between two points
template <class num>
num sqdist(const vector3d<num> a,const vector3d<num> b)
{
num dx,dy,dz;
dx = a.x - b.x;
dy = a.y - b.y;
dz = a.z - b.z;
return(dx*dx + dy*dy + dz*dz);
}
template <class num>
inline num sqdistance(const vector3d<num> a,const vector3d<num> b)
{
return(sqdist(a,b));
}
// returns distance from point p to line x0-x1
template <class num>
num distance_to_line(const vector3d<num> x0,const vector3d<num> x1,const vector3d<num> p)
{
// FIXME: this is probably broken
vector3d<num> x;
num t;
t = ((p.x - x0.x) + (p.y - x0.y) + (p.z - x0.z)) / (x1.x + x1.y + x1.z);
x = x0 + (x1 - x0) * t;
return(distance(x,p));
}
//=====================================================================//
// Vector2D Class
//=====================================================================//
template <class num>
class vector2d{
public:
num x,y;
vector2d()
{}
vector2d(num nx,num ny)
{x=nx; y=ny;}
/// set the components of the vector
void set(num nx,num ny)
{x=nx; y=ny;}
/// set the components of the vector to the same value
void setAll(num nx)
{x=y=nx;}
/// set the components of the vector
void set(vector2d<num> p)
{x=p.x; y=p.y;}
/// zero all components of the vector
void zero()
{x=y=0;}
/// copy constructor
vector2d<num> &operator=(vector2d<num> p)
{set(p); return(*this);}
/// element accessor
num &operator[](int idx)
{return(((num*)this)[idx]);}
const num &operator[](int idx) const
{return(((num*)this)[idx]);}
/// calculate Euclidean length
num length() const MustUseResult;
/// calculate squared Euclidean length (faster than length())
num sqlength() const MustUseResult;
/// calculate the clockwise angle from <1,0>
num angle() const MustUseResult
{return(atan2(y,x));}
/// make a unit vector at given angle
void heading(num angle)
{x=cos(angle); y=sin(angle);}
/// return a unit length vector in the same direction
vector2d<num> norm() const MustUseResult;
/// return a length 'len' vector in the same direction
vector2d<num> norm(const num len) const MustUseResult;
/// normalize to unit length in place
void normalize();
/// bound vector to a maximum length
vector2d<num> bound(const num max_length) const MustUseResult;
/// return if vector has any length at all
bool nonzero() const MustUseResult
{return(x!=0 || y!=0);}
/// return dot product of vector with p
num dot(const vector2d<num> p) const MustUseResult;
/// return dot product of vector with p, equivalent to (this->perp()).dot(p)
num perpdot(const vector2d<num> p) const MustUseResult;
/// return z component of 3D cross product on 2D vectors. right handed.
num cross(const vector2d<num> p) const MustUseResult;
/// return the perpendicular of a vector (i.e. rotated 90 deg clockwise)
vector2d<num> perp() const MustUseResult
{return(vector2d(-y, x));}
/// add a vector to the current element values
vector2d<num> &operator+=(const vector2d<num> p);
/// subtract a vector from the current element values
vector2d<num> &operator-=(const vector2d<num> p);
/// multiply (elementwise) a vector with the current element values
vector2d<num> &operator*=(const vector2d<num> p);
/// divide (elementwise) a vector with the current element values
vector2d<num> &operator/=(const vector2d<num> p);
/// return vector sum of this vector and p
vector2d<num> operator+(const vector2d<num> p) const;
/// return vector difference of this vector and p
vector2d<num> operator-(const vector2d<num> p) const;
/// return elementwise product of this vector and p
vector2d<num> operator*(const vector2d<num> p) const;
/// return elementwise division of this vector by p
vector2d<num> operator/(const vector2d<num> p) const;
/// return this vector scaled by f
vector2d<num> operator*(const num f) const;
/// return this vector scaled by 1/f
vector2d<num> operator/(const num f) const;
/// scale this vector by f
vector2d<num> &operator*=(num f);
/// scale this vector by 1/f
vector2d<num> &operator/=(num f);
/// negate vector (reflect through origin) <x,y> -> <-x,-y>
vector2d<num> operator-() const;
bool operator==(const vector2d<num> p) const;
bool operator!=(const vector2d<num> p) const;
bool operator< (const vector2d<num> p) const;
bool operator> (const vector2d<num> p) const;
bool operator<=(const vector2d<num> p) const;
bool operator>=(const vector2d<num> p) const;
/// return vector rotated by angle a
vector2d<num> rotate(const double a) const MustUseResult;
// vector2d<num> project(const vector2d<num> p) const;
vector2d<num> project_in(const vector2d<num> p) const MustUseResult;
vector2d<num> project_out(const vector2d<num> p) const MustUseResult;
/// return true if both elements are finite, otherwise return false
bool finite() const MustUseResult
{return(::finite(x) && ::finite(y));}
/// set the vector to the minimum of its components and p's components
void take_min(const vector2d<num> p);
/// set the vector to the maximum of its components and p's components
void take_max(const vector2d<num> p);
};
template <class num>
num vector2d<num>::length() const
{
return(sqrt(x*x + y*y));
}
template <class num>
num vector2d<num>::sqlength() const
{
return(x*x + y*y);
}
template <class num>
vector2d<num> vector2d<num>::norm() const
{
vector2d<num> p;
num l;
l = sqrt(x*x + y*y);
p.x = x / l;
p.y = y / l;
return(p);
}
template <class num>
vector2d<num> vector2d<num>::norm(const num len) const
{
vector2d<num> p;
num f;
f = len / sqrt(x*x + y*y);
p.x = x * f;
p.y = y * f;
return(p);
}
template <class num>
void vector2d<num>::normalize()
{
num l;
l = sqrt(x*x + y*y);
x /= l;
y /= l;
}
template <class num>
vector2d<num> vector2d<num>::bound(const num max_length) const
{
vector2d<num> p;
num lsq,f;
lsq = x*x + y*y;
if(lsq < sq(max_length)){
p.set(x,y);
}else{
f = max_length / sqrt(lsq);
p.set(f*x,f*y);
}
return(p);
}
template <class num>
num vector2d<num>::dot(const vector2d<num> p) const
{
return(x*p.x + y*p.y);
}
template <class num>
num vector2d<num>::perpdot(const vector2d<num> p) const
// perp product, equivalent to (this->perp()).dot(p)
{
return(x*p.y - y*p.x);
}
template <class num>
num dot(const vector2d<num> a,const vector2d<num> b)
{
return(a.x*b.x + a.y*b.y);
}
template <class num>
num cosine(const vector2d<num> a,const vector2d<num> b)
// equivalent to dot(a.norm(),b.norm())
{
num l;
l = sqrt(a.x*a.x + a.y*a.y) * sqrt(b.x*b.x + b.y*b.y);
return((a.x*b.x + a.y*b.y) / l);
}
template <class num>
num vector2d<num>::cross(const vector2d<num> p) const
{
// right handed
return(x*p.y - p.x*y);
}
// returns point rotated by <a> radians
template <class num>
vector2d<num> vector2d<num>::rotate(const double a) const
{
vector2d<num> q;
double s,c;
s = sin(a);
c = cos(a);
q.x = c*x + -s*y;
q.y = s*x + c*y;
return(q);
}
/* Depricated: replace "p.project(basis)" with "basis.project_out(p)"
/// returns vector projected onto (p, p.perp()) basis.
/// equivalent to q = p*x + p.perp()*y;
template <class num>
vector2d<num> vector2d<num>::project(const vector2d<num> p) const
{
vector2d<num> q;
q.x = p.x*x - p.y*y;
q.y = p.y*x + p.x*y;
return(q);
}
*/
/// takes a vector p in outer coordinate space and returns one
/// projected onto basis given by this,this.perp()
template <class num>
vector2d<num> vector2d<num>::project_in(const vector2d<num> p) const
{
vector2d<num> q;
q.x = x*p.x + y*p.y; // q.x = this->dot(p);
q.y = x*p.y - y*p.x; // q.y = this->perpdot(p);
return(q);
}
/// takes a vector p in basis given by this,this.perp() and returns
/// one in the outer coordinate space
template <class num>
vector2d<num> vector2d<num>::project_out(const vector2d<num> p) const
{
vector2d<num> q;
q.x = x*p.x - y*p.y;
q.y = y*p.x + x*p.y;
return(q);
}
#define VECTOR2D_EQUAL_BINARY_OPERATOR(opr) \
template <class num> \
vector2d<num> &vector2d<num>::operator opr (const vector2d<num> p) \
{ \
x = x opr p.x; \
y = y opr p.y; \
return(*this); \
}
VECTOR2D_EQUAL_BINARY_OPERATOR(+=)
VECTOR2D_EQUAL_BINARY_OPERATOR(-=)
VECTOR2D_EQUAL_BINARY_OPERATOR(*=)
VECTOR2D_EQUAL_BINARY_OPERATOR(/=)
#define VECTOR2D_BINARY_OPERATOR(opr) \
template <class num> \
vector2d<num> vector2d<num>::operator opr (const vector2d<num> p) const \
{ \
vector2d<num> r; \
r.x = x opr p.x; \
r.y = y opr p.y; \
return(r); \
}
VECTOR2D_BINARY_OPERATOR(+)
VECTOR2D_BINARY_OPERATOR(-)
VECTOR2D_BINARY_OPERATOR(*)
VECTOR2D_BINARY_OPERATOR(/)
#define VECTOR2D_SCALAR_OPERATOR(opr) \
template <class num> \
vector2d<num> vector2d<num>::operator opr (const num f) const \
{ \
vector2d<num> r; \
r.x = x opr f; \
r.y = y opr f; \
return(r); \
}
VECTOR2D_SCALAR_OPERATOR(*)
VECTOR2D_SCALAR_OPERATOR(/)
#define VECTOR2D_EQUAL_SCALAR_OPERATOR(opr) \
template <class num> \
vector2d<num> &vector2d<num>::operator opr (num f) \
{ \
x = x opr f; \
y = y opr f; \
return(*this); \
}
VECTOR2D_EQUAL_SCALAR_OPERATOR(*=)
VECTOR2D_EQUAL_SCALAR_OPERATOR(/=)
#define VECTOR2D_LOGIC_OPERATOR(opr,combine) \
template <class num> \
bool vector2d<num>::operator opr (const vector2d<num> p) const \
{ \
return((x opr p.x) combine \
(y opr p.y)); \
}
VECTOR2D_LOGIC_OPERATOR(==,&&)
VECTOR2D_LOGIC_OPERATOR(!=,||)
VECTOR2D_LOGIC_OPERATOR(< ,&&)
VECTOR2D_LOGIC_OPERATOR(> ,&&)
VECTOR2D_LOGIC_OPERATOR(<=,&&)
VECTOR2D_LOGIC_OPERATOR(>=,&&)
template <class num>
vector2d<num> vector2d<num>::operator-() const
{
vector2d<num> r;
r.x = -x;
r.y = -y;
return(r);
}
template <class num1,class num2>
vector2d<num2> operator*(num1 f,const vector2d<num2> &a)
{
vector2d<num2> r;
r.x = f * a.x;
r.y = f * a.y;
return(r);
}
template <class num>
void vector2d<num>::take_min(const vector2d<num> p)
{
if(p.x < x) x = p.x;
if(p.y < y) y = p.y;
}
template <class num>
void vector2d<num>::take_max(const vector2d<num> p)
{
if(p.x > x) x = p.x;
if(p.y > y) y = p.y;
}
template <class num>
inline vector2d<num> abs(vector2d<num> a)
{
a.x = ::fabs(a.x);
a.y = ::fabs(a.y);
return(a);
}
template <class num>
inline vector2d<num> min(vector2d<num> a,vector2d<num> b)
{
vector2d<num> v;
v.x = ::min(a.x,b.x);
v.y = ::min(a.y,b.y);
return(v);
}
template <class num>
inline vector2d<num> max(vector2d<num> a,vector2d<num> b)
{
vector2d<num> v;
v.x = ::max(a.x,b.x);
v.y = ::max(a.y,b.y);
return(v);
}
template <class num>
inline vector2d<num> bound(vector2d<num> v,num low,num high)
{
v.x = ::bound(v.x,low,high);
v.y = ::bound(v.y,low,high);
return(v);
}
template <class num>
num dist(const vector2d<num> a,const vector2d<num> b)
{
num dx,dy;
dx = a.x - b.x;
dy = a.y - b.y;
return(sqrt(dx*dx + dy*dy));
}
template <class num>
inline num distance(const vector2d<num> a,const vector2d<num> b)
{
return(dist(a,b));
}
// returns square of distance between two points
template <class num>
num sqdist(const vector2d<num> a,const vector2d<num> b)
{
num dx,dy;
dx = a.x - b.x;
dy = a.y - b.y;
return(dx*dx + dy*dy);
}
template <class num>
inline num sqdistance(const vector2d<num> a,const vector2d<num> b)
{
return(sqdist(a,b));
}
}; // namespace vector
#endif
// __VECTOR_H__
|
horacehylee/southtransport-abt-app
|
src/theme.js
|
<gh_stars>1-10
export const Theme = {
primary: "#157cbe",
primaryDark: "#00508d"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.