max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
535 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* util/cmd: utility package for parsing `<key>=<value>` pairs among shell
* command arguments.
*/
#include <string.h>
#include <limits.h>
#include "defs/error.h"
#include "mn_socket/mn_socket.h"
#include "parse/parse.h"
#include "cmdarg/cmdarg.h"
/**
* Locates the index of the first '=' character in the provided string.
*/
static int
cmdarg_equals_off(const char *arg)
{
char *eq;
eq = strchr(arg, '=');
if (eq == NULL) {
return -1;
}
return eq - arg;
}
/**
* Given a key, finds the first argument with the following contents:
*
* <key>=[val]
*
* @param argc The argument count.
* @param argv The argument list.
* @param key The key to search for.
* @param out_val On success, points to the start of the located
* value string.
*
* @return Argument index on success; -1 on failure.
*/
static int
cmdarg_find_idx(int argc, char **argv, const char *key, char **out_val)
{
char *arg;
int eq_off;
int i;
for (i = 0; i < argc; i++) {
arg = argv[i];
if (arg != NULL) {
eq_off = cmdarg_equals_off(arg);
if (eq_off == -1) {
if (strcmp(arg, key) == 0) {
if (out_val != NULL) {
*out_val = NULL;
}
return i;
}
} else {
if (strncmp(arg, key, eq_off) == 0) {
if (out_val != NULL) {
*out_val = arg + eq_off + 1;
}
return i;
}
}
}
}
return -1;
}
static char *
cmdarg_find_priv(int argc, char **argv, const char *key, bool erase,
char **out_val)
{
char *arg;
int idx;
idx = cmdarg_find_idx(argc, argv, key, out_val);
if (idx == -1) {
return NULL;
}
arg = argv[idx];
if (erase) {
argv[idx] = NULL;
}
return arg;
}
char *
cmdarg_find(int argc, char **argv, const char *key, char **out_val)
{
return cmdarg_find_priv(argc, argv, key, false, out_val);
}
char *
cmdarg_extract(int argc, char **argv, const char *key, char **out_val)
{
return cmdarg_find_priv(argc, argv, key, true, out_val);
}
int
cmdarg_find_str(int argc, char **argv, const char *key, char **out_s)
{
const char *arg;
arg = cmdarg_find(argc, argv, key, out_s);
if (arg == NULL) {
return SYS_ENOENT;
}
return 0;
}
int
cmdarg_extract_str(int argc, char **argv, const char *key, char **out_s)
{
const char *arg;
arg = cmdarg_extract(argc, argv, key, out_s);
if (arg == NULL) {
return SYS_ENOENT;
}
return 0;
}
static int
cmdarg_find_ll_priv(int argc, char **argv, const char *name,
long long min, long long max, bool erase,
long long *out_ll)
{
const char *arg;
char *val;
long long ll;
int rc;
arg = cmdarg_find_priv(argc, argv, name, erase, &val);
if (arg == NULL) {
return SYS_ENOENT;
}
ll = parse_ll_bounds(val, min, max, &rc);
if (rc != 0) {
return rc;
}
if (out_ll != NULL) {
*out_ll = ll;
}
return 0;
}
int
cmdarg_find_ll(int argc, char **argv, const char *key,
long long min, long long max, long long *out_ll)
{
return cmdarg_find_ll_priv(argc, argv, key, min, max, false, out_ll);
}
int
cmdarg_extract_ll(int argc, char **argv, const char *key,
long long min, long long max, long long *out_ll)
{
return cmdarg_find_ll_priv(argc, argv, key, min, max, true, out_ll);
}
static int
cmdarg_find_ll_dflt_priv(int argc, char **argv, const char *key,
long long min, long long max, long long dflt,
bool erase, long long *out_ll)
{
int rc;
rc = cmdarg_find_ll_priv(argc, argv, key, min, max, erase, out_ll);
if (rc == SYS_ENOENT) {
rc = 0;
if (out_ll != NULL) {
*out_ll = dflt;
}
}
return rc;
}
int
cmdarg_find_ll_dflt(int argc, char **argv, const char *key,
long long min, long long max, long long dflt,
long long *out_ll)
{
return cmdarg_find_ll_dflt_priv(argc, argv, key, min, max, dflt, false,
out_ll);
}
int
cmdarg_extract_ll_dflt(int argc, char **argv, const char *key,
long long min, long long max, long long dflt,
long long *out_ll)
{
return cmdarg_find_ll_dflt_priv(argc, argv, key, min, max, dflt, true,
out_ll);
}
static int
cmdarg_find_ull_priv(int argc, char **argv, const char *key,
unsigned long long min, unsigned long long max,
bool erase, unsigned long long *out_ull)
{
unsigned long long ull;
const char *arg;
char *val;
int rc;
arg = cmdarg_find_priv(argc, argv, key, erase, &val);
if (arg == NULL) {
return SYS_ENOENT;
}
ull = parse_ull_bounds(val, min, max, &rc);
if (rc != 0) {
return rc;
}
if (out_ull != NULL) {
*out_ull = ull;
}
return 0;
}
int
cmdarg_find_ull(int argc, char **argv, const char *key,
unsigned long long min, unsigned long long max,
unsigned long long *out_ull)
{
return cmdarg_find_ull_priv(argc, argv, key, min, max, false, out_ull);
}
int
cmdarg_extract_ull(int argc, char **argv, const char *key,
unsigned long long min, unsigned long long max,
unsigned long long *out_ull)
{
return cmdarg_find_ull_priv(argc, argv, key, min, max, true, out_ull);
}
static int
cmdarg_find_ull_dflt_priv(int argc, char **argv, const char *key,
unsigned long long min, unsigned long long max,
unsigned long long dflt, bool erase,
unsigned long long *out_ull)
{
int rc;
rc = cmdarg_find_ull_priv(argc, argv, key, min, max, erase, out_ull);
if (rc == SYS_ENOENT) {
rc = 0;
if (out_ull != NULL) {
*out_ull = dflt;
}
}
return rc;
}
int
cmdarg_find_ull_dflt(int argc, char **argv, const char *key,
unsigned long long min, unsigned long long max,
unsigned long long dflt, unsigned long long *out_ull)
{
return cmdarg_find_ull_dflt_priv(argc, argv, key, min, max, dflt, false,
out_ull);
}
int
cmdarg_extract_ull_dflt(int argc, char **argv, const char *key,
unsigned long long min, unsigned long long max,
unsigned long long dflt, unsigned long long *out_ull)
{
return cmdarg_find_ull_dflt_priv(argc, argv, key, min, max, dflt,
true, out_ull);
}
static int
cmdarg_find_bool_priv(int argc, char **argv, const char *key, bool erase,
bool *out_b)
{
const char *arg;
char *val;
bool b;
int rc;
arg = cmdarg_find_priv(argc, argv, key, erase, &val);
if (arg == NULL) {
return SYS_ENOENT;
}
b = parse_bool(key, &rc);
if (rc != 0) {
return rc;
}
if (out_b != NULL) {
*out_b = b;
}
return 0;
}
int
cmdarg_find_bool(int argc, char **argv, const char *key, bool *out_b)
{
return cmdarg_find_bool_priv(argc, argv, key, false, out_b);
}
int
cmdarg_extract_bool(int argc, char **argv, const char *key, bool *out_b)
{
return cmdarg_find_bool_priv(argc, argv, key, true, out_b);
}
static int
cmdarg_find_bool_dflt_priv(int argc, char **argv, const char *key,
bool dflt, bool erase, bool *out_b)
{
int rc;
rc = cmdarg_find_bool_priv(argc, argv, key, erase, out_b);
if (rc == SYS_ENOENT) {
rc = 0;
if (out_b != NULL) {
*out_b = dflt;
}
}
return rc;
}
int
cmdarg_find_bool_dflt(int argc, char **argv, const char *key, bool dflt,
bool *out_b)
{
return cmdarg_find_bool_dflt_priv(argc, argv, key, dflt, false, out_b);
}
int
cmdarg_extract_bool_dflt(int argc, char **argv, const char *key, bool dflt,
bool *out_b)
{
return cmdarg_find_bool_dflt_priv(argc, argv, key, dflt, true, out_b);
}
static int
cmdarg_find_int_priv(int argc, char **argv, const char *key,
int min, int max, bool erase,
int *out_i)
{
long long ll;
int rc;
rc = cmdarg_find_ll_priv(argc, argv, key, min, max, erase, &ll);
if (rc == 0 && out_i != NULL) {
*out_i = ll;
}
return rc;
}
int
cmdarg_find_int(int argc, char **argv, const char *key, int min, int max,
int *out_i)
{
return cmdarg_find_int_priv(argc, argv, key, min, max, false, out_i);
}
int
cmdarg_extract_int(int argc, char **argv, const char *key, int min, int max,
int *out_i)
{
return cmdarg_find_int_priv(argc, argv, key, min, max, true, out_i);
}
static int
cmdarg_find_int_dflt_priv(int argc, char **argv, const char *key,
int min, int max, int dflt, bool erase,
int *out_i)
{
int rc;
rc = cmdarg_find_int_priv(argc, argv, key, min, max, erase, out_i);
if (rc == SYS_ENOENT) {
rc = 0;
if (out_i != NULL) {
*out_i = dflt;
}
}
return rc;
}
int
cmdarg_find_int_dflt(int argc, char **argv, const char *key,
int min, int max, int dflt,
int *out_i)
{
return cmdarg_find_int_dflt_priv(argc, argv, key, min, max, dflt, false,
out_i);
}
int
cmdarg_extract_int_dflt(int argc, char **argv, const char *key,
int min, int max, int dflt,
int *out_i)
{
return cmdarg_find_int_dflt_priv(argc, argv, key, min, max, dflt, true,
out_i);
}
static int
cmdarg_find_bytes_priv(int argc, char **argv, const char *key,
int max_len, bool erase,
uint8_t *out_val, int *out_len)
{
const char *arg;
char *val;
arg = cmdarg_find_priv(argc, argv, key, erase, &val);
if (arg == NULL) {
return SYS_ENOENT;
}
return parse_byte_stream(val, max_len, out_val, out_len);
}
int
cmdarg_find_bytes(int argc, char **argv, const char *key,
int max_len, uint8_t *out_val, int *out_len)
{
return cmdarg_find_bytes_priv(argc, argv, key, max_len, false, out_val,
out_len);
}
int
cmdarg_extract_bytes(int argc, char **argv, const char *key,
int max_len, uint8_t *out_val, int *out_len)
{
return cmdarg_find_bytes_priv(argc, argv, key, max_len, true, out_val,
out_len);
}
static int
cmdarg_find_eui_priv(int argc, char **argv, const char *key, bool erase,
uint8_t *out_eui)
{
const char *arg;
char *val;
arg = cmdarg_find_priv(argc, argv, key, erase, &val);
if (arg == NULL) {
return SYS_ENOENT;
}
return parse_byte_stream_exact_length_base(val, 16, out_eui, 8);
}
int
cmdarg_find_eui(int argc, char **argv, const char *key, uint8_t *out_eui)
{
return cmdarg_find_eui_priv(argc, argv, key, false, out_eui);
}
int
cmdarg_extract_eui(int argc, char **argv, const char *key, uint8_t *out_eui)
{
return cmdarg_find_eui_priv(argc, argv, key, true, out_eui);
}
static int
cmdarg_find_ip6_addr_priv(int argc, char **argv, const char *key,
bool erase, struct mn_in6_addr *out_addr)
{
struct mn_in6_addr addr;
const char *arg;
char *val;
int rc;
arg = cmdarg_find_priv(argc, argv, key, erase, &val);
if (arg == NULL) {
return SYS_ENOENT;
}
rc = mn_inet_pton(MN_AF_INET6, val, &addr);
if (rc != 1) {
return SYS_EINVAL;
}
if (out_addr != NULL) {
*out_addr = addr;
}
return 0;
}
int
cmdarg_find_ip6_addr(int argc, char **argv, const char *key,
struct mn_in6_addr *out_addr)
{
return cmdarg_find_ip6_addr_priv(argc, argv, key, false, out_addr);
}
int
cmdarg_extract_ip6_addr(int argc, char **argv, const char *key,
struct mn_in6_addr *out_addr)
{
return cmdarg_find_ip6_addr_priv(argc, argv, key, true, out_addr);
}
static int
cmdarg_find_ip6_net_priv(int argc, char **argv, const char *key,
bool erase, struct mn_in6_addr *out_addr,
uint8_t *out_prefix_len)
{
const char *arg;
char *val;
arg = cmdarg_find_priv(argc, argv, key, erase, &val);
if (arg == NULL || val == NULL) {
return SYS_ENOENT;
}
return parse_ip6_net(val, out_addr, out_prefix_len);
}
int
cmdarg_find_ip6_net(int argc, char **argv, const char *key,
struct mn_in6_addr *out_addr, uint8_t *out_prefix_len)
{
return cmdarg_find_ip6_net_priv(argc, argv, key, false, out_addr,
out_prefix_len);
}
int
cmdarg_extract_ip6_net(int argc, char **argv, const char *key,
struct mn_in6_addr *out_addr, uint8_t *out_prefix_len)
{
return cmdarg_find_ip6_net_priv(argc, argv, key, true, out_addr,
out_prefix_len);
}
| 7,330 |
11,356 | /*=============================================================================
Phoenix V1.2.1
Copyright (c) 2001-2003 <NAME>
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <iostream>
#include <boost/detail/lightweight_test.hpp>
#define PHOENIX_LIMIT 15
#include <boost/spirit/include/phoenix1_primitives.hpp>
#include <boost/spirit/include/phoenix1_composite.hpp>
#include <boost/spirit/include/phoenix1_functions.hpp>
#include <boost/spirit/include/phoenix1_operators.hpp>
using namespace phoenix;
using namespace std;
///////////////////////////////////////////////////////////////////////////////
struct sqr_ {
template <typename ArgT>
struct result { typedef ArgT type; };
template <typename ArgT>
ArgT operator()(ArgT n) const { return n * n; }
};
function<sqr_> sqr;
///////////////////////////////////////////////////////////////////////////////
struct adder_ {
template <typename Arg1T, typename Arg2T, typename ArgT3>
struct result { typedef Arg1T type; };
template <typename Arg1T, typename Arg2T, typename ArgT3>
Arg1T operator()(Arg1T a, Arg2T b, ArgT3 c) const { return a + b + c; }
};
function<adder_> adder;
///////////////////////////////////////////////////////////////////////////////
int
main()
{
int i2 = 2, i = 4, i50 = 50, i10 = 10, i20 = 20, i100 = 100;
double d5 = 5, d10 = 10;
string hello = "hello";
///////////////////////////////////////////////////////////////////////////////
//
// More complex expressions
//
///////////////////////////////////////////////////////////////////////////////
BOOST_TEST((10 - arg1)(i100) == (10 - i100));
BOOST_TEST((20 - arg1)(i100) == (20 - i100));
BOOST_TEST((arg1 - 10)(i100) == (i100 - 10));
BOOST_TEST((arg1 - 20)(i100) == (i100 - 20));
BOOST_TEST((arg1 - arg2)(i100, i50) == (i100 - i50));
BOOST_TEST((arg1 - var(i))(i10) == (i10 - i));
BOOST_TEST((arg1 + arg2 - arg3)(i100, i50, i20) == (i100 + i50 - i20));
BOOST_TEST((sqr(arg1) + arg2 - arg3)(i100, i50, i20) == ((i100*i100) + i50 - i20));
int ii = i;
BOOST_TEST((var(i) += arg1)(i2) == (ii += i2));
BOOST_TEST((sqr(sqr(arg1)))(i100) == (i100*i100*i100*i100));
#if 0 /*** SHOULD NOT COMPILE ***/
(val(3) += arg1)(i100);
(val(3) = 3)();
#endif
BOOST_TEST(((adder(arg1, arg2, arg3) + arg2 - arg3)(i100, i50, i20)) == (i100 + i50 + i20) + i50 - i20);
BOOST_TEST((adder(arg1, arg2, arg3)(i100, i50, i20)) == (i100 + i50 + i20));
BOOST_TEST((sqr(sqr(sqr(sqr(arg1)))))(d10) == 1e16);
BOOST_TEST((sqr(sqr(arg1)) / arg1 / arg1)(d5) == 25);
for (int j = 0; j < 20; ++j)
{
cout << (10 < arg1)(j);
BOOST_TEST((10 < arg1)(j) == (10 < j));
}
cout << endl;
for (int k = 0; k < 20; ++k)
{
bool r = ((arg1 % 2 == 0) && (arg1 < 15))(k);
cout << r;
BOOST_TEST(r == ((k % 2 == 0) && (k < 15)));
}
cout << endl;
///////////////////////////////////////////////////////////////////////////////
//
// End asserts
//
///////////////////////////////////////////////////////////////////////////////
return boost::report_errors();
}
| 1,361 |
799 | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
HTML_TEMPLATE = (
"</br>"
"<div style='color:#404142; text-align:center; font-size:17px;'>"
"{status}"
"</div>"
"<div class='editable-field-wrapper' style='text-align:center;'>"
"{message}"
"</div>"
"<div draggable='false' class='section-item-content' style='width: 220px; min-height: 22px; padding-top:10px;'>"
"<div class='field-wrapper row'>"
"<div class='header-wrapper'>"
"<span class='header-value label-text opacity-description ellipsis' title='LastMirroredInTime'>"
"LastMirroredInTime"
"</span>"
"</div>"
"<div class='value-wrapper'>"
"<span class=''>"
"<div class='date-field-wrapper small'>"
"<div class='date-display-value-wrapper'>"
"<div class='date-display-value'>"
"{last_mirror_in_time}"
"</div>"
"</div>"
"</div>"
"</span>"
"</div>"
"</div>"
"</div>"
)
def main():
try:
incident = demisto.incident()
custom_fields = incident.get('CustomFields', {})
last_mirror_in_time = custom_fields.get('lastmirroredintime', None)
message = custom_fields.get('incomingmirrorerror', '')
if message == '':
status = 'Not Started'
elif message == 'Mirroring events has reached events limit in this incident.':
status = 'Completed and Stopped'
elif message == 'All available events in the offense were mirrored.':
status = 'Completed'
elif message == 'In queue.':
status = 'In Progress'
else:
status = 'Failure'
html = HTML_TEMPLATE.format(status=status, message=message, last_mirror_in_time=last_mirror_in_time)
return {
'ContentsFormat': 'html',
'Type': entryTypes['note'],
'Contents': html
}
except Exception as exp:
return_error('could not parse QRadar offense', error=exp)
if __name__ in ('__main__', '__builtin__', 'builtins'):
return_results(main())
| 873 |
1,144 | <reponame>dram/metasfresh
/*
* #%L
* metasfresh-webui-api
* %%
* Copyright (C) 2020 metas GmbH
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package de.metas.ui.web.quickinput.ddorderline;
import com.google.common.collect.ImmutableSet;
import de.metas.handlingunits.HUPIItemProductId;
import de.metas.handlingunits.ddorder.api.DDOrderLineCreateRequest;
import de.metas.handlingunits.ddorder.api.IHUDDOrderBL;
import de.metas.product.ProductId;
import de.metas.ui.web.quickinput.IQuickInputProcessor;
import de.metas.ui.web.quickinput.QuickInput;
import de.metas.ui.web.window.datatypes.DocumentId;
import de.metas.util.Services;
import org.eevolution.api.DDOrderLineId;
import org.eevolution.model.I_DD_Order;
import java.math.BigDecimal;
import java.util.Set;
public class DDOrderLineQuickInputProcessor implements IQuickInputProcessor
{
private final IHUDDOrderBL huddOrderBL = Services.get(IHUDDOrderBL.class);
@Override
public Set<DocumentId> process(final QuickInput quickInput)
{
final IDDOrderLineQuickInput ddOrderQuickInput = quickInput.getQuickInputDocumentAs(IDDOrderLineQuickInput.class);
final ProductId productId = ProductId.ofRepoId(ddOrderQuickInput.getM_Product_ID());
final HUPIItemProductId mHUPIProductID = HUPIItemProductId.ofRepoIdOrNull(ddOrderQuickInput.getM_HU_PI_Item_Product_ID());
final BigDecimal qty = ddOrderQuickInput.getQty();
final I_DD_Order ddOrder = quickInput.getRootDocumentAs(I_DD_Order.class);
final DDOrderLineCreateRequest ddOrderLineCreateRequest = DDOrderLineCreateRequest.builder()
.ddOrder(ddOrder)
.productId(productId)
.mHUPIProductID(mHUPIProductID)
.qtyEntered(qty)
.build();
final DDOrderLineId ddOrderLineId = huddOrderBL.addDDOrderLine(ddOrderLineCreateRequest);
final DocumentId documentId = DocumentId.of(ddOrderLineId.getRepoId());
return ImmutableSet.of(documentId);
}
}
| 839 |
482 | package io.cattle.platform.process.externalevent;
import static io.cattle.platform.core.constants.ExternalEventConstants.*;
import static io.cattle.platform.core.model.tables.AgentTable.*;
import static io.cattle.platform.core.model.tables.StackTable.*;
import static io.cattle.platform.core.model.tables.ServiceTable.*;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.ExternalEventConstants;
import io.cattle.platform.core.constants.VolumeConstants;
import io.cattle.platform.core.dao.AccountDao;
import io.cattle.platform.core.dao.GenericResourceDao;
import io.cattle.platform.core.dao.HostDao;
import io.cattle.platform.core.dao.StoragePoolDao;
import io.cattle.platform.core.dao.VolumeDao;
import io.cattle.platform.core.model.Agent;
import io.cattle.platform.core.model.Stack;
import io.cattle.platform.core.model.ExternalEvent;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.core.model.StoragePoolHostMap;
import io.cattle.platform.core.model.Volume;
import io.cattle.platform.docker.process.lock.DockerStoragePoolVolumeCreateLock;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.engine.process.impl.ProcessCancelException;
import io.cattle.platform.lock.LockCallbackNoReturn;
import io.cattle.platform.lock.LockManager;
import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.object.util.DataUtils;
import io.cattle.platform.object.util.ObjectUtils;
import io.cattle.platform.process.base.AbstractDefaultProcessHandler;
import io.cattle.platform.util.type.CollectionUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Named
public class ExternalEventCreate extends AbstractDefaultProcessHandler {
public static final String FIELD_AGENT_ID = "agentId";
private static final Logger log = LoggerFactory.getLogger(ExternalEventCreate.class);
@Inject
AccountDao accountDao;
@Inject
LockManager lockManager;
@Inject
GenericResourceDao resourceDao;
@Inject
StoragePoolDao storagePoolDao;
@Inject
VolumeDao volumeDao;
@Inject
HostDao hostDao;
@Override
public HandlerResult handle(ProcessState state, ProcessInstance process) {
ExternalEvent event = (ExternalEvent)state.getResource();
if (StringUtils.isEmpty(event.getExternalId())) {
log.debug("External event doesn't have an external id: {}", event.getId());
return null;
}
if (ExternalEventConstants.KIND_VOLUME_EVENT.equals(event.getKind())) {
handleVolumeEvent(event, state, process);
} else if (ExternalEventConstants.KIND_STORAGE_POOL_EVENT.equals(event.getKind())) {
handleStoragePoolEvent(event, state, process);
} else if (ExternalEventConstants.KIND_EXTERNAL_DNS_EVENT.equals(event.getKind())) {
handleExternalDnsEvent(event, state, process);
}
return null;
}
// TODO We don't use this logic. Consider completely removing it.
protected void handleVolumeEvent(final ExternalEvent event, ProcessState state, ProcessInstance process) {
//new DockerStoragePoolVolumeCreateLock(storagePool, dVol.getUri())
Object driver = CollectionUtils.getNestedValue(DataUtils.getFields(event), FIELD_VOLUME, VolumeConstants.FIELD_VOLUME_DRIVER);
final Object name = CollectionUtils.getNestedValue(DataUtils.getFields(event), FIELD_VOLUME, FIELD_NAME);
if (driver == null || name == null) {
log.warn("Driver or volume name not specified. Returning. Event: {}", event);
return;
}
String driverName = driver.toString();
List<? extends StoragePool> pools = storagePoolDao.findStoragePoolByDriverName(event.getAccountId(), driverName);
if (pools.size() == 0) {
log.warn("Unknown storage pool. Returning. Driver name: {}", driverName);
return;
}
final StoragePool storagePool = pools.get(0);
lockManager.lock(new DockerStoragePoolVolumeCreateLock(storagePool, event.getExternalId()), new LockCallbackNoReturn() {
@Override
public void doWithLockNoResult() {
Volume volume = volumeDao.findVolumeByExternalId(storagePool.getId(), event.getExternalId());
switch (event.getEventType()) {
case ExternalEventConstants.TYPE_VOLUME_CREATE:
if (volume == null) {
Map<String, Object> volumeData = CollectionUtils.toMap(DataUtils.getFields(event).get(FIELD_VOLUME));
if (volumeData.isEmpty()) {
log.warn("Empty volume for externalVolumeEvent: {}. StoragePool: {}", event, volumeData);
return;
}
volumeData.put(ObjectMetaDataManager.ACCOUNT_FIELD, event.getAccountId());
volumeData.put(FIELD_ATTACHED_STATE, CommonStatesConstants.INACTIVE);
volumeData.put(FIELD_ALLOC_STATE, CommonStatesConstants.ACTIVE);
volumeData.put(FIELD_ZONE_ID, 1L);
volumeData.put(FIELD_DEV_NUM, -1);
try {
volumeDao.createVolumeInStoragePool(volumeData, name.toString(), storagePool);
} catch (ProcessCancelException e) {
log.info("Create process cancelled for volumeData {}. ProcessCancelException message: {}", volumeData, e.getMessage());
}
}
break;
default:
log.error("Unknown event type: {} for event {}", event.getEventType(), event);
return;
}
}
});
}
protected void handleStoragePoolEvent(final ExternalEvent event, ProcessState state, ProcessInstance process) {
lockManager.lock(new ExternalEventLock(STORAGE_POOL_LOCK_NAME, event.getAccountId(), event.getExternalId()), new LockCallbackNoReturn() {
@Override
public void doWithLockNoResult() {
Object driver = CollectionUtils.getNestedValue(DataUtils.getFields(event), FIELD_STORAGE_POOL, FIELD_DRIVER_NAME);
if (driver == null) {
log.warn("Driver not specified. Returning. Event: {}", ObjectUtils.toStringWrapper(event));
return;
}
String driverName = driver.toString();
List<? extends StoragePool> pools = storagePoolDao.findStoragePoolByDriverName(event.getAccountId(), driverName);
StoragePool storagePool = pools.size() > 0 ? pools.get(0) : null;
Map<String, Object> spData = CollectionUtils.toMap(DataUtils.getFields(event).get(FIELD_STORAGE_POOL));
if (spData.isEmpty()) {
log.warn("Null or empty storagePool for externalStoragePoolEvent: {}. StoragePool: {}", event, spData);
return;
}
if (storagePool == null) {
spData.put(ObjectMetaDataManager.ACCOUNT_FIELD, event.getAccountId());
spData.put(FIELD_ZONE_ID, 1L);
Agent agent = objectManager.findOne(Agent.class, AGENT.ACCOUNT_ID, event.getReportedAccountId(),
AGENT.STATE, CommonStatesConstants.ACTIVE);
spData.put(FIELD_AGENT_ID, agent.getId());
try {
storagePool = resourceDao.createAndSchedule(StoragePool.class, spData);
} catch (ProcessCancelException e) {
log.info("Create process cancelled for storagePool {}. ProcessCancelException message: {}", storagePool, e.getMessage());
}
} else {
Agent agent = objectManager.findOne(Agent.class, AGENT.ACCOUNT_ID, event.getReportedAccountId(),
AGENT.STATE, CommonStatesConstants.ACTIVE);
spData.put(FIELD_AGENT_ID, agent.getId());
storagePool.setAgentId(agent.getId());
try {
storagePool = resourceDao.updateAndSchedule(storagePool);
} catch (ProcessCancelException e) {
log.info("Create process cancelled for storagePool {}. ProcessCancelException message: {}", storagePool, e.getMessage());
}
}
List<String> hostUuids = new ArrayList<String>();
for (Object item : CollectionUtils.toList(DataUtils.getFields(event).get(FIELD_HOST_UUIDS))) {
if (item != null)
hostUuids.add(item.toString());
}
Map<Long, StoragePoolHostMap> maps = constructStoragePoolMaps(storagePool, hostUuids);
try {
removeOldMaps(storagePool, maps);
createNewMaps(storagePool, maps);
} catch (ProcessCancelException e) {
log.info("Process cancelled while syncing volumes to storagePool {}. ProcessCancelException message: {}", storagePool, e.getMessage());
}
}
});
}
protected void handleExternalDnsEvent(final ExternalEvent event, ProcessState state, ProcessInstance process) {
lockManager.lock(new ExternalEventLock(EXERNAL_DNS_LOCK_NAME, event.getAccountId(), event.getExternalId()),
new LockCallbackNoReturn() {
@Override
public void doWithLockNoResult() {
String fqdn = DataAccessor.fieldString(event, ExternalEventConstants.FIELD_FQDN);
String serviceName = DataAccessor
.fieldString(event, ExternalEventConstants.FIELD_SERVICE_NAME);
String stackName = DataAccessor.fieldString(event, ExternalEventConstants.FIELD_STACK_NAME);
if (fqdn == null || serviceName == null || stackName == null) {
log.info("External DNS [event: " + event.getId() + "] misses some fields");
return;
}
Stack stack = objectManager.findAny(Stack.class, STACK.ACCOUNT_ID,
event.getAccountId(), STACK.REMOVED, null, STACK.NAME, stackName);
if (stack == null) {
log.info("Stack not found for external DNS [event: " + event.getId() + "]");
return;
}
Service service = objectManager.findAny(Service.class, SERVICE.ACCOUNT_ID,
event.getAccountId(), SERVICE.REMOVED, null, SERVICE.STACK_ID, stack.getId(),
SERVICE.NAME, serviceName);
if (service == null) {
log.info("Service not found for external DNS [event: " + event.getId() + "]");
return;
}
Map<String, Object> data = new HashMap<>();
data.put(ExternalEventConstants.FIELD_FQDN, fqdn);
DataUtils.getWritableFields(service).putAll(data);
objectManager.persist(service);
objectProcessManager.scheduleStandardProcessAsync(StandardProcess.UPDATE, service, data);
}
});
}
protected void createNewMaps(StoragePool storagePool, Map<Long, StoragePoolHostMap> maps) {
for (StoragePoolHostMap m : maps.values()) {
storagePoolDao.createStoragePoolHostMap(m);
}
}
protected void removeOldMaps(StoragePool storagePool, Map<Long, StoragePoolHostMap> newMaps) {
List<? extends StoragePoolHostMap> existingMaps = storagePoolDao.findMapsToRemove(storagePool.getId());
List<StoragePoolHostMap> toRemove = new ArrayList<StoragePoolHostMap>();
for (StoragePoolHostMap m : existingMaps) {
if (!newMaps.containsKey(m.getHostId())) {
toRemove.add(m);
}
}
for (StoragePoolHostMap m : toRemove) {
StoragePoolHostMap remove = storagePoolDao.findNonremovedMap(m.getStoragePoolId(), m.getHostId());
if (remove != null) {
objectProcessManager.scheduleStandardProcess(StandardProcess.REMOVE, remove, null);
}
}
}
protected Map<Long, StoragePoolHostMap> constructStoragePoolMaps(StoragePool storagePool, List<String> hostUuids) {
List<? extends Host> hosts = hostDao.getHosts(storagePool.getAccountId(), hostUuids);
Map<Long, StoragePoolHostMap> maps = new HashMap<Long, StoragePoolHostMap>();
for (Host h : hosts) {
StoragePoolHostMap sphm = objectManager.newRecord(StoragePoolHostMap.class);
sphm.setHostId(h.getId());
sphm.setStoragePoolId(storagePool.getId());
maps.put(h.getId(), sphm);
}
return maps;
}
}
| 6,151 |
1,481 | <filename>src/assets/cmesh.c
#include "assets/cmesh.h"
#include "data/vertex_list.h"
static sphere ctri_bound(ctri t) {
vec3 center = vec3_div(vec3_add(vec3_add(t.a, t.b), t.c), 3);
float radius = 0;
radius = max(radius, vec3_dist_sqrd(t.a, center));
radius = max(radius, vec3_dist_sqrd(t.b, center));
radius = max(radius, vec3_dist_sqrd(t.c, center));
return sphere_new(center, sqrt(radius));
}
ctri ctri_new(vec3 a, vec3 b, vec3 c, vec3 norm) {
ctri t;
t.a = a;
t.b = b;
t.c = c;
t.norm = norm;
t.bound = sphere_unit();
t.bound = ctri_bound(t);
return t;
}
bool ctri_inside_plane(ctri t, plane p) {
return (point_inside_plane(t.a, p) &&
point_inside_plane(t.b, p) &&
point_inside_plane(t.c, p));
}
bool ctri_outside_plane(ctri t, plane p) {
return (point_outside_plane(t.a, p) &&
point_outside_plane(t.b, p) &&
point_outside_plane(t.c, p));
}
bool ctri_intersects_plane(ctri t, plane p) {
return (!ctri_inside_plane(t, p) && !ctri_outside_plane(t, p));
}
ctri ctri_transform(ctri t, mat4 m, mat3 mn) {
t.a = mat4_mul_vec3(m, t.a);
t.b = mat4_mul_vec3(m, t.b);
t.c = mat4_mul_vec3(m, t.c);
t.norm = vec3_normalize(mat3_mul_vec3(mn, t.norm));
t.bound = ctri_bound(t);
return t;
}
ctri ctri_transform_space(ctri t, mat3 s, mat3 sn) {
t.a = mat3_mul_vec3(s, t.a);
t.b = mat3_mul_vec3(s, t.b);
t.c = mat3_mul_vec3(s, t.c);
t.norm = vec3_normalize(mat3_mul_vec3(sn, t.norm));
t.bound = ctri_bound(t);
return t;
}
void cmesh_delete(cmesh* cm) {
if (cm->is_leaf) {
free(cm->triangles);
} else {
cmesh_delete(cm->front);
cmesh_delete(cm->back);
}
free(cm);
}
static vec3 cmesh_center(cmesh* cm) {
if (!cm->is_leaf) {
error("cmesh is not leaf type!");
return vec3_zero();
}
if (cm->triangles_num == 0) {
error("Can't find center of mesh with no triangles");
return vec3_zero();
}
vec3 center = vec3_zero();
for(int i = 0; i < cm->triangles_num; i++) {
center = vec3_add(center, cm->triangles[i].a);
center = vec3_add(center, cm->triangles[i].b);
center = vec3_add(center, cm->triangles[i].c);
}
center = vec3_div(center, cm->triangles_num * 3);
return center;
}
static float cmesh_radius(cmesh* cm) {
if (!cm->is_leaf) {
error("cmesh is not leaf type!");
return 0;
}
vec3 center = cmesh_center(cm);
float radius = 0;
for (int i = 0; i < cm->triangles_num; i++) {
radius = max(radius, vec3_dist(center, cm->triangles[i].a));
radius = max(radius, vec3_dist(center, cm->triangles[i].b));
radius = max(radius, vec3_dist(center, cm->triangles[i].c));
}
return radius;
}
static box cmesh_box(cmesh* cm) {
if (!cm->is_leaf) {
error("cmesh is not leaf type!");
return box_new(0,0,0,0,0,0);
}
if (cm->triangles_num == 0) {
error("Can't find box of mesh with no triangles");
return box_new(0,0,0,0,0,0);
}
float x_min = 0; float x_max = 0;
float y_min = 0; float y_max = 0;
float z_min = 0; float z_max = 0;
for(int i = 0; i < cm->triangles_num; i++) {
x_min = min(x_min, cm->triangles[i].a.x);
x_max = max(x_max, cm->triangles[i].a.x);
y_min = min(y_min, cm->triangles[i].a.y);
y_max = max(y_max, cm->triangles[i].a.y);
z_min = min(z_min, cm->triangles[i].a.z);
z_max = max(z_max, cm->triangles[i].a.z);
x_min = min(x_min, cm->triangles[i].b.x);
x_max = max(x_max, cm->triangles[i].b.x);
y_min = min(y_min, cm->triangles[i].b.y);
y_max = max(y_max, cm->triangles[i].b.y);
z_min = min(z_min, cm->triangles[i].b.z);
z_max = max(z_max, cm->triangles[i].b.z);
x_min = min(x_min, cm->triangles[i].c.x);
x_max = max(x_max, cm->triangles[i].c.x);
y_min = min(y_min, cm->triangles[i].c.y);
y_max = max(y_max, cm->triangles[i].c.y);
z_min = min(z_min, cm->triangles[i].c.z);
z_max = max(z_max, cm->triangles[i].c.z);
}
return box_new(x_min, x_max, y_min, y_max, z_min, z_max);
}
static plane cmesh_division(cmesh* cm) {
box bb = cmesh_box(cm);
plane p;
p.position = cmesh_center(cm);
float x_diff = bb.left.position.x - bb.right.position.x;
float y_diff = bb.top.position.y - bb.bottom.position.y;
float z_diff = bb.front.position.z - bb.back.position.z;
if ((x_diff >= y_diff) &&
(x_diff >= z_diff)) {
p.direction = vec3_new(1,0,0);
} else if ((y_diff >= x_diff) &&
(y_diff >= z_diff)) {
p.direction = vec3_new(0,1,0);
} else if ((z_diff >= x_diff) &&
(z_diff >= y_diff)) {
p.direction = vec3_new(0,0,1);
} else {
p.direction = vec3_new(1,0,0);
}
return p;
}
sphere cmesh_bound(cmesh* cm) {
if (!cm->is_leaf) {
error("cmesh is not leaf type!");
return sphere_new(vec3_zero(), 0);
}
return sphere_new(cmesh_center(cm), cmesh_radius(cm));
}
void cmesh_subdivide(cmesh* cm, int iterations) {
if (!cm->is_leaf) {
error("Attempt to subdivide non-leaf bsp tree!");
return;
}
if (iterations == 0) { return; }
if (cm->triangles_num < 10) { return; }
plane division = cmesh_division(cm);
int num_front = 0;
int num_back = 0;
for(int i = 0; i < cm->triangles_num; i++) {
ctri t = cm->triangles[i];
if (ctri_inside_plane(t, division)) {
num_back++;
} else if (ctri_outside_plane(t, division)) {
num_front++;
} else {
num_back++;
num_front++;
}
}
if (num_front > cm->triangles_num * 0.75) { return; }
if (num_back > cm->triangles_num * 0.75) { return; }
cmesh* front = malloc(sizeof(cmesh));
front->is_leaf = true;
front->triangles_num = num_front;
front->triangles = malloc(sizeof(ctri) * num_front);
cmesh* back = malloc(sizeof(cmesh));
back->is_leaf = true;
back->triangles_num = num_back;
back->triangles = malloc(sizeof(ctri) * num_back);
int i_front = 0;
int i_back = 0;
for(int i = 0; i < cm->triangles_num; i++) {
ctri t = cm->triangles[i];
if (ctri_inside_plane(t, division)) {
back->triangles[i_back] = t;
i_back++;
} else if (ctri_outside_plane(t, division)) {
front->triangles[i_front] = t;
i_front++;
} else {
back->triangles[i_back] = t;
front->triangles[i_front] = t;
i_back++;
i_front++;
}
}
if (front->triangles_num > 0) {
front->bound = cmesh_bound(front);
} else {
front->bound = sphere_new(vec3_zero(), 0);
}
if (back->triangles_num > 0) {
back->bound = cmesh_bound(back);
} else {
back->bound = sphere_new(vec3_zero(), 0);
}
cmesh_subdivide(front, iterations-1);
cmesh_subdivide(back, iterations-1);
free(cm->triangles);
cm->is_leaf = false;
cm->division = division;
cm->front = front;
cm->back = back;
}
static int SDL_RWreadline(SDL_RWops* file, char* buffer, int buffersize) {
char c;
int status = 0;
int i = 0;
while(1) {
status = SDL_RWread(file, &c, 1, 1);
if (status == -1) return -1;
if (i == buffersize-1) return -1;
if (status == 0) break;
buffer[i] = c;
i++;
if (c == '\n') {
buffer[i] = '\0';
return i;
}
}
if(i > 0) {
buffer[i] = '\0';
return i;
} else {
return 0;
}
}
cmesh* col_load_file(char* filename) {
cmesh* cm = malloc(sizeof(cmesh));
cm->is_leaf = true;
vertex_list* vert_positions = vertex_list_new();
vertex_list* vert_triangles = vertex_list_new();
SDL_RWops* file = SDL_RWFromFile(filename, "r");
if(file == NULL) {
error("Could not load file %s", filename);
}
char line[1024];
while(SDL_RWreadline(file, line, 1024)) {
float px, py, pz;
if (sscanf(line, "v %f %f %f", &px, &py, &pz) == 3) {
vertex vert = vertex_new();
vert.position = vec3_new(px, py, pz);
vertex_list_push_back(vert_positions, vert);
}
int pi1, ti1, ni1, pi2, ti2, ni2, pi3, ti3, ni3, pi4;
if (sscanf(line, "f %i// %i// %i// %i//", &pi1, &pi2, &pi3, &pi4) == 4) {
vertex a1 = vertex_list_get(vert_positions, pi1-1);
vertex b1 = vertex_list_get(vert_positions, pi2-1);
vertex c1 = vertex_list_get(vert_positions, pi3-1);
vertex_list_push_back(vert_triangles, a1);
vertex_list_push_back(vert_triangles, b1);
vertex_list_push_back(vert_triangles, c1);
vertex a2 = vertex_list_get(vert_positions, pi1-1);
vertex b2 = vertex_list_get(vert_positions, pi3-1);
vertex c2 = vertex_list_get(vert_positions, pi4-1);
vertex_list_push_back(vert_triangles, a2);
vertex_list_push_back(vert_triangles, b2);
vertex_list_push_back(vert_triangles, c2);
}
else if (sscanf(line, "f %i/%i/%i %i/%i/%i %i/%i/%i", &pi1, &ti1, &ni1, &pi2, &ti2, &ni2, &pi3, &ti3, &ni3) == 9) {
vertex a = vertex_list_get(vert_positions, pi1-1);
vertex b = vertex_list_get(vert_positions, pi2-1);
vertex c = vertex_list_get(vert_positions, pi3-1);
vertex_list_push_back(vert_triangles, a);
vertex_list_push_back(vert_triangles, b);
vertex_list_push_back(vert_triangles, c);
}
else if (sscanf(line, "f %i//%i %i//%i %i//%i", &pi1, &ni1, &pi2, &ni2, &pi3, &ni3) == 6) {
vertex a = vertex_list_get(vert_positions, pi1-1);
vertex b = vertex_list_get(vert_positions, pi2-1);
vertex c = vertex_list_get(vert_positions, pi3-1);
vertex_list_push_back(vert_triangles, a);
vertex_list_push_back(vert_triangles, b);
vertex_list_push_back(vert_triangles, c);
}
else if (sscanf(line, "f %i/%i %i/%i %i/%i", &pi1, &ti1, &pi2, &ti2, &pi3, &ti3) == 6) {
vertex a = vertex_list_get(vert_positions, pi1-1);
vertex b = vertex_list_get(vert_positions, pi2-1);
vertex c = vertex_list_get(vert_positions, pi3-1);
vertex_list_push_back(vert_triangles, a);
vertex_list_push_back(vert_triangles, b);
vertex_list_push_back(vert_triangles, c);
}
else if (sscanf(line, "f %i %i %i", &pi1, &pi2, &pi3) == 3) {
vertex a = vertex_list_get(vert_positions, pi1-1);
vertex b = vertex_list_get(vert_positions, pi2-1);
vertex c = vertex_list_get(vert_positions, pi3-1);
vertex_list_push_back(vert_triangles, a);
vertex_list_push_back(vert_triangles, b);
vertex_list_push_back(vert_triangles, c);
}
else if (sscanf(line, "f %i// %i// %i//", &pi1, &pi2, &pi3) == 3) {
vertex a = vertex_list_get(vert_positions, pi1-1);
vertex b = vertex_list_get(vert_positions, pi2-1);
vertex c = vertex_list_get(vert_positions, pi3-1);
vertex_list_push_back(vert_triangles, a);
vertex_list_push_back(vert_triangles, b);
vertex_list_push_back(vert_triangles, c);
}
}
SDL_RWclose(file);
cm->triangles_num = vert_triangles->num_items / 3;
cm->triangles = malloc(sizeof(ctri) * cm->triangles_num);
for(int i = 0; i < vert_triangles->num_items; i += 3) {
vertex a = vertex_list_get(vert_triangles, i+0);
vertex b = vertex_list_get(vert_triangles, i+1);
vertex c = vertex_list_get(vert_triangles, i+2);
vec3 norm = triangle_normal(a, b, c);
cm->triangles[i / 3] = ctri_new(a.position, b.position, c.position, norm);
}
vertex_list_delete(vert_positions);
vertex_list_delete(vert_triangles);
if (cm->triangles_num != 0) {
cm->bound = cmesh_bound(cm);
} else {
cm->bound = sphere_new(vec3_zero(), 0);
}
cmesh_subdivide(cm, 5);
return cm;
}
| 5,739 |
4,625 | <gh_stars>1000+
// Copyright 2019 JanusGraph 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.
package org.janusgraph.diskstorage.inmemory;
import org.janusgraph.diskstorage.Entry;
import org.janusgraph.diskstorage.EntryList;
import java.util.ArrayList;
import java.util.Iterator;
public class MemoryEntryList extends ArrayList<Entry> implements EntryList {
public MemoryEntryList(int size) {
super(size);
}
@Override
public Iterator<Entry> reuseIterator() {
return iterator();
}
@Override
public int getByteSize() {
int size = 48;
for (Entry e : this) {
size += 8 + 16 + 8 + 8 + e.length();
}
return size;
}
}
| 402 |
2,151 | // Copyright 2013 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 CONTENT_SHELL_RENDERER_SHELL_RENDER_VIEW_OBSERVER_H_
#define CONTENT_SHELL_RENDERER_SHELL_RENDER_VIEW_OBSERVER_H_
#include "base/macros.h"
#include "content/public/renderer/render_view_observer.h"
namespace blink {
class WebLocalFrame;
}
namespace content {
class RenderView;
class ShellRenderViewObserver : public RenderViewObserver {
public:
explicit ShellRenderViewObserver(RenderView* render_view);
~ShellRenderViewObserver() override;
private:
// RenderViewObserver implementation.
void DidClearWindowObject(blink::WebLocalFrame* frame) override;
void OnDestruct() override;
DISALLOW_COPY_AND_ASSIGN(ShellRenderViewObserver);
};
} // namespace content
#endif // CONTENT_SHELL_RENDERER_SHELL_RENDER_VIEW_OBSERVER_H_
| 310 |
564 | /*
* sdbg.c
*
* Debug helpers (data formatting, etc.).
*
* Copyright (c) 2015-2020 <NAME>. All rights reserved.
* Released under the BSD 3-Clause License (see the doc/LICENSE)
*/
#include "sdbg.h"
const char *sv_type_to_label(const enum eSV_Type t)
{
switch (t) {
#define CXSV(t) \
case t: \
return #t
CXSV(SV_I8);
CXSV(SV_U8);
CXSV(SV_I16);
CXSV(SV_U16);
CXSV(SV_I32);
CXSV(SV_U32);
CXSV(SV_I64);
CXSV(SV_U64);
CXSV(SV_F);
CXSV(SV_D);
CXSV(SV_GEN);
default:
break;
}
return "?";
}
void sv_log_obj(srt_string **log, const srt_vector *v)
{
size_t elems;
enum eSV_Type t;
size_t elem_size, i;
srt_string *aux;
const char *buf;
if (!log)
return;
elems = sd_size((const srt_data *)v);
t = v ? (enum eSV_Type)v->d.sub_type : SV_GEN;
elem_size = v ? v->d.elem_size : 0;
ss_cat_printf(log, 512,
"srt_vector: t: %s, elem size: " FMT_ZU ", sz: " FMT_ZU
", { ",
sv_type_to_label(t), elem_size, elems);
i = 0;
aux = ss_alloca(elem_size * 2);
buf = (const char *)sv_get_buffer_r(v);
for (; i < elems; i++) {
ss_cpy_cn(&aux, buf + i * elem_size, elem_size);
ss_cat_enc_hex(log, aux);
if (i + 1 < elems)
ss_cat_cn(log, ", ", 2);
}
ss_cat_c(log, " }\n");
}
struct st_log_context_data {
srt_string **log;
ss_cat_stn tf;
};
static int aux_st_log_traverse(struct STraverseParams *tp)
{
struct st_log_context_data *d =
(struct st_log_context_data *)tp->context;
if (tp->c == ST_NIL) {
ss_cat_printf(d->log, 128, "\nLevel: %u\n",
(unsigned)tp->level);
} else {
const srt_tnode *cn = get_node_r(tp->t, tp->c);
d->tf(d->log, cn, tp->c);
ss_cat_c(d->log, " ");
}
return 0;
}
void st_log_obj(srt_string **log, const srt_tree *t, ss_cat_stn f)
{
ssize_t levels;
struct st_log_context_data context = {log, f};
if (!log)
return;
ss_cpy_c(log, "");
levels = st_traverse_levelorder(t, aux_st_log_traverse, &context);
if (levels == 0)
ss_cat_c(log, "empty tree");
else
ss_cat_printf(log, 128, "\nlevels: %i, nodes: %u\n",
(int)levels, (unsigned)st_size(t));
fprintf(stdout, "%s", ss_to_c(*log));
}
static void ndx2s(char *out, size_t out_max, srt_tndx id)
{
if (id == ST_NIL)
strcpy(out, "nil");
else
snprintf(out, out_max, "%u", (unsigned)id);
}
static int aux_sm_log_traverse(struct STraverseParams *tp)
{
char id[128], l[128], r[128];
char k[4096] = "", v[4096] = "";
srt_string **log = (srt_string **)tp->context;
const srt_tnode *cn;
if (tp->c == ST_NIL) {
ss_cat_printf(log, 128, "\nLevel: %u\n", (unsigned)tp->level);
return 0;
}
cn = get_node_r(tp->t, tp->c);
switch (tp->t->d.sub_type) {
case SM_II32:
sprintf(k, FMT_I32, ((const struct SMapii *)cn)->x.k);
sprintf(v, FMT_I32, ((const struct SMapii *)cn)->v);
break;
case SM_UU32:
sprintf(k, FMT_U32, ((const struct SMapuu *)cn)->x.k);
sprintf(v, FMT_U32, ((const struct SMapuu *)cn)->v);
break;
case SM_II:
case SM_IS:
case SM_IP:
sprintf(k, FMT_I, ((const struct SMapI *)cn)->k);
break;
case SM_SI:
sprintf(k, "%s",
ss_to_c(sso_get((const srt_stringo *)&(
(const struct SMapSI *)cn)
->x.k)));
break;
case SM_SS:
case SM_SP:
sprintf(k, "%s",
ss_to_c(sso_get(
(const srt_stringo *)&((const struct SMapS *)cn)
->k)));
break;
}
switch (tp->t->d.sub_type) {
case SM_II:
sprintf(v, FMT_I, ((const struct SMapII *)cn)->v);
break;
case SM_SI:
sprintf(v, FMT_I, ((const struct SMapSI *)cn)->v);
break;
case SM_IS:
sprintf(k, "%s",
ss_to_c(sso_get((const srt_stringo *)&(
(const struct SMapIS *)cn)
->v)));
break;
case SM_IP:
sprintf(k, "%p", (const void *)((const struct SMapIP *)cn)->v);
break;
case SM_SS:
sprintf(k, "%s",
ss_to_c(sso_get(&((const struct SMapSS *)cn)->s)));
break;
case SM_SP:
sprintf(k, "%p", (const void *)((const struct SMapSP *)cn)->v);
break;
}
ndx2s(id, sizeof(id), tp->c);
ndx2s(l, sizeof(l), cn->x.l);
ndx2s(r, sizeof(r), cn->r);
ss_cat_printf(log, 128, "[%s: (%s, %s) -> (%s, %s; r:%u)] ", id, k, v,
l, r, cn->x.is_red);
return 0;
}
void sm_log_obj(srt_string **log, const srt_map *m)
{
ssize_t levels;
if (!log)
return;
ss_cpy_c(log, "");
levels = st_traverse_levelorder((const srt_tree *)m,
(st_traverse)aux_sm_log_traverse, log);
if (levels == 0)
ss_cat_c(log, "empty map");
else
ss_cat_printf(log, 128, "\nlevels: %i, nodes: %u\n",
(int)levels, (unsigned)st_size(m));
fprintf(stdout, "%s", ss_to_c(*log));
}
void shm_log_obj(srt_string **log, const srt_hmap *h)
{
size_t es, i;
const struct SHMBucket *b;
const struct SHMapii *e;
if (!log)
return;
ss_cpy_c(log, "");
switch (h->d.sub_type) {
case SHM0_II32:
case SHM0_UU32:
b = shm_get_buckets_r(h);
e = (const struct SHMapii *)shm_get_buffer_r(h);
ss_cat_printf(log, 128,
"hbits: %u, size: " FMT_ZU ", max_size: " FMT_ZU
"\n",
h->hbits, shm_size(h), shm_max_size(h));
for (i = 0; i < (size_t)h->hmask + 1; i++) {
ss_cat_printf(log, 128,
"b[" FMT_ZU
"] h: %08x "
"l: %u cnt: %u\n",
i, b[i].hash, b[i].loc, b[i].cnt);
}
es = shm_size(h);
for (i = 0; i < es; i++)
ss_cat_printf(log, 128, "e[" FMT_ZU "] kv: %u, %u\n", i,
e[i].x.k, e[i].v);
break;
default:
ss_cpy_c(log, "[not implemented]");
break;
}
}
void s_hex_dump(srt_string **log, const char *label, const char *buf,
size_t buf_size)
{
srt_string *aux;
if (!log)
return;
aux = ss_dup_cn(buf, buf_size);
if (label)
ss_cat_c(log, label);
ss_cat_enc_hex(log, aux);
ss_free(&aux);
}
| 3,058 |
303 | <gh_stars>100-1000
#ifndef _LANG_CONTEXT_HEADER
#define _LANG_CONTEXT_HEADER
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#define _CRTDBG_MAP_ALLOC
//#define _CRTDBG_MAP_ALLOC_NEW
#include <crtdbg.h>
#endif
#include <functional>
#include <string>
#include <map>
#include <algorithm>
#include "Value.h"
#include "VMStack.h"
#include "Parser.h"
#include "JetInstructions.h"
#include "JetExceptions.h"
#include "GarbageCollector.h"
#ifdef _WIN32
#include <Windows.h>
//#define JET_TIME_EXECUTION
#endif
#define GC_INTERVAL 200//number of allocations before running the GC
#define GC_STEPS 4//number of g0 collections before a gen1 collection
#define JET_STACK_SIZE 800
#define JET_MAX_CALLDEPTH 400
namespace Jet
{
typedef std::function<void(Jet::JetContext*,Jet::Value*,int)> JetFunction;
#define JetBind(context, fun) auto temp__bind_##fun = [](Jet::JetContext* context,Jet::Value* args, int numargs) { return Value(fun(args[0]));};context[#fun] = Jet::Value(temp__bind_##fun);
//void(*temp__bind_##fun)(Jet::JetContext*,Jet::Value*,int)> temp__bind_##fun = &[](Jet::JetContext* context,Jet::Value* args, int numargs) { context->Return(fun(args[0]));}; context[#fun] = &temp__bind_##fun;
#define JetBind2(context, fun) auto temp__bind_##fun = [](Jet::JetContext* context,Jet::Value* args, int numargs) { return Value(fun(args[0],args[1]));};context[#fun] = Jet::Value(temp__bind_##fun);
#define JetBind3(context, fun, type) auto temp__bind_##fun = [](Jet::JetContext* context,Jet::Value* args, int numargs) { return Value(fun((type)args[0],(type)args[1]));};context[#fun] = Jet::Value(temp__bind_##fun);
//builtin function definitions
Value gc(JetContext* context,Value* args, int numargs);
Value print(JetContext* context,Value* args, int numargs);
Value tostring(JetContext* context, Value* args, int numargs);
class JetContext
{
friend struct Generator;
friend struct Value;
friend class JetObject;
friend class GarbageCollector;
VMStack<Value> stack;
VMStack<std::pair<unsigned int, Closure*> > callstack;
std::map<std::string, Function*> functions;
std::vector<Function*> entrypoints;
std::map<std::string, unsigned int> variables;//mapping from string to location in vars array
//actual data being worked on
std::vector<Value> vars;//where they are actually stored
CompilerContext compiler;//root compiler context
//core library prototypes
JetObject* string;
JetObject* Array;
JetObject* object;
JetObject* arrayiter;
JetObject* objectiter;
JetObject* function;
//require cache
std::map<std::string, Value> require_cache;
std::map<std::string, Value> libraries;
//manages memory
GarbageCollector gc;
std::vector<JetObject*> prototypes;
Closure* lastadded;
struct OpenCapture
{
Capture* capture;
#ifdef _DEBUG
Closure* creator;
#endif
};
std::deque<OpenCapture> opencaptures;
public:
//use these
Value NewObject();
Value NewArray();
Value NewUserdata(void* data, const Value& proto);
Value NewString(const char* string, bool copy = true);//if copy is false, it takes ownership of the char array
void AddLibrary(const std::string& name, Value& library)
{
library.AddRef();
this->libraries[name] = library;
}
//a helper function for registering metatables for userdata, these are never gc'd
//and are freed with the context
Value NewPrototype(const char* Typename);
JetContext();
~JetContext();
//allows assignment and reading of gobal variables
Value& operator[](const std::string& id);
Value Get(const std::string& name);
void Set(const std::string& name, const Value& value);
std::string Script(const std::string code, const std::string filename = "file");
Value Script(const char* code, const char* filename = "file");//compiles, assembles and executes the script
//compiles source code to ASM for the VM to read in
std::vector<IntermediateInstruction> Compile(const char* code, const char* filename = "file");
//parses in ASM, returns a function
Value Assemble(const std::vector<IntermediateInstruction>& code);
//executes a function in the VM context
Value Call(const char* function, Value* args = 0, unsigned int numargs = 0);
Value Call(const Value* function, Value* args = 0, unsigned int numargs = 0);
void RunGC();//runs an iteration of the garbage collector
private:
Value* sptr;//stack pointer
Closure* curframe;
Value localstack[JET_STACK_SIZE];
//begin executing instructions at iptr index
Value Execute(int iptr, Closure* frame);
unsigned int Call(const Value* function, unsigned int iptr, unsigned int args);//used for calls in the VM
//debug functions
void GetCode(int ptr, Closure* closure, std::string& ret, unsigned int& line);
void StackTrace(int curiptr, Closure* cframe);
static Value Callstack(JetContext* context, Value* v, int ar);
};
}
#endif | 1,692 |
348 | {"nom":"Sireix","circ":"2ème circonscription","dpt":"Hautes-Pyrénées","inscrits":54,"abs":20,"votants":34,"blancs":1,"nuls":0,"exp":33,"res":[{"nuance":"RDG","nom":"<NAME>","voix":26},{"nuance":"REM","nom":"<NAME>","voix":7}]} | 95 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-7qw8-4g2g-2m86",
"modified": "2022-05-13T01:28:35Z",
"published": "2022-05-13T01:28:35Z",
"aliases": [
"CVE-2013-5709"
],
"details": "The authentication implementation in the web server on Siemens SCALANCE X-200 switches with firmware before 5.0.0 does not use a sufficient source of entropy for generating values of random numbers, which makes it easier for remote attackers to hijack sessions by predicting a value.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2013-5709"
},
{
"type": "WEB",
"url": "https://cert-portal.siemens.com/productcert/pdf/ssa-850708.pdf"
},
{
"type": "WEB",
"url": "http://ics-cert.us-cert.gov/advisories/ICSA-13-254-01"
},
{
"type": "WEB",
"url": "http://www.siemens.com/corporate-technology/pool/de/forschungsfelder/siemens_security_advisory_ssa-850708.pdf"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 494 |
2,389 | <reponame>Ankit01Mishra/java
/*
Copyright 2020 The Kubernetes 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.
*/
package io.kubernetes.client.examples;
import io.kubernetes.client.Copy;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.util.Config;
import io.kubernetes.client.util.Streams;
import io.kubernetes.client.util.exception.CopyNotSupportedException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
/**
* A simple example of how to use the Java API
*
* <p>Easiest way to run this: mvn exec:java
* -Dexec.mainClass="io.kubernetes.client.examples.CopyExample"
*
* <p>From inside $REPO_DIR/examples
*/
public class CopyExample {
public static void main(String[] args)
throws IOException, ApiException, InterruptedException, CopyNotSupportedException {
String podName = "kube-addon-manager-minikube";
String namespace = "kube-system";
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
Copy copy = new Copy();
InputStream dataStream = copy.copyFileFromPod(namespace, podName, "/etc/motd");
Streams.copy(dataStream, System.out);
copy.copyDirectoryFromPod(namespace, podName, null, "/etc", Paths.get("/tmp/etc"));
System.out.println("Done!");
}
}
| 603 |
314 | <gh_stars>100-1000
/*****************************************************************************
* ------------------------------------------------------------------------- *
* 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.google.mu.protobuf.util;
import static java.util.Arrays.stream;
import java.util.stream.Collector;
import javax.annotation.Nullable;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.protobuf.ListValue;
import com.google.protobuf.NullValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
/**
* Additional utilities to help create {@link Value} and {@link ListValue} messages.
*
* @since 5.8
*/
@CheckReturnValue
public final class MoreValues {
/** The {@link Value} for null. */
public static final Value NULL =
Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build();
/** The {@link Value} for boolean {@code true}. */
public static final Value TRUE = Value.newBuilder().setBoolValue(true).build();
/** The {@link Value} for boolean {@code false}. */
public static final Value FALSE = Value.newBuilder().setBoolValue(false).build();
/** Returns {@link Value} wrapper for {@code string} if not null, or else returns {@link #NULL}. */
public static Value nullableValueOf(@Nullable String string) {
return string == null ? NULL : valueOf(string);
}
/** Returns {@link ListValue} wrapping {@code values}. */
public static ListValue listValueOf(double... values) {
return stream(values).mapToObj(MoreValues::valueOf).collect(toListValue());
}
/**
* Returns {@link ListValue} wrapping {@code values}.
* Null strings are converted to {@link NULL}.
*/
public static ListValue listValueOf(@Nullable String... values) {
return stream(values).map(MoreValues::nullableValueOf).collect(toListValue());
}
/**
* Returns {@link ListValue} wrapping {@code values}.
* Null structs are converted to {@link NULL}.
*/
public static ListValue listValueOf(@Nullable Struct... values) {
return stream(values).map(MoreValues::nullableValueOf).collect(toListValue());
}
/** Returns a {@link Collector} that collects the input values into {@link ListValue}. */
public static Collector<Value, ?, ListValue> toListValue() {
return Collector.of(
ListValue::newBuilder,
ListValue.Builder::addValues,
(a, b) -> a.addAllValues(b.getValuesList()),
ListValue.Builder::build);
}
static Value valueOf(double n) {
return Value.newBuilder().setNumberValue(n).build();
}
static Value valueOf(boolean b) {
return b ? TRUE : FALSE;
}
static Value valueOf(String s) {
return Value.newBuilder().setStringValue(s).build();
}
static Value valueOf(Struct v) {
return Value.newBuilder().setStructValue(v).build();
}
static Value valueOf(ListValue v) {
return Value.newBuilder().setListValue(v).build();
}
/** Returns {@link Value} wrapper for {@code struct} if not null, or else returns {@link #NULL}. */
private static Value nullableValueOf(@Nullable Struct struct) {
return struct == null ? NULL : valueOf(struct);
}
private MoreValues() {}
}
| 1,407 |
16,989 | // Copyright 2020 The Bazel 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.
package com.google.devtools.build.lib.testing.common;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.Options;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link FakeOptions} utility. */
@RunWith(JUnit4.class)
public class FakeOptionsTest {
@Test
public void getOptions_unspecifiedClass_returnsNull() {
OptionsProvider optionsProvider = FakeOptions.builder().put(new TestOptions()).build();
assertThat(optionsProvider.getOptions(TestOptions2.class)).isNull();
}
@Test
public void getOptions_returnsProvidedValue() {
TestOptions options = new TestOptions();
options.value = "value";
OptionsProvider optionsProvider = FakeOptions.builder().put(options).build();
assertThat(optionsProvider.getOptions(TestOptions.class)).isEqualTo(options);
}
@Test
public void getOptions_of_returnsOnlyProvidedValue() {
TestOptions options = new TestOptions();
options.value = "value";
OptionsProvider optionsProvider = FakeOptions.of(options);
assertThat(optionsProvider.getOptions(TestOptions.class)).isEqualTo(options);
assertThat(optionsProvider.getOptions(TestOptions2.class)).isNull();
}
@Test
public void getOptions_specifiedDefaultsClass_returnsDefaultOptions() {
assertGetOptionsReturnsDefaults(
FakeOptions.builder().putDefaults(TestOptions.class, TestOptions2.class).build());
}
@Test
public void getOptions_ofDefaults_returnsDefaultOptions() {
assertGetOptionsReturnsDefaults(FakeOptions.ofDefaults(TestOptions.class, TestOptions2.class));
}
private static void assertGetOptionsReturnsDefaults(OptionsProvider optionsProvider) {
assertThat(optionsProvider.getOptions(TestOptions.class))
.isEqualTo(Options.getDefaults(TestOptions.class));
assertThat(optionsProvider.getOptions(TestOptions2.class))
.isEqualTo(Options.getDefaults(TestOptions2.class));
}
@Test
public void getStarlarkOptions_returnsEmpty() {
OptionsProvider optionsProvider =
FakeOptions.builder().put(new TestOptions()).putDefaults(TestOptions2.class).build();
assertThat(optionsProvider.getStarlarkOptions()).isEmpty();
}
@Test
public void getStarlarkOptions_emptyOptions_returnsEmpty() {
assertThat(FakeOptions.builder().build().getStarlarkOptions()).isEmpty();
}
@Test
public void build_specifiedValueTwiceForSameClass_fails() {
FakeOptions.Builder builder =
FakeOptions.builder().put(new TestOptions()).put(new TestOptions());
assertThrows(IllegalArgumentException.class, builder::build);
}
@Test
public void build_specifiedValueAndDefaultsForSameClass_fails() {
FakeOptions.Builder builder =
FakeOptions.builder().put(new TestOptions()).putDefaults(TestOptions.class);
assertThrows(IllegalArgumentException.class, builder::build);
}
@Test
public void build_defaultsTwiceForSameClass_fails() {
FakeOptions.Builder builder =
FakeOptions.builder().putDefaults(TestOptions.class, TestOptions.class);
assertThrows(IllegalArgumentException.class, builder::build);
}
/** Simple test option class example. */
public static final class TestOptions extends OptionsBase {
@Option(
name = "option1",
defaultValue = "TestOptions default",
effectTags = OptionEffectTag.NO_OP,
documentationCategory = OptionDocumentationCategory.UNDOCUMENTED)
public String value;
}
/** Simple test option class, different from {@link TestOptions}. */
public static final class TestOptions2 extends OptionsBase {
@Option(
name = "option2",
defaultValue = "TestOptions2 default",
effectTags = OptionEffectTag.NO_OP,
documentationCategory = OptionDocumentationCategory.UNDOCUMENTED)
public String value;
}
}
| 1,475 |
335 | {
"word": "Shipbuilding",
"definitions": [
"The design and construction of ships."
],
"parts-of-speech": "Noun"
} | 59 |
1,775 | <reponame>nightfuryyy/mmpose<filename>.dev_scripts/github/update_copyright.py<gh_stars>1000+
#!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import re
import sys
HEADER = 'Copyright (c) OpenMMLab. All rights reserved.\n'
HEADER_KEYWORDS = {'Copyright', 'License'}
def contains_header(lines, comment_symbol, max_header_lines):
for line in lines[:max_header_lines]:
if line.startswith('#!'):
# skip shebang line
continue
elif re.match(f'{comment_symbol}.*({"|".join(HEADER_KEYWORDS)})',
line):
return True
return False
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'files',
type=str,
nargs='*',
help='Files to add copyright header. If an empty list is given, '
'search target files according to "--src", "--exclude" and '
'"--suffixes"')
parser.add_argument(
'--src', type=str, default=None, help='Root path to search files.')
parser.add_argument(
'--exclude', type=str, default=None, help='Path to exclude in search.')
parser.add_argument(
'--suffixes',
type=str,
nargs='+',
default=['.py', '.c', '.cpp', '.cu', '.sh'],
help='Only files with one of the given suffixes will be searched.')
parser.add_argument(
'--max-header-lines',
type=int,
default=5,
help='Only checkout copyright information in the first several lines '
'of a file.')
args = parser.parse_args()
return args
def main():
args = parse_args()
file_list = []
if args.files:
file_list = args.files
else:
assert args.src is not None
for root, _, files in os.walk(args.src):
if args.exclude and osp.realpath(root).startswith(
osp.realpath(args.exclude)):
continue
for file in files:
if osp.splitext(file)[1] in args.suffixes:
file_list.append(osp.join(root, file))
modified = False
for file in file_list:
suffix = osp.splitext(file)[1]
if suffix in {'.py', '.sh'}:
comment_symbol = '# '
elif suffix in {'.c', '.cpp', '.cu'}:
comment_symbol = '// '
else:
raise ValueError(f'Comment symbol of files with suffix {suffix} '
'is unspecified.')
with open(file, 'r') as f:
lines = f.readlines()
if not contains_header(lines, comment_symbol, args.max_header_lines):
if lines and lines[0].startswith('#!'):
lines.insert(1, comment_symbol + HEADER)
else:
lines.insert(0, comment_symbol + HEADER)
with open(file, 'w') as f:
f.writelines(lines)
modified = True
return int(modified)
if __name__ == '__main__':
sys.exit(main())
| 1,406 |
23,439 | /*
* Copyright 1999-2020 Alibaba Group Holding 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.alibaba.nacos.common.utils;
/**
* Number utils.
* @author zzq
*/
public class NumberUtils {
/**
* Convert a <code>String</code> to an <code>int</code>, returning
* <code>zero</code> if the conversion fails.
*
* @param str the string to convert, may be null
* @return the int represented by the string, or <code>zero</code> if
* conversion fails
*/
public static int toInt(String str) {
return toInt(str, 0);
}
/**
* Convert a <code>String</code> to an <code>int</code>, returning a
* default value if the conversion fails.
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the int represented by the string, or the default if conversion fails
*/
public static int toInt(String str, int defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.parseInt(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
/**
* Convert a <code>String</code> to a <code>long</code>, returning a
* default value if the conversion fails.
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the long represented by the string, or the default if conversion fails
*/
public static long toLong(String str, long defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Long.parseLong(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
/**
* Convert a <code>String</code> to a <code>double</code>, returning a
* default value if the conversion fails.
*
* @param str the string to convert, may be <code>null</code>
* @param defaultValue the default value
* @return the double represented by the string, or defaultValue
* if conversion fails
*/
public static double toDouble(String str, double defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
/**
* Checks whether the <code>String</code> contains only
* digit characters.
*
* @param str the <code>String</code> to check
* @return <code>true</code> if str contains only unicode numeric
*/
public static boolean isDigits(String str) {
if (StringUtils.isEmpty(str)) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* Convert a <code>String</code> to a <code>float</code>, returning
* <code>0.0f</code> if the conversion fails.
*
* @param str the string to convert, may be <code>null</code>
* @return the float represented by the string, or <code>0.0f</code>
* if conversion fails
*/
public static float toFloat(final String str) {
return toFloat(str, 0.0f);
}
/**
* Convert a <code>String</code> to a <code>float</code>, returning a
* default value if the conversion fails.
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the float represented by the string, or defaultValue
* if conversion fails
*/
public static float toFloat(final String str, final float defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Float.parseFloat(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
}
| 1,796 |
385 | #ifndef Corrade_Interconnect_Connection_h
#define Corrade_Interconnect_Connection_h
/*
This file is part of Corrade.
Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
2017, 2018, 2019, 2020, 2021
<NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/** @file
* @brief Class @ref Corrade::Interconnect::Connection
*/
#include <cstddef>
#include "Corrade/Containers/Reference.h"
#include "Corrade/Interconnect/Interconnect.h"
#include "Corrade/Interconnect/visibility.h"
namespace Corrade { namespace Interconnect {
namespace Implementation {
struct SignalDataHash;
enum: std::size_t { FunctionPointerSize =
#ifndef CORRADE_TARGET_WINDOWS
2*sizeof(void*)/sizeof(std::size_t)
#else
/* On MSVC, pointers to members with a virtual base class
are the biggest and have 16 bytes both on 32bit and 64bit. */
16/sizeof(std::size_t)
#endif
};
class SignalData {
public:
#ifndef CORRADE_MSVC2019_COMPATIBILITY
template<class Emitter, class ...Args> SignalData(typename Emitter::Signal(Emitter::*signal)(Args...)): data() {
typedef typename Emitter::Signal(Emitter::*BaseSignal)(Args...);
*reinterpret_cast<BaseSignal*>(data) = signal;
}
#else
/* MSVC is not able to detect template parameters, so I need to
shovel these in explicitly using "static constructor" */
template<class Emitter, class ...Args> static SignalData create(typename Emitter::Signal(Emitter::*signal)(Args...)) {
/* Member function pointers on Windows have different size
based on whether the class has no/single inheritance,
multiple inheritance or virtual inheritance. Casting to
(Emitter::*) which has no inheritance (like done for other
platforms) would thus lose information and cause problems
when classes with multiple or virtual inheritance are used,
so we create a new type, virtually inherited from emitter,
cast the pointer to that and then save its representation. */
SignalData d;
struct VirtuallyInheritedEmitter: virtual Emitter {};
typedef typename Emitter::Signal(VirtuallyInheritedEmitter::*VirtuallyDerivedSignal)(Args...);
*reinterpret_cast<VirtuallyDerivedSignal*>(d.data) = signal;
return d;
}
#endif
bool operator==(const SignalData& other) const {
for(std::size_t i = 0; i != FunctionPointerSize; ++i)
if(data[i] != other.data[i]) return false;
return true;
}
bool operator!=(const SignalData& other) const {
return !operator==(other);
}
private:
/* https://bugzilla.gnome.org/show_bug.cgi?id=776986 */
#ifndef DOXYGEN_GENERATING_OUTPUT
friend Interconnect::Emitter;
friend SignalDataHash;
#endif
#ifdef CORRADE_MSVC2019_COMPATIBILITY
SignalData(): data() {}
#endif
std::size_t data[FunctionPointerSize];
};
}
/**
@brief Connection
Returned by @ref Interconnect::connect(), allows to remove the connection
later using @ref Interconnect::disconnect(). Destruction of the @ref Connection
object does not remove the connection, after that the only possibility to
remove the connection is to disconnect the whole emitter or receiver or
disconnect everything connected to given signal using
@ref Emitter::disconnectSignal(), @ref Emitter::disconnectAllSignals() or
@ref Receiver::disconnectAllSlots(), or destroy either the emitter or receiver
object.
@see @ref interconnect, @ref Emitter, @ref Receiver
*/
class CORRADE_INTERCONNECT_EXPORT Connection {
public:
#ifdef CORRADE_BUILD_DEPRECATED
/**
* @brief Whether the connection exists
* @m_deprecated_since{2019,10} This function is dangerous as it has no
* way to check that the original @ref Emitter object still
* exists, use @ref Emitter::isConnected() instead.
*/
CORRADE_DEPRECATED("dangerous, use Emitter::isConnected() instead") bool isConnected() const;
/**
* @brief Remove the connection
* @m_deprecated_since{2019,10} This function is dangerous as it has no
* way to check that the original @ref Emitter object still
* exists, use @ref Interconnect::disconnect() instead.
*/
CORRADE_DEPRECATED("dangerous, use Interconnect::disconnect() instead") void disconnect();
/**
* @brief Whether connection is possible
* @m_deprecated_since{2019,10} Re-connecting a disconnected signal is
* not possible anymore in order to make the library more
* efficient. This function now just returns the value of (also
* deprecated) @ref isConnected().
*/
CORRADE_DEPRECATED("re-connecting a disconnected signal is not possible anymore") bool isConnectionPossible() const {
CORRADE_IGNORE_DEPRECATED_PUSH
return isConnected();
CORRADE_IGNORE_DEPRECATED_POP
}
/**
* @brief Re-establish the connection
* @m_deprecated_since{2019,10} Re-connecting a disconnected signal is
* not possible anymore in order to make the library more
* efficient. This function now just returns the value of (also
* deprecated) @ref isConnected().
*/
CORRADE_DEPRECATED("re-connecting a disconnected signal is not possible anymore") bool connect() {
CORRADE_IGNORE_DEPRECATED_PUSH
return isConnected();
CORRADE_IGNORE_DEPRECATED_POP
}
#endif
#ifdef DOXYGEN_GENERATING_OUTPUT
private:
#endif
explicit Connection(
#ifdef CORRADE_BUILD_DEPRECATED
Emitter& emitter,
#endif
Implementation::SignalData signal, Implementation::ConnectionData& data);
private:
/* https://bugzilla.gnome.org/show_bug.cgi?id=776986 */
#ifndef DOXYGEN_GENERATING_OUTPUT
friend Emitter;
friend Receiver;
friend CORRADE_INTERCONNECT_EXPORT bool disconnect(Emitter&, const Connection&);
#endif
#ifdef CORRADE_BUILD_DEPRECATED
Containers::Reference<Emitter> _emitter;
#endif
Implementation::SignalData _signal;
/* Note: this might become dangling at some point */
Implementation::ConnectionData* _data;
};
}}
#endif
| 3,139 |
680 | <filename>ff4j-core/src/test/java/org/ff4j/test/strategy/el/ExpressionParserTest.java
package org.ff4j.test.strategy.el;
/*
* #%L
* ff4j-core
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2013 Ff4J
* %%
* 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.
* #L%
*/
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import junit.framework.TestCase;
import org.ff4j.strategy.el.ExpressionNode;
import org.ff4j.strategy.el.ExpressionOperator;
import org.ff4j.strategy.el.ExpressionParser;
import org.junit.Test;
/**
* Unit Testing
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class ExpressionParserTest extends TestCase {
/**
* Check Expression Parsing.
*
* @param expression
* @param state
* @param expected
*/
private void assertNode(String expression, Map<String, Boolean> state, boolean expected) {
ExpressionNode n = ExpressionParser.parseExpression(expression);
Assert.assertEquals(expected, n.evalue(state));
}
/**
* Check Expression parsing
*
* @param expected
* expected output toString()
* @param input
* expression
*/
private void assertOutPut(String expected, String input) {
Assert.assertEquals(expected, ExpressionParser.parseExpression(input).toString());
}
@Test
public void testInit() {
ExpressionNode en = new ExpressionNode("sheet");
en.setOperator(ExpressionOperator.NOT);
en.setValue("sheet");
}
@Test
public void testBlank() {
Map<String, Boolean> state = new HashMap<String, Boolean>();
state.put("A", true);
assertNode("|", state, false);
}
@Test
public void testExpresionA() {
Map<String, Boolean> state = new HashMap<String, Boolean>();
state.put("A", true);
assertNode("A", state, true);
}
@Test
public void testExpresionNotA() {
Map<String, Boolean> state = new HashMap<String, Boolean>();
state.put("A", true);
assertNode("!A", state, false);
}
@Test
public void testExpresionAOrB() {
Map<String, Boolean> state = new HashMap<String, Boolean>();
state.put("A", false);
state.put("B", false);
assertNode("A|B", state, false);
state.put("B", true);
assertNode("A|B", state, true);
}
@Test
public void testExpresionAAndB() {
Map<String, Boolean> state = new HashMap<String, Boolean>();
state.put("A", true);
state.put("B", false);
assertNode("A&B", state, false);
state.put("B", true);
assertNode("A&B", state, true);
}
@Test
public void testOperateurPriority1() {
assertOutPut("A OR (B AND C)", "A|B&C");
}
@Test
public void testOperateurPriorite2() {
assertOutPut("A OR (B AND C) OR D", "A|B&C|D");
}
@Test
public void testExpresionNot() {
assertOutPut("(!A) OR (B AND (!C)) OR D", " !A | B&!C | D");
}
@Test
public void testExpresionsWithParenthesis() {
assertOutPut("(A OR B) AND (C OR D)", "(A|B) & (C|D)");
}
@Test
public void testParenthesis3TermsWithNot() {
assertOutPut("(A OR B) AND (C OR D OR (!E))", "(A|B) & (C|D|!E)");
}
@Test
public void testParenthesisSingleNot() {
assertOutPut("(!C) AND (A OR B)", "(A|B) & !C");
}
@Test
public void testNotBeforeParenthesis() {
assertOutPut("(A OR B) AND (!(C OR D))", "(A|B) & !(C|D)");
}
@Test
public void testEmbeddedParenthesis() {
assertOutPut("(A OR B) AND (((E AND F) OR G) OR (H AND I))", "(A|B) & ( (E&F|G) | (H&I) )");
}
@Test
public void testDeepTree() {
ExpressionNode n = ExpressionParser
.parseExpression("( (sampleA|sampleB) & (C|D|!B) & !(A|D) ) | ( (A&B&C)|(C&D)|((A|B)&D) )");
Assert.assertEquals(2, n.getSubNodes().size());
Assert.assertEquals(ExpressionOperator.OR, n.getOperator());
}
@Test
public void testConstructor() {
try {
Constructor<ExpressionParser> ce = ExpressionParser.class.getDeclaredConstructor();
ce.setAccessible(true);
ce.newInstance();
} catch (Exception e) {
fail();
}
}
@Test
public void testValuesOf() {
ExpressionOperator eo = ExpressionOperator.valueOf("OR");
Assert.assertNotNull(eo);
Assert.assertTrue(ExpressionOperator.values().length > 0);
}
}
| 2,150 |
410 | {
"category": "toberone-gate",
"dId": "e8a979de28fef3fdc3a5f6ee1c971260273dd814493fa1760d0b098c",
"date_publish": "2016-11-08 17:04:00",
"description": "TOBLERONE has angered consumers for shrinking its famous triangular chocolate chunks but the company insists Brexit is not to blame.",
"filename": "e8a979de28fef3fdc3a5f6ee1c971260273dd814493fa1760d0b098c",
"fiveWoneH": {
"how": {
"annotated": [
{
"coderPhraseCount": 3,
"text": "shrinks chocolate bar"
},
{
"coderPhraseCount": 1,
"text": "denies Brexit link"
}
],
"label": "how"
},
"what": {
"annotated": [
{
"coderPhraseCount": 3,
"text": "shrinks chocolate bar"
},
{
"coderPhraseCount": 2,
"text": "outraged"
}
],
"label": "what"
},
"when": {
"annotated": [
{
"coderPhraseCount": 3,
"parsed": "2016-11-08"
}
],
"label": "when"
},
"where": {
"annotated": [
{
"coderPhraseCount": 2
}
],
"label": "where"
},
"who": {
"annotated": [
{
"coderPhraseCount": 3,
"text": "Toblerone"
},
{
"coderPhraseCount": 2,
"text": "Toblerone lovers"
}
],
"label": "who"
},
"why": {
"annotated": [
{
"coderPhraseCount": 3,
"text": "rising cost of ingredients"
}
],
"label": "why"
}
},
"mimeType": "text/xml",
"originalFilename": "express-7",
"parsingError": "true",
"publisher": "express",
"text": "PA Toblerone lovers outraged as favourite chocolate bar is redesigned The iconic chocolate bar is distinctive in its peaking pyramid-like shapes filled with chunks of nougat. But makers Mondelez International has decided to widen the gap between the triangular pieces, thereby narrowing the amount of chocolate. The company insists the move was due to the rising cost of ingredients, which left it with the choice to either change the shape of increase price. But rather than relief the prices will stay the same, many customers have criticised the downsize and blamed it on the UK's decision to leave the EU. REUTERS Some of the bars have longer gaps between the previously tight-knit chocolate peaks It's all about production costs and the cost of ingredients. It's not related to Brexit Gemma Pryor Gemma Pryor from Mondelez International told Express.co.uk: \"It's all about production costs and the cost of ingredients. It's not related to Brexit. \"We don't take these decisions lightly at all. We were certainly looking into this pre-Brexit.\" Mondelez has responded to the rising ingredient costs seen over the last few months, but insists the projection is far longer term. Ms Pryor said: \"Everyone is finding the ingredient costs for food products are rising, but we mostly look at long term trends. We would look at the five- or three-year trends of cocoa prices as well as prices from the last three months.\" The weight of 400g bars has been decreased to 360g while the 170g bars are now just 150g. Sharing the new-look chocolate on its Facebook page, Toblerone wrote: \"We chose to change the shape to keep the product affordable for our customers, and it enables us to keep offering a great value product. \"It had to make a decision between changing the look of the bars or raising their price.\" But it's invited a heavy backlash of criticism on social media. REUTERS Customers are now getting nearly 10 per cent less of their favourite bar REUTERS The design change was described as looking like a 'toothless comb'",
"title": "Toblerone shrinks chocolate bar and denies Brexit link",
"url": "http://www.express.co.uk/life-style/food/730108/Toblerone-shrinks-chocolate-bar-denies-Brexit-link"
} | 1,445 |
930 | package com.foxinmy.weixin4j.response;
/**
* 回复视频消息
*
* @className VideoResponse
* @author jinyu(<EMAIL>)
* @date 2015年5月5日
* @since JDK 1.6
* @see
*/
public class VideoResponse implements WeixinResponse {
/**
* 通过上传多媒体文件,得到的id
*/
private String mediaId;
/**
* 视频消息标题
*/
private String title;
/**
* 视频消息描述
*/
private String desc;
public VideoResponse(String mediaId) {
this.mediaId = mediaId;
}
public VideoResponse(String mediaId, String title, String desc) {
this.mediaId = mediaId;
this.title = title;
this.desc = desc;
}
@Override
public String toContent() {
StringBuilder content = new StringBuilder();
content.append("<Video>");
content.append(String.format("<MediaId><![CDATA[%s]]></MediaId>",
mediaId));
content.append(String.format("<Title><![CDATA[%s]]></Title>",
title != null ? title : ""));
content.append(String.format(
"<Description><![CDATA[%s]]></Description>",
desc != null ? desc : ""));
content.append("</Video>");
return content.toString();
}
public String getMediaId() {
return mediaId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String getMsgType() {
return "video";
}
}
| 584 |
965 | class CMyLargeDocument : public CDocument
{
public:
virtual void Serialize(CArchive &ar);
};
void CMyLargeDocument::Serialize(CArchive &ar)
{
if (ar.IsStoring())
ar.SetStoreParams(); // use large defaults
else
ar.SetLoadParams();
if (ar.IsStoring())
{
// code for storing CMyLargeDocument
}
else
{
// code for loading CMyLargeDocument
}
} | 154 |
558 | <reponame>wibeasley/readr<filename>src/SourceString.h
#ifndef FASTREAD_SOURCESTRING_H_
#define FASTREAD_SOURCESTRING_H_
#include "cpp11/strings.hpp"
#include "Source.h"
class SourceString : public Source {
cpp11::sexp string_;
const char* begin_;
const char* end_;
public:
SourceString(
cpp11::strings x,
int skip = 0,
bool skipEmptyRows = true,
const std::string& comment = "",
bool skipQuotes = true)
: string_(static_cast<SEXP>(x[0])) {
begin_ = CHAR(string_);
end_ = begin_ + Rf_xlength(string_);
// Skip byte order mark, if needed
begin_ = skipBom(begin_, end_);
// Skip lines, if needed
begin_ = skipLines(begin_, end_, skip, skipEmptyRows, comment, skipQuotes);
}
const char* begin() { return begin_; }
const char* end() { return end_; }
};
#endif
| 344 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.jsf.impl.metamodel;
import org.netbeans.modules.j2ee.metadata.model.api.support.annotation.AnnotationModelHelper;
import org.netbeans.modules.j2ee.metadata.model.api.support.annotation.PersistentObjectManager;
import org.netbeans.modules.web.jsf.impl.facesmodel.AbstractJsfModel;
/**
* @author ads
*
*/
abstract class JsfModelManagers extends AbstractJsfModel {
JsfModelManagers( AnnotationModelHelper helper ) {
myHelper = helper;
myBehaviorManager = helper.createPersistentObjectManager(
new ObjectProviders.BehaviorProvider( helper) );
myComponentManager = helper.createPersistentObjectManager(
new ObjectProviders.ComponentProvider( helper) );
myConverterManager = helper.createPersistentObjectManager(
new ObjectProviders.ConverterProvider( helper) );
myManagedBeanManager = helper.createPersistentObjectManager(
new ObjectProviders.ManagedBeanProvider( helper) );
myValidatorManager = helper.createPersistentObjectManager(
new ObjectProviders.ValidatorProvider( helper) );
myRendererManager = helper.createPersistentObjectManager(
new ObjectProviders.RendererProvider( helper));
myClientBehaviorManager = helper.createPersistentObjectManager(
new ObjectProviders.ClientBehaviorProvider(helper));
mySystemEventManager = helper.createPersistentObjectManager(
new ObjectProviders.SystemEventListenerProvider(helper));
}
PersistentObjectManager<BehaviorImpl> getBeahviorManager(){
return myBehaviorManager;
}
PersistentObjectManager<ComponentImpl> getComponentManager(){
return myComponentManager;
}
PersistentObjectManager<ConverterImpl> getConverterManager(){
return myConverterManager;
}
PersistentObjectManager<ManagedBeanImpl> getManagedBeanManager(){
return myManagedBeanManager;
}
PersistentObjectManager<ValidatorImpl> getValidatorManager(){
return myValidatorManager;
}
PersistentObjectManager<RendererImpl> getRendererManager(){
return myRendererManager;
}
PersistentObjectManager<ClientBehaviorRendererImpl> getClientBehaviorManager(){
return myClientBehaviorManager;
}
PersistentObjectManager<SystemEventListenerImpl> getSystemEventManager(){
return mySystemEventManager;
}
AnnotationModelHelper getHelper(){
return myHelper;
}
private final PersistentObjectManager<BehaviorImpl> myBehaviorManager;
private final PersistentObjectManager<ComponentImpl> myComponentManager;
private final PersistentObjectManager<ConverterImpl> myConverterManager;
private final PersistentObjectManager<ManagedBeanImpl> myManagedBeanManager;
private final PersistentObjectManager<ValidatorImpl> myValidatorManager;
private final PersistentObjectManager<RendererImpl> myRendererManager;
private final PersistentObjectManager<ClientBehaviorRendererImpl>
myClientBehaviorManager;
private final PersistentObjectManager<SystemEventListenerImpl>
mySystemEventManager;
private AnnotationModelHelper myHelper;
}
| 1,464 |
7,073 | class JSON:
def keyword_in_json(self):
pass
class resource:
def keyword_in_resource(self):
pass
| 53 |
1,615 | <filename>ThirtyPartyFramework/Pods/FLEX/Classes/ViewHierarchy/FLEXHierarchyTableViewController.h
//
// FLEXHierarchyTableViewController.h
// Flipboard
//
// Created by <NAME> on 2014-05-01.
// Copyright (c) 2014 Flipboard. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol FLEXHierarchyTableViewControllerDelegate;
@interface FLEXHierarchyTableViewController : UITableViewController
- (instancetype)initWithViews:(NSArray<UIView *> *)allViews viewsAtTap:(NSArray<UIView *> *)viewsAtTap selectedView:(UIView *)selectedView depths:(NSDictionary<NSValue *, NSNumber *> *)depthsForViews;
@property (nonatomic, weak) id <FLEXHierarchyTableViewControllerDelegate> delegate;
@end
@protocol FLEXHierarchyTableViewControllerDelegate <NSObject>
- (void)hierarchyViewController:(FLEXHierarchyTableViewController *)hierarchyViewController didFinishWithSelectedView:(UIView *)selectedView;
@end
| 306 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "StartupReasonReporter",
"version": "0.1.0",
"summary": "Provides the reason that an iOS application has launched.",
"description": "The Startup Reason Reporter provides developers the the reason that an iOS application has launched, or equivalently, the reason that the application terminated on the prior launch.",
"homepage": "https://github.com/uber/startup-reason-reporter",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"source": {
"git": "https://github.com/uber/startup-reason-reporter.git",
"tag": "0.1.0"
},
"authors": "Uber",
"platforms": {
"ios": "8.0"
},
"subspecs": [
{
"name": "Core",
"source_files": "StartupReasonReporter/StartupReasonReporter/*"
},
{
"name": "PriorRunInfo",
"source_files": "StartupReasonReporter/StartupReasonReporterPriorRunInfo/*",
"dependencies": {
"StartupReasonReporter/Core": [
]
}
}
]
}
| 389 |
2,047 | """
This module contains an IPython extension.
"""
| 13 |
358 | /* ==========================================================================
* cache.c - Simple Query Cache for dns.c
* --------------------------------------------------------------------------
* Copyright (c) 2010 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#include <stddef.h> /* NULL */
#include <stdlib.h> /* malloc(3) free(3) */
#include <stdio.h> /* FILE fprintf(3) */
#include <string.h> /* strcasecmp(3) memset(3) */
#include <errno.h> /* errno */
#include <assert.h> /* assert(3) */
#include "dns.h"
#include "zone.h"
#include "cache.h"
#include "tree.h"
#define SAY_(fmt, ...) \
do { fprintf(stderr, fmt "%.1s", __func__, __LINE__, __VA_ARGS__); } while (0)
#define SAY(...) SAY_(">>>> (%s:%d) " __VA_ARGS__, "\n")
#define HAI SAY("HAI")
struct rrset {
char name[DNS_D_MAXNAME + 1];
enum dns_type type;
union {
struct dns_packet packet;
unsigned char pbuf[dns_p_calcsize(1024)];
};
RB_ENTRY(rrset) rbe;
}; /* struct rrset */
static int rrset_init(struct rrset *set, const char *name, enum dns_type type) {
int error;
memset(set, 0, sizeof *set);
dns_strlcpy(set->name, name, sizeof set->name);
set->type = type;
dns_p_init(&set->packet, sizeof set->pbuf);
if ((error = dns_p_push(&set->packet, DNS_S_QD, name, strlen(name), type, DNS_C_IN, 0, NULL)))
return error;
return 0;
} /* rrset_init() */
RB_HEAD(rrcache, rrset);
static inline int rrset_cmp(struct rrset *a, struct rrset *b) {
int cmp;
return ((cmp = a->type - b->type))? cmp : strcasecmp(a->name, b->name);
}
RB_PROTOTYPE(rrcache, rrset, rbe, rrset_cmp)
RB_GENERATE(rrcache, rrset, rbe, rrset_cmp)
struct cache {
struct dns_cache res;
struct rrcache root;
}; /* struct cache */
static struct rrset *cache_find(struct cache *C, const char *name, enum dns_type type, _Bool make, int *error_) {
struct rrset key, *set;
int error;
dns_strlcpy(key.name, name, sizeof key.name);
key.type = type;
if ((set = RB_FIND(rrcache, &C->root, &key)))
return set;
if (!make)
return NULL;
if (!(set = malloc(sizeof *set)))
goto syerr;
if ((error = rrset_init(set, name, type)))
goto error;
assert(!RB_INSERT(rrcache, &C->root, set));
return set;
syerr:
error = errno;
error:
*error_ = error;
free(set);
return NULL;
} /* cache_find() */
int cache_insert(struct cache *C, const char *name, enum dns_type type, unsigned ttl, const void *any) {
struct rrset *set;
int error;
if (!(set = cache_find(C, name, type, 1, &error)))
return error;
if ((error = dns_p_push(&set->packet, DNS_S_AN, name, strlen(name), type, DNS_C_IN, ttl, any)))
return error;
return 0;
} /* cache_insert() */
struct dns_packet *cache_query(struct dns_packet *query, struct dns_cache *res, int *error) {
struct cache *cache = res->state;
struct dns_packet *ans = NULL;
char qname[DNS_D_MAXNAME + 1];
struct dns_rr rr;
struct rrset *set;
if ((*error = dns_rr_parse(&rr, 12, query)))
return NULL;
if (!dns_d_expand(qname, sizeof qname, rr.dn.p, query, error))
goto error;
if (!(set = cache_find(cache, qname, rr.type, 0, error)))
return NULL;
if (!(ans = malloc(dns_p_sizeof(&set->packet))))
goto syerr;
dns_p_init(ans, dns_p_sizeof(&set->packet));
return dns_p_copy(ans, &set->packet);
syerr:
*error = errno;
error:
free(ans);
return NULL;
} /* cache_query() */
struct dns_cache *cache_resi(struct cache *cache) {
return &cache->res;
} /* cache_resi() */
void cache_close(struct cache *C) {
struct rrset *set;
if (!C)
return;
while ((set = RB_MIN(rrcache, &C->root))) {
RB_REMOVE(rrcache, &C->root, set);
free(set);
}
free(C);
} /* cache_close() */
struct cache *cache_open(int *error) {
struct cache *C;
if (!(C = malloc(sizeof *C)))
goto syerr;
dns_cache_init(&C->res);
C->res.state = C;
C->res.query = &cache_query;
RB_INIT(&C->root);
return C;
syerr:
*error = errno;
cache_close(C);
return NULL;
} /* cache_open() */
int cache_loadfile(struct cache *C, FILE *fp, const char *origin, unsigned ttl) {
struct zonefile *zone;
struct zonerr rr;
struct dns_soa *soa;
int error;
if (!(zone = zone_open(origin, ttl, &error)))
goto error;
while (zone_parsefile(zone, fp)) {
while (zone_getrr(&rr, &soa, zone)) {
if ((error = cache_insert(C, rr.name, rr.type, rr.ttl, &rr.data)))
goto error;
}
}
zone_close(zone);
return 0;
error:
zone_close(zone);
return error;
} /* cache_loadfile() */
int cache_loadpath(struct cache *C, const char *path, const char *origin, unsigned ttl) {
FILE *fp;
int error;
if (!strcmp(path, "-"))
return cache_loadfile(C, stdin, origin, ttl);
if (!(fp = fopen(path, "r")))
return errno;
error = cache_loadfile(C, fp, origin, ttl);
fclose(fp);
return error;
} /* cache_loadpath() */
static void cache_showpkt(struct dns_packet *pkt, FILE *fp) {
char buf[1024];
struct dns_rr rr;
union dns_any data;
int error;
dns_rr_foreach(&rr, pkt, .section = DNS_S_AN) {
dns_d_expand(buf, sizeof buf, rr.dn.p, pkt, &error);
fprintf(fp, "%s %u IN %s ", buf, rr.ttl, dns_strtype(rr.type));
dns_any_parse(dns_any_init(&data, sizeof data), &rr, pkt);
dns_any_print(buf, sizeof buf, &data, rr.type);
fprintf(fp, "%s\n", buf);
}
} /* cache_showpkt() */
int cache_dumpfile(struct cache *C, FILE *fp) {
struct rrset *set;
RB_FOREACH(set, rrcache, &C->root) {
cache_showpkt(&set->packet, fp);
}
return 0;
} /* cache_dumpfile() */
#if CACHE_MAIN
#include <ctype.h> /* tolower(3) */
#include <unistd.h> /* getopt(3) */
struct {
char *progname;
char *origin;
unsigned ttl;
struct dns_resolv_conf *resconf;
struct dns_hosts *hosts;
struct dns_hints *hints;
struct cache *cache;
} MAIN = {
.origin = ".",
.ttl = 3600,
};
static struct dns_resolv_conf *resconf(void) {
int error;
if (!MAIN.resconf) {
assert(MAIN.resconf = dns_resconf_local(&error));
MAIN.resconf->lookup[2] = MAIN.resconf->lookup[1];
MAIN.resconf->lookup[1] = MAIN.resconf->lookup[0];
MAIN.resconf->lookup[0] = 'c';
}
return MAIN.resconf;
} /* resconf() */
static struct dns_hosts *hosts(void) {
int error;
if (!MAIN.hosts)
assert(MAIN.hosts = dns_hosts_local(&error));
return MAIN.hosts;
} /* hosts() */
static struct dns_hints *hints(void) {
int error;
if (!MAIN.hints)
assert(MAIN.hints = dns_hints_local(resconf(), &error));
return MAIN.hints;
} /* hints() */
static struct cache *cache(void) {
int error;
if (!MAIN.cache) {
assert(MAIN.cache = cache_open(&error));
assert(!cache_loadfile(MAIN.cache, stdin, MAIN.origin, MAIN.ttl));
}
return MAIN.cache;
} /* cache() */
static void usage(FILE *fp) {
static const char *usage =
" [OPTIONS] [QNAME [QTYPE]]\n"
" -o ORIGIN Zone origin\n"
" -t TTL Zone TTL\n"
" -V Print version info\n"
" -h Print this usage message\n"
"\n"
"Report bugs to <NAME> <<EMAIL>>\n";
fputs(MAIN.progname, fp);
fputs(usage, fp);
fflush(fp);
} /* usage() */
static unsigned parsettl(const char *opt) {
unsigned ttl;
char *end;
ttl = strtoul(opt, &end, 10);
switch (tolower((unsigned char)*end)) {
case 'w':
ttl *= 7;
case 'd':
ttl *= 24;
case 'h':
ttl *= 60;
case 'm':
ttl *= 60;
case 's':
ttl *= 1;
case '\0':
break;
default:
fprintf(stderr, "%s: ", MAIN.progname);
for (; *opt; opt++) {
if (opt == end)
fprintf(stderr, "[%c]", *opt);
else
fputc(*opt, stderr);
}
fputs(": invalid TTL\n", stderr);
exit(EXIT_FAILURE);
}
return ttl;
} /* parsettl() */
int main(int argc, char **argv) {
extern int optind;
extern char *optarg;
int opt;
const char *qname = NULL;
int qtype = DNS_T_A;
struct dns_resolver *res;
struct dns_packet *ans;
int error;
MAIN.progname = argv[0];
while (-1 != (opt = getopt(argc, argv, "o:t:Vh"))) {
switch (opt) {
case 'o':
MAIN.origin = optarg;
break;
case 't':
MAIN.ttl = parsettl(optarg);
break;
case 'h':
usage(stdout);
return 0;
default:
usage(stderr);
return EXIT_FAILURE;
} /* switch() */
} /* while(getopt()) */
argc -= optind;
argv += optind;
if (argc > 0)
qname = argv[0];
if (argc > 1)
assert(qtype = dns_itype(argv[1]));
if (qname) {
assert(res = dns_res_open(resconf(), hosts(), hints(), cache_resi(cache()), dns_opts(), &error));
assert(!dns_res_submit(res, qname, qtype, DNS_C_IN));
while ((error = dns_res_check(res))) {
assert(error == EAGAIN);
assert(!dns_res_poll(res, 5));
}
assert((ans = dns_res_fetch(res, &error)));
cache_showpkt(ans, stdout);
free(ans);
dns_res_close(res);
} else {
cache_dumpfile(cache(), stdout);
}
return 0;
} /* main() */
#endif /* CACHE_MAIN */
| 4,048 |
1,526 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.pack.alpha.ui.vo;
import java.util.ArrayList;
import java.util.List;
public class DataTablesResponseDTO {
private int draw;
private long recordsTotal;
private long recordsFiltered;
private List<TransactionRowDTO> data = new ArrayList<>();
public int getDraw() {
return draw;
}
public long getRecordsTotal() {
return recordsTotal;
}
public long getRecordsFiltered() {
return recordsFiltered;
}
public List<TransactionRowDTO> getData() {
return data;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private int draw;
private long recordsTotal;
private long recordsFiltered;
private List<TransactionRowDTO> data = new ArrayList<>();
private Builder() {
}
public Builder draw(int draw) {
this.draw = draw;
return this;
}
public Builder recordsTotal(long recordsTotal) {
this.recordsTotal = recordsTotal;
return this;
}
public Builder recordsFiltered(long recordsFiltered) {
this.recordsFiltered = recordsFiltered;
return this;
}
public Builder data(List<TransactionRowDTO> data) {
this.data = data;
return this;
}
public DataTablesResponseDTO build() {
DataTablesResponseDTO dataTablesResponseDTO = new DataTablesResponseDTO();
dataTablesResponseDTO.recordsTotal = this.recordsTotal;
dataTablesResponseDTO.recordsFiltered = this.recordsFiltered;
dataTablesResponseDTO.draw = this.draw;
dataTablesResponseDTO.data = this.data;
return dataTablesResponseDTO;
}
}
}
| 775 |
803 | <reponame>savegame/oxygine-framework
#pragma once
#include "../oxygine-include.h"
#include "Aligner.h"
#include "../core/Object.h"
#include "../math/Color.h"
#include "../math/Vector2.h"
#include <string>
#include <vector>
namespace pugi
{
class xml_node;
}
namespace oxygine
{
class RenderState;
struct glyph;
class Aligner;
class STDRenderer;
class RenderState;
namespace text
{
typedef std::vector<Symbol> text_data;
class DrawContext
{
public:
DrawContext() {}
Color color;
Color primary;
};
class Node: public PoolObject
{
public:
Node();
virtual ~Node();
void appendNode(Node* tn);
virtual void resize(Aligner& rd);
void finalPass(Aligner& rd);
void drawChildren(DrawContext& dc);
void resizeChildren(Aligner& rd);
virtual Symbol* getSymbol(int& pos);
virtual void draw(DrawContext& dc);
virtual void xresize(Aligner& rd) {}
virtual void xfinalPass(Aligner& rd) {}
void updateMaterial(const STDMaterial& mat);
virtual void xupdateMaterial(const STDMaterial& mat) {}
Node* _firstChild;
Node* _lastChild;
Node* _nextSibling;
};
class TextNode: public Node
{
public:
static void setDefaultMissingSymbol(int);
TextNode(const char* v);
text_data _data;
void xresize(Aligner& rd) override;
void xfinalPass(Aligner& rd) override;
void draw(DrawContext& dc) override;
void xupdateMaterial(const STDMaterial& mat) override;
Symbol* getSymbol(int& pos) override;
#ifdef OX_DEBUG
std::string _text;//only for debug
#endif
};
class DivNode: public Node
{
public:
DivNode(const pugi::xml_node& node);
void resize(Aligner& rd) override;
void draw(DrawContext& dc) override;
Color color;
unsigned int options;
};
class BrNode: public Node
{
public:
void xresize(Aligner& rd)
{
rd.nextLine();
}
};
}
}
| 1,183 |
335 | {
"word": "Copy",
"definitions": [
"A thing made to be similar or identical to another.",
"A single specimen of a particular book, record, or other publication or issue.",
"Matter to be printed.",
"Material for a newspaper or magazine article.",
"The text of an advertisement.",
"A blank booklet or notebook used for schoolwork."
],
"parts-of-speech": "Noun"
} | 153 |
484 | /*
* Copyright 2017 Xiaomi, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xiaomi.shepher.dao;
import com.xiaomi.shepher.BaseTest;
import com.xiaomi.shepher.common.Role;
import com.xiaomi.shepher.common.Status;
import com.xiaomi.shepher.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by banchuanyu on 16-8-6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class UserMapperTest extends BaseTest {
@Autowired
private UserMapper userMapper;
@Test
public void testGetByName() {
User user = userMapper.getByName("banchuanyu");
Assert.assertEquals(1, user.getId());
}
@Test
public void testGetById() {
User user = userMapper.getById(1);
Assert.assertEquals(1, user.getId());
}
@Test
public void testList() {
Set<Long> teams = new HashSet<>();
teams.add(1L);
teams.add(5L);
List<User> users = userMapper.list(teams, Status.PENDING.getValue(), Role.MEMBER.getValue());
Assert.assertNotNull(users);
Assert.assertEquals(3, users.size());
}
@Test
public void testCreate() {
String name = "testuser1";
User user = new User(name);
int result = userMapper.create(user);
Assert.assertEquals(4, user.getId());
Assert.assertEquals(1, result);
}
}
| 783 |
348 | {"nom":"Ernestviller","circ":"5ème circonscription","dpt":"Moselle","inscrits":384,"abs":206,"votants":178,"blancs":9,"nuls":3,"exp":166,"res":[{"nuance":"LR","nom":"<NAME>","voix":88},{"nuance":"REM","nom":"Mme <NAME>","voix":78}]} | 94 |
6,034 | <reponame>ssSlowDown/onemall
package cn.iocoder.mall.shopweb.service.promotion;
import cn.iocoder.common.framework.enums.CommonStatusEnum;
import cn.iocoder.common.framework.util.CollectionUtils;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.productservice.rpc.spu.ProductSpuRpc;
import cn.iocoder.mall.productservice.rpc.spu.dto.ProductSpuRespDTO;
import cn.iocoder.mall.promotion.api.rpc.recommend.ProductRecommendRpc;
import cn.iocoder.mall.promotion.api.rpc.recommend.dto.ProductRecommendListReqDTO;
import cn.iocoder.mall.promotion.api.rpc.recommend.dto.ProductRecommendRespDTO;
import cn.iocoder.mall.shopweb.controller.product.vo.product.ProductSpuRespVO;
import cn.iocoder.mall.shopweb.convert.promotion.ProductRecommendConvert;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* 商品推荐 Manager
*/
@Service
@Validated
public class ProductRecommendManager {
@DubboReference(version = "${dubbo.consumer.ProductRecommendRpc.version}")
private ProductRecommendRpc productRecommendRpc;
@DubboReference(version = "${dubbo.consumer.ProductSpuRpc.version}")
private ProductSpuRpc productSpuRpc;
public Map<Integer, Collection<ProductSpuRespVO>> listProductRecommends() {
// 查询商品推荐列表
CommonResult<List<ProductRecommendRespDTO>> listProductRecommendsResult = productRecommendRpc.listProductRecommends(
new ProductRecommendListReqDTO().setStatus(CommonStatusEnum.ENABLE.getValue()));
listProductRecommendsResult.checkError();
listProductRecommendsResult.getData().sort(Comparator.comparing(ProductRecommendRespDTO::getSort)); // 排序,按照 sort 升序
// 获得商品集合
Map<Integer, ProductSpuRespDTO> spuMap = this.getProductSkuMap(listProductRecommendsResult.getData());
// 组合结果,返回
Multimap<Integer, ProductSpuRespVO> result = HashMultimap.create();
listProductRecommendsResult.getData().forEach(productRecommendBO -> result.put(productRecommendBO.getType(),
ProductRecommendConvert.INSTANCE.convert(spuMap.get(productRecommendBO.getProductSpuId()))));
return result.asMap();
}
private Map<Integer, ProductSpuRespDTO> getProductSkuMap(List<ProductRecommendRespDTO> productRecommends) {
CommonResult<List<ProductSpuRespDTO>> listProductSpusResult = productSpuRpc.listProductSpus(
CollectionUtils.convertSet(productRecommends, ProductRecommendRespDTO::getProductSpuId));
listProductSpusResult.checkError();
return CollectionUtils.convertMap(listProductSpusResult.getData(), ProductSpuRespDTO::getId);
}
}
| 1,121 |
3,069 | #!/usr/bin/env python
'''
Copyright (C) 2020, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'Nemesida (PentestIt)'
def is_waf(self):
schemes = [
self.matchContent(r'@?nemesida(\-security)?\.com'),
self.matchContent(r'Suspicious activity detected.{0,10}?Access to the site is blocked'),
self.matchContent(r'nwaf@'),
self.matchStatus(222)
]
if any(i for i in schemes):
return True
return False | 200 |
2,151 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 android.webkit;
import android.net.Uri;
/**
* This class defines a permission request and is used when web content
* requests access to protected resources. The permission request related events
* are delivered via {@link WebChromeClient#onPermissionRequest} and
* {@link WebChromeClient#onPermissionRequestCanceled}.
*
* Either {@link #grant(String[]) grant()} or {@link #deny()} must be called in UI
* thread to respond to the request.
*
* New protected resources whose names are not defined here may be requested in
* future versions of WebView, even when running on an older Android release. To
* avoid unintentionally granting requests for new permissions, you should pass the
* specific permissions you intend to grant to {@link #grant(String[]) grant()},
* and avoid writing code like this example:
* <pre>
* permissionRequest.grant(permissionRequest.getResources()) // This is wrong!!!
* </pre>
* See the WebView's release notes for information about new protected resources.
*/
public abstract class PermissionRequest {
/**
* Resource belongs to video capture device, like camera.
*/
public final static String RESOURCE_VIDEO_CAPTURE = "android.webkit.resource.VIDEO_CAPTURE";
/**
* Resource belongs to audio capture device, like microphone.
*/
public final static String RESOURCE_AUDIO_CAPTURE = "android.webkit.resource.AUDIO_CAPTURE";
/**
* Resource belongs to protected media identifier.
* After the user grants this resource, the origin can use EME APIs to generate the license
* requests.
*/
public final static String RESOURCE_PROTECTED_MEDIA_ID =
"android.webkit.resource.PROTECTED_MEDIA_ID";
/**
* Resource will allow sysex messages to be sent to or received from MIDI devices. These
* messages are privileged operations, e.g. modifying sound libraries and sampling data, or
* even updating the MIDI device's firmware.
*
* Permission may be requested for this resource in API levels 21 and above, if the Android
* device has been updated to WebView 45 or above.
*/
public final static String RESOURCE_MIDI_SYSEX = "android.webkit.resource.MIDI_SYSEX";
/**
* Call this method to get the origin of the web page which is trying to access
* the restricted resources.
*
* @return the origin of web content which attempt to access the restricted
* resources.
*/
public abstract Uri getOrigin();
/**
* Call this method to get the resources the web page is trying to access.
*
* @return the array of resources the web content wants to access.
*/
public abstract String[] getResources();
/**
* Call this method to grant origin the permission to access the given resources.
* The granted permission is only valid for this WebView.
*
* @param resources the resources granted to be accessed by origin, to grant
* request, the requested resources returned by {@link #getResources()}
* must be equals or a subset of granted resources.
* This parameter is designed to avoid granting permission by accident
* especially when new resources are requested by web content.
*/
public abstract void grant(String[] resources);
/**
* Call this method to deny the request.
*/
public abstract void deny();
}
| 1,178 |
1,647 | <reponame>davidbrochart/pythran
#ifndef PYTHONIC_INCLUDE_TYPES_FLOAT128_HPP
#define PYTHONIC_INCLUDE_TYPES_FLOAT128_HPP
#endif
| 70 |
412 | int main()
{
double a, b;
union {
double f;
long long unsigned int i; // needs to have 64 bits
} au, bu;
au.f = a;
bu.f = b;
assert((au.i == bu.i) == __CPROVER_equal(a, b));
}
| 89 |
2,637 | <reponame>nateglims/amazon-freertos<gh_stars>1000+
/**
* \file
* \brief Software implementation of the SHA256 algorithm.
*
* \copyright (c) 2015-2018 Microchip Technology Inc. and its subsidiaries.
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT,
* SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE
* OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF
* MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE
* FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL
* LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED
* THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR
* THIS SOFTWARE.
*/
#ifndef SHA2_ROUTINES_H
#define SHA2_ROUTINES_H
#include <stdint.h>
#define SHA256_DIGEST_SIZE (32)
#define SHA256_BLOCK_SIZE (64)
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
uint32_t total_msg_size; //!< Total number of message bytes processed
uint32_t block_size; //!< Number of bytes in current block
uint8_t block[SHA256_BLOCK_SIZE * 2]; //!< Unprocessed message storage
uint32_t hash[8]; //!< Hash state
} sw_sha256_ctx;
void sw_sha256_init(sw_sha256_ctx* ctx);
void sw_sha256_update(sw_sha256_ctx* ctx, const uint8_t* message, uint32_t len);
void sw_sha256_final(sw_sha256_ctx * ctx, uint8_t digest[SHA256_DIGEST_SIZE]);
void sw_sha256(const uint8_t * message, unsigned int len, uint8_t digest[SHA256_DIGEST_SIZE]);
#ifdef __cplusplus
}
#endif
#endif // SHA2_ROUTINES_H
| 792 |
675 | #pragma once
#include "engine/core/memory/MemAllocDef.h"
#include <thirdparty/pugixml/pugixml.hpp>
#include "engine/core/io/stream/DataStream.h"
namespace Echo
{
class XmlBinaryReader
{
public:
// data
struct Data
{
String m_name;
String m_type;
i32 m_offset = 0;
i32 m_size = 0;
ByteArray m_data;
bool isEmpty() { return m_data.empty(); }
};
public:
XmlBinaryReader();
~XmlBinaryReader();
// root node
pugi::xml_node getRoot();
// get data
bool getData(const char* name, Data& binaryData);
// get binary names
StringArray getBinaryNames();
// load
bool load(const char* path);
private:
pugi::xml_document m_doc;
DataStream* m_stream = nullptr;
};
class XmlBinaryWriter
{
public:
XmlBinaryWriter();
~XmlBinaryWriter();
// root node
pugi::xml_node getRoot();
// add binary data
void addData(const char* name, const char* type, void* data, i32 bytes);
// save
void save(const char* path);
private:
pugi::xml_document m_doc;
vector<Byte>::type m_binary;
};
}
| 469 |
623 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.addon.reports.automation;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.addon.automation.AutomationData;
import org.zaproxy.addon.automation.AutomationEnvironment;
import org.zaproxy.addon.automation.AutomationJob;
import org.zaproxy.addon.automation.AutomationProgress;
import org.zaproxy.addon.automation.jobs.JobData;
import org.zaproxy.addon.automation.jobs.JobUtils;
import org.zaproxy.addon.automation.jobs.PassiveScanJobResultData;
import org.zaproxy.addon.automation.jobs.PassiveScanJobResultData.RuleData;
import org.zaproxy.addon.reports.ExtensionReports;
import org.zaproxy.addon.reports.HttpStatusReason;
import org.zaproxy.zap.extension.alert.AlertNode;
public class OutputSummaryJob extends AutomationJob {
public static final String JOB_NAME = "outputSummary";
private static final String PARAM_FORMAT = "format";
private ExtensionReportAutomation extReportAuto;
private PrintStream out = System.out;
protected enum Format {
NONE,
SHORT,
LONG
};
protected enum Result {
IGNORE,
INFO,
WARN_NEW,
FAIL_NEW
}
private Data data;
private Parameters parameters = new Parameters();
private ExtensionReports extReport;
private AlertNode root;
private Map<Integer, String> customMessageMap = null;
public OutputSummaryJob() {
this.data = new Data(this, parameters);
}
@Override
public void verifyParameters(AutomationProgress progress) {
Map<?, ?> jobData = this.getJobData();
if (jobData == null) {
return;
}
JobUtils.applyParamsToObject(
(LinkedHashMap<?, ?>) jobData.get("parameters"),
this.parameters,
this.getName(),
null,
progress);
if (this.getParameters().getSummaryFile() == null) {
progress.error(
Constant.messages.getString(
"reports.automation.error.noparent", this.getName(), ""));
} else {
File parent = new File(this.getParameters().getSummaryFile()).getParentFile();
if (!parent.exists()) {
progress.error(
Constant.messages.getString(
"reports.automation.error.noparent",
this.getName(),
parent.getAbsolutePath()));
} else if (!parent.canWrite()) {
progress.error(
Constant.messages.getString(
"reports.automation.error.roparent",
this.getName(),
parent.getAbsolutePath()));
}
}
// Load rule data
Object o = jobData.get("rules");
if (o instanceof ArrayList<?>) {
ArrayList<?> ruleData = (ArrayList<?>) o;
for (Object rule : ruleData) {
if (rule instanceof LinkedHashMap<?, ?>) {
LinkedHashMap<?, ?> ruleMap = (LinkedHashMap<?, ?>) rule;
this.getData()
.getRules()
.add(
new Rule(
(Integer) ruleMap.get("id"),
(String) ruleMap.get("action"),
(String) ruleMap.get("customMessage")));
}
}
}
}
@Override
public void applyParameters(AutomationProgress progress) {
// Nothing to do
}
/**
* Prints a summary to std out as per the packaged scans. The output is deliberately not
* internationalised as neither was the output of the packaged scans.
*/
@Override
public void runJob(AutomationEnvironment env, AutomationProgress progress) {
String summaryFile = this.getParameters().getSummaryFile();
Format format = this.getParameters().getFormat();
if (Format.NONE.equals(format)) {
return;
}
int pass = 0;
int warnNew = 0;
int failNew = 0;
int ignore = 0;
int info = 0;
List<Integer> ignoreIds = new ArrayList<>();
List<Integer> infoIds = new ArrayList<>();
List<Integer> failIds = new ArrayList<>();
for (Rule rule : this.getData().getRules()) {
switch (rule.getAction()) {
case "IGNORE":
ignoreIds.add(rule.getId());
break;
case "INFO":
infoIds.add(rule.getId());
break;
case "FAIL":
failIds.add(rule.getId());
break;
default: // Default to WARN
}
}
// Number of URLs, as per logic behind the core.urls API endpoint
int numUrls = getExtReportAuto().countNumberOfUrls();
if (numUrls == 0) {
out.println(
"No URLs found - is the target URL accessible? Local services may not be accessible from a Docker container");
} else {
if (Format.LONG.equals(format)) {
out.println("Total of " + numUrls + " URLs");
}
// Passing rules, for now just passive, ordered by id
PassiveScanJobResultData pscanData =
(PassiveScanJobResultData) progress.getJobResultData("passiveScanData");
if (pscanData != null) {
Collection<RuleData> pscanRuleData = pscanData.getAllRuleData();
Map<Integer, Integer> alertCounts = getExtReport().getAlertCountsByRule();
RuleData[] pscanRuleArray = new RuleData[pscanRuleData.size()];
pscanRuleData.toArray(pscanRuleArray);
Arrays.sort(
pscanRuleArray,
new Comparator<RuleData>() {
@Override
public int compare(RuleData o1, RuleData o2) {
// Compare as strings, for backwards compatibility
return Integer.toString(o1.getId())
.compareTo(Integer.toString(o2.getId()));
}
});
for (RuleData psRule : pscanRuleArray) {
if (!alertCounts.containsKey(psRule.getId())) {
if (Format.LONG.equals(format)) {
out.println("PASS: " + psRule.getName() + " [" + psRule.getId() + "]");
}
pass++;
}
}
// Output the results in the expected order
ignore =
outputResults(
pscanRuleArray,
alertCounts,
ignoreIds,
infoIds,
failIds,
Result.IGNORE);
info =
outputResults(
pscanRuleArray,
alertCounts,
ignoreIds,
infoIds,
failIds,
Result.INFO);
warnNew =
outputResults(
pscanRuleArray,
alertCounts,
ignoreIds,
infoIds,
failIds,
Result.WARN_NEW);
failNew =
outputResults(
pscanRuleArray,
alertCounts,
ignoreIds,
infoIds,
failIds,
Result.FAIL_NEW);
}
// Obviously most of these are not supported yet :)
out.println(
"FAIL-NEW: "
+ failNew
+ "\tFAIL-INPROG: 0\tWARN-NEW: "
+ warnNew
+ "\tWARN-INPROG: 0\tINFO: "
+ info
+ "\tIGNORE: "
+ ignore
+ "\tPASS: "
+ pass);
if (summaryFile != null) {
JSONObject summary = new JSONObject();
summary.put("pass", pass);
summary.put("warn", warnNew);
summary.put("fail", failNew);
try {
Files.write(Paths.get(summaryFile), summary.toString().getBytes("utf-8"));
} catch (IOException e) {
progress.error(
Constant.messages.getString(
"reports.automation.error.badsummaryfile",
this.getName(),
e.getMessage()));
}
}
}
}
private int outputResults(
RuleData[] pscanRuleArray,
Map<Integer, Integer> alertCounts,
List<Integer> ignoreIds,
List<Integer> infoIds,
List<Integer> failIds,
Result result) {
int total = 0;
String resStr;
for (RuleData rule : pscanRuleArray) {
if (alertCounts.containsKey(rule.getId())) {
if (ignoreIds.contains(rule.getId())) {
if (!Result.IGNORE.equals(result)) {
continue;
}
resStr = "IGNORE";
} else if (infoIds.contains(rule.getId())) {
if (!Result.INFO.equals(result)) {
continue;
}
resStr = "INFO";
} else if (failIds.contains(rule.getId())) {
if (!Result.FAIL_NEW.equals(result)) {
continue;
}
resStr = "FAIL-NEW";
} else {
if (!Result.WARN_NEW.equals(result)) {
continue;
}
resStr = "WARN-NEW";
}
total++;
int count = alertCounts.get(rule.getId());
out.println(
resStr
+ ": "
+ getAlertName(rule.getId(), rule.getName())
+ " ["
+ rule.getId()
+ "] x "
+ count
+ " "
+ getCustomMessage(rule.getId()));
if (Format.LONG.equals(this.getParameters().getFormat())) {
for (HttpMessage msg : getExtReport().getHttpMessagesForRule(rule.getId(), 5)) {
int code = msg.getResponseHeader().getStatusCode();
out.println(
"\t"
+ msg.getRequestHeader().getURI()
+ " ("
+ code
+ " "
+ HttpStatusReason.get(code)
+ ")");
}
}
}
}
return total;
}
private String getCustomMessage(int ruleId) {
if (customMessageMap == null) {
customMessageMap = new HashMap<>();
for (Rule rule : this.getData().getRules()) {
String cm = rule.getCustomMessage();
if (cm != null) {
customMessageMap.put(rule.getId(), cm);
}
}
}
if (customMessageMap.containsKey(ruleId)) {
return customMessageMap.get(ruleId);
}
return "";
}
/**
* Get the name to use for the given alert. This is done by finding the first raised alert with
* the given ID. If multiple sites are being scanned then this will not work so well, but for
* the packaged scans it should be fine.
*/
private String getAlertName(int pluginId, String defaultName) {
AlertNode node = this.getAlertNode(pluginId);
if (node != null) {
if (node.getChildCount() > 0) {
return ((AlertNode) node.getFirstChild()).getUserObject().getName();
}
}
return defaultName;
}
private AlertNode getAlertNode(int pluginId) {
try {
if (root == null) {
root = this.getExtReport().getRootAlertNode();
}
if (root.getChildCount() > 0) {
AlertNode child = (AlertNode) root.getFirstChild();
while (child != null) {
if (child.getUserObject().getPluginId() == pluginId) {
return child;
}
child = (AlertNode) root.getChildAfter(child);
}
}
} catch (Exception e) {
// Ignore
}
return null;
}
/** Only to be used for the unit tests. */
void setOutput(PrintStream ps) {
this.out = ps;
}
@Override
public Map<String, String> getCustomConfigParameters() {
Map<String, String> map = super.getCustomConfigParameters();
map.put(PARAM_FORMAT, Format.NONE.name());
return map;
}
private ExtensionReportAutomation getExtReportAuto() {
if (extReportAuto == null) {
extReportAuto =
Control.getSingleton()
.getExtensionLoader()
.getExtension(ExtensionReportAutomation.class);
}
return extReportAuto;
}
private ExtensionReports getExtReport() {
if (extReport == null) {
extReport =
Control.getSingleton()
.getExtensionLoader()
.getExtension(ExtensionReports.class);
}
return extReport;
}
@Override
public String getTemplateDataMin() {
return ExtensionReportAutomation.getResourceAsString(this.getType() + "-min.yaml");
}
@Override
public String getTemplateDataMax() {
return ExtensionReportAutomation.getResourceAsString(this.getType() + "-max.yaml");
}
@Override
public String getType() {
return JOB_NAME;
}
@Override
public Order getOrder() {
return Order.REPORT;
}
@Override
public Object getParamMethodObject() {
return null;
}
@Override
public String getParamMethodName() {
return null;
}
@Override
public Data getData() {
return data;
}
@Override
public Parameters getParameters() {
return parameters;
}
public static class Data extends JobData {
private Parameters parameters;
private List<Rule> rules = new ArrayList<>();
public Data(AutomationJob job, Parameters parameters) {
super(job);
this.parameters = parameters;
}
public Parameters getParameters() {
return parameters;
}
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
public static class Rule extends AutomationData {
private Integer id;
private String action;
private String customMessage;
public Rule(Integer id, String action, String customMessage) {
super();
this.id = id;
this.action = action;
this.customMessage = customMessage;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getCustomMessage() {
return customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
}
public static class Parameters extends AutomationData {
private Format format = Format.NONE;
private String summaryFile;
public Format getFormat() {
return format;
}
public void setFormat(Format format) {
this.format = format;
}
public String getSummaryFile() {
return summaryFile;
}
public void setSummaryFile(String summaryFile) {
this.summaryFile = summaryFile;
}
}
}
| 9,959 |
457 | """
The top-level model of training-time PixLoc.
Encapsulates the feature extraction, pose optimization, loss and metrics.
"""
import torch
from torch.nn import functional as nnF
import logging
from copy import deepcopy
import omegaconf
from .base_model import BaseModel
from . import get_model
from .utils import masked_mean
from ..geometry.losses import scaled_barron
logger = logging.getLogger(__name__)
class TwoViewRefiner(BaseModel):
default_conf = {
'extractor': {
'name': 's2dnet',
},
'optimizer': {
'name': 'basic_optimizer',
},
'duplicate_optimizer_per_scale': False,
'success_thresh': 2,
'clamp_error': 50,
'normalize_features': True,
'normalize_dt': True,
# deprecated entries
'init_target_offset': None,
}
required_data_keys = {
'ref': ['image', 'camera', 'T_w2cam'],
'query': ['image', 'camera', 'T_w2cam'],
}
strict_conf = False # need to pass new confs to children models
def _init(self, conf):
self.extractor = get_model(conf.extractor.name)(conf.extractor)
assert hasattr(self.extractor, 'scales')
Opt = get_model(conf.optimizer.name)
if conf.duplicate_optimizer_per_scale:
oconfs = [deepcopy(conf.optimizer) for _ in self.extractor.scales]
feature_dim = self.extractor.conf.output_dim
if not isinstance(feature_dim, int):
for d, oconf in zip(feature_dim, oconfs):
with omegaconf.read_write(oconf):
with omegaconf.open_dict(oconf):
oconf.feature_dim = d
self.optimizer = torch.nn.ModuleList([Opt(c) for c in oconfs])
else:
self.optimizer = Opt(conf.optimizer)
if conf.init_target_offset is not None:
raise ValueError('This entry has been deprecated. Please instead '
'use the `init_pose` config of the dataloader.')
def _forward(self, data):
def process_siamese(data_i):
pred_i = self.extractor(data_i)
pred_i['camera_pyr'] = [data_i['camera'].scale(1/s)
for s in self.extractor.scales]
return pred_i
pred = {i: process_siamese(data[i]) for i in ['ref', 'query']}
p3D_ref = data['ref']['points3D']
T_init = data['T_r2q_init']
pred['T_r2q_init'] = []
pred['T_r2q_opt'] = []
pred['valid_masks'] = []
for i in reversed(range(len(self.extractor.scales))):
F_ref = pred['ref']['feature_maps'][i]
F_q = pred['query']['feature_maps'][i]
cam_ref = pred['ref']['camera_pyr'][i]
cam_q = pred['query']['camera_pyr'][i]
if self.conf.duplicate_optimizer_per_scale:
opt = self.optimizer[i]
else:
opt = self.optimizer
p2D_ref, visible = cam_ref.world2image(p3D_ref)
F_ref, mask, _ = opt.interpolator(F_ref, p2D_ref)
mask &= visible
W_ref_q = None
if self.extractor.conf.get('compute_uncertainty', False):
W_ref = pred['ref']['confidences'][i]
W_q = pred['query']['confidences'][i]
W_ref, _, _ = opt.interpolator(W_ref, p2D_ref)
W_ref_q = (W_ref, W_q)
if self.conf.normalize_features:
F_ref = nnF.normalize(F_ref, dim=2) # B x N x C
F_q = nnF.normalize(F_q, dim=1) # B x C x W x H
T_opt, failed = opt(dict(
p3D=p3D_ref, F_ref=F_ref, F_q=F_q, T_init=T_init, cam_q=cam_q,
mask=mask, W_ref_q=W_ref_q))
pred['T_r2q_init'].append(T_init)
pred['T_r2q_opt'].append(T_opt)
T_init = T_opt.detach()
return pred
def loss(self, pred, data):
cam_q = data['query']['camera']
def project(T_r2q):
return cam_q.world2image(T_r2q * data['ref']['points3D'])
p2D_q_gt, mask = project(data['T_r2q_gt'])
p2D_q_i, mask_i = project(data['T_r2q_init'])
mask = (mask & mask_i).float()
too_few = torch.sum(mask, -1) < 10
if torch.any(too_few):
logger.warning(
'Few points in batch '+str([
(data['scene'][i], data['ref']['index'][i].item(),
data['query']['index'][i].item())
for i in torch.where(too_few)[0]]))
def reprojection_error(T_r2q):
p2D_q, _ = project(T_r2q)
err = torch.sum((p2D_q_gt - p2D_q)**2, dim=-1)
err = scaled_barron(1., 2.)(err)[0]/4
err = masked_mean(err, mask, -1)
return err
num_scales = len(self.extractor.scales)
success = None
losses = {'total': 0.}
for i, T_opt in enumerate(pred['T_r2q_opt']):
err = reprojection_error(T_opt).clamp(max=self.conf.clamp_error)
loss = err / num_scales
if i > 0:
loss = loss * success.float()
thresh = self.conf.success_thresh * self.extractor.scales[-1-i]
success = err < thresh
losses[f'reprojection_error/{i}'] = err
losses['total'] += loss
losses['reprojection_error'] = err
losses['total'] *= (~too_few).float()
err_init = reprojection_error(pred['T_r2q_init'][0])
losses['reprojection_error/init'] = err_init
return losses
def metrics(self, pred, data):
T_q2r_gt = data['ref']['T_w2cam'] @ data['query']['T_w2cam'].inv()
@torch.no_grad()
def scaled_pose_error(T_r2q):
err_R, err_t = (T_r2q @ T_q2r_gt).magnitude()
if self.conf.normalize_dt:
err_t /= torch.norm(T_q2r_gt.t, dim=-1)
return err_R, err_t
metrics = {}
for i, T_opt in enumerate(pred['T_r2q_opt']):
err = scaled_pose_error(T_opt)
metrics[f'R_error/{i}'], metrics[f't_error/{i}'] = err
metrics['R_error'], metrics['t_error'] = err
err_init = scaled_pose_error(pred['T_r2q_init'][0])
metrics['R_error/init'], metrics['t_error/init'] = err_init
return metrics
| 3,323 |
3,084 | <gh_stars>1000+
#ifndef __INC_TDLSGEN_H
#define __INC_TDLSGEN_H
#if (TDLS_SUPPORT == 1)
VOID
TDLS_Init(
PADAPTER Adapter
);
VOID
TDLS_Reset(
PADAPTER Adapter
);
VOID
TDLS_QueryCapability(
PADAPTER Adapter,
PRT_TCB pTcb
);
BOOLEAN
TDLS_IndicatePacket(
PADAPTER Adapter,
POCTET_STRING pPduOS
);
BOOLEAN
TDLS_IsRxTDLSPacket(
PADAPTER Adapter,
PRT_RFD pRfd
);
BOOLEAN
TDLS_IsTxTDLSPacket(
PADAPTER Adapter,
PRT_RFD pRfd
);
VOID
TDLS_OnAsocOK(
PADAPTER Adapter,
OCTET_STRING asocpdu
);
VOID
TDLS_OnAddBaRsp(
PADAPTER Adapter,
POCTET_STRING pPduOS
);
VOID
TDLS_OnBeacon_BSS(
PADAPTER pAdapter,
OCTET_STRING osBeacon
);
PRT_WLAN_STA
TDLS_PS_CheckPsTx(
PADAPTER Adapter,
PRT_TCB pTcb
);
BOOLEAN
TDLS_PS_OnTx(
PADAPTER pAdapter,
PRT_WLAN_STA pEntry,
PRT_TCB pTcb
);
PRT_WLAN_STA
TDLS_PS_UpdatePeerPSState(
PADAPTER Adapter,
POCTET_STRING pPduOS,
BOOLEAN bTriggerFrame
);
VOID
TDLS_PS_Sleep(
PADAPTER Adapter,
RT_TDLS_PS_STATE StateToSet
);
BOOLEAN
TDLS_CS_BufferCSTx(
PADAPTER Adapter,
PRT_TCB pTcb
);
BOOLEAN
TDLS_PrepareTxFeedback(
PADAPTER Adapter,
PRT_TCB pTcb
);
VOID
TDLS_UpdatePeer(
PADAPTER Adapter,
PRT_WLAN_STA pEntry
);
VOID
TDLS_UpdatePeerStatus(
PADAPTER Adapter
);
BOOLEAN
TDLS_GetPwrMgntInfo(
PADAPTER Adapter,
PRT_TCB pTcb
);
VOID
TDLS_SetConfiguration(
IN PADAPTER Adapter,
IN pu1Byte InformationBuffer,
IN u4Byte InformationBufferLength
);
BOOLEAN
TDLS_CheckPeer(
PADAPTER Adapter,
pu1Byte Addr
);
VOID
TDLS_RemovePeer(
PADAPTER Adapter,
pu1Byte Addr
);
VOID
TDLS_LinkStatusWatchDog(
PADAPTER Adapter
);
VOID
TDLS_Stop(
PADAPTER Adapter
);
VOID
TDLS_Release(
PADAPTER Adapter
);
RT_STATUS
TDLS_AllocateMemory(
IN PADAPTER Adapter
);
VOID
TDLS_FreeMemory(
IN PADAPTER Adapter
);
RT_STATUS
TDLS_OnDiscoveryRsp(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS
);
RT_STATUS
TDLS_OnSetupReq(
IN PADAPTER pAdapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnSetupRsp(
IN PADAPTER pAdapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnSetupConfirm(
IN PADAPTER pAdapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnTearDown(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnDiscoveryReq(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnTrafficInd(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnTrafficRsp(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnChnlSwitchReq(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnChnlSwitchRsp(
IN PADAPTER Adapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnTunneledProbeReq(
IN PADAPTER pAdapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
RT_STATUS
TDLS_OnTunneledProbeRsp(
IN PADAPTER pAdapter,
IN PRT_RFD pRfd,
IN POCTET_STRING pPduOS,
IN u4Byte contentOffset
);
VOID
TDLS_CountTxStatistics(
IN PADAPTER Adapter,
IN PRT_TCB pTcb
);
VOID
TDLS_GetTxMacId(
IN PADAPTER Adapter,
IN pu1Byte Addr,
OUT pu4Byte MacID
);
VOID
TDLS_GetHtAMPDU(
IN PADAPTER Adapter,
IN pu1Byte Addr,
IN PRT_TCB pTcb
);
VOID
TDLS_GetTxRatrIndex(
IN PADAPTER Adapter,
IN pu1Byte Addr,
OUT pu1Byte RatrIndex
);
VOID
TDLS_CheckCapability(
IN PADAPTER Adapter
);
VOID
TDLS_GetValueFromBeaconOrProbeRsp(
IN PADAPTER Adapter,
IN POCTET_STRING pMmpdu,
IN PRT_WLAN_BSS pBssDesc
);
VOID
TDLS_RxTranslateHeader(
IN PADAPTER Adapter,
IN PRT_RFD pRfd
);
VOID
TDLS_TxTranslateHeader(
IN PADAPTER Adapter,
IN PRT_TCB pTcb,
IN PROTOCOL_TYPE Type
);
VOID
TDLS_CheckAggregation(
IN PADAPTER Adapter,
IN pu1Byte Addr,
IN PRT_TCB pTcb
);
#else // #if (TDLS_SUPPORT != 1)
#define TDLS_Init(Adapter)
#define TDLS_Reset(Adapter)
#define TDLS_QueryCapability(Adapter, pTcb)
#define TDLS_IndicatePacket(Adapter, pPduOS) (FALSE)
#define TDLS_IsRxTDLSPacket(Adapter, pRfd) (FALSE)
#define TDLS_IsTxTDLSPacket(Adapter, pTcb) (FALSE)
#define TDLS_OnAsocOK(Adapter, asocpdu)
#define TDLS_OnAddBaRsp(Adapter, pPduOS)
#define TDLS_OnBeacon_BSS(pAdapter, osBeacon)
#define TDLS_PS_CheckPsTx(Adapter, pTcb) (NULL)
#define TDLS_PS_OnTx(pAdapter, pEntry, pTcb) (FALSE)
#define TDLS_PS_UpdatePeerPSState(Adapter, pPduOS, bTriggerFrame) (NULL)
#define TDLS_PS_Sleep(Adapter, StateToSet)
#define TDLS_CS_BufferCSTx(Adapter, pTcb) (FALSE)
#define TDLS_PrepareTxFeedback(Adapter, pTcb) (FALSE)
#define TDLS_UpdatePeer(Adapter, pEntry)
#define TDLS_UpdatePeerStatus(Adapter)
#define TDLS_GetPwrMgntInfo(Adapter,pTcb) (FALSE)
#define TDLS_SetConfiguration(Adapter, InformationBuffer, InformationBufferLength)
#define TDLS_CheckPeer(Adapter, Addr) (FALSE)
#define TDLS_RemovePeer(Adapter,Addr)
#define TDLS_LinkStatusWatchDog(Adapter)
#define TDLS_Stop(Adapter)
#define TDLS_Release(Adapter)
#define TDLS_AllocateMemory(Adapter) (RT_STATUS_SUCCESS)
#define TDLS_FreeMemory(Adapter)
#define TDLS_ResetAsocEntry(_pAdapter, _pEntry)
#define TDLS_CountTxStatistics(_pAdapter, _pTcb)
#define TDLS_GetTxMacId(_pAdapter, _Addr, _MacID)
#define TDLS_GetHtAMPDU(_pAdapter, _Addr, _pTcb)
#define TDLS_GetTxRatrIndex(_pAdapter, _Addr, _RatrIndex)
#define TDLS_CheckCapability(_pAdapter)
#define TDLS_GetValueFromBeaconOrProbeRsp(_pAdapter, _pMmpdu, _pBssDesc)
#define TDLS_RxTranslateHeader(_pAdapter, _pRfd)
#define TDLS_TxTranslateHeader(_pAdapter, _pTcb, _Type)
#define TDLS_CheckAggregation(_pAdapter, _Addr, _pTcb)
__inline RT_STATUS TDLS_OnDiscoveryRsp(PADAPTER Adapter, PRT_RFD pRfd, POCTET_STRING pPduOS) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnSetupReq(PADAPTER pAdapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnSetupRsp(PADAPTER pAdapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnSetupConfirm(PADAPTER pAdapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnTearDown(PADAPTER Adapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnDiscoveryReq(PADAPTER Adapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnTrafficInd(PADAPTER Adapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnTrafficRsp(PADAPTER Adapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnChnlSwitchReq(PADAPTER Adapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnChnlSwitchRsp(PADAPTER Adapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnTunneledProbeReq(PADAPTER pAdapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
__inline RT_STATUS TDLS_OnTunneledProbeRsp(PADAPTER pAdapter, PRT_RFD pRfd, POCTET_STRING pPduOS, u4Byte contentOffset) {return RT_STATUS_SUCCESS;}
#define GET_TDLS_ENABLED(__pMgntInfo) FALSE
#define SET_TDLS_ENABLED(__pMgntInfo, _value)
#define GET_TDLS_WIFITEST(__pMgntInfo) FALSE
#define IS_TDL_EXIST(_pMgntInfo) FALSE
#define GET_TDLS_WIFITESTBED_RADIO_OFF(__pMgntInfo) FALSE
#endif // end of else of #if (TDLS_SUPPORT == 1)
#endif
| 4,365 |
5,411 | #include <StdInc.h>
#include <Hooking.h>
#include <netObjectMgr.h>
static rage::netObjectMgr** g_objectMgr;
static hook::cdecl_stub<rage::netObject*(rage::netObjectMgr*, uint16_t, bool)> _getNetworkObject([]()
{
return hook::get_pattern("44 38 B1 08 27 00 00 0F 84", -0x23);
});
namespace rage
{
netObjectMgr* netObjectMgr::GetInstance()
{
return *g_objectMgr;
}
netObject* netObjectMgr::GetNetworkObject(uint16_t id, bool a3)
{
return _getNetworkObject(this, id, a3);
}
}
static HookFunction hookFunction([]()
{
// 1737: arxan!!
// 2060: arxan!!!!
g_objectMgr = hook::get_address<rage::netObjectMgr**>(hook::get_pattern("2B C3 3D 88 13 00 00 0F 82 ? ? ? ? 48 8B 05", 16));
});
| 283 |
1,948 | /*
* Copyright (c) 2021 VMware, Inc. or its affiliates, 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.netty.examples.documentation.udp.client.uds;
import io.netty.channel.unix.DomainSocketAddress;
import reactor.core.publisher.Mono;
import reactor.netty.Connection;
import reactor.netty.udp.UdpClient;
import java.io.File;
public class Application {
public static void main(String[] args) {
Connection connection =
UdpClient.create()
.bindAddress(Application::newDomainSocketAddress)
.remoteAddress(() -> new DomainSocketAddress("/tmp/test-server.sock")) //<1>
.handle((in, out) ->
out.sendString(Mono.just("hello"))
.then(in.receive()
.asString()
.doOnNext(System.out::println)
.then()))
.connectNow();
connection.onDispose()
.block();
}
private static DomainSocketAddress newDomainSocketAddress() {
try {
File tempFile = new File("/tmp/test-client.sock");
tempFile.delete();
tempFile.deleteOnExit();
return new DomainSocketAddress(tempFile);
}
catch (Exception e) {
throw new RuntimeException("Error creating a temporary file", e);
}
}
} | 676 |
348 | {"nom":"Saint-Germain-la-Blanche-Herbe","circ":"1ère circonscription","dpt":"Calvados","inscrits":1736,"abs":868,"votants":868,"blancs":16,"nuls":5,"exp":847,"res":[{"nuance":"REM","nom":"<NAME>","voix":320},{"nuance":"FI","nom":"Mme <NAME>","voix":107},{"nuance":"SOC","nom":"M. <NAME>","voix":99},{"nuance":"UDI","nom":"Mme <NAME>","voix":90},{"nuance":"FN","nom":"Mme <NAME>","voix":87},{"nuance":"ECO","nom":"M. <NAME>","voix":37},{"nuance":"DVG","nom":"<NAME>","voix":30},{"nuance":"COM","nom":"Mme <NAME>","voix":24},{"nuance":"EXG","nom":"M. <NAME>","voix":13},{"nuance":"EXG","nom":"<NAME>","voix":12},{"nuance":"ECO","nom":"M. <NAME>","voix":10},{"nuance":"DLF","nom":"Mme <NAME>","voix":9},{"nuance":"DIV","nom":"Mme <NAME>","voix":6},{"nuance":"DVD","nom":"M. <NAME>","voix":2},{"nuance":"DVG","nom":"Mme <NAME>","voix":1},{"nuance":"DVG","nom":"Mme <NAME>","voix":0},{"nuance":"DVG","nom":"M. <NAME>","voix":0}]} | 381 |
359 | {
"model": {
"category": "CNN",
"description": "Trained SqueezeNet model on Caffe2",
"files": {
"golden_output": {
"filename": "labels.txt",
"location": "https://s3.amazonaws.com/download.caffe2.ai/models/benchmark_models/images_tensor.txt",
"md5": "6c4c7ba189284368b1956246f7e3dce1"
},
"init": {
"filename": "init_net.pb",
"location": "https://s3.amazonaws.com/download.caffe2.ai/models/squeezenet/init_net.pb",
"md5": "a589d31d93c44d353ae2cd92af4d5a3f"
},
"predict": {
"filename": "predict_net.pb",
"location": "https://s3.amazonaws.com/download.caffe2.ai/models/squeezenet/predict_net.pb",
"md5": "694bfdd02e9ccb57bfc4acb451fbfb2d"
}
},
"format": "caffe2",
"kind": "deployment",
"name": "squeezenet"
},
"tests": [
{
"commands": [
"{program} --net {files.predict} --init_net {files.init} --warmup {warmup} --iter {iter} --input \"data\" --input_file {input_files.images_tensor} --input_type float --output softmaxout --text_output true --output_folder '{TGTDIR}'"
],
"identifier": "{ID}",
"input_files": {
"images_tensor": {
"filename": "images_tensor.pb",
"location": "https://s3.amazonaws.com/download.caffe2.ai/models/benchmark_models/images_tensor.pb",
"md5": "2dd998216e13eaa470d6f38fb52e83d7"
}
},
"iter": 1,
"metric": "accuracy",
"output_files": {
"softmaxout": {
"filename": "softmaxout.txt",
"location": "{TGTDIR}/softmaxout.txt"
}
},
"postprocess": {
"commands": [
"{FAIPEPROOT}/libraries/python/classification_compare.py --name {name} --benchmark-output {output_files.softmaxout} --labels {files.golden_output} --top 1 --metric-keyword 'Caffe2Observer ' "
]
},
"warmup": 0
}
]
}
| 958 |
1,099 | <filename>go/deps.bzl
# Copyright 2019 The Bazel 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.
# deps.bzl loads definitions for use in WORKSPACE files. It's important
# to keep this file and the .bzl files it loads separate from the files
# loaded by def.bzl. def.bzl and its dependencies may depend on repositories
# declared here, but at the time this file is loaded, we can't assume
# anything has been declared.
load(
"@io_bazel_rules_go//go/private:repositories.bzl",
_go_rules_dependencies = "go_rules_dependencies",
)
load(
"@io_bazel_rules_go//go/private:sdk.bzl",
_go_download_sdk = "go_download_sdk",
_go_host_sdk = "go_host_sdk",
_go_local_sdk = "go_local_sdk",
_go_register_toolchains = "go_register_toolchains",
_go_wrap_sdk = "go_wrap_sdk",
)
go_rules_dependencies = _go_rules_dependencies
go_register_toolchains = _go_register_toolchains
go_download_sdk = _go_download_sdk
go_host_sdk = _go_host_sdk
go_local_sdk = _go_local_sdk
go_wrap_sdk = _go_wrap_sdk
| 521 |
3,263 | /*
* Copyright 2019 Immutables Authors and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.immutables.criteria.geode;
import io.reactivex.Flowable;
import io.reactivex.subscribers.TestSubscriber;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.pdx.ReflectionBasedAutoSerializer;
import org.immutables.criteria.backend.WatchEvent;
import org.immutables.criteria.personmodel.Person;
import org.immutables.criteria.personmodel.PersonCriteria;
import org.immutables.criteria.personmodel.PersonGenerator;
import org.immutables.criteria.personmodel.PersonRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.stream.Collectors;
import static org.immutables.check.Checkers.check;
/**
* Unfortunately CQ can't be tested with an embedded server. For Geode, there can be only
* one instance of Cache in JVM: server or client. CQ is client / server topology.
*
* <p>This test requires an external Geode instance
*
* <p>Temporary test until we have a proper way to start real geode server
*
* <pre>
* copy artifact jars from common/target/*.jar into $GEMFIRE_HOME/extensions/
* manually start gfsh
* $ start locator --name=locator1 --port=10334
* $ start server --name=server1 --server-port=40411
* $ create region --name=persons --type=REPLICATE
* </pre>
*/
@Disabled // ignored because requires external gemfire instance
public class GeodeCqTest {
private ClientCache clientCache;
private Region<String, Person> region;
@BeforeEach
public void setUp() throws Exception {
this.clientCache = new ClientCacheFactory()
.addPoolLocator("127.0.0.1", 10334)
.setPdxSerializer(new ReflectionBasedAutoSerializer(Person.class.getPackage().getName()))
.setPoolSubscriptionEnabled(true)
.create();
this.region = clientCache
.<String, Person>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
.create("persons");
region.clear();
}
@AfterEach
public void tearDown() throws Exception {
if (clientCache != null) {
clientCache.close();
}
}
@Test
public void pubsub() throws Exception {
PersonRepository repository = new PersonRepository(new GeodeBackend(GeodeSetup.of(x -> region)));
TestSubscriber<WatchEvent<Person>> events = Flowable.fromPublisher(repository.watcher(PersonCriteria.person).watch())
.test();
final PersonGenerator generator = new PersonGenerator();
final int count = 4;
for (int i = 0; i < count; i++) {
repository.insert(generator.next().withId("id" + i));
}
check(region.keySet()).notEmpty();
// ensure (de)serialization is successful
check(region.query("true")).hasSize(count);
events.awaitCount(count);
events.assertNoErrors();
events.assertValueCount(count);
check(events.values().stream().map(e -> e.newValue().get().id()).collect(Collectors.toList())).hasContentInAnyOrder("id0", "id1", "id2", "id3");
}
}
| 1,248 |
988 | //------------------------------------------------------------------------------
// GB_mex_dup: copy a matrix
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// copy and typecast a matrix
#include "GB_mex.h"
#define USAGE "C = GB_mex_dup (A, type, method, sparsity)"
#define FREE_ALL \
{ \
GrB_Matrix_free_(&A) ; \
GrB_Matrix_free_(&C) ; \
GrB_Descriptor_free_(&desc) ; \
GB_mx_put_global (true) ; \
}
void mexFunction
(
int nargout,
mxArray *pargout [ ],
int nargin,
const mxArray *pargin [ ]
)
{
bool malloc_debug = GB_mx_get_global (true) ;
GrB_Matrix A = NULL, C = NULL ;
GrB_Descriptor desc = NULL ;
// check inputs
if (nargout > 1 || nargin < 1 || nargin > 4)
{
mexErrMsgTxt ("Usage: " USAGE) ;
}
#define GET_DEEP_COPY ;
#define FREE_DEEP_COPY ;
// get A (shallow copy)
A = GB_mx_mxArray_to_Matrix (pargin [0], "A input", false, true) ;
if (A == NULL)
{
FREE_ALL ;
mexErrMsgTxt ("A failed") ;
}
// get ctype of output matrix
GrB_Type ctype = GB_mx_string_to_Type (PARGIN (1), A->type) ;
// get method
int GET_SCALAR (2, int, method, 0) ;
// get sparsity
int GET_SCALAR (3, int, sparsity, GxB_DEFAULT) ;
if (ctype == A->type)
{
// copy C with the same type as A, with default sparsity
if (method == 0 && sparsity == GxB_DEFAULT)
{
METHOD (GrB_Matrix_dup (&C, A)) ;
}
else
{
// try another method, just for testing (see User Guide)
// C = create an exact copy of A, just like GrB_Matrix_dup
GrB_Type type ;
GrB_Index nrows, ncols ;
#undef GET_DEEP_COPY
#undef FREE_DEEP_COPY
#define GET_DEEP_COPY \
{ \
GxB_Matrix_type (&type, A) ; \
GrB_Matrix_nrows (&nrows, A) ; \
GrB_Matrix_ncols (&ncols, A) ; \
GrB_Matrix_new (&C, type, nrows, ncols) ; \
GrB_Descriptor_new (&desc) ; \
if (sparsity != GxB_DEFAULT) \
{ \
GxB_Matrix_Option_set (C, GxB_SPARSITY_CONTROL, sparsity) ;\
} \
GxB_Desc_set (desc, GrB_INP0, GrB_TRAN) ; \
}
#define FREE_DEEP_COPY \
{ \
GrB_Matrix_free_(&C) ; \
GrB_Descriptor_free_(&desc) ; \
}
GET_DEEP_COPY ;
if (method == 1)
{
// C = A using GrB_transpose with a desc.inp0 = transpose
METHOD (GrB_transpose (C, NULL, NULL, A, desc)) ;
}
else
{
// C = A using GrB_assign
METHOD (GrB_assign (C, NULL, NULL, A,
GrB_ALL, nrows, GrB_ALL, ncols, NULL)) ;
}
#undef GET_DEEP_COPY
#undef FREE_DEEP_COPY
}
}
else
{
// typecast
if (A->type == Complex && Complex != GxB_FC64)
{
A->type = GxB_FC64 ;
}
// C = (ctype) A
GrB_Index nrows, ncols ;
#define GET_DEEP_COPY \
{ \
GrB_Matrix_nrows (&nrows, A) ; \
GrB_Matrix_ncols (&ncols, A) ; \
GrB_Matrix_new (&C, ctype, nrows, ncols) ; \
GrB_Descriptor_new (&desc) ; \
if (sparsity != GxB_DEFAULT) \
{ \
GxB_Matrix_Option_set (C, GxB_SPARSITY_CONTROL, sparsity) ; \
} \
GxB_Desc_set (desc, GrB_INP0, GrB_TRAN) ; \
}
#define FREE_DEEP_COPY \
{ \
GrB_Matrix_free_(&C) ; \
GrB_Descriptor_free_(&desc) ; \
}
GET_DEEP_COPY ;
if (method == 1)
{
// C = A using GrB_transpose with a desc.inp0 = transpose
METHOD (GrB_transpose (C, NULL, NULL, A, desc)) ;
}
else
{
// C = A using GrB_assign
METHOD (GrB_assign (C, NULL, NULL, A,
GrB_ALL, nrows, GrB_ALL, ncols, NULL)) ;
}
#undef GET_DEEP_COPY
#undef FREE_DEEP_COPY
}
// return C as a struct and free the GraphBLAS C
pargout [0] = GB_mx_Matrix_to_mxArray (&C, "C output", true) ;
FREE_ALL ;
}
| 3,376 |
313 | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.common.util.grpc.reactor.server;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.base.Preconditions;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Empty;
import com.netflix.titus.common.util.ReflectionExt;
import io.grpc.MethodDescriptor;
import io.grpc.ServiceDescriptor;
import io.grpc.protobuf.ProtoMethodDescriptorSupplier;
import org.springframework.aop.support.AopUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.netflix.titus.common.util.grpc.GrpcToReactUtil.toMethodNameFromFullName;
class MethodHandlersBuilder<CONTEXT, REACT_SERVICE> {
private final Map<String, Method> reactorMethodMap;
private final Class<CONTEXT> contextType;
private final List<UnaryMethodHandler> unaryMethodHandlers;
private final List<ServerStreamingMethodHandler> serverStreamingMethodHandlers;
MethodHandlersBuilder(Object reactorService,
ServiceDescriptor serviceDefinition,
Class<CONTEXT> contextType,
Supplier<CONTEXT> contextResolver,
Class<REACT_SERVICE> reactorDetailedFallbackClass) {
// CGLIB proxies do not retain generic type info. For these proxies we rely on a detailed fallback class definition to derive generic type info.
Stream<Method> methodStream = AopUtils.isCglibProxy(reactorService) ? Stream.of(reactorDetailedFallbackClass.getMethods()) : Stream.of(reactorService.getClass().getMethods());
this.reactorMethodMap = methodStream
.filter(m -> !ReflectionExt.isObjectMethod(m))
.collect(Collectors.toMap(Method::getName, Function.identity()));
this.contextType = contextType;
List<UnaryMethodHandler> unaryMethodHandlers = new ArrayList<>();
List<ServerStreamingMethodHandler> serverStreamingMethodHandlers = new ArrayList<>();
serviceDefinition.getMethods().forEach(methodDescriptor -> {
GrpcToReactorMethodBinding binding = findReactorMethod(methodDescriptor);
if (binding.isMono()) {
unaryMethodHandlers.add(new UnaryMethodHandler<>(binding, contextResolver, reactorService));
} else {
serverStreamingMethodHandlers.add(new ServerStreamingMethodHandler<>(binding, contextResolver, reactorService));
}
});
this.unaryMethodHandlers = unaryMethodHandlers;
this.serverStreamingMethodHandlers = serverStreamingMethodHandlers;
}
List<UnaryMethodHandler> getUnaryMethodHandlers() {
return unaryMethodHandlers;
}
List<ServerStreamingMethodHandler> getServerStreamingMethodHandlers() {
return serverStreamingMethodHandlers;
}
private GrpcToReactorMethodBinding findReactorMethod(MethodDescriptor<?, ?> methodDescriptor) {
String methodName = toMethodNameFromFullName(methodDescriptor.getFullMethodName());
Method reactorMethod = reactorMethodMap.get(methodName);
Preconditions.checkNotNull(reactorMethod, "Cannot find corresponding Reactor method for: {}", methodDescriptor);
ProtoMethodDescriptorSupplier methodDescriptorSupplier = (ProtoMethodDescriptorSupplier) methodDescriptor.getSchemaDescriptor();
Descriptors.MethodDescriptor md = methodDescriptorSupplier.getMethodDescriptor();
String inputTypeName = md.getInputType().getName();
String outputTypeName = md.getOutputType().getName();
Class<?> reactorReturnType = reactorMethod.getReturnType();
boolean isMono = reactorReturnType.isAssignableFrom(Mono.class);
boolean isFlux = !isMono && reactorReturnType.isAssignableFrom(Flux.class);
Preconditions.checkArgument(isMono || isFlux, "Mono or Flux return types allowed only");
Type[] returnTypeParameters = ((ParameterizedType) reactorMethod.getGenericReturnType()).getActualTypeArguments();
Preconditions.checkArgument(
returnTypeParameters != null && returnTypeParameters.length == 1,
"Expected one type parameter in the return type: %s", methodDescriptor.getFullMethodName()
);
Class returnTypeParameter = (Class) returnTypeParameters[0];
// Check return types
if (returnTypeParameter == Void.class) {
Preconditions.checkArgument(
outputTypeName.equals("Empty"),
"Reactor Mono<Void>/Flux<Void> can be mapped to GRPC/Empty only: %s", methodDescriptor.getFullMethodName()
);
} else {
Preconditions.checkArgument(
returnTypeParameter.getSimpleName().equals(outputTypeName),
"Different GRPC and Reactor API return types: %s", methodDescriptor.getFullMethodName()
);
}
// Check method arguments
if (reactorMethod.getParameterCount() == 0) {
Preconditions.checkArgument(
inputTypeName.equals(Empty.class.getSimpleName()),
"Only Empty request argument allowed for Reactor methods with no parameters: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, -1, isMono, returnTypeParameter);
}
if (reactorMethod.getParameterCount() == 1) {
if (reactorMethod.getParameterTypes()[0] == contextType) {
Preconditions.checkArgument(
inputTypeName.equals(Empty.class.getSimpleName()),
"Only Empty request argument allowed for Reactor methods with no parameters: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, 0, isMono, returnTypeParameter);
}
Preconditions.checkArgument(
inputTypeName.equals(reactorMethod.getParameterTypes()[0].getSimpleName()),
"Reactor and GRPC parameter types do not match: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, -1, isMono, returnTypeParameter);
}
if (reactorMethod.getParameterCount() == 2) {
Preconditions.checkArgument(
reactorMethod.getParameterTypes()[0] == contextType || reactorMethod.getParameterTypes()[1] == contextType,
"Expected one GRPC method argument, and one CallMetadata value in Reactor method mapped to: %s", methodDescriptor.getFullMethodName()
);
int callMetadataPos = reactorMethod.getParameterTypes()[0] == contextType ? 0 : 1;
int grpcArgumentPos = callMetadataPos == 0 ? 1 : 0;
Preconditions.checkArgument(
inputTypeName.equals(reactorMethod.getParameterTypes()[grpcArgumentPos].getSimpleName()),
"Reactor and GRPC parameter types do not match: %s", methodDescriptor.getFullMethodName()
);
return new GrpcToReactorMethodBinding<>(methodDescriptor, reactorMethod, callMetadataPos, isMono, returnTypeParameter);
}
throw new IllegalArgumentException("Cannot map GRPC method to any reactor method: " + methodDescriptor.getFullMethodName());
}
}
| 3,136 |
325 | <filename>Code/src/main/java/nl/utwente/viskell/ui/components/Connection.java
package nl.utwente.viskell.ui.components;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Point2D;
import javafx.scene.paint.Color;
import javafx.scene.shape.CubicCurve;
import javafx.scene.transform.Transform;
import nl.utwente.viskell.haskell.expr.LetExpression;
import nl.utwente.viskell.haskell.type.*;
import nl.utwente.viskell.ui.BlockContainer;
import nl.utwente.viskell.ui.ComponentLoader;
import nl.utwente.viskell.ui.serialize.Bundleable;
import com.google.common.collect.ImmutableMap;
/**
* This is a Connection that represents a flow between an {@link InputAnchor}
* and {@link OutputAnchor}. Both anchors are stored referenced respectively as
* startAnchor and endAnchor {@link Optional} within this class.
* Visually a connection is represented as a cubic Bezier curve.
*
* Connection is also a changeListener for a Transform, in order to be able to
* update the Line's position when the anchor's positions change.
*/
public class Connection extends CubicCurve implements
ChangeListener<Transform>, Bundleable, ComponentLoader {
/**
* Control offset for this bezier curve of this line.
* It determines how a far a line attempts to goes straight from its end points.
*/
public static final double BEZIER_CONTROL_OFFSET = 150f;
/**
* Labels for serialization to and from JSON
*/
private static final String SOURCE_LABEL = "from";
private static final String SINK_LABEL = "to";
/** Starting point of this Line that can be Anchored onto other objects. */
private final OutputAnchor startAnchor;
/** Ending point of this Line that can be Anchored onto other objects. */
private final InputAnchor endAnchor;
/** Whether this connection produced an error in the latest type unification. */
private boolean errorState;
/** Whether this connection is impossible due to scope restrictions */
private boolean scopeError;
/**
* Construct a new Connection.
* @param source The OutputAnchor this connection comes from
* @param sink The InputAnchor this connection goes to
*/
public Connection(OutputAnchor source, InputAnchor sink) {
this.setMouseTransparent(true);
this.setFill(null);
this.startAnchor = source;
this.endAnchor = sink;
this.errorState = false;
this.scopeError = false;
source.getPane().addConnection(this);
this.invalidateAnchorPositions();
this.startAnchor.addConnection(this);
this.startAnchor.localToSceneTransformProperty().addListener(this);
this.endAnchor.setConnection(this);
this.endAnchor.localToSceneTransformProperty().addListener(this);
// typecheck the new connection to mark potential errors at the best location
try {
TypeChecker.unify("new connection", this.startAnchor.getType(Optional.of(this)), this.endAnchor.getType());
} catch (HaskellTypeError e) {
this.endAnchor.setErrorState(true);
this.errorState = true;
}
}
/**
* @return the output anchor of this connection.
*/
public OutputAnchor getStartAnchor() {
return this.startAnchor;
}
/**
* @return the input anchor of this connection.
*/
public InputAnchor getEndAnchor() {
return this.endAnchor;
}
/**
* Handles the upward connections changes through an connection.
* Also perform typechecking for this connection.
* @param finalPhase whether the change propagation is in the second (final) phase.
*/
public void handleConnectionChangesUpwards(boolean finalPhase) {
// first make sure the output anchor block and types are fresh
if (!finalPhase) {
this.startAnchor.prepareConnectionChanges();
}
// for connections in error state typechecking is delayed to the final phase to keep error locations stable
if (finalPhase == this.errorState) {
try {
// first a trial unification on a copy of the types to minimize error propagation
TypeScope scope = new TypeScope();
TypeChecker.unify("trial connection", this.startAnchor.getType(Optional.of(this)).getFresh(scope), this.endAnchor.getType().getFresh(scope));
// unify the actual types
TypeChecker.unify("connection", this.startAnchor.getType(Optional.of(this)), this.endAnchor.getType());
this.endAnchor.setErrorState(false);
this.errorState = false;
} catch (HaskellTypeError e) {
this.endAnchor.setErrorState(true);
this.errorState = true;
}
}
// continue with propagating connections changes in the output anchor block
this.startAnchor.handleConnectionChanges(finalPhase);
}
/**
* Removes this Connection, disconnecting its anchors and removing this Connection from the pane it is on.
*/
public final void remove() {
this.startAnchor.localToSceneTransformProperty().removeListener(this);
this.endAnchor.localToSceneTransformProperty().removeListener(this);
this.startAnchor.dropConnection(this);
this.endAnchor.removeConnections();
this.startAnchor.getPane().removeConnection(this);
// propagate the connection changes of both anchors simultaneously in two phases to avoid duplicate work
this.startAnchor.handleConnectionChanges(false);
this.endAnchor.handleConnectionChanges(false);
this.startAnchor.handleConnectionChanges(true);
this.endAnchor.handleConnectionChanges(true);
}
@Override
public final void changed(ObservableValue<? extends Transform> observable, Transform oldValue, Transform newValue) {
this.invalidateAnchorPositions();
}
/** Update the UI positions of both start and end anchors. */
private void invalidateAnchorPositions() {
this.setStartPosition(this.startAnchor.getAttachmentPoint());
this.setEndPosition(this.endAnchor.getAttachmentPoint());
}
@Override
public String toString() {
return "Connection connecting \n(out) " + startAnchor + " to\n(in) " + endAnchor;
}
@Override
public Map<String, Object> toBundle() {
ImmutableMap.Builder<String, Object> bundle = ImmutableMap.builder();
bundle.put(SOURCE_LABEL, this.startAnchor.toBundle());
bundle.put(SINK_LABEL, this.endAnchor.toBundle());
return bundle.build();
}
public static void fromBundle(Map<String,Object> connectionBundle,
Map<Integer, Block> blockLookupTable) {
Map<String,Object> source = (Map<String,Object>)connectionBundle.get(SOURCE_LABEL);
Integer sourceId = ((Double)source.get(ConnectionAnchor.BLOCK_LABEL)).intValue();
Block sourceBlock = blockLookupTable.get(sourceId);
OutputAnchor sourceAnchor = sourceBlock.getAllOutputs().get(0);
Map<String,Object> sink = (Map<String,Object>)connectionBundle.get(SINK_LABEL);
Integer sinkId = ((Double)sink.get(ConnectionAnchor.BLOCK_LABEL)).intValue();
Integer sinkAnchorNumber = ((Double)sink.get(ConnectionAnchor.ANCHOR_LABEL)).intValue();
Block sinkBlock = blockLookupTable.get(sinkId);
InputAnchor sinkAnchor = sinkBlock.getAllInputs().get(sinkAnchorNumber);
Connection connection = new Connection(sourceAnchor, sinkAnchor);
connection.invalidateVisualState();
sinkBlock.invalidateVisualState();
}
/**
* Sets the start coordinates for this Connection.
* @param point Coordinates local to this Line's parent.
*/
private void setStartPosition(Point2D point) {
this.setStartX(point.getX());
this.setStartY(point.getY());
updateBezierControlPoints(this);
}
/**
* Sets the end coordinates for this Connection.
* @param point coordinates local to this Line's parent.
*/
private void setEndPosition(Point2D point) {
this.setEndX(point.getX());
this.setEndY(point.getY());
updateBezierControlPoints(this);
}
/** Returns the current bezier offset based on the current start and end positions. */
private static double getBezierYOffset(CubicCurve wire) {
double distX = Math.abs(wire.getEndX() - wire.getStartX())/3;
double diffY = wire.getEndY() - wire.getStartY();
double distY = diffY > 0 ? diffY/2 : Math.max(0, -diffY-10);
if (distY < BEZIER_CONTROL_OFFSET) {
if (distX < BEZIER_CONTROL_OFFSET) {
// short lines are extra flexible
return Math.max(1, Math.max(distX, distY));
} else {
return BEZIER_CONTROL_OFFSET;
}
} else {
return Math.cbrt(distY / BEZIER_CONTROL_OFFSET) * BEZIER_CONTROL_OFFSET;
}
}
/** Updates the Bezier offset (curviness) according to the current start and end positions. */
protected static void updateBezierControlPoints(CubicCurve wire) {
double yOffset = getBezierYOffset(wire);
wire.setControlX1(wire.getStartX());
wire.setControlY1(wire.getStartY() + yOffset);
wire.setControlX2(wire.getEndX());
wire.setControlY2(wire.getEndY() - yOffset);
}
protected static double lengthSquared(CubicCurve wire) {
double diffX = wire.getStartX() - wire.getEndX();
double diffY = wire.getStartY() - wire.getEndY();
return diffX*diffX + diffY*diffY;
}
/**
* Extends the expression graph to include all subexpression required
* @param exprGraph the let expression representing the current expression graph
* @param container the container to which this expression graph is constrained
* @param outsideAnchors a mutable set of required OutputAnchors from a surrounding container
*/
protected void extendExprGraph(LetExpression exprGraph, BlockContainer container, Set<OutputAnchor> outsideAnchors) {
OutputAnchor anchor = this.getStartAnchor();
if (container == anchor.getContainer())
anchor.extendExprGraph(exprGraph, container, outsideAnchors);
else
outsideAnchors.add(anchor);
}
public void invalidateVisualState() {
this.scopeError = !this.endAnchor.getContainer().isContainedWithin(this.startAnchor.getContainer());
if (this.errorState) {
this.setStroke(Color.RED);
this.getStrokeDashArray().clear();
this.setStrokeWidth(3);
} else if (this.scopeError) {
this.setStroke(Color.RED);
this.setStrokeWidth(3);
if (this.getStrokeDashArray().isEmpty()) {
this.getStrokeDashArray().addAll(10.0, 10.0);
}
} else {
this.setStroke(Color.BLACK);
this.getStrokeDashArray().clear();
this.setStrokeWidth(calculateTypeWidth(this.endAnchor.getType()));
}
}
private static int calculateTypeWidth(Type wireType) {
Type type = wireType.getConcrete();
int fcount = 0;
while (type instanceof FunType) {
fcount++;
type = ((FunType)type).getResult();
}
if (fcount > 0) {
return 4 + 2*fcount;
}
int arity = 0;
while (type instanceof TypeApp) {
arity++;
type = ((TypeApp)type).getTypeFun();
}
if (type instanceof ListTypeCon) {
return 5;
}
return 3 + arity;
}
public boolean hasTypeError() {
return this.errorState;
}
public boolean hasScopeError() {
return this.scopeError;
}
}
| 4,579 |
5,169 | {
"name": "SwiftyState",
"version": "1.1.0",
"summary": "A State Engine with a debug UI on iOS and iPadOS",
"description": "With SwiftyState you create a single struct to keep all your data in, then you create actions to change that data. That struct is a central source of truth and you can subscribe to receive changes without worry about the rest of the application. You also get a GUI where you can see the state and even revert and replay the changes.",
"homepage": "https://github.com/mrtksn/SwiftyState",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"mrtksn": "<EMAIL>"
},
"source": {
"git": "https://github.com/mrtksn/SwiftyState.git",
"tag": "1.1.0"
},
"platforms": {
"ios": "11.0"
},
"swift_versions": "5.0",
"source_files": "SwiftyState/Classes/**/*",
"swift_version": "5.0"
}
| 308 |
687 | <reponame>Madara9744/kestra
package io.kestra.core.tasks.scripts;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public abstract class AbstractLogThread extends Thread {
private final InputStream inputStream;
private int logsCount = 0;
protected final Map<String, Object> outputs = new ConcurrentHashMap<>();
protected AbstractLogThread(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
this.logsCount++;
this.call(line);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
abstract protected void call(String line);
public int getLogsCount() {
return logsCount;
}
public Map<String, Object> getOutputs() {
return outputs;
}
}
| 545 |
506 | <filename>atcoder/abc085/cgen.py<gh_stars>100-1000
#!/usr/bin/env python2
import random
a = random.randint(0, 10)
b = random.randint(0, 10)
c = random.randint(0, 10)
print a + b + c, a * 10000 + b * 5000 + c * 1000
print a, b, c
| 101 |
945 | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 itkGPUCastImageFilter_hxx
#define itkGPUCastImageFilter_hxx
#include "itkGPUCastImageFilter.h"
#include "itkOpenCLUtil.h"
namespace itk
{
template <typename TInputImage, typename TOutputImage>
GPUCastImageFilter<TInputImage, TOutputImage>::GPUCastImageFilter()
{
std::ostringstream defines;
if (TInputImage::ImageDimension > 3 || TInputImage::ImageDimension < 1)
{
itkExceptionMacro("GPUCastImageFilter supports 1/2/3D image.");
}
defines << "#define DIM_" << TInputImage::ImageDimension << "\n";
defines << "#define INPIXELTYPE ";
GetTypenameInString(typeid(typename TInputImage::PixelType), defines);
defines << "#define OUTPIXELTYPE ";
GetTypenameInString(typeid(typename TOutputImage::PixelType), defines);
// OpenCL kernel source
const char * GPUSource = GPUCastImageFilterKernel::GetOpenCLSource();
// load and build program
this->m_GPUKernelManager->LoadProgramFromString(GPUSource, defines.str().c_str());
// create kernel
this->m_UnaryFunctorImageFilterGPUKernelHandle = this->m_GPUKernelManager->CreateKernel("CastImageFilter");
}
template <typename TInputImage, typename TOutputImage>
void
GPUCastImageFilter<TInputImage, TOutputImage>::GPUGenerateData()
{
itkDebugMacro(<< "Calling GPUCastImageFilter::GPUGenerateData()");
GPUSuperclass::GPUGenerateData();
itkDebugMacro(<< "GPUCastImageFilter::GPUGenerateData() finished");
}
} // end of namespace itk
#endif /* itkGPUCastImageFilter_hxx */
| 670 |
518 | <gh_stars>100-1000
{
"name": "Lucca",
"category": "HR & Legal",
"start_url": "https://{{subdomain}}.ilucca.net/login/",
"icons": [
{
"src": "https://cdn.filestackcontent.com/JH5y8urQP6dUqZyVMLGS",
"platform": "browserx"
}
],
"theme_color": "#F27020",
"scope": "https://*.ilucca.net",
"bx_legacy_service_id": "lucca",
"bx_multi_instance_config": {
"preset": "subdomain",
"presets": [
"subdomain"
],
"instance_label_tpl": "{{subdomain}}.ilucca.net",
"start_url_tpl": "https://{{subdomain}}.ilucca.net/login/",
"subdomain_title": "Lucca domain",
"subdomain_ui_help": "Enter your company Lucca domain.",
"subdomain_ui_suffix": ".ilucca.net"
}
}
| 331 |
3,552 | /*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.gateway.handler.predicate;
import java.time.Duration;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.gateway.handler.predicate.RemoteAddrRoutePredicateFactory.Config;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.gateway.support.ipresolver.XForwardedRemoteAddressResolver;
import org.springframework.cloud.gateway.test.BaseWebClientTests;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.web.reactive.function.client.ClientResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.cloud.gateway.test.TestUtils.assertStatus;
@SpringBootTest(webEnvironment = RANDOM_PORT)
@DirtiesContext
@ActiveProfiles({ "remote-address" })
public class RemoteAddrRoutePredicateFactoryTests extends BaseWebClientTests {
@Test
public void remoteAddrWorks() {
Mono<ClientResponse> result = webClient.get().uri("/ok/httpbin/").exchangeToMono(Mono::just);
StepVerifier.create(result).consumeNextWith(response -> assertStatus(response, HttpStatus.OK)).expectComplete()
.verify(DURATION);
}
@Test
public void remoteAddrRejects() {
Mono<ClientResponse> result = webClient.get().uri("/nok/httpbin/").exchangeToMono(Mono::just);
StepVerifier.create(result).consumeNextWith(response -> assertStatus(response, HttpStatus.NOT_FOUND))
.expectComplete().verify(DURATION);
}
@Test
public void remoteAddrWorksWithXForwardedRemoteAddress() {
Mono<ClientResponse> result = webClient.get().uri("/xforwardfor").header("X-Forwarded-For", "12.34.56.78")
.exchangeToMono(Mono::just);
StepVerifier.create(result).consumeNextWith(response -> assertStatus(response, HttpStatus.OK)).expectComplete()
.verify(Duration.ofSeconds(20));
}
@Test
public void toStringFormat() {
Config config = new Config();
config.setSources("1.2.3.4", "5.6.7.8");
Predicate predicate = new RemoteAddrRoutePredicateFactory().apply(config);
assertThat(predicate.toString()).contains("RemoteAddrs: [1.2.3.4, 5.6.7.8]");
}
@EnableAutoConfiguration
@SpringBootConfiguration
@Import(DefaultTestConfig.class)
public static class TestConfig {
@Value("${test.uri}")
String uri;
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("x_forwarded_for_test",
r -> r.path("/xforwardfor").and()
.remoteAddr(XForwardedRemoteAddressResolver.maxTrustedIndex(1), "12.34.56.78")
.filters(f -> f.setStatus(200)).uri(uri))
.build();
}
}
}
| 1,277 |
2,611 | <filename>ApkPatchLibraryServer/jni/com_cundong_utils_DiffUtils.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_cundong_utils_JDiff */
#ifndef _Included_com_cundong_utils_JDiff
#define _Included_com_cundong_utils_JDiff
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_cundong_utils_DiffUtils
* Method: genDiff
* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_cundong_utils_DiffUtils_genDiff
(JNIEnv *, jclass, jstring, jstring, jstring);
#ifdef __cplusplus
}
#endif
#endif
| 244 |
747 | //
// bisearch.c
// Algorithms - Binary search
//
// Created by YourtionGuo on 11/05/2017.
// Copyright © 2017 Yourtion. All rights reserved.
//
#include <stdlib.h>
#include <string.h>
#include "search.h"
#pragma mark - Public
int bisearch(void *sorted, const void *target, int size, int esize,
int(*compare)(const void *key1, const void *key2))
{
int left, middle, right;
/// 持续执行搜索,直到 left 和 right 相交
left = 0;
right = size - 1;
while (left <= right) {
middle = (left + right) / 2;
switch (compare(((char *)sorted + (esize * middle)), target)) {
case -1:
/// 准备向中间元素右方执行搜索
left = middle + 1;
break;
case 1:
/// 准备向中间元素左方执行搜索
right = middle - 1;
break;
case 0:
/// 将找到的元素索引返回
return middle;
}
}
/// 没找到元素返回 -1
return -1;
}
| 483 |
14,668 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/devtools/device/cast_device_provider.h"
#include "base/bind.h"
#include "chrome/browser/devtools/device/android_device_manager.h"
#include "net/base/host_port_pair.h"
#include "testing/gtest/include/gtest/gtest.h"
using local_discovery::ServiceDescription;
using DeviceInfo = AndroidDeviceManager::DeviceInfo;
using BrowserInfo = AndroidDeviceManager::BrowserInfo;
namespace {
void CompareDeviceInfo(bool* was_run,
const DeviceInfo& expected,
const DeviceInfo& actual) {
EXPECT_EQ(expected.model, actual.model);
EXPECT_EQ(expected.connected, actual.connected);
const BrowserInfo& exp_br_info = expected.browser_info[0];
const BrowserInfo& act_br_info = actual.browser_info[0];
EXPECT_EQ(exp_br_info.socket_name, act_br_info.socket_name);
EXPECT_EQ(exp_br_info.display_name, act_br_info.display_name);
EXPECT_EQ(exp_br_info.type, act_br_info.type);
*was_run = true;
}
void DummyCallback(bool* was_run, const DeviceInfo& device_info) {
*was_run = true;
}
} // namespace
TEST(CastDeviceProviderTest, ServiceDiscovery) {
scoped_refptr<CastDeviceProvider> device_provider_ = new CastDeviceProvider();
// Create a cast service.
const std::string cast_display_name = "FakeCast1337";
const std::string cast_service_type = "_googlecast._tcp.local";
const std::string cast_service_name = "abcdefgh";
const std::string cast_service_model = "Fake Cast Device";
ServiceDescription cast_service;
cast_service.service_name = cast_service_name + "." + cast_service_type;
cast_service.address = net::HostPortPair("192.168.1.101", 8009);
cast_service.metadata.push_back("id=0123456789abcdef0123456789abcdef");
cast_service.metadata.push_back("ve=00");
cast_service.metadata.push_back("md=" + cast_service_model);
cast_service.metadata.push_back("fn=" + cast_display_name);
ASSERT_TRUE(cast_service.ip_address.AssignFromIPLiteral("192.168.1.101"));
device_provider_->OnDeviceChanged(cast_service_type, true, cast_service);
BrowserInfo exp_browser_info;
exp_browser_info.socket_name = "9222";
exp_browser_info.display_name = cast_display_name; // From metadata::fn
exp_browser_info.type = BrowserInfo::kTypeChrome;
DeviceInfo expected;
expected.model = cast_service_model; // From metadata::md
expected.connected = true;
expected.browser_info.push_back(exp_browser_info);
bool was_run = false;
// Callback should be run, and the queried service should match the expected.
device_provider_->QueryDeviceInfo(
cast_service.address.host(),
base::BindOnce(&CompareDeviceInfo, &was_run, expected));
ASSERT_TRUE(was_run);
was_run = false;
// Create a non-cast service.
const std::string other_service_display_name = "OtherDevice";
const std::string other_service_type = "_other._tcp.local";
const std::string other_service_model = "Some Other Device";
ServiceDescription other_service;
other_service.service_name =
other_service_display_name + "." + other_service_type;
other_service.address = net::HostPortPair("10.64.1.101", 1234);
other_service.metadata.push_back("id=0123456789abcdef0123456789abcdef");
other_service.metadata.push_back("ve=00");
other_service.metadata.push_back("md=" + other_service_model);
ASSERT_TRUE(other_service.ip_address.AssignFromIPLiteral("10.64.1.101"));
// Callback should not be run, since this service is not yet discovered.
device_provider_->QueryDeviceInfo(other_service.address.host(),
base::BindOnce(&DummyCallback, &was_run));
ASSERT_FALSE(was_run);
device_provider_->OnDeviceChanged(cast_service_type, true, other_service);
// Callback should not be run, since non-cast services are not discovered by
// this device provider.
device_provider_->QueryDeviceInfo(other_service.address.host(),
base::BindOnce(&DummyCallback, &was_run));
ASSERT_FALSE(was_run);
// Remove the cast service.
device_provider_->OnDeviceRemoved(cast_service_type,
cast_service.service_name);
// Callback should not be run, since the cast service has been removed.
device_provider_->QueryDeviceInfo(cast_service.address.host(),
base::BindOnce(&DummyCallback, &was_run));
ASSERT_FALSE(was_run);
}
| 1,616 |
3,084 | <reponame>ixjf/Windows-driver-samples<filename>avstream/avscamera/sys/Util.cpp
/**************************************************************************
A/V Stream Camera Sample
Copyright (c) 2013, Microsoft Corporation.
File:
util.cpp
Abstract:
Contains miscellaneous helper functions such as random number
generation and bounds checking functions.
History:
created 7/12/2013
**************************************************************************/
#include "Common.h"
#include <bcrypt.h>
#ifdef ALLOC_PRAGMA
#pragma code_seg()
#endif // ALLOC_PRAGMA
//
// Generate a random number using the standard Crypto library.
// Fall back to the QPC, if crypto library reports an error.
//
ULONG
GetRandom(
_In_ ULONG Minimum,
_In_ ULONG Maximum
)
{
ULONG Value=0;
NTSTATUS Status = STATUS_UNSUCCESSFUL;
if( KeGetCurrentIrql()==PASSIVE_LEVEL )
{
Status=
BCryptGenRandom( NULL, (PUCHAR) &Value, sizeof(Value), BCRYPT_USE_SYSTEM_PREFERRED_RNG );
}
// Fallback to QPC if BCRYPT isn't available.
if( !NT_SUCCESS(Status) )
{
LARGE_INTEGER QPC = KeQueryPerformanceCounter(NULL);
Value = QPC.u.LowPart;
}
// Make sure we don't divide by 0.
if( Minimum < Maximum )
{
Value = ((Value - Minimum) % (Maximum - Minimum +1)) + Minimum;
}
else
{
Value = Minimum ;
}
return Value;
}
//
// Generate a random number using the standard Crypto library.
// Fall back to the QPC, if crypto library reports an error.
//
LONG
GetRandom(
_In_ LONG Minimum,
_In_ LONG Maximum
)
{
ULONG Value=0;
NTSTATUS Status = STATUS_UNSUCCESSFUL;
if( KeGetCurrentIrql()==PASSIVE_LEVEL )
{
Status=
BCryptGenRandom( NULL, (PUCHAR) &Value, sizeof(Value), BCRYPT_USE_SYSTEM_PREFERRED_RNG );
}
// Fallback to QPC if BCRYPT isn't available.
if( !NT_SUCCESS(Status) )
{
LARGE_INTEGER QPC = KeQueryPerformanceCounter(NULL);
Value = QPC.u.LowPart;
}
// Make sure we don't divide by 0.
if( Minimum < Maximum )
{
Value = ((Value - Minimum) % (Maximum - Minimum +1)) + Minimum;
}
else
{
Value = Minimum ;
}
return Value;
}
#ifdef ALLOC_PRAGMA
#pragma code_seg("PAGE")
#endif // ALLOC_PRAGMA
//
// Convert an EV Compensation flag into the denominator of a fraction.
//
LONG
EVFlags2Denominator(
_In_ ULONGLONG Flags
)
{
PAGED_CODE( );
static
LONG val[] = {1,2,3,4,6};
switch( Flags )
{
case KSCAMERA_EXTENDEDPROP_EVCOMP_SIXTHSTEP:
return 6;
case KSCAMERA_EXTENDEDPROP_EVCOMP_QUARTERSTEP:
return 4;
case KSCAMERA_EXTENDEDPROP_EVCOMP_THIRDSTEP:
return 3;
case KSCAMERA_EXTENDEDPROP_EVCOMP_HALFSTEP:
return 2;
case KSCAMERA_EXTENDEDPROP_EVCOMP_FULLSTEP:
return 1;
case KSCAMERA_PERFRAMESETTING_AUTO:
return val[GetRandom( (ULONG) 0, (ULONG) SIZEOF_ARRAY(val)-1)];
}
return 0;
}
// Convert white balance presets to a temperature.
ULONG
WhiteBalancePreset2Temperature(
_In_ ULONG WBPreset
)
{
PAGED_CODE();
ULONG temp = 0;
switch (WBPreset)
{
case KSCAMERA_EXTENDEDPROP_WBPRESET_CLOUDY:
temp = 6000;
break;
case KSCAMERA_EXTENDEDPROP_WBPRESET_DAYLIGHT:
temp = 5200;
break;
case KSCAMERA_EXTENDEDPROP_WBPRESET_FLASH:
temp = 6000;
break;
case KSCAMERA_EXTENDEDPROP_WBPRESET_FLUORESCENT:
temp = 4000;
break;
case KSCAMERA_EXTENDEDPROP_WBPRESET_TUNGSTEN:
temp = 3200;
break;
case KSCAMERA_EXTENDEDPROP_WBPRESET_CANDLELIGHT:
temp = 1000;
break;
default:
temp = 5000;
break;
}
return min( max( temp, WHITEBALANCE_MIN ), WHITEBALANCE_MAX );
}
typedef struct
{
LONG exposureBinaryLog;
LONGLONG exposure100ns;
} ExposurePresetStruct;
const ExposurePresetStruct ExposurePresets[] =
{
{ -10, 10000 }, // 1/1024s -> 9765.625 (100 ns) (Min is 1 ms)
{ -9, 19531 }, // 1/512s -> 19531.25 (100 ns)
{ -8, 39063 }, // 1/256s -> 39062.5 (100 ns)
{ -7, 78125 }, // 1/128s -> 78125 (100 ns)
{ -6, 196250 }, // 1/64s -> 196250 (100 ns)
{ -5, 312500 }, // 1/32s -> 312500 (100 ns)
{ -4, 625000 }, // 1/16s -> 625000 (100 ns)
{ -3, 1250000 }, // 1/8s -> 1250000 (100 ns)
{ -2, 2500000 }, // 1/4s -> 2500000 (100 ns)
{ -1, 5000000 }, // 1/2s -> 5000000 (100 ns)
{ 0, 10000000 },// 1s -> 1 * 10000000 (100 ns)
{ 1, 20000000 },// 2s -> 2 * 10000000 (100 ns)
{ 2, 40000000 },// 4s -> 4 * 10000000 (100 ns)
{ 3, 80000000 },// 8s -> 8 * 10000000 (100 ns)
{ 4, 160000000 },// 16s -> 16 * 10000000 (100 ns)
{ 5, 320000000 },// 32s -> 32 * 10000000 (100 ns)
{ 6, 640000000 },// 64s -> 64 * 10000000 (100 ns)
{ 7, 1280000000 },// 128s -> 128 * 10000000 (100 ns)
{ 8, 2560000000 },// 256s -> 256 * 10000000 (100 ns)
{ 9, 3600000000 } // 512s -> 512 * 10000000 (100 ns) (Max is 360 s)
};
const ExposurePresetStruct ExposureMidpoints[] =
{
{ -10, 13811 }, // 2^(-9.5) -> .001381067
{ -9, 27621 }, // 2^(-8.5) -> .002762136
{ -8, 55243 }, // 2^(-7.5) -> .005524271
{ -7, 110485 }, // 2^(-6.5) -> .011048543
{ -6, 220970 }, // 2^(-5.5) -> .022097086
{ -5, 441941 }, // 2^(-4.5) -> .044194174
{ -4, 883883 }, // 2^(-3.5) -> .0883883476
{ -3, 1767767 }, // 2^(-2.5) -> .1767766953
{ -2, 3535534 }, // 2^(-1.5) -> .3535533905
{ -1, 7071067 }, // 2^(-0.5) -> .7071067811
{ 0, 14142136 },// 2^(0.5) -> 1.414213562
{ 1, 28284271 },// 2^(1.5) -> 2.828427125
{ 2, 56568542 },// 2^(2.5) -> 5.656854250
{ 3, 113137085 },// 2^(3.5) -> 11.31370850
{ 4, 226274170 },// 2^(4.5) -> 22.62741700
{ 5, 452548340 },// 2^(5.5) -> 45.25483400
{ 6, 905096680 },// 2^(6.5) -> 90.50966799
{ 7, 1810193360 },// 2^(7.5) -> 181.0193360
{ 8, 3080000000 },// Halfway between 8 and Max: 30800
{ 9, 3600000000 } // Above
};
BOOL
ExposureBinaryLogIsValid(
_In_ LONG ExposureBL
)
{
PAGED_CODE();
return
ExposurePresets[0].exposureBinaryLog <= ExposureBL &&
ExposurePresets[_countof(ExposurePresets) - 1].exposureBinaryLog >= ExposureBL;
}
// Changes a Legacy Preset value into 100 ns units for Exposure. If the
// preset is out of range of what we support, return 0 to indicate failure.
LONGLONG
ExposureBinaryLogTo100ns(
_In_ LONG ExposureBL
)
{
PAGED_CODE( );
for( LONG i = 0; i < _countof(ExposurePresets); i++ )
{
if (ExposureBL == ExposurePresets[i].exposureBinaryLog)
{
return ExposurePresets[i].exposure100ns;
}
}
return 0;
}
LONG
Exposure100nsToBinaryLog(
_In_ LONGLONG Exposure100ns
)
{
PAGED_CODE( );
for( LONG i = 0; i < _countof(ExposureMidpoints) - 1; i++ )
{
if(Exposure100ns <= ExposureMidpoints[i].exposure100ns)
{
return ExposureMidpoints[i].exposureBinaryLog;
}
}
return ExposureMidpoints[_countof(ExposureMidpoints) - 1].exposureBinaryLog;
}
static
ULONGLONG PotentialIsoSetting[] =
{
KSCAMERA_EXTENDEDPROP_ISO_50
, KSCAMERA_EXTENDEDPROP_ISO_80
, KSCAMERA_EXTENDEDPROP_ISO_100
, KSCAMERA_EXTENDEDPROP_ISO_200
, KSCAMERA_EXTENDEDPROP_ISO_400
, KSCAMERA_EXTENDEDPROP_ISO_800
, KSCAMERA_EXTENDEDPROP_ISO_1600
, KSCAMERA_EXTENDEDPROP_ISO_3200
, KSCAMERA_EXTENDEDPROP_ISO_6400
, KSCAMERA_EXTENDEDPROP_ISO_12800
, KSCAMERA_EXTENDEDPROP_ISO_25600
};
//
// Convert ISO preset flags to a preset number
//
ULONG
IsoPreset2Value(
_In_ ULONGLONG Flags
)
{
PAGED_CODE( );
static
ULONG IsoValue[] =
{
50
, 80
, 100
, 200
, 400
, 800
, 1600
, 3200
, 6400
, 12800
, 25600
};
// Simple scan for min
for( ULONG i=0; i<_countof(PotentialIsoSetting); i++ )
{
if( PotentialIsoSetting[i] & Flags )
{
return IsoValue[i];
}
}
return MAXULONG;
}
//
// Convert ISO Mode & Value to legacy presets.
//
// Note: This function will simply pass legacy presets through.
//
ULONGLONG
IsoModeValue2Preset(
_In_ ULONGLONG Mode,
_In_ ULONG Value
)
{
PAGED_CODE( );
// These values are staggerred midpoints along a logrithmic scale.
// Using these pre-calculated values simplifies our search to a
// simple set of comparisons.
static
ULONG IsoValue[] =
{
64 //50 //KSCAMERA_EXTENDEDPROP_ISO_50
,90 //, 80 //KSCAMERA_EXTENDEDPROP_ISO_80
, 142 //, 100 //KSCAMERA_EXTENDEDPROP_ISO_100
, 283 //, 200 //KSCAMERA_EXTENDEDPROP_ISO_200
, 566 //, 400 //KSCAMERA_EXTENDEDPROP_ISO_400
, 1132 //, 800 //KSCAMERA_EXTENDEDPROP_ISO_800
, 2263 //, 1600 //KSCAMERA_EXTENDEDPROP_ISO_1600
, 4526 //, 3200 //KSCAMERA_EXTENDEDPROP_ISO_3200
, 9051 //, 6400 //KSCAMERA_EXTENDEDPROP_ISO_6400
, 18102 //, 12800 //KSCAMERA_EXTENDEDPROP_ISO_12800
};
if( Mode & KSCAMERA_EXTENDEDPROP_ISO_MANUAL )
{
// Simple scan for min
for( ULONG i=0; i<_countof(PotentialIsoSetting)-1; i++ )
{
if( Value < IsoValue[i] )
{
return PotentialIsoSetting[i];
}
}
return KSCAMERA_EXTENDEDPROP_ISO_25600;
}
return Mode;
}
LPCSTR
KSStateToStateName(
_In_ KSSTATE state
)
{
PAGED_CODE( );
static const CHAR *txt[] =
{
"STOP",
"ACQUIRE",
"PAUSE",
"RUN"
};
return ((KSSTATE_STOP <= state && KSSTATE_RUN >= state) ? txt[state] : "UNK");
}
// Debugging helper.
PCSTR
FocusStateDbgTxt(
_In_ KSCAMERA_EXTENDEDPROP_FOCUSSTATE State
)
{
PAGED_CODE();
switch( State )
{
case KSCAMERA_EXTENDEDPROP_FOCUSSTATE_UNINITIALIZED:
return "FOCUSSTATE_UNINITIALIZED";
case KSCAMERA_EXTENDEDPROP_FOCUSSTATE_LOST:
return "FOCUSSTATE_LOST";
case KSCAMERA_EXTENDEDPROP_FOCUSSTATE_SEARCHING:
return "FOCUSSTATE_SEARCHING";
case KSCAMERA_EXTENDEDPROP_FOCUSSTATE_FOCUSED:
return "FOCUSSTATE_FOCUSED";
case KSCAMERA_EXTENDEDPROP_FOCUSSTATE_FAILED:
return "FOCUSSTATE_FAILED";
default:
return "FOCUSSTATE_unknown";
}
}
BOOL
MultiplyCheckOverflow (
ULONG a,
ULONG b,
ULONG *pab
)
/*++
Routine Description:
Perform a 32 bit unsigned multiplication and check for arithmetic overflow.
Arguments:
a -
First operand
b -
Second operand
pab -
Result
Return Value:
TRUE -
no overflow
FALSE -
overflow occurred
--*/
{
PAGED_CODE();
*pab = a * b;
if ((a == 0) || (((*pab) / a) == b))
{
return TRUE;
}
return FALSE;
}
int
DbgRotation2Degrees(
AcpiPldRotation r
)
{
PAGED_CODE();
switch( r )
{
case AcpiPldRotation0 : return 0;
case AcpiPldRotation45 : return 45;
case AcpiPldRotation90 : return 90;
case AcpiPldRotation135: return 135;
case AcpiPldRotation180: return 180;
case AcpiPldRotation225: return 225;
case AcpiPldRotation270: return 270;
case AcpiPldRotation315: return 315;
}
return -1;
}
CCameraExtrinsics_2Transforms::
CCameraExtrinsics_2Transforms( ULONG Seed )
{
PAGED_CODE();
static
KS_CAMERA_EXTRINSICS_CALIBRATEDTRANSFORM temp =
{
{0x2eef2648, 0x67e7, 0x48a0, 0xa2, 0x27, 0x46, 0xed, 0x5c, 0xdc, 0x84, 0xb4}, // CalibrationId
{0.5, 0.5, 0.5}, // Position
{0.5, 0.5, 0.5, 0.5} // Orientation
};
TransformCount = 2;
PKS_CAMERA_EXTRINSICS_CALIBRATEDTRANSFORM pTransform = CalibratedTransforms;
for( UINT32 i=0; i<2; i++ )
{
*pTransform = temp;
pTransform->CalibrationId.Data4[7] = (unsigned char) i;
pTransform->CalibrationId.Data1 = Seed;
pTransform++;
}
}
CCameraIntrinsics_2Models::
CCameraIntrinsics_2Models()
{
PAGED_CODE();
static
KS_PINHOLECAMERAINTRINSIC_INTRINSICMODEL temp =
{
0xBADF00D, // Width
0xBADF00D, // Height
{ {1.0,2.0}, {3.0,4.0} }, // CameraModel
{ 1.0, 2.0, 3.0, (float)3.1415296, (float)2.71828 } // DistortionModel
};
static
POINT Dimension[]=
{
{DMAX_X, DMAX_Y},
{D_X, D_Y}
};
IntrinsicModelCount = 2;
PKS_PINHOLECAMERAINTRINSIC_INTRINSICMODEL pModel = IntrinsicModels;
for( UINT32 i=0; i<2; i++ )
{
*pModel = temp;
pModel->Width = Dimension[i].x;
pModel->Height = Dimension[i].y;
pModel++;
}
}
| 7,698 |
348 | {"nom":"Nordhouse","circ":"5ème circonscription","dpt":"Bas-Rhin","inscrits":1382,"abs":852,"votants":530,"blancs":24,"nuls":15,"exp":491,"res":[{"nuance":"LR","nom":"<NAME>","voix":323},{"nuance":"REG","nom":"<NAME>","voix":168}]} | 92 |
11,356 | /*
Copyright 2005-2007 Adobe Systems Incorporated
Use, modification and distribution are subject to the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
See http://stlab.adobe.com/gil for most recent version including documentation.
*/
/*************************************************************************************************/
#ifndef GIL_DEVICE_N_H
#define GIL_DEVICE_N_H
////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief Support for color space of N channels and variants
/// \author <NAME> and <NAME> \n
/// Adobe Systems Incorporated
/// \date 2005-2009 \n Last updated on February 20, 2009
////////////////////////////////////////////////////////////////////////////////////////
#include <cstddef>
#include <boost/type_traits.hpp>
#include <boost/config.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/vector_c.hpp>
#include "gil_config.hpp"
#include "utilities.hpp"
#include "metafunctions.hpp"
namespace boost { namespace gil {
/// \brief unnamed color
/// \ingroup ColorNameModel
template <int N> struct devicen_color_t {};
template <int N> struct devicen_t;
/// \brief unnamed color space of one channel
/// \ingroup ColorSpaceModel
template <> struct devicen_t<1> : public mpl::vector1<devicen_color_t<0> > {};
/// \brief unnamed color space of two channels
/// \ingroup ColorSpaceModel
template <> struct devicen_t<2> : public mpl::vector2<devicen_color_t<0>, devicen_color_t<1> > {};
/// \brief unnamed color space of three channels
/// \ingroup ColorSpaceModel
template <> struct devicen_t<3> : public mpl::vector3<devicen_color_t<0>, devicen_color_t<1>, devicen_color_t<2> > {};
/// \brief unnamed color space of four channels
/// \ingroup ColorSpaceModel
template <> struct devicen_t<4> : public mpl::vector4<devicen_color_t<0>, devicen_color_t<1>, devicen_color_t<2>, devicen_color_t<3> > {};
/// \brief unnamed color space of five channels
/// \ingroup ColorSpaceModel
template <> struct devicen_t<5> : public mpl::vector5<devicen_color_t<0>, devicen_color_t<1>, devicen_color_t<2>, devicen_color_t<3>, devicen_color_t<4> > {};
/// \brief unnamed color layout of up to five channels
/// \ingroup LayoutModel
template <int N> struct devicen_layout_t : public layout<devicen_t<N> > {};
/// \ingroup ImageViewConstructors
/// \brief from 2-channel planar data
template <typename IC>
inline typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<2> > >::view_t
planar_devicen_view(std::size_t width, std::size_t height, IC c0, IC c1, std::ptrdiff_t rowsize_in_bytes) {
typedef typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<2> > >::view_t view_t;
return view_t(width, height, typename view_t::locator(typename view_t::x_iterator(c0,c1), rowsize_in_bytes));
}
/// \ingroup ImageViewConstructors
/// \brief from 3-channel planar data
template <typename IC>
inline typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<3> > >::view_t
planar_devicen_view(std::size_t width, std::size_t height, IC c0, IC c1, IC c2, std::ptrdiff_t rowsize_in_bytes) {
typedef typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<3> > >::view_t view_t;
return view_t(width, height, typename view_t::locator(typename view_t::x_iterator(c0,c1,c2), rowsize_in_bytes));
}
/// \ingroup ImageViewConstructors
/// \brief from 4-channel planar data
template <typename IC>
inline typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<4> > >::view_t
planar_devicen_view(std::size_t width, std::size_t height, IC c0, IC c1, IC c2, IC c3, std::ptrdiff_t rowsize_in_bytes) {
typedef typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<4> > >::view_t view_t;
return view_t(width, height, typename view_t::locator(typename view_t::x_iterator(c0,c1,c2,c3), rowsize_in_bytes));
}
/// \ingroup ImageViewConstructors
/// \brief from 5-channel planar data
template <typename IC>
inline typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<5> > >::view_t
planar_devicen_view(std::size_t width, std::size_t height, IC c0, IC c1, IC c2, IC c3, IC c4, std::ptrdiff_t rowsize_in_bytes) {
typedef typename type_from_x_iterator<planar_pixel_iterator<IC,devicen_t<5> > >::view_t view_t;
return view_t(width, height, typename view_t::locator(typename view_t::x_iterator(c0,c1,c2,c3,c4), rowsize_in_bytes));
}
} } // namespace boost::gil
#endif
| 1,651 |
8,865 | /*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER 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.
*/
#ifndef _ELF_H
#define _ELF_H
#include <linux/auxvec.h>
#include <linux/elf.h>
#include <linux/elf-em.h>
#include <machine/elf_machdep.h>
#define ELF32_R_INFO(sym, type) ((((Elf32_Word)sym) << 8) | ((type) & 0xff))
#define ELF64_R_INFO(sym, type) ((((Elf64_Xword)sym) << 32) | ((type) & 0xffffffff))
typedef __s64 Elf32_Sxword;
typedef struct {
__u32 a_type;
union {
__u32 a_val;
} a_un;
} Elf32_auxv_t;
typedef struct {
__u64 a_type;
union {
__u64 a_val;
} a_un;
} Elf64_auxv_t;
typedef Elf32_Half Elf32_Versym;
typedef Elf64_Half Elf64_Versym;
typedef struct {
Elf32_Half vd_version;
Elf32_Half vd_flags;
Elf32_Half vd_ndx;
Elf32_Half vd_cnt;
Elf32_Word vd_hash;
Elf32_Word vd_aux;
Elf32_Word vd_next;
} Elf32_Verdef;
typedef struct {
Elf32_Word vda_name;
Elf32_Word vda_next;
} Elf32_Verdaux;
typedef struct {
Elf64_Half vd_version;
Elf64_Half vd_flags;
Elf64_Half vd_ndx;
Elf64_Half vd_cnt;
Elf64_Word vd_hash;
Elf64_Word vd_aux;
Elf64_Word vd_next;
} Elf64_Verdef;
typedef struct {
Elf64_Word vda_name;
Elf64_Word vda_next;
} Elf64_Verdaux;
typedef struct {
Elf32_Half vn_version;
Elf32_Half vn_cnt;
Elf32_Word vn_file;
Elf32_Word vn_aux;
Elf32_Word vn_next;
} Elf32_Verneed;
typedef struct {
Elf32_Word vna_hash;
Elf32_Half vna_flags;
Elf32_Half vna_other;
Elf32_Word vna_name;
Elf32_Word vna_next;
} Elf32_Vernaux;
typedef struct {
Elf64_Half vn_version;
Elf64_Half vn_cnt;
Elf64_Word vn_file;
Elf64_Word vn_aux;
Elf64_Word vn_next;
} Elf64_Verneed;
typedef struct {
Elf64_Word vna_hash;
Elf64_Half vna_flags;
Elf64_Half vna_other;
Elf64_Word vna_name;
Elf64_Word vna_next;
} Elf64_Vernaux;
#define DF_ORIGIN 0x00000001
#define DF_SYMBOLIC 0x00000002
#define DF_TEXTREL 0x00000004
#define DF_BIND_NOW 0x00000008
#define DF_STATIC_TLS 0x00000010
#define DF_1_NOW 0x00000001 /* Perform complete relocation processing. */
#define DF_1_GLOBAL 0x00000002 /* implies RTLD_GLOBAL */
#define DF_1_GROUP 0x00000004
#define DF_1_NODELETE 0x00000008 /* implies RTLD_NODELETE */
#define DF_1_LOADFLTR 0x00000010
#define DF_1_INITFIRST 0x00000020
#define DF_1_NOOPEN 0x00000040 /* Object can not be used with dlopen(3) */
#define DF_1_ORIGIN 0x00000080
#define DF_1_DIRECT 0x00000100
#define DF_1_TRANS 0x00000200
#define DF_1_INTERPOSE 0x00000400
#define DF_1_NODEFLIB 0x00000800
#define DF_1_NODUMP 0x00001000 /* Object cannot be dumped with dldump(3) */
#define DF_1_CONFALT 0x00002000
#define DF_1_ENDFILTEE 0x00004000
#define DF_1_DISPRELDNE 0x00008000
#define DF_1_DISPRELPND 0x00010000
#define DF_1_NODIRECT 0x00020000
#define DF_1_IGNMULDEF 0x00040000 /* Internal use */
#define DF_1_NOKSYMS 0x00080000 /* Internal use */
#define DF_1_NOHDR 0x00100000 /* Internal use */
#define DF_1_EDITED 0x00200000
#define DF_1_NORELOC 0x00400000 /* Internal use */
#define DF_1_SYMINTPOSE 0x00800000
#define DF_1_GLOBAUDIT 0x01000000
#define DF_1_SINGLETON 0x02000000
#define DF_1_STUB 0x04000000
#define DF_1_PIE 0x08000000
#define DT_BIND_NOW 24
#define DT_INIT_ARRAY 25
#define DT_FINI_ARRAY 26
#define DT_INIT_ARRAYSZ 27
#define DT_FINI_ARRAYSZ 28
#define DT_RUNPATH 29
#define DT_FLAGS 30
/* glibc and BSD disagree for DT_ENCODING; glibc looks wrong. */
#define DT_PREINIT_ARRAY 32
#define DT_PREINIT_ARRAYSZ 33
/* Android compressed rel/rela sections */
#define DT_ANDROID_REL (DT_LOOS + 2)
#define DT_ANDROID_RELSZ (DT_LOOS + 3)
#define DT_ANDROID_RELA (DT_LOOS + 4)
#define DT_ANDROID_RELASZ (DT_LOOS + 5)
/* gnu hash entry */
#define DT_GNU_HASH 0x6ffffef5
#define ELFOSABI_SYSV 0 /* Synonym for ELFOSABI_NONE used by valgrind. */
#define PT_GNU_RELRO 0x6474e552
#define STB_LOOS 10
#define STB_HIOS 12
#define STB_LOPROC 13
#define STB_HIPROC 15
#define SHT_LOOS 0x60000000
#define SHT_HIOS 0x6fffffff
#define STT_GNU_IFUNC 10
#define STT_LOOS 10
#define STT_HIOS 12
#define STT_LOPROC 13
#define STT_HIPROC 15
#define STV_DEFAULT 0
#define STV_INTERNAL 1
#define STV_HIDDEN 2
#define STV_PROTECTED 3
/* The kernel uses NT_PRFPREG but glibc also offers NT_FPREGSET */
#define NT_FPREGSET NT_PRFPREG
#define ELF_NOTE_GNU "GNU"
#define NT_GNU_BUILD_ID 3
#define VER_FLG_BASE 0x1
#define VER_FLG_WEAK 0x2
#define VER_NDX_LOCAL 0
#define VER_NDX_GLOBAL 1
#endif /* _ELF_H */
| 2,476 |
14,668 | <gh_stars>1000+
// Copyright 2020 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_SHARING_FAKE_SHARING_HANDLER_REGISTRY_H_
#define CHROME_BROWSER_SHARING_FAKE_SHARING_HANDLER_REGISTRY_H_
#include <map>
#include "chrome/browser/sharing/sharing_handler_registry.h"
class FakeSharingHandlerRegistry : public SharingHandlerRegistry {
public:
FakeSharingHandlerRegistry();
FakeSharingHandlerRegistry(const FakeSharingHandlerRegistry&) = delete;
FakeSharingHandlerRegistry& operator=(const FakeSharingHandlerRegistry&) =
delete;
~FakeSharingHandlerRegistry() override;
// SharingHandlerRegistry:
SharingMessageHandler* GetSharingHandler(
chrome_browser_sharing::SharingMessage::PayloadCase payload_case)
override;
void RegisterSharingHandler(
std::unique_ptr<SharingMessageHandler> handler,
chrome_browser_sharing::SharingMessage::PayloadCase payload_case)
override;
void UnregisterSharingHandler(
chrome_browser_sharing::SharingMessage::PayloadCase payload_case)
override;
void SetSharingHandler(
chrome_browser_sharing::SharingMessage::PayloadCase payload_case,
SharingMessageHandler* handler);
private:
std::map<chrome_browser_sharing::SharingMessage::PayloadCase,
SharingMessageHandler*>
handler_map_;
};
#endif // CHROME_BROWSER_SHARING_FAKE_SHARING_HANDLER_REGISTRY_H_
| 508 |
1,301 | <gh_stars>1000+
package com.silencedut.knowweather.api;
import com.silencedut.baselib.commonhelper.log.LogHelper;
import com.silencedut.hub_annotation.HubInject;
import com.silencedut.knowweather.entity.AqiEntity;
import com.silencedut.knowweather.entity.HeWeather;
import com.silencedut.knowweather.entity.WeatherTransverter;
import com.silencedut.knowweather.repository.WeatherRepository;
import com.silencedut.weather_core.AppHttpClient;
import com.silencedut.weather_core.CoreManager;
import com.silencedut.weather_core.api.cityprovider.City;
import com.silencedut.weather_core.api.cityprovider.ICityProvider;
import com.silencedut.weather_core.api.weatherprovider.WeatherData;
import com.silencedut.weather_core.corebase.StatusDataResource;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import retrofit2.Call;
import retrofit2.Response;
/**
* Created by SilenceDut on 2018/1/21 .
*/
@HubInject(api = IFetchWeather.class)
public class WeatherFetchImpl implements IFetchWeather {
private static final String TAG = "WeatherFetchImpl";
private static final String $ = "$";
private NetWeatherApi mNetWeatherApi;
private AtomicReference<String> mStringAtomicReference = new AtomicReference<>($);
@Override
public void onCreate() {
mNetWeatherApi = AppHttpClient.getInstance().getService(NetWeatherApi.class);
}
@Override
public void queryWeather(final String cityId) {
if(cityId == null || cityId.equals(mStringAtomicReference.get())) {
return;
}
mStringAtomicReference.set(cityId);
WeatherRepository.getInstance().getWeatherWorkHandler().post(new Runnable() {
@Override
public void run() {
try {
WeatherRepository.getInstance().updateWeather(cityId,StatusDataResource.<WeatherData>loading());
CoreManager.getImpl(ICityProvider.class).saveCurrentCityId(cityId);
Call<HeWeather> weatherEntityCall = mNetWeatherApi.getWeather(NetWeatherApi.sHeyWeatherKey,cityId);
/*
和风天气不支持县级空气质量
*/
City currentCity = CoreManager.getImpl(ICityProvider.class).searchCity(cityId);
String cityName = cityId;
if(currentCity !=null) {
cityName = currentCity.cityName;
}
Call<AqiEntity> aqiEntityCall = mNetWeatherApi.getAqi(NetWeatherApi.sHeyWeatherKey,cityName);
Response<HeWeather> heWeatherResponse = weatherEntityCall.execute();
Response<AqiEntity> aqiEntityResponse = aqiEntityCall.execute();
if(heWeatherResponse.isSuccessful()) {
WeatherData weatherData = WeatherTransverter.convertFromHeWeather(heWeatherResponse.body(),aqiEntityResponse.body());
WeatherRepository.getInstance().updateWeather(cityId,StatusDataResource.success(weatherData));
}else {
LogHelper.error(TAG, "fetchWeather fail,response is %s",heWeatherResponse.errorBody());
WeatherRepository.getInstance().updateWeather(cityId,StatusDataResource.<WeatherData>error(heWeatherResponse.errorBody().string()));
}
} catch (Exception e) {
LogHelper.error(TAG, "fetchWeather fail , error " +e);
WeatherRepository.getInstance().updateWeather(cityId,StatusDataResource.<WeatherData>error("更新失败"));
}
mStringAtomicReference.set($);
}
});
}
@Override
public void queryWeather(List<String> citys) {
}
}
| 1,617 |
427 | <filename>MUKit/Classes/MUImagePickerManager/MUCircleView.h
//
// MUCircleView.h
// MUKit_Example
//
// Created by Jekity on 2017/11/8.
// Copyright © 2017年 Jeykit. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MUCircleView : UIView
@property (nonatomic, assign) IBInspectable CGFloat borderWidth;
@property (nonatomic, strong) IBInspectable UIColor *borderColor;
@end
| 149 |
2,671 | if 1 < 1 > 1 == 1 >= 5 <= 0x15 <= 0x12 != 1 and 5 in 1 not in 1 is 1 or 5 is not 1: pass
| 37 |
5,169 | {
"name": "Insights",
"version": "1.0.0-beta02",
"summary": "Insights SDK for iOS Hyperwallet UI SDK to capture the events",
"homepage": "https://github.com/hyperwallet/hyperwallet-ios-insight",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"Hyperwallet Systems Inc": "<EMAIL>"
},
"platforms": {
"ios": "10.0"
},
"source": {
"git": "https://github.com/hyperwallet/hyperwallet-ios-insight.git",
"tag": "1.0.0-beta02"
},
"source_files": "Sources/**/*.swift",
"requires_arc": true,
"swift_versions": "5.0",
"swift_version": "5.0"
}
| 251 |
585 | #include "../Ui/TextInput.h"
#include "../Interop/Interop.hpp"
#include "../Localisation/StringManager.h"
#include <SDL2/SDL.h>
using namespace OpenLoco::Interop;
namespace OpenLoco::Ui::TextInput
{
static loco_global<int32_t, 0x0112C876> _currentFontSpriteBase;
// Common code from 0x0044685C, 0x004CE910
bool InputSession::handleInput(uint32_t charCode, uint32_t keyCode)
{
if ((charCode >= SDLK_SPACE && charCode < SDLK_F12) || (charCode >= 159 && charCode <= 255))
{
if (buffer.length() == 199)
{
return false;
}
if (cursorPosition == buffer.length())
{
buffer.append(1, (char)charCode);
}
else
{
buffer.insert(cursorPosition, 1, (char)charCode);
}
cursorPosition += 1;
}
else if (charCode == SDLK_BACKSPACE)
{
if (cursorPosition == 0)
{
// Cursor is at beginning
return false;
}
buffer.erase(cursorPosition - 1, 1);
cursorPosition -= 1;
}
else if (keyCode == SDLK_DELETE)
{
if (cursorPosition == buffer.length())
{
return false;
}
buffer.erase(cursorPosition, 1);
}
else if (keyCode == SDLK_HOME)
{
cursorPosition = 0;
}
else if (keyCode == SDLK_END)
{
cursorPosition = buffer.length();
}
else if (keyCode == SDLK_LEFT)
{
if (cursorPosition == 0)
{
// Cursor is at beginning
return false;
}
cursorPosition -= 1;
}
else if (keyCode == SDLK_RIGHT)
{
if (cursorPosition == buffer.length())
{
// Cursor is at end
return false;
}
cursorPosition += 1;
}
cursorFrame = 0;
return true;
}
bool InputSession::needsReoffsetting(int16_t containerWidth)
{
std::string cursorStr = buffer.substr(0, cursorPosition);
_currentFontSpriteBase = Font::medium_bold;
auto stringWidth = Gfx::getStringWidth(buffer.c_str());
auto cursorX = Gfx::getStringWidth(cursorStr.c_str());
int x = xOffset + cursorX;
if (x < textboxPadding)
return true;
if (x > containerWidth - textboxPadding)
return true;
if (xOffset + stringWidth < containerWidth - textboxPadding)
return true;
return false;
}
/**
* 0x004CEB67
*
* @param containerWidth @<edx>
*/
void InputSession::calculateTextOffset(int16_t containerWidth)
{
std::string cursorStr = buffer.substr(0, cursorPosition);
_currentFontSpriteBase = Font::medium_bold;
auto stringWidth = Gfx::getStringWidth(buffer.c_str());
auto cursorX = Gfx::getStringWidth(cursorStr.c_str());
auto midX = containerWidth / 2;
// Prefer to centre cursor
xOffset = -1 * (cursorX - midX);
// Make sure that text will always be at the left edge
int16_t minOffset = textboxPadding;
int16_t maxOffset = textboxPadding;
if (stringWidth + textboxPadding * 2 > containerWidth)
{
// Make sure that the whole textbox is filled up
minOffset = -stringWidth + containerWidth - textboxPadding;
}
xOffset = std::clamp<int16_t>(xOffset, minOffset, maxOffset);
}
// 0x004CEBFB
void InputSession::sanitizeInput()
{
buffer.erase(
std::remove_if(
buffer.begin(),
buffer.end(),
[](unsigned char chr) {
if (chr < ' ')
{
return true;
}
else if (chr <= 'z')
{
return false;
}
else if (chr == 171)
{
return false;
}
else if (chr == 187)
{
return false;
}
else if (chr >= 191)
{
return false;
}
return true;
}),
buffer.end());
}
}
| 2,511 |
14,668 | // Copyright 2017 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 UI_GL_GL_WORKAROUNDS_H_
#define UI_GL_GL_WORKAROUNDS_H_
namespace gl {
struct GLWorkarounds {
// glClearColor does not always work on Intel 6xxx Mac drivers. See
// crbug.com/710443.
bool clear_to_zero_or_one_broken = false;
// Reset texImage2D base level to workaround pixel comparison failure
// above Mac OS 10.12.4 on Intel Mac. See crbug.com/705865.
bool reset_teximage2d_base_level = false;
};
} // namespace gl
#endif // UI_GL_GL_WORKAROUNDS_H_
| 220 |
448 | <reponame>miniksa/BuildXL
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdio.h>
int main(int argc, char** argv)
{
printf("Hello World!\n");
return 0;
}
| 92 |
4,538 | /* mbed Microcontroller Library
*******************************************************************************
* Copyright (c) 2015, Realtek Semiconductor Corp.
* All rights reserved.
*
* This module is a confidential and proprietary property of RealTek and
* possession or use of this module requires written permission of RealTek.
*******************************************************************************
*/
#ifndef EX_API_H
#define EX_API_H
#include "device.h"
#include "serial_api.h"
#include "spi_api.h"
#include "dma_api.h"
#include "flash_api.h"
#include "gpio_ex_api.h"
#include "gpio_irq_ex_api.h"
#include "i2c_ex_api.h"
#include "i2s_api.h"
#include "serial_ex_api.h"
#include "sleep_ex_api.h"
#include "spi_ex_api.h"
#include "sys_api.h"
#include "wdt_api.h"
#if defined(CONFIG_PLATFORM_8195A) && (CONFIG_PLATFORM_8195A == 1)
#include "nfc_api.h"
#include "ethernet_ex_api.h"
#endif //CONFIG_PLATFORM_8195A
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif
| 366 |
5,169 | <gh_stars>1000+
{
"name": "Navy",
"version": "0.3.1",
"summary": "This is a tool which could easily observe and visualize each route and flow we are tracking on the real time.",
"description": "For a big App, sometime it's hard to check and debug which route we are using. what reaction will be happened once we click somewhere. in order to easily check those scenario whether or not meet the expectation, this tool is created to tackle this requirement.",
"homepage": "https://github.com/AppScaffold/Navy",
"license": "MIT",
"platforms": {
"ios": "9.0"
},
"swift_version": "4.2",
"source": {
"git": "https://github.com/AppScaffold/Navy.git",
"tag": "0.3.1"
},
"source_files": "Navy/**/*.{h,m,swift}",
"exclude_files": "Navy/NavyTests/",
"public_header_files": [
"Navy/Navi.h",
"Navy/AllTouchesGestureRecognizer.h"
],
"authors": "AppScaffold"
}
| 328 |
965 | class ATL_NO_VTABLE CConnect2 :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CConnect2, &CLSID_Connect2>,
public IConnectionPointContainerImpl<CConnect2>,
public IPropertyNotifySinkCP<CConnect2>
{
public:
BEGIN_CONNECTION_POINT_MAP(CConnect2)
CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink)
END_CONNECTION_POINT_MAP()
// Remainder of class declaration omitted. | 153 |
1,443 | <reponame>cssence/mit-license<filename>users/mango-domx.json
{
"copyright": "<NAME>",
"url": "https://mm.co",
"email": "<EMAIL>",
"format": "html",
"license": "mit",
"theme": "default-dark",
"gravatar": true
} | 93 |
711 | package com.java110.utils.constant;
/**
* Created by wuxw on 2017/7/23.
*/
public class RuleDomain {
//RULE_COND_RETURN
public static final String RULE_COND_RETURN_0000 = "0000";//成功
public static final String RULE_COND_RETURN_0001 = "0001";//继续调存过校验
public static final String RULE_COND_RETURN_0002 = "0002";//存过校验失败
public static final String RULE_COND_RETURN_0003 = "0003";//国漫预存款校验-免预存
public static final String RULE_COND_RETURN_0004 = "0004";//国漫预存款校验-不免预存
public static final String RULE_COND_RETURN_0005 = "0005";//JAVA校验失败
public static final String RULE_COND_RETURN_0006 = "0006";//特定员工不需要校验
public static final String RULE_COND_RETURN_1999 = "1999";//程序异常
/**
* 规则编码默认值
*/
public static final String RULE_SERVICE_CODE_DEFAULT = "SVC0000";
/**
* 规则类型
*/
public static final String RULE_TYPE_DEFAULT = "RULE0000";
/*******************************************规则实现方式***************************************/
public static final String RULE_TYPE_JAVA_METHOD = "1";//1 反射调用java 方法实现,
public static final String RULE_TYPE_COND_CFG = "2";//2 通过 rule_cond_cfg 配置逻辑实现
public static final String RULE_TYPE_STORED_PROCEDURE = "3" ;//3 调用存储过程实现,存储过程入参可以在rule_cond_cfg 表中配置
//分隔符
public final static String RULE_SIGN_1 = "@@";
public final static String RULE_SIGN_2 = "$-";
public final static String RULE_SIGN_3 = "'";
public final static String RULE_SIGN_4 = ",";
public final static String RULE_SIGN_5 = "#";
public final static String RULE_SIGN_6 = ">";
public final static String RULE_SIGN_7 = "@";
public final static String RULE_SIGN_8 = ".";
public final static String RULE_SIGN_9 = ";";
public final static String RULE_IS_Y = "Y";
public final static String RULE_IS_N = "N";
public static final String PART_STRING_ORIGINAL_VALUE = "ORIGINAL_VALUE"; //表示字符串:ORIGINAL_VALUE,含义是在处理字符串时表示没有被任何改变的“原始值”标识
/**
* redis key 开始设置
*/
public final static String REDIS_KEY_RULE_ENTRANCE ="RuleEntrance"; // redis key RuleEntrance
public final static String REDIS_KEY_RULE ="Rule"; // redis key Rule
public final static String REDIS_KEY_RULE_GROUP ="Rule_Group"; // redis key Rule
public final static String REPLAY_TYPE_A = "########"; //'yyyyMMdd'
public final static String REPLAY_TYPE_E = "##########"; //'yyyyMMddHH'
public final static String REPLAY_TYPE_F = "############"; //'yyyyMMddHHmm'
public final static String REPLAY_TYPE_SQL = "select"; //文件名支持sql查询
}
| 1,269 |
329 | package com.github.rongi.rotate_layout.layout;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import com.github.rongi.rotate_layout.R;
import static android.view.View.MeasureSpec.UNSPECIFIED;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
/**
* Rotates first view in this layout by specified angle.
* <p>
* This layout is supposed to have only one view. Behaviour of the views after the first one
* is not defined.
* <p>
* XML attributes
* See com.github.rongi.rotate_layout.R.styleable#RotateLayout RotateLayout Attributes,
*/
public class RotateLayout extends ViewGroup {
private int angle;
private final Matrix rotateMatrix = new Matrix();
private final Rect viewRectRotated = new Rect();
private final RectF tempRectF1 = new RectF();
private final RectF tempRectF2 = new RectF();
private final float[] viewTouchPoint = new float[2];
private final float[] childTouchPoint = new float[2];
private boolean angleChanged = true;
public RotateLayout(Context context) {
this(context, null);
}
public RotateLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RotateLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RotateLayout);
angle = a.getInt(R.styleable.RotateLayout_angle, 0);
a.recycle();
setWillNotDraw(false);
}
/**
* Returns current angle of this layout
*/
public int getAngle() {
return angle;
}
/**
* Sets current angle of this layout.
*/
public void setAngle(int angle) {
if (this.angle != angle) {
this.angle = angle;
angleChanged = true;
requestLayout();
invalidate();
}
}
/**
* Returns this layout's child or null if there is no any
*/
public View getView() {
if (getChildCount() > 0) {
return getChildAt(0);
} else {
return null;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final View child = getView();
if (child != null) {
if (abs(angle % 180) == 90) {
//noinspection SuspiciousNameCombination
measureChild(child, heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(
resolveSize(child.getMeasuredHeight(), widthMeasureSpec),
resolveSize(child.getMeasuredWidth(), heightMeasureSpec));
} else if (abs(angle % 180) == 0) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(
resolveSize(child.getMeasuredWidth(), widthMeasureSpec),
resolveSize(child.getMeasuredHeight(), heightMeasureSpec));
} else {
int childWithMeasureSpec = MeasureSpec.makeMeasureSpec(0, UNSPECIFIED);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, UNSPECIFIED);
measureChild(child, childWithMeasureSpec, childHeightMeasureSpec);
int measuredWidth = (int) ceil(child.getMeasuredWidth() * abs(cos(angle_c())) + child.getMeasuredHeight() * abs(sin(angle_c())));
int measuredHeight = (int) ceil(child.getMeasuredWidth() * abs(sin(angle_c())) + child.getMeasuredHeight() * abs(cos(angle_c())));
setMeasuredDimension(
resolveSize(measuredWidth, widthMeasureSpec),
resolveSize(measuredHeight, heightMeasureSpec));
}
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int layoutWidth = r - l;
int layoutHeight = b - t;
if (angleChanged || changed) {
final RectF layoutRect = tempRectF1;
layoutRect.set(0, 0, layoutWidth, layoutHeight);
final RectF layoutRectRotated = tempRectF2;
rotateMatrix.setRotate(angle, layoutRect.centerX(), layoutRect.centerY());
rotateMatrix.mapRect(layoutRectRotated, layoutRect);
layoutRectRotated.round(viewRectRotated);
angleChanged = false;
}
final View child = getView();
if (child != null) {
int childLeft = (layoutWidth - child.getMeasuredWidth()) / 2;
int childTop = (layoutHeight - child.getMeasuredHeight()) / 2;
int childRight = childLeft + child.getMeasuredWidth();
int childBottom = childTop + child.getMeasuredHeight();
child.layout(childLeft, childTop, childRight, childBottom);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.rotate(-angle, getWidth() / 2f, getHeight() / 2f);
super.dispatchDraw(canvas);
canvas.restore();
}
@Override
public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
invalidate();
return super.invalidateChildInParent(location, dirty);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
viewTouchPoint[0] = event.getX();
viewTouchPoint[1] = event.getY();
rotateMatrix.mapPoints(childTouchPoint, viewTouchPoint);
event.setLocation(childTouchPoint[0], childTouchPoint[1]);
boolean result = super.dispatchTouchEvent(event);
event.setLocation(viewTouchPoint[0], viewTouchPoint[1]);
return result;
}
/**
* Circle angle, from 0 to TAU
*/
private Double angle_c() {
// True circle constant, not that petty imposter known as "PI"
double TAU = 2 * PI;
return TAU * angle / 360;
}
}
| 2,021 |
12,278 | <reponame>geenen124/iresearch
// Copyright (C) 2020 <NAME>
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_TEXT_GRAPHEME_VIEW_HPP
#define BOOST_TEXT_GRAPHEME_VIEW_HPP
#include <boost/text/grapheme_iterator.hpp>
#include <boost/text/transcode_algorithm.hpp>
#include <boost/text/transcode_view.hpp>
#include <boost/stl_interfaces/view_interface.hpp>
namespace boost { namespace text {
namespace detail {
template<typename CPIter, typename Sentinel>
using gr_view_sentinel_t = std::conditional_t<
std::is_same<CPIter, Sentinel>::value,
grapheme_iterator<CPIter, Sentinel>,
Sentinel>;
}
/** A view over graphemes that occur in an underlying sequence of code
points. */
#if BOOST_TEXT_USE_CONCEPTS
template<code_point_iter I, std::sentinel_for<I> S = I>
#else
template<typename I, typename S = I>
#endif
struct grapheme_view : stl_interfaces::view_interface<grapheme_view<I, S>>
{
using iterator = grapheme_iterator<I, S>;
using sentinel = detail::gr_view_sentinel_t<I, S>;
constexpr grapheme_view() : first_(), last_() {}
/** Construct a grapheme view that covers the entirety of the view
of graphemes that `begin()` and `end()` lie within. */
constexpr grapheme_view(iterator first, sentinel last) :
first_(first),
last_(last)
{}
/** Construct a grapheme view that covers the entirety of the view
of graphemes that `begin()` and `end()` lie within. */
constexpr grapheme_view(I first, S last) :
first_(first, first, last),
last_(detail::make_iter<sentinel>(first, last, last))
{}
/** Construct a view covering a subset of the view of graphemes that
`begin()` and `end()` lie within. */
#if BOOST_TEXT_USE_CONCEPTS
template<code_point_iter I2>
// clang-format off
requires std::constructible_from<iterator, I2, I2, I2> &&
std::constructible_from<sentinel, I2, I2, I2>
#else
template<
typename I2 = I,
typename S2 = S,
typename Enable = std::enable_if_t<std::is_same<I2, S2>::value>>
#endif
constexpr grapheme_view(
I2 first, I2 view_first, I2 view_last, I2 last) :
// clang-format on
first_(first, view_first, last),
last_(first, view_last, last)
{}
constexpr iterator begin() const noexcept { return first_; }
constexpr sentinel end() const noexcept { return last_; }
friend constexpr bool operator==(grapheme_view lhs, grapheme_view rhs)
{
return lhs.begin() == rhs.begin() && lhs.end() == rhs.end();
}
friend constexpr bool operator!=(grapheme_view lhs, grapheme_view rhs)
{
return !(lhs == rhs);
}
/** Stream inserter; performs unformatted output, in UTF-8
encoding. */
friend std::ostream & operator<<(std::ostream & os, grapheme_view v)
{
boost::text::transcode_to_utf8(
v.begin().base(),
v.end().base(),
std::ostreambuf_iterator<char>(os));
return os;
}
#if defined(BOOST_TEXT_DOXYGEN) || defined(_MSC_VER)
/** Stream inserter; performs unformatted output, in UTF-16 encoding.
Defined on Windows only. */
friend std::wostream & operator<<(std::wostream & os, grapheme_view v)
{
boost::text::transcode_to_utf16(
v.begin(), v.end(), std::ostreambuf_iterator<wchar_t>(os));
return os;
}
#endif
private:
iterator first_;
sentinel last_;
};
}}
namespace boost { namespace text { BOOST_TEXT_NAMESPACE_V1 {
/** Returns a `grapheme_view` over the data in `[first, last)`, transcoding
the data if necessary. */
template<typename Iter, typename Sentinel>
constexpr auto as_graphemes(Iter first, Sentinel last) noexcept
{
auto unpacked = detail::unpack_iterator_and_sentinel(first, last);
auto r =
detail::make_utf32_range_(unpacked.tag_, unpacked.f_, unpacked.l_);
return grapheme_view<decltype(r.f_), decltype(r.l_)>(r.f_, r.l_);
}
namespace dtl {
template<
typename Range,
bool Pointer =
detail::char_ptr<std::remove_reference_t<Range>>::value ||
detail::_16_ptr<std::remove_reference_t<Range>>::value ||
detail::cp_ptr<std::remove_reference_t<Range>>::value>
struct as_graphemes_dispatch
{
static constexpr auto call(Range && r_) noexcept
{
auto r = boost::text::as_utf32(r_);
return grapheme_view<decltype(r.begin()), decltype(r.end())>(
r.begin(), r.end());
}
};
template<typename Ptr>
struct as_graphemes_dispatch<Ptr, true>
{
static constexpr auto call(Ptr p) noexcept
{
auto r = boost::text::as_utf32(p);
return grapheme_view<decltype(r.begin()), null_sentinel>(
r.begin(), null_sentinel{});
}
};
}
/** Returns a `grapheme_view` over the data in `r`, transcoding the data
if necessary. */
template<typename Range>
constexpr auto as_graphemes(Range && r) noexcept->decltype(
dtl::as_graphemes_dispatch<Range &&>::call((Range &&) r))
{
return dtl::as_graphemes_dispatch<Range &&>::call((Range &&) r);
}
}}}
#if defined(BOOST_TEXT_DOXYGEN) || BOOST_TEXT_USE_CONCEPTS
namespace boost { namespace text { BOOST_TEXT_NAMESPACE_V2 {
/** Returns a `grapheme_view` over the data in `[first, last)`, transcoding
the data if necessary. */
template<utf_iter I, std::sentinel_for<I> S>
constexpr auto as_graphemes(I first, S last) noexcept
{
auto unpacked = detail::unpack_iterator_and_sentinel(first, last);
auto r =
detail::make_utf32_range_(unpacked.tag_, unpacked.f_, unpacked.l_);
return grapheme_view<decltype(r.f_), decltype(r.l_)>(r.f_, r.l_);
}
/** Returns a `grapheme_view` over the data in `r`, transcoding the data
if necessary. */
template<utf_range_like R>
constexpr auto as_graphemes(R && r) noexcept
{
auto intermediate = boost::text::as_utf32(r);
return grapheme_view<
std::ranges::iterator_t<decltype(intermediate)>,
std::ranges::sentinel_t<decltype(intermediate)>>(
intermediate.begin(), intermediate.end());
}
}}}
#endif
#if BOOST_TEXT_USE_CONCEPTS
namespace std::ranges {
template<typename CPIter, typename Sentinel>
inline constexpr bool
enable_borrowed_range<boost::text::grapheme_view<CPIter, Sentinel>> =
true;
}
#endif
#endif
| 3,295 |
4,071 | <filename>blaze/blaze/graph/graph.h
/*
* \file graph.h
* \brief The graph definition
*/
#pragma once
#include <map>
#include <set>
#include <string>
#include "blaze/common/common_defines.h"
#include "blaze/proto/blaze.pb.h"
namespace blaze {
// Graph node
struct Node {
Node() { }
// Get the node index, whose oname contains name.
int GetParentIdx(const std::string& name) const;
// Get the output name's index in op's output list
int GetOutputIdx(const std::string& name) const;
OperatorDef op;
bool active = true;
int idx;
// idx = index of child or parent
// tensor list = a list of string, containing the tensors that connects the
// nodes.
std::map<int, std::vector<std::string>> parents;
std::map<int, std::vector<std::string>> children;
};
// The visitor function, The return function will be the visistor's return.
typedef std::function<bool(Node&, void* arg)> FVisitor;
typedef std::function<bool(std::vector<Node*>&, void* arg)> FVecVisitor;
// Graph
class Graph {
public:
const std::vector<std::pair<std::string, int>> GetSubgraphInput(const std::vector<int>& subgraph);
const std::vector<std::pair<std::string, int>> GetSubgraphOutput(const std::vector<int>& subgraph);
explicit Graph(const NetDef& net_def, bool inactive_solo_node = true);
virtual ~Graph() {}
// Remove inactive nodes.
NetDef GetNetDef();
// Deactivate subgraph for removing useless nodes.
void DeactivateSubgraph(const std::vector<int>& subgraph);
// Deactivate indepency node of oname
void DeactivateIndependency(const std::string& oname);
// get complementary nodes
bool ComplementNodes(const std::vector<int>& src_nodes,
std::vector<int>* complementary_nodes) const;
// Add a ConcatFill node as input for node.
// Return the added ConstantFill node idx.
int AddConstantFillNode(Node* node);
// Insert a new fusion node before idx-th node..
int InsertNode(const OperatorDef& op);
// Rename input of specified node
int RenameInput(int node_idx, const std::string& input_name,
const std::string& new_input_name);
// Remove input of specified node
int RemoveInput(int node_idx, const std::string& input_name);
// BFS Search, WARN: if you modify Graph in visitor function, you can not
// refer the node function.
bool BFS(const FVisitor& visitor, void* arg);
// Max connected sub graph Search
bool MaxConnectedSearch(const FVisitor& visitor, void* arg);
// Find sibling of node_idx, the sibling's op type is op_type.
int FindSibling(int node_idx, const std::string& input_name, const std::string& op_type);
int FindSibling(int node_idx, const std::string& input_name, const std::string& op_type, int output_size);
// Check and deactivate node, if the node's children are empty
void CheckAndDeactivateNode(int node_idx);
inline const size_t size() const { return nodes_.size(); }
inline void push_node(const Node& new_node) { nodes_.push_back(new_node); }
inline void resize_nodes(size_t new_size) { nodes_.resize(new_size); }
inline const Node& node(size_t idx) const { return nodes_.at(idx); }
inline Node& node(size_t idx) { return nodes_.at(idx); }
inline bool is_node_active(size_t idx) { return node(idx).active; }
inline size_t active_size() const {
size_t cnt = 0;
for (auto& node : nodes_) {
if (node.active) {
cnt++;
}
}
return cnt;
}
inline const DeviceOption& device_option(const Node& node) const {
return node.op.has_device_option() ?
node.op.device_option() : net_def_.device_option();
}
std::string DeviceStr(const DeviceOption& device_option) {
return std::to_string(device_option.device_type()) + "/" +
std::to_string(device_option.device_id()) + "/" +
std::to_string(device_option.is_pipe());
}
// Get debug string
std::string DebugStr();
inline const std::set<std::string>& external_input() const { return external_input_; }
inline const std::set<std::string>& external_output() const { return external_output_; }
// Return the not denpendency idx
inline const std::vector<int>& not_dependency_idx() const { return not_dependency_idx_; }
// Return the not dependent idx
inline const std::vector<int>& not_be_dependent_idx() const { return not_be_dependent_idx_; }
private:
const std::vector<std::pair<std::string, int>> GetSubgraphParameterHelper(
bool from_children, const std::vector<int>& match);
NetDef net_def_;
std::unordered_map<std::string, int> edge_parent_; // iname producer
std::unordered_map<std::string, std::vector<int>> edge_child_; // oname consumer
std::set<std::string> external_input_;
std::set<std::string> external_output_;
std::vector<Node> nodes_;
std::vector<int> not_dependency_idx_;
std::vector<int> not_be_dependent_idx_;
};
} // namespace blaze
| 1,636 |
2,133 | #!/usr/bin/env python
import os
qgc_rc = "qgroundcontrol.qrc"
res_rc = "qgcresources.qrc"
qgc_exc = "qgroundcontrol.exclusion"
res_exc = "qgcresources.exclusion"
def read_file(filename):
with open(filename) as src:
return [line.rstrip().lstrip() for line in src.readlines()]
def process(src, exclusion, dst):
file1 = read_file(src)
file2 = read_file(exclusion)
file3 = open(dst, 'w')
for line in file1:
if line not in file2:
if line.startswith('<qresource') or line.startswith('</qresource'):
file3.write('\t')
if line.startswith('<file') or line.startswith('</file'):
file3.write('\t\t')
newLine = str(line)
if line.startswith('<file'):
newLine = newLine.replace(">", ">../", 1)
file3.write(newLine + '\n')
else:
print('Excluded:', line)
file3.close()
def main():
if(os.path.isfile(qgc_exc)):
process(os.path.join("../",qgc_rc), qgc_exc, qgc_rc)
if(os.path.isfile(res_exc)):
process(os.path.join("../",res_rc), res_exc, res_rc)
if __name__ == '__main__':
main()
| 573 |
640 | /*
* aPLib compression library - the smaller the better :)
*
* C safe depacker, header file
*
* Copyright (c) 1998-2004 by <NAME> / Jibz
* All Rights Reserved
*
* http://www.ibsensoftware.com/
*/
#ifndef DEPACKS_H_INCLUDED
#define DEPACKS_H_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
#ifndef APLIB_ERROR
# define APLIB_ERROR (-1)
#endif
/* function prototype */
unsigned int aP_depack_safe(const void *source,
unsigned int srclen,
void *destination,
unsigned int dstlen);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* DEPACKS_H_INCLUDED */
| 331 |
2,151 | // Copyright 2016 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 MEDIA_MOJO_SERVICES_GPU_MOJO_MEDIA_CLIENT_H_
#define MEDIA_MOJO_SERVICES_GPU_MOJO_MEDIA_CLIENT_H_
#include <memory>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/single_thread_task_runner.h"
#include "gpu/config/gpu_driver_bug_workarounds.h"
#include "gpu/config/gpu_preferences.h"
#include "media/base/android_overlay_mojo_factory.h"
#include "media/cdm/cdm_proxy.h"
#include "media/mojo/services/mojo_media_client.h"
namespace media {
class MediaGpuChannelManager;
class GpuMojoMediaClient : public MojoMediaClient {
public:
// |media_gpu_channel_manager| must only be used on |gpu_task_runner|, which
// is expected to be the GPU main thread task runner.
// |cdm_proxy_factory_cb| can be used to create a CdmProxy. May be null if
// CdmProxy is not supported on the platform.
GpuMojoMediaClient(
const gpu::GpuPreferences& gpu_preferences,
const gpu::GpuDriverBugWorkarounds& gpu_workarounds,
scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner,
base::WeakPtr<MediaGpuChannelManager> media_gpu_channel_manager,
AndroidOverlayMojoFactoryCB android_overlay_factory_cb,
CdmProxyFactoryCB cdm_proxy_factory_cb);
~GpuMojoMediaClient() final;
// MojoMediaClient implementation.
void Initialize(service_manager::Connector* connector) final;
std::unique_ptr<AudioDecoder> CreateAudioDecoder(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) final;
std::unique_ptr<VideoDecoder> CreateVideoDecoder(
scoped_refptr<base::SingleThreadTaskRunner> task_runner,
MediaLog* media_log,
mojom::CommandBufferIdPtr command_buffer_id,
RequestOverlayInfoCB request_overlay_info_cb,
const gfx::ColorSpace& target_color_space) final;
std::unique_ptr<CdmFactory> CreateCdmFactory(
service_manager::mojom::InterfaceProvider* interface_provider) final;
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
std::unique_ptr<CdmProxy> CreateCdmProxy(const std::string& cdm_guid) final;
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
private:
gpu::GpuPreferences gpu_preferences_;
gpu::GpuDriverBugWorkarounds gpu_workarounds_;
scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_;
base::WeakPtr<MediaGpuChannelManager> media_gpu_channel_manager_;
AndroidOverlayMojoFactoryCB android_overlay_factory_cb_;
CdmProxyFactoryCB cdm_proxy_factory_cb_;
DISALLOW_COPY_AND_ASSIGN(GpuMojoMediaClient);
};
} // namespace media
#endif // MEDIA_MOJO_SERVICES_GPU_MOJO_MEDIA_CLIENT_H_
| 1,002 |
309 | <reponame>cvandijck/VTKExamples<gh_stars>100-1000
#include <vtkCamera.h>
#include <vtkContourFilter.h>
#include <vtkNamedColors.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProgrammableSource.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkReverseSense.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkSurfaceReconstructionFilter.h>
#include <vtkXMLPolyDataReader.h>
int main(int argc, char* argv[])
{
auto colors = vtkSmartPointer<vtkNamedColors>::New();
vtkSmartPointer<vtkPolyData> input;
if (argc > 1)
{
auto reader = vtkSmartPointer<vtkXMLPolyDataReader>::New();
reader->SetFileName(argv[1]);
reader->Update();
input = reader->GetOutput();
}
else
{
auto sphereSource = vtkSmartPointer<vtkSphereSource>::New();
sphereSource->Update();
input = sphereSource->GetOutput();
}
auto polydata = vtkSmartPointer<vtkPolyData>::New();
polydata->SetPoints(input->GetPoints());
// Construct the surface and create isosurface.
auto surf = vtkSmartPointer<vtkSurfaceReconstructionFilter>::New();
surf->SetInputData(polydata);
auto cf = vtkSmartPointer<vtkContourFilter>::New();
cf->SetInputConnection(surf->GetOutputPort());
cf->SetValue(0, 0.0);
// Sometimes the contouring algorithm can create a volume whose gradient
// vector and ordering of polygon (using the right hand rule) are
// inconsistent. vtkReverseSense cures this problem.
auto reverse = vtkSmartPointer<vtkReverseSense>::New();
reverse->SetInputConnection(cf->GetOutputPort());
reverse->ReverseCellsOn();
reverse->ReverseNormalsOn();
auto map = vtkSmartPointer<vtkPolyDataMapper>::New();
map->SetInputConnection(reverse->GetOutputPort());
map->ScalarVisibilityOff();
auto surfaceActor = vtkSmartPointer<vtkActor>::New();
surfaceActor->SetMapper(map);
surfaceActor->GetProperty()->SetDiffuseColor(
colors->GetColor3d("Tomato").GetData());
surfaceActor->GetProperty()->SetSpecularColor(
colors->GetColor3d("Seashell").GetData());
surfaceActor->GetProperty()->SetSpecular(.4);
surfaceActor->GetProperty()->SetSpecularPower(50);
// Create the RenderWindow, Renderer and both Actors
auto renderer = vtkSmartPointer<vtkRenderer>::New();
auto renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
renderWindow->SetSize(640, 480);
auto interactor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
interactor->SetRenderWindow(renderWindow);
// Add the actors to the renderer, set the background and size
renderer->AddActor(surfaceActor);
renderer->SetBackground(colors->GetColor3d("Burlywood").GetData());
renderWindow->Render();
interactor->Start();
return EXIT_SUCCESS;
}
| 978 |
2,151 | // Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_MODULES_LOCKS_LOCK_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_LOCKS_LOCK_H_
#include "third_party/blink/public/platform/modules/locks/lock_manager.mojom-blink.h"
#include "third_party/blink/renderer/core/dom/pausable_object.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
class LockManager;
class ScriptPromise;
class ScriptPromiseResolver;
class ScriptState;
class Lock final : public ScriptWrappable, public PausableObject {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(Lock);
public:
static Lock* Create(ScriptState*,
const String& name,
mojom::blink::LockMode,
mojom::blink::LockHandlePtr,
LockManager*);
~Lock() override;
void Trace(blink::Visitor*) override;
EAGERLY_FINALIZE();
// Lock.idl
String name() const { return name_; }
String mode() const;
// PausableObject
void ContextDestroyed(ExecutionContext*) override;
// The lock is held until the passed promise resolves. When it is released,
// the passed resolver is invoked with the promise's result.
void HoldUntil(ScriptPromise, ScriptPromiseResolver*);
static mojom::blink::LockMode StringToMode(const String&);
static String ModeToString(mojom::blink::LockMode);
private:
class ThenFunction;
Lock(ScriptState*,
const String& name,
mojom::blink::LockMode,
mojom::blink::LockHandlePtr,
LockManager*);
void ReleaseIfHeld();
void OnConnectionError();
Member<ScriptPromiseResolver> resolver_;
const String name_;
const mojom::blink::LockMode mode_;
// An opaque handle; this one end of a mojo pipe. When this is closed,
// the lock is released by the back end.
mojom::blink::LockHandlePtr handle_;
// LockManager::OnLockReleased() is called when this lock is released, to
// stop artificially keeping this instance alive. It is necessary in the
// case where the resolver's promise could potentially be GC'd.
Member<LockManager> manager_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_LOCKS_LOCK_H_
| 909 |
467 | <gh_stars>100-1000
package com.yoyiyi.soleil.event;
import com.yoyiyi.soleil.bean.app.video.VideoDetail;
import com.yoyiyi.soleil.bean.app.video.VideoDetailComment;
import com.yoyiyi.soleil.bean.search.Search;
import com.yoyiyi.soleil.bean.user.UpDetail;
import java.util.List;
/**
* @author zzq 作者 E-mail: <EMAIL>
* @date 创建时间:2017/6/4 15:24
* 描述:事件
*/
public class Event {
public static class RegionEntrancePositionEvent {
public int position;
}
public static class ExitEvent {
public int exit;
}
public static class AllStationPositionEvent {
public int position;
}
public static class StartNavigationEvent {
public boolean start;
}
public static class VideoDetailEvent {
public VideoDetail.DataBean videoDetail;
}
public static class VideoDetailCommentEvent {
public VideoDetailComment.DataBean videoDetailComment;
}
public static class UpDetailArchiveEvent {
public UpDetail.DataBean.ArchiveBean archive;
public UpDetail.DataBean.SettingBean setting;
public UpDetail.DataBean.FavouriteBean favourite;
public UpDetail.DataBean.LiveBean live;
}
public static class UpDetailSubmitedVideoEvent {
public List<UpDetail.DataBean.ArchiveBean.ItemBean> archivList;
}
public static class UpDetailFavourteEvent {
public List<UpDetail.DataBean.FavouriteBean.ItemBeanX> favouriteList;
}
public static class SearchArchiveEvent {
public Search.DataBean.ItemsBean itemBean;
public int seasonCount;
public int movieCount;
}
}
| 659 |
1,359 | package com.kalessil.phpStorm.phpInspectionsEA.classes;
import com.kalessil.phpStorm.phpInspectionsEA.PhpCodeInsightFixtureTestCase;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalAnalysis.classes.ClassMethodNameMatchesFieldNameInspector;
final public class ClassMethodNameMatchesFieldNameInspectorTest extends PhpCodeInsightFixtureTestCase {
public void testIfFindsAllPatterns() {
myFixture.enableInspections(new ClassMethodNameMatchesFieldNameInspector());
myFixture.configureByFile("testData/fixtures/classes/class-field-method-named-identically.php");
myFixture.testHighlighting(true, false, true);
}
}
| 227 |
359 | package com.tngtech.archunit.exampletest.junit5;
import com.tngtech.archunit.example.layers.anticorruption.WrappedResult;
import com.tngtech.archunit.example.layers.security.Secured;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noCodeUnits;
@AnalyzeClasses(packages = "com.tngtech.archunit.example.layers")
public class MethodsTest {
@ArchTest
static ArchRule all_public_methods_in_the_controller_layer_should_return_API_response_wrappers =
methods()
.that().areDeclaredInClassesThat().resideInAPackage("..anticorruption..")
.and().arePublic()
.should().haveRawReturnType(WrappedResult.class)
.because("we do not want to couple the client code directly to the return types of the encapsulated module");
@ArchTest
static ArchRule code_units_in_DAO_layer_should_not_be_Secured =
noCodeUnits()
.that().areDeclaredInClassesThat().resideInAPackage("..persistence..")
.should().beAnnotatedWith(Secured.class);
} | 528 |
9,425 | """
:codeauthor: <NAME> <<EMAIL>>
"""
import pytest
import salt.states.influxdb08_user as influxdb08_user
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {influxdb08_user: {}}
def test_present():
"""
Test to ensure that the cluster admin or database user is present.
"""
name = "salt"
passwd = "<PASSWORD>"
ret = {"name": name, "result": False, "comment": "", "changes": {}}
mock = MagicMock(side_effect=[False, False, False, True])
mock_t = MagicMock(side_effect=[True, False])
mock_f = MagicMock(return_value=False)
with patch.dict(
influxdb08_user.__salt__,
{
"influxdb08.db_exists": mock_f,
"influxdb08.user_exists": mock,
"influxdb08.user_create": mock_t,
},
):
comt = "Database mydb does not exist"
ret.update({"comment": comt})
assert influxdb08_user.present(name, passwd, database="mydb") == ret
with patch.dict(influxdb08_user.__opts__, {"test": True}):
comt = "User {} is not present and needs to be created".format(name)
ret.update({"comment": comt, "result": None})
assert influxdb08_user.present(name, passwd) == ret
with patch.dict(influxdb08_user.__opts__, {"test": False}):
comt = "User {} has been created".format(name)
ret.update(
{"comment": comt, "result": True, "changes": {"salt": "Present"}}
)
assert influxdb08_user.present(name, passwd) == ret
comt = "Failed to create user {}".format(name)
ret.update({"comment": comt, "result": False, "changes": {}})
assert influxdb08_user.present(name, passwd) == ret
comt = "User {} is already present".format(name)
ret.update({"comment": comt, "result": True})
assert influxdb08_user.present(name, passwd) == ret
def test_absent():
"""
Test to ensure that the named cluster admin or database user is absent.
"""
name = "salt"
ret = {"name": name, "result": None, "comment": "", "changes": {}}
mock = MagicMock(side_effect=[True, True, True, False])
mock_t = MagicMock(side_effect=[True, False])
with patch.dict(
influxdb08_user.__salt__,
{"influxdb08.user_exists": mock, "influxdb08.user_remove": mock_t},
):
with patch.dict(influxdb08_user.__opts__, {"test": True}):
comt = "User {} is present and needs to be removed".format(name)
ret.update({"comment": comt})
assert influxdb08_user.absent(name) == ret
with patch.dict(influxdb08_user.__opts__, {"test": False}):
comt = "User {} has been removed".format(name)
ret.update({"comment": comt, "result": True, "changes": {"salt": "Absent"}})
assert influxdb08_user.absent(name) == ret
comt = "Failed to remove user {}".format(name)
ret.update({"comment": comt, "result": False, "changes": {}})
assert influxdb08_user.absent(name) == ret
comt = "User {} is not present, so it cannot be removed".format(name)
ret.update({"comment": comt, "result": True})
assert influxdb08_user.absent(name) == ret
| 1,423 |
971 | package com.ucar.datalink.common.jvm;
/**
* Created by lubiao on 2018/4/2.
*/
public class JvmSnapshot {
private long startTime;
private long youngUsed;//新生代已用内存
private long youngMax;//新生代最大内存
private long oldUsed;//老年代已用内存
private long oldMax;//老年代最大内存
private long youngCollectionCount;//新生代当前累积的垃圾回收次数
private long oldCollectionCount;//老年代当前累积的垃圾回收次数
private long youngCollectionTime;//新生代当前累积的垃圾回收时间
private long oldCollectionTime;//老年代当前累积的垃圾回收时间
private int currentThreadCount;//当前线程数
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getYoungUsed() {
return youngUsed;
}
public void setYoungUsed(long youngUsed) {
this.youngUsed = youngUsed;
}
public long getYoungMax() {
return youngMax;
}
public void setYoungMax(long youngMax) {
this.youngMax = youngMax;
}
public long getOldUsed() {
return oldUsed;
}
public void setOldUsed(long oldUsed) {
this.oldUsed = oldUsed;
}
public long getOldMax() {
return oldMax;
}
public void setOldMax(long oldMax) {
this.oldMax = oldMax;
}
public long getYoungCollectionCount() {
return youngCollectionCount;
}
public void setYoungCollectionCount(long youngCollectionCount) {
this.youngCollectionCount = youngCollectionCount;
}
public long getOldCollectionCount() {
return oldCollectionCount;
}
public void setOldCollectionCount(long oldCollectionCount) {
this.oldCollectionCount = oldCollectionCount;
}
public long getYoungCollectionTime() {
return youngCollectionTime;
}
public void setYoungCollectionTime(long youngCollectionTime) {
this.youngCollectionTime = youngCollectionTime;
}
public long getOldCollectionTime() {
return oldCollectionTime;
}
public void setOldCollectionTime(long oldCollectionTime) {
this.oldCollectionTime = oldCollectionTime;
}
public int getCurrentThreadCount() {
return currentThreadCount;
}
public void setCurrentThreadCount(int currentThreadCount) {
this.currentThreadCount = currentThreadCount;
}
}
| 997 |
4,538 | <reponame>wstong999/AliOS-Things<gh_stars>1000+
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef K_COMPILER_H
#define K_COMPILER_H
#if defined(__CC_ARM)
#define RHINO_INLINE static __inline
/* get the return address of the current function
unsigned int __return_address(void) */
#define RHINO_GET_RA() (void *)__return_address()
/* get the the value of the stack pointer
unsigned int __current_sp(void) */
#define RHINO_GET_SP() (void *)__current_sp()
/* Returns the number of leading 0-bits in x,
starting at the most signifi cant bit position. */
#define RHINO_BIT_CLZ(x) __builtin_clz(x)
/* Returns the number of trailing 0-bits in x,
starting at the least signifi cant bit position. */
#define RHINO_BIT_CTZ(x) __builtin_ctz(x)
#ifndef RHINO_WEAK
#define RHINO_WEAK __weak
#endif
#ifndef RHINO_ASM
#define RHINO_ASM __asm
#endif
/* Instruction Synchronization Barrier */
#define OS_ISB() __isb(15) /* Full system Any-Any */
/* Data Memory Barrier */
#define OS_DMB() __dmb(15) /* Full system Any-Any */
/* Data Synchronization Barrier */
#define OS_DSB() __dsb(15) /* Full system Any-Any */
#elif defined(__ICCARM__)
#include "intrinsics.h"
#define RHINO_INLINE static inline
/* get the return address of the current function
unsigned int __get_LR(void) */
#define RHINO_GET_RA() (void *)__get_LR()
/* get the the value of the stack pointer
unsigned int __get_SP(void) */
#define RHINO_GET_SP() (void *)__get_SP()
/* Returns the number of leading 0-bits in x,
starting at the most signifi cant bit position. */
#define RHINO_BIT_CLZ(x) __CLZ(x)
//#define RHINO_BIT_CTZ(x)
#ifndef RHINO_WEAK
#define RHINO_WEAK __weak
#endif
#ifndef RHINO_ASM
#define RHINO_ASM asm
#endif
/* Instruction Synchronization Barrier */
#define OS_ISB() __isb(15) /* Full system Any-Any */
/* Data Memory Barrier */
#define OS_DMB() __dmb(15) /* Full system Any-Any */
/* Data Synchronization Barrier */
#define OS_DSB() __dsb(15) /* Full system Any-Any */
#elif defined(__GNUC__)
#define RHINO_INLINE static inline
/* get the return address of the current function
void * __builtin_return_address (unsigned int level) */
#define RHINO_GET_RA() __builtin_return_address(0)
/* get the return address of the current function */
__attribute__((always_inline)) RHINO_INLINE void *RHINO_GET_SP(void)
{
void *sp;
__asm__ volatile("mov %0, SP\n":"=r"(sp));
return sp;
}
/* Returns the number of leading 0-bits in x,
starting at the most signifi cant bit position. */
#define RHINO_BIT_CLZ(x) __builtin_clz(x)
/* Returns the number of trailing 0-bits in x,
starting at the least signifi cant bit position. */
#define RHINO_BIT_CTZ(x) __builtin_ctz(x)
#ifndef RHINO_WEAK
#define RHINO_WEAK __attribute__((weak))
#endif
#ifndef RHINO_ASM
#define RHINO_ASM __asm__
#endif
/* Instruction Synchronization Barrier */
#define OS_ISB() __asm volatile ("isb sy":::"memory")
/* Data Memory Barrier */
#define OS_DMB() __asm volatile ("dmb sy":::"memory")
/* Data Synchronization Barrier */
#define OS_DSB() __asm volatile ("dsb sy":::"memory")
#else
#error "Unsupported compiler"
#endif
#endif /* K_COMPILER_H */
| 1,603 |
16,789 | <reponame>vivithemage/certbot<gh_stars>1000+
"""Tests for certbot.helpful_parser"""
import unittest
try:
import mock
except ImportError: # pragma: no cover
from unittest import mock
from certbot import errors
from certbot._internal.cli import HelpfulArgumentParser
from certbot._internal.cli import _DomainsAction
from certbot._internal import constants
class TestScanningFlags(unittest.TestCase):
'''Test the prescan_for_flag method of HelpfulArgumentParser'''
def test_prescan_no_help_flag(self):
arg_parser = HelpfulArgumentParser(['run'], {})
detected_flag = arg_parser.prescan_for_flag('--help',
['all', 'certonly'])
self.assertIs(detected_flag, False)
detected_flag = arg_parser.prescan_for_flag('-h',
['all, certonly'])
self.assertIs(detected_flag, False)
def test_prescan_unvalid_topic(self):
arg_parser = HelpfulArgumentParser(['--help', 'all'], {})
detected_flag = arg_parser.prescan_for_flag('--help',
['potato'])
self.assertIs(detected_flag, True)
detected_flag = arg_parser.prescan_for_flag('-h',
arg_parser.help_topics)
self.assertIs(detected_flag, False)
def test_prescan_valid_topic(self):
arg_parser = HelpfulArgumentParser(['-h', 'all'], {})
detected_flag = arg_parser.prescan_for_flag('-h',
arg_parser.help_topics)
self.assertEqual(detected_flag, 'all')
detected_flag = arg_parser.prescan_for_flag('--help',
arg_parser.help_topics)
self.assertIs(detected_flag, False)
class TestDetermineVerbs(unittest.TestCase):
'''Tests for determine_verb methods of HelpfulArgumentParser'''
def test_determine_verb_wrong_verb(self):
arg_parser = HelpfulArgumentParser(['potato'], {})
self.assertEqual(arg_parser.verb, "run")
self.assertEqual(arg_parser.args, ["potato"])
def test_determine_verb_help(self):
arg_parser = HelpfulArgumentParser(['--help', 'everything'], {})
self.assertEqual(arg_parser.verb, "help")
self.assertEqual(arg_parser.args, ["--help", "everything"])
arg_parser = HelpfulArgumentParser(['-d', 'some_domain', '--help',
'all'], {})
self.assertEqual(arg_parser.verb, "help")
self.assertEqual(arg_parser.args, ['-d', 'some_domain', '--help',
'all'])
def test_determine_verb(self):
arg_parser = HelpfulArgumentParser(['certonly'], {})
self.assertEqual(arg_parser.verb, 'certonly')
self.assertEqual(arg_parser.args, [])
arg_parser = HelpfulArgumentParser(['auth'], {})
self.assertEqual(arg_parser.verb, 'certonly')
self.assertEqual(arg_parser.args, [])
arg_parser = HelpfulArgumentParser(['everything'], {})
self.assertEqual(arg_parser.verb, 'run')
self.assertEqual(arg_parser.args, [])
class TestAdd(unittest.TestCase):
'''Tests for add method in HelpfulArgumentParser'''
def test_add_trivial_argument(self):
arg_parser = HelpfulArgumentParser(['run'], {})
arg_parser.add(None, "--hello-world")
parsed_args = arg_parser.parser.parse_args(['--hello-world',
'Hello World!'])
self.assertIs(parsed_args.hello_world, 'Hello World!')
self.assertFalse(hasattr(parsed_args, 'potato'))
def test_add_expected_argument(self):
arg_parser = HelpfulArgumentParser(['--help', 'run'], {})
arg_parser.add(
[None, "run", "certonly", "register"],
"--eab-kid", dest="eab_kid", action="store",
metavar="EAB_KID",
help="Key Identifier for External Account Binding")
parsed_args = arg_parser.parser.parse_args(["--eab-kid", None])
self.assertIsNone(parsed_args.eab_kid)
self.assertTrue(hasattr(parsed_args, 'eab_kid'))
class TestAddGroup(unittest.TestCase):
'''Test add_group method of HelpfulArgumentParser'''
def test_add_group_no_input(self):
arg_parser = HelpfulArgumentParser(['run'], {})
self.assertRaises(TypeError, arg_parser.add_group)
def test_add_group_topic_not_visible(self):
# The user request help on run. A topic that given somewhere in the
# args won't be added to the groups in the parser.
arg_parser = HelpfulArgumentParser(['--help', 'run'], {})
arg_parser.add_group("auth",
description="description of auth")
self.assertEqual(arg_parser.groups, {})
def test_add_group_topic_requested_help(self):
arg_parser = HelpfulArgumentParser(['--help', 'run'], {})
arg_parser.add_group("run",
description="description of run")
self.assertTrue(arg_parser.groups["run"])
arg_parser.add_group("certonly", description="description of certonly")
with self.assertRaises(KeyError):
self.assertIs(arg_parser.groups["certonly"], False)
class TestParseArgsErrors(unittest.TestCase):
'''Tests for errors that should be met for some cases in parse_args method
in HelpfulArgumentParser'''
def test_parse_args_renew_force_interactive(self):
arg_parser = HelpfulArgumentParser(['renew', '--force-interactive'],
{})
arg_parser.add(
None, constants.FORCE_INTERACTIVE_FLAG, action="store_true")
with self.assertRaises(errors.Error):
arg_parser.parse_args()
def test_parse_args_non_interactive_and_force_interactive(self):
arg_parser = HelpfulArgumentParser(['--force-interactive',
'--non-interactive'], {})
arg_parser.add(
None, constants.FORCE_INTERACTIVE_FLAG, action="store_true")
arg_parser.add(
None, "--non-interactive", dest="noninteractive_mode",
action="store_true"
)
with self.assertRaises(errors.Error):
arg_parser.parse_args()
def test_parse_args_subset_names_wildcard_domain(self):
arg_parser = HelpfulArgumentParser(['--domain',
'*.example.com,potato.example.com',
'--allow-subset-of-names'], {})
# The following arguments are added because they have to be defined
# in order for arg_parser to run completely. They are not used for the
# test.
arg_parser.add(
None, constants.FORCE_INTERACTIVE_FLAG, action="store_true")
arg_parser.add(
None, "--non-interactive", dest="noninteractive_mode",
action="store_true")
arg_parser.add(
None, "--staging"
)
arg_parser.add(None, "--dry-run")
arg_parser.add(None, "--csr")
arg_parser.add(None, "--must-staple")
arg_parser.add(None, "--validate-hooks")
arg_parser.add(None, "-d", "--domain", dest="domains",
metavar="DOMAIN", action=_DomainsAction)
arg_parser.add(None, "--allow-subset-of-names")
# with self.assertRaises(errors.Error):
# arg_parser.parse_args()
def test_parse_args_hosts_and_auto_hosts(self):
arg_parser = HelpfulArgumentParser(['--hsts', '--auto-hsts'], {})
arg_parser.add(
None, "--hsts", action="store_true", dest="hsts")
arg_parser.add(
None, "--auto-hsts", action="store_true", dest="auto_hsts")
# The following arguments are added because they have to be defined
# in order for arg_parser to run completely. They are not used for the
# test.
arg_parser.add(
None, constants.FORCE_INTERACTIVE_FLAG, action="store_true")
arg_parser.add(
None, "--non-interactive", dest="noninteractive_mode",
action="store_true")
arg_parser.add(None, "--staging")
arg_parser.add(None, "--dry-run")
arg_parser.add(None, "--csr")
arg_parser.add(None, "--must-staple")
arg_parser.add(None, "--validate-hooks")
arg_parser.add(None, "--allow-subset-of-names")
with self.assertRaises(errors.Error):
arg_parser.parse_args()
class TestAddDeprecatedArgument(unittest.TestCase):
"""Tests for add_deprecated_argument method of HelpfulArgumentParser"""
@mock.patch.object(HelpfulArgumentParser, "modify_kwargs_for_default_detection")
def test_no_default_detection_modifications(self, mock_modify):
arg_parser = HelpfulArgumentParser(["run"], {}, detect_defaults=True)
arg_parser.add_deprecated_argument("--foo", 0)
arg_parser.parse_args()
mock_modify.assert_not_called()
if __name__ == '__main__':
unittest.main() # pragma: no cover
| 4,291 |
2,226 |
#include <inttypes.h>
#include <math.h>
#include <limits.h>
#include <signal.h>
#include <stdint.h>
#include "types.h"
#include "player.h"
#include "stream_handler.h"
static void do_exit(VideoState *is)
{
if (is) {
StreamHandler::stream_close(is);
}
if (renderer)
SDL_DestroyRenderer(renderer);
if (window)
SDL_DestroyWindow(window);
uninit_opts();
#if CONFIG_AVFILTER
av_freep(&vfilters_list);
#endif
avformat_network_deinit();
if (show_status)
printf("\n");
SDL_Quit();
av_log(NULL, AV_LOG_QUIET, "%s", "");
exit(0);
}
static void sigterm_handler(int sig)
{
exit(123);
}
static int opt_frame_size(void *optctx, const char *opt, const char *arg)
{
av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
return opt_default(NULL, "video_size", arg);
}
static int opt_width(void *optctx, const char *opt, const char *arg)
{
screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
return 0;
}
static int opt_height(void *optctx, const char *opt, const char *arg)
{
screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
return 0;
}
static int opt_format(void *optctx, const char *opt, const char *arg)
{
file_iformat = av_find_input_format(arg);
if (!file_iformat) {
av_log(NULL, AV_LOG_FATAL, "Unknown input format: %s\n", arg);
return AVERROR(EINVAL);
}
return 0;
}
static int opt_frame_pix_fmt(void *optctx, const char *opt, const char *arg)
{
av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
return opt_default(NULL, "pixel_format", arg);
}
static int opt_sync(void *optctx, const char *opt, const char *arg)
{
if (!strcmp(arg, "audio"))
av_sync_type = AV_SYNC_AUDIO_MASTER;
else if (!strcmp(arg, "video"))
av_sync_type = AV_SYNC_VIDEO_MASTER;
else if (!strcmp(arg, "ext"))
av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
else {
av_log(NULL, AV_LOG_ERROR, "Unknown value for %s: %s\n", opt, arg);
exit(1);
}
return 0;
}
static int opt_seek(void *optctx, const char *opt, const char *arg)
{
start_time = parse_time_or_die(opt, arg, 1);
return 0;
}
static int opt_duration(void *optctx, const char *opt, const char *arg)
{
duration = parse_time_or_die(opt, arg, 1);
return 0;
}
static int opt_show_mode(void *optctx, const char *opt, const char *arg)
{
show_mode = (ShowMode) !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
!strcmp(arg, "waves") ? SHOW_MODE_WAVES :
!strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
(ShowMode) parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
return 0;
}
static void opt_input_file(void *optctx, const char *filename)
{
if (input_filename) {
av_log(NULL, AV_LOG_FATAL,
"Argument '%s' provided as input filename, but '%s' was already specified.\n",
filename, input_filename);
exit(1);
}
if (!strcmp(filename, "-"))
filename = "pipe:";
input_filename = filename;
}
static int opt_codec(void *optctx, const char *opt, const char *arg)
{
const char *spec = strchr(opt, ':');
if (!spec) {
av_log(NULL, AV_LOG_ERROR,
"No media specifier was specified in '%s' in option '%s'\n",
arg, opt);
return AVERROR(EINVAL);
}
spec++;
switch (spec[0]) {
case 'a' : audio_codec_name = arg; break;
case 's' : subtitle_codec_name = arg; break;
case 'v' : video_codec_name = arg; break;
default:
av_log(NULL, AV_LOG_ERROR,
"Invalid media specifier '%s' in option '%s'\n", spec, opt);
return AVERROR(EINVAL);
}
return 0;
}
static int dummy;
const char program_name[] = "ffplay";
const int program_birth_year = 2003;
static const OptionDef options[] = {
CMDUTILS_COMMON_OPTIONS
{ "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
{ "y", HAS_ARG, { .func_arg = opt_height }, "force displayed height", "height" },
{ "s", HAS_ARG | OPT_VIDEO, { .func_arg = opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
{ "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
{ "an", OPT_BOOL, { &audio_disable }, "disable audio" },
{ "vn", OPT_BOOL, { &video_disable }, "disable video" },
{ "sn", OPT_BOOL, { &subtitle_disable }, "disable subtitling" },
{ "ast", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_specifier" },
{ "vst", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_specifier" },
{ "sst", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_specifier" },
{ "ss", HAS_ARG, { .func_arg = opt_seek }, "seek to a given position in seconds", "pos" },
{ "t", HAS_ARG, { .func_arg = opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
{ "bytes", OPT_INT | HAS_ARG, { &seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
{ "seek_interval", OPT_FLOAT | HAS_ARG, { &seek_interval }, "set seek interval for left/right keys, in seconds", "seconds" },
{ "nodisp", OPT_BOOL, { &display_disable }, "disable graphical display" },
{ "noborder", OPT_BOOL, { &borderless }, "borderless window" },
{ "alwaysontop", OPT_BOOL, { &alwaysontop }, "window always on top" },
{ "volume", OPT_INT | HAS_ARG, { &startup_volume}, "set startup volume 0=min 100=max", "volume" },
{ "f", HAS_ARG, { .func_arg = opt_format }, "force format", "fmt" },
{ "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_frame_pix_fmt }, "set pixel format", "format" },
{ "stats", OPT_BOOL | OPT_EXPERT, { &show_status }, "show status", "" },
{ "fast", OPT_BOOL | OPT_EXPERT, { &fast }, "non spec compliant optimizations", "" },
{ "genpts", OPT_BOOL | OPT_EXPERT, { &genpts }, "generate pts", "" },
{ "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { &decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
{ "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { &lowres }, "", "" },
{ "sync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
{ "autoexit", OPT_BOOL | OPT_EXPERT, { &autoexit }, "exit at the end", "" },
{ "exitonkeydown", OPT_BOOL | OPT_EXPERT, { &exit_on_keydown }, "exit on key down", "" },
{ "exitonmousedown", OPT_BOOL | OPT_EXPERT, { &exit_on_mousedown }, "exit on mouse down", "" },
{ "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { &loop }, "set number of times the playback shall be looped", "loop count" },
{ "framedrop", OPT_BOOL | OPT_EXPERT, { &framedrop }, "drop frames when cpu is too slow", "" },
{ "infbuf", OPT_BOOL | OPT_EXPERT, { &infinite_buffer }, "don't limit the input buffer size (useful with realtime streams)", "" },
{ "window_title", OPT_STRING | HAS_ARG, { &window_title }, "set window title", "window title" },
{ "left", OPT_INT | HAS_ARG | OPT_EXPERT, { &screen_left }, "set the x position for the left of the window", "x pos" },
{ "top", OPT_INT | HAS_ARG | OPT_EXPERT, { &screen_top }, "set the y position for the top of the window", "y pos" },
#if CONFIG_AVFILTER
{ "vf", OPT_EXPERT | HAS_ARG, { .func_arg = StreamHandler::opt_add_vfilter }, "set video filters", "filter_graph" },
{ "af", OPT_STRING | HAS_ARG, { &afilters }, "set audio filters", "filter_graph" },
#endif
{ "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { &rdftspeed }, "rdft speed", "msecs" },
{ "showmode", HAS_ARG, { .func_arg = opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
{ "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default }, "generic catch all option", "" },
{ "i", OPT_BOOL, { &dummy}, "read specified file", "input_file"},
{ "codec", HAS_ARG, { .func_arg = opt_codec}, "force decoder", "decoder_name" },
{ "acodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &audio_codec_name }, "force audio decoder", "decoder_name" },
{ "scodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &subtitle_codec_name }, "force subtitle decoder", "decoder_name" },
{ "vcodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &video_codec_name }, "force video decoder", "decoder_name" },
{ "autorotate", OPT_BOOL, { &autorotate }, "automatically rotate video", "" },
{ "find_stream_info", OPT_BOOL | OPT_INPUT | OPT_EXPERT, { &find_stream_info },
"read and decode the streams to fill missing information with heuristics" },
{ "filter_threads", HAS_ARG | OPT_INT | OPT_EXPERT, { &filter_nbthreads }, "number of filter threads per graph" },
{ NULL, },
};
static void show_usage(void)
{
av_log(NULL, AV_LOG_INFO, "Simple media player\n");
av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
av_log(NULL, AV_LOG_INFO, "\n");
}
void show_help_default(const char *opt, const char *arg)
{
av_log_set_callback(log_callback_help);
show_usage();
show_help_options(options, "Main options:", 0, OPT_EXPERT, 0);
show_help_options(options, "Advanced options:", OPT_EXPERT, 0, 0);
printf("\n");
show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
#if !CONFIG_AVFILTER
show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
#else
show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
#endif
printf("\nWhile playing:\n"
"q, ESC quit\n"
"f toggle full screen\n"
"p, SPC pause\n"
"m toggle mute\n"
"9, 0 decrease and increase volume respectively\n"
"/, * decrease and increase volume respectively\n"
"a cycle audio channel in the current program\n"
"v cycle video channel\n"
"t cycle subtitle channel in the current program\n"
"c cycle program\n"
"w cycle video filters or show modes\n"
"s activate frame-step mode\n"
"left/right seek backward/forward 10 seconds or to custom interval if -seek_interval is set\n"
"down/up seek backward/forward 1 minute\n"
"page down/page up seek backward/forward 10 minutes\n"
"right mouse click seek to percentage in file corresponding to fraction of width\n"
"left double-click toggle full screen\n"
);
}
/* Called from the main */
int main(int argc, char **argv)
{
int flags;
VideoState *is;
init_dynload();
av_log_set_flags(AV_LOG_SKIP_REPEATED);
parse_loglevel(argc, argv, options);
/* register all codecs, demux and protocols */
#if CONFIG_AVDEVICE
avdevice_register_all();
#endif
avformat_network_init();
init_opts();
signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
show_banner(argc, argv, options);
parse_options(NULL, argc, argv, options, opt_input_file);
if (!input_filename) {
show_usage();
av_log(NULL, AV_LOG_FATAL, "An input file must be specified\n");
av_log(NULL, AV_LOG_FATAL,
"Use -h to get full help or, even better, run 'man %s'\n", program_name);
exit(1);
}
// Debug
//CoInitializeEx(NULL, COINIT_MULTITHREADED);
//CoInitialize(NULL);
if (display_disable) {
video_disable = 1;
}
flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
if (audio_disable)
flags &= ~SDL_INIT_AUDIO;
else {
/* Try to work around an occasional ALSA buffer underflow issue when the
* period size is NPOT due to ALSA resampling by forcing the buffer size. */
if (!SDL_getenv("SDL_AUDIO_ALSA_SET_BUFFER_SIZE"))
SDL_setenv("SDL_AUDIO_ALSA_SET_BUFFER_SIZE","1", 1);
}
if (display_disable)
flags &= ~SDL_INIT_VIDEO;
if (SDL_Init (flags)) {
av_log(NULL, AV_LOG_FATAL, "Could not initialize SDL - %s\n", SDL_GetError());
av_log(NULL, AV_LOG_FATAL, "(Did you set the DISPLAY variable?)\n");
exit(1);
}
SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
av_init_packet(&flush_pkt);
flush_pkt.data = (uint8_t *)&flush_pkt;
if (!display_disable) {
int flags = SDL_WINDOW_HIDDEN;
if (alwaysontop)
#if SDL_VERSION_ATLEAST(2,0,5)
flags |= SDL_WINDOW_ALWAYS_ON_TOP;
#else
av_log(NULL, AV_LOG_WARNING, "Your SDL version doesn't support SDL_WINDOW_ALWAYS_ON_TOP. Feature will be inactive.\n");
#endif
if (borderless)
flags |= SDL_WINDOW_BORDERLESS;
else
flags |= SDL_WINDOW_RESIZABLE;
window = SDL_CreateWindow(program_name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, default_width, default_height, flags);
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
renderer = 0;
if (window) {
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
av_log(NULL, AV_LOG_WARNING, "Failed to initialize a hardware accelerated renderer: %s\n", SDL_GetError());
renderer = SDL_CreateRenderer(window, -1, 0);
}
if (renderer) {
if (!SDL_GetRendererInfo(renderer, &renderer_info))
av_log(NULL, AV_LOG_VERBOSE, "Initialized %s renderer.\n", renderer_info.name);
}
}
if (!window || !renderer || !renderer_info.num_texture_formats) {
av_log(NULL, AV_LOG_FATAL, "Failed to create window or renderer: %s", SDL_GetError());
do_exit(NULL);
}
}
is = StreamHandler::stream_open(input_filename, file_iformat);
if (!is) {
av_log(NULL, AV_LOG_FATAL, "Failed to initialize VideoState!\n");
do_exit(NULL);
}
Player::event_loop(is);
/* never returns */
return 0;
}
| 6,354 |
819 | # -*- encoding: utf-8 -*-
"""基于环形数组实现的一个简单队列
数组A[1..n]实现最多容纳n-1个元素的队列。
"""
class ArrayQueue:
def __init__(self, size):
self.head = 0 # 队头元素下标
self.tail = 0 # 下一个插入位置
self._arr = [None] * size # 实际存放数据的数组
def is_empty(self):
return self.head == self.tail
def is_full(self):
return self.size() == len(self._arr) - 1
def size(self):
return (len(self._arr) + self.tail - self.head) % len(self._arr)
def enqueue(self, item):
# 队列满了则抛出异常
if self.is_full():
raise LookupError('Queue is full')
self._arr[self.tail] = item
self.tail = (self.tail + 1) % len(self._arr)
def dequeue(self):
# 队列空则抛出异常
if self.is_empty():
raise LookupError('Queue underflow')
item = self._arr[self.head]
self._arr[self.head] = None
self.head = (self.head + 1) % len(self._arr)
return item
def __iter__(self):
while not self.is_empty():
yield self.dequeue()
if __name__ == '__main__':
q = ArrayQueue(6)
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
| 872 |
1,086 | <gh_stars>1000+
/* alplatf.h is generated from alplatf.h.cmake */
/* #undef ALLEGRO_MINGW32 */
/* #undef ALLEGRO_UNIX */
#define ALLEGRO_MSVC
/* #undef ALLEGRO_MACOSX */
/* #undef ALLEGRO_BCC32 */
/* #undef ALLEGRO_IPHONE */
/* #undef ALLEGRO_ANDROID */
/* #undef ALLEGRO_RASPBERRYPI */
/* #undef ALLEGRO_CFG_NO_FPU */
/* #undef ALLEGRO_CFG_DLL_TLS */
/* #undef ALLEGRO_CFG_PTHREADS_TLS */
#define ALLEGRO_CFG_RELEASE_LOGGING
#define ALLEGRO_CFG_D3D
/* #undef ALLEGRO_CFG_D3D9EX */
#define ALLEGRO_CFG_D3DX9
#define ALLEGRO_CFG_XINPUT
#define ALLEGRO_CFG_OPENGL
/* #undef ALLEGRO_CFG_OPENGLES */
/* #undef ALLEGRO_CFG_OPENGLES1 */
/* #undef ALLEGRO_CFG_OPENGLES2 */
/* #undef ALLEGRO_CFG_OPENGLES3 */
#define ALLEGRO_CFG_OPENGL_FIXED_FUNCTION
#define ALLEGRO_CFG_OPENGL_PROGRAMMABLE_PIPELINE
#define ALLEGRO_CFG_SHADER_GLSL
#define ALLEGRO_CFG_SHADER_HLSL
/* #undef ALLEGRO_CFG_ANDROID_LEGACY */
/*---------------------------------------------------------------------------*/
/* Define to 1 if you have the corresponding header file. */
/* #undef ALLEGRO_HAVE_DIRENT_H */
#define ALLEGRO_HAVE_INTTYPES_H
/* #undef ALLEGRO_HAVE_LINUX_AWE_VOICE_H */
/* #undef ALLEGRO_HAVE_LINUX_INPUT_H */
/* #undef ALLEGRO_HAVE_LINUX_SOUNDCARD_H */
/* #undef ALLEGRO_HAVE_MACHINE_SOUNDCARD_H */
/* #undef ALLEGRO_HAVE_SOUNDCARD_H */
#define ALLEGRO_HAVE_STDBOOL_H
#define ALLEGRO_HAVE_STDINT_H
/* #undef ALLEGRO_HAVE_SV_PROCFS_H */
/* #undef ALLEGRO_HAVE_SYS_IO_H */
/* #undef ALLEGRO_HAVE_SYS_SOUNDCARD_H */
#define ALLEGRO_HAVE_SYS_STAT_H
/* #undef ALLEGRO_HAVE_SYS_TIME_H */
#define ALLEGRO_HAVE_TIME_H
/* #undef ALLEGRO_HAVE_SYS_UTSNAME_H */
#define ALLEGRO_HAVE_SYS_TYPES_H
/* #undef ALLEGRO_HAVE_OSATOMIC_H */
/* #undef ALLEGRO_HAVE_SYS_INOTIFY_H */
#define ALLEGRO_HAVE_SAL_H
/* Define to 1 if the corresponding functions are available. */
/* #undef ALLEGRO_HAVE_GETEXECNAME */
/* #undef ALLEGRO_HAVE_MKSTEMP */
/* #undef ALLEGRO_HAVE_MMAP */
/* #undef ALLEGRO_HAVE_MPROTECT */
/* #undef ALLEGRO_HAVE_SCHED_YIELD */
/* #undef ALLEGRO_HAVE_SYSCONF */
/* #undef ALLEGRO_HAVE_SYSCTL */
/* #undef ALLEGRO_HAVE_FSEEKO */
/* #undef ALLEGRO_HAVE_FTELLO */
/* #undef ALLEGRO_HAVE_STRERROR_R */
#define ALLEGRO_HAVE_STRERROR_S
#define ALLEGRO_HAVE_VA_COPY
#define ALLEGRO_HAVE_FTELLI64
#define ALLEGRO_HAVE_FSEEKI64
/* Define to 1 if procfs reveals argc and argv */
/* #undef ALLEGRO_HAVE_PROCFS_ARGCV */
/*---------------------------------------------------------------------------*/
/* Define if target machine is little endian. */
#define ALLEGRO_LITTLE_ENDIAN
/* Define if target machine is big endian. */
/* #undef ALLEGRO_BIG_ENDIAN */
/* Define if target platform is Darwin. */
/* #undef ALLEGRO_DARWIN */
/*---------------------------------------------------------------------------*/
/* Define if you need support for X-Windows. */
/* #undef ALLEGRO_WITH_XWINDOWS */
/* Define if XCursor ARGB extension is available. */
/* #undef ALLEGRO_XWINDOWS_WITH_XCURSOR */
/* Define if XF86VidMode extension is supported. */
/* #undef ALLEGRO_XWINDOWS_WITH_XF86VIDMODE */
/* Define if Xinerama extension is supported. */
/* #undef ALLEGRO_XWINDOWS_WITH_XINERAMA */
/* Define if XRandR extension is supported. */
/* #undef ALLEGRO_XWINDOWS_WITH_XRANDR */
/* Define if XScreenSaver extension is supported. */
/* #undef ALLEGRO_XWINDOWS_WITH_XSCREENSAVER */
/* Define if XIM extension is supported. */
/* #undef ALLEGRO_XWINDOWS_WITH_XIM */
/* Define if XInput 2.2 X11 extension is supported. */
/* #undef ALLEGRO_XWINDOWS_WITH_XINPUT2 */
/* Define if Xpm is found. Useful on Ubuntu Unity to set icon. */
/* #undef ALLEGRO_XWINDOWS_WITH_XPM */
/*---------------------------------------------------------------------------*/
/* Define if target platform is linux. */
/* #undef ALLEGRO_LINUX */
/* Define if we are building with SDL backend. */
/* #undef ALLEGRO_SDL */
/* Define if sleep should be used instead of threads (only useful for emscripten without web workers) */
/* #undef ALLEGRO_WAIT_EVENT_SLEEP */
/*---------------------------------------------------------------------------*/
/* vi: set ft=c ts=3 sts=3 sw=3 et: */
| 1,731 |
95,154 | <gh_stars>1000+
{
"name": "zone.js/webapis-shadydom.min",
"main": "../../bundles/webapis-shadydom.umd.min.js",
"fesm2015": "../../fesm2015/webapis-shadydom.min.js",
"es2015": "../../fesm2015/webapis-shadydom.min.js",
"module": "../../fesm2015/webapis-shadydom.min.js"
}
| 134 |
7,713 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.views.art;
import javax.annotation.Nullable;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Region;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.uimanager.annotations.ReactProp;
/**
* Shadow node for virtual ARTGroup view
*/
public class ARTGroupShadowNode extends ARTVirtualNode {
protected @Nullable RectF mClipping;
@ReactProp(name = "clipping")
public void setClipping(@Nullable ReadableArray clippingDims) {
float[] clippingData = PropHelper.toFloatArray(clippingDims);
if (clippingData != null) {
mClipping = createClipping(clippingData);
markUpdated();
}
}
@Override
public boolean isVirtual() {
return true;
}
public void draw(Canvas canvas, Paint paint, float opacity) {
opacity *= mOpacity;
if (opacity > MIN_OPACITY_FOR_DRAW) {
saveAndSetupCanvas(canvas);
if (mClipping != null) {
canvas.clipRect(
mClipping.left * mScale,
mClipping.top * mScale,
mClipping.right * mScale,
mClipping.bottom * mScale,
Region.Op.REPLACE);
}
for (int i = 0; i < getChildCount(); i++) {
ARTVirtualNode child = (ARTVirtualNode) getChildAt(i);
child.draw(canvas, paint, opacity);
child.markUpdateSeen();
}
restoreCanvas(canvas);
}
}
/**
* Creates a {@link RectF} from an array of dimensions
* (e.g. [x, y, width, height])
*
* @param data the array of dimensions
* @return the {@link RectF} that can used to clip the canvas
*/
private static RectF createClipping(float[] data) {
if (data.length != 4) {
throw new JSApplicationIllegalArgumentException(
"Clipping should be array of length 4 (e.g. [x, y, width, height])");
}
RectF clippingRect = new RectF(
data[0], data[1], data[0] + data[2], data[1] + data[3]);
return clippingRect;
}
}
| 884 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.