max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
3,651 | package com.orientechnologies.orient.distributed.impl.structural.submit;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public interface OStructuralSubmitResponse {
void serialize(DataOutput output) throws IOException;
void deserialize(DataInput input) throws IOException;
int getResponseType();
}
| 97 |
335 | <reponame>mrslezak/Engine<filename>OREData/ored/configuration/iborfallbackconfig.cpp
/*
Copyright (C) 2021 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ored/configuration/iborfallbackconfig.hpp>
#include <ored/utilities/to_string.hpp>
namespace ore {
namespace data {
IborFallbackConfig::IborFallbackConfig() { clear(); }
IborFallbackConfig::IborFallbackConfig(const bool enableIborFallbacks, const bool useRfrCurveInTodaysMarket,
const bool useRfrCurveInSimulationMarket,
const std::map<std::string, FallbackData>& fallbacks)
: enableIborFallbacks_(enableIborFallbacks), useRfrCurveInTodaysMarket_(useRfrCurveInTodaysMarket),
useRfrCurveInSimulationMarket_(useRfrCurveInSimulationMarket), fallbacks_(fallbacks) {}
void IborFallbackConfig::clear() {
enableIborFallbacks_ = true;
useRfrCurveInTodaysMarket_ = true;
useRfrCurveInSimulationMarket_ = false;
fallbacks_.clear();
}
bool IborFallbackConfig::useRfrCurveInTodaysMarket() const { return useRfrCurveInTodaysMarket_; }
bool IborFallbackConfig::useRfrCurveInSimulationMarket() const { return useRfrCurveInSimulationMarket_; }
bool IborFallbackConfig::enableIborFallbacks() const { return enableIborFallbacks_; }
void IborFallbackConfig::addIndexFallbackRule(const string& iborIndex, const FallbackData& fallbackData) {
fallbacks_[iborIndex] = fallbackData;
}
bool IborFallbackConfig::isIndexReplaced(const string& iborIndex, const Date& asof) const {
if (!enableIborFallbacks())
return false;
auto i = fallbacks_.find(iborIndex);
return i != fallbacks_.end() && asof >= i->second.switchDate;
}
const IborFallbackConfig::FallbackData& IborFallbackConfig::fallbackData(const string& iborIndex) const {
auto i = fallbacks_.find(iborIndex);
QL_REQUIRE(
i != fallbacks_.end(),
"No fallback data found for ibor index '"
<< iborIndex
<< "', client code should check whether an index is replaced with IsIndexReplaced() before querying data.");
return i->second;
}
void IborFallbackConfig::fromXML(XMLNode* node) {
clear();
XMLUtils::checkNode(node, "IborFallbackConfig");
if (auto global = XMLUtils::getChildNode(node, "GlobalSettings")) {
enableIborFallbacks_ = XMLUtils::getChildValueAsBool(global, "EnableIborFallbacks", true);
useRfrCurveInTodaysMarket_ = XMLUtils::getChildValueAsBool(global, "UseRfrCurveInTodaysMarket", true);
useRfrCurveInSimulationMarket_ = XMLUtils::getChildValueAsBool(global, "UseRfrCurveInSimulationMarket", true);
}
if (auto fallbacks = XMLUtils::getChildNode(node, "Fallbacks")) {
for (auto const repl : XMLUtils::getChildrenNodes(fallbacks, "Fallback")) {
XMLUtils::checkNode(repl, "Fallback");
string ibor = XMLUtils::getChildValue(repl, "IborIndex", true);
fallbacks_[ibor].rfrIndex = XMLUtils::getChildValue(repl, "RfrIndex", true);
fallbacks_[ibor].spread = parseReal(XMLUtils::getChildValue(repl, "Spread", true));
fallbacks_[ibor].switchDate = parseDate(XMLUtils::getChildValue(repl, "SwitchDate", true));
}
}
}
XMLNode* IborFallbackConfig::toXML(XMLDocument& doc) {
XMLNode* node = doc.allocNode("IborFallbackConfig");
XMLNode* global = XMLUtils::addChild(doc, node, "GlobalSettings");
XMLUtils::addChild(doc, global, "EnableIborFallbacks", enableIborFallbacks_);
XMLUtils::addChild(doc, global, "UseRfrCurveInTodaysMarket", useRfrCurveInTodaysMarket_);
XMLUtils::addChild(doc, global, "UseRfrCurveInSimulationMarket", useRfrCurveInSimulationMarket_);
XMLNode* repl = XMLUtils::addChild(doc, node, "Fallbacks");
for (auto const& r : fallbacks_) {
XMLNode* tmp = XMLUtils::addChild(doc, repl, "Fallback");
XMLUtils::addChild(doc, tmp, "IborIndex", r.first);
XMLUtils::addChild(doc, tmp, "RfrIndex", r.second.rfrIndex);
XMLUtils::addChild(doc, tmp, "Spread", r.second.spread);
XMLUtils::addChild(doc, tmp, "SwitchDate", ore::data::to_string(r.second.switchDate));
}
return node;
}
IborFallbackConfig IborFallbackConfig::defaultConfig() {
// A switch date 1 Jan 2022 indicates that the cessation date is not yet known. Sources:
// [1] BBG ISDA IBOR Fallback Dashboard (Tenor Effective Date = switchDate, Spread Adjustment Today => spread)
// [2] https://assets.bbhub.io/professional/sites/10/IBOR-Fallbacks-LIBOR-Cessation_Announcement_20210305.pdf
// [3] https://www.isda.org/2021/03/05/isda-statement-on-uk-fca-libor-announcement/
// [4] https://www.fca.org.uk/publication/documents/future-cessation-loss-representativeness-libor-benchmarks.pdf
// [5] https://www.isda.org/2021/03/29/isda-statement-on-jbata-announcement-on-yen-tibor-and-euroyen-tibor/
// [6] https://www.isda.org/a/rwNTE/CDOR-tenor-cessation_ISDA-guidance_17.11.2020_PDF.pdf
static IborFallbackConfig c = {true,
true,
false,
{{"CHF-LIBOR-SN", FallbackData{"CHF-SARON", -0.000551, Date(1, Jan, 2022)}},
{"CHF-LIBOR-1W", FallbackData{"CHF-SARON", -0.000705, Date(1, Jan, 2022)}},
{"CHF-LIBOR-1M", FallbackData{"CHF-SARON", -0.000571, Date(1, Jan, 2022)}},
{"CHF-LIBOR-2M", FallbackData{"CHF-SARON", -0.000231, Date(1, Jan, 2022)}},
{"CHF-LIBOR-3M", FallbackData{"CHF-SARON", 0.000031, Date(1, Jan, 2022)}},
{"CHF-LIBOR-6M", FallbackData{"CHF-SARON", 0.000741, Date(1, Jan, 2022)}},
{"CHF-LIBOR-12M", FallbackData{"CHF-SARON", 0.002048, Date(1, Jan, 2022)}},
{"EUR-EURIBOR-1W", FallbackData{"EUR-ESTER", 0.000577, Date(1, Jan, 2100)}},
{"EUR-EURIBOR-1M", FallbackData{"EUR-ESTER", 0.000738, Date(1, Jan, 2100)}},
{"EUR-EURIBOR-3M", FallbackData{"EUR-ESTER", 0.001244, Date(1, Jan, 2100)}},
{"EUR-EURIBOR-6M", FallbackData{"EUR-ESTER", 0.001977, Date(1, Jan, 2100)}},
{"EUR-EURIBOR-12M", FallbackData{"EUR-ESTER", 0.002048, Date(1, Jan, 2100)}},
{"EUR-LIBOR-ON", FallbackData{"EUR-ESTER", 0.000017, Date(1, Jan, 2022)}},
{"EUR-LIBOR-1W", FallbackData{"EUR-ESTER", 0.000243, Date(1, Jan, 2022)}},
{"EUR-LIBOR-1M", FallbackData{"EUR-ESTER", 0.000456, Date(1, Jan, 2022)}},
{"EUR-LIBOR-2M", FallbackData{"EUR-ESTER", 0.000753, Date(1, Jan, 2022)}},
{"EUR-LIBOR-3M", FallbackData{"EUR-ESTER", 0.000962, Date(1, Jan, 2022)}},
{"EUR-LIBOR-6M", FallbackData{"EUR-ESTER", 0.001537, Date(1, Jan, 2022)}},
{"EUR-LIBOR-12M", FallbackData{"EUR-ESTER", 0.002993, Date(1, Jan, 2022)}},
{"JPY-TIBOR-1W", FallbackData{"JPY-TONAR", 0.0005564, Date(1, Jan, 2025)}},
{"JPY-TIBOR-1M", FallbackData{"JPY-TONAR", 0.0009608, Date(1, Jan, 2025)}},
{"JPY-TIBOR-3M", FallbackData{"JPY-TONAR", 0.0010989, Date(1, Jan, 2025)}},
{"JPY-TIBOR-6M", FallbackData{"JPY-TONAR", 0.0016413, Date(1, Jan, 2025)}},
{"JPY-TIBOR-12M", FallbackData{"JPY-TONAR", 0.0018181, Date(1, Jan, 2025)}},
{"JPY-EYTIBOR-1W", FallbackData{"JPY-TONAR", 0.0006506, Date(1, Jan, 2025)}},
{"JPY-EYTIBOR-1M", FallbackData{"JPY-TONAR", 0.0013485, Date(1, Jan, 2025)}},
{"JPY-EYTIBOR-3M", FallbackData{"JPY-TONAR", 0.0010252, Date(1, Jan, 2025)}},
{"JPY-EYTIBOR-6M", FallbackData{"JPY-TONAR", 0.0014848, Date(1, Jan, 2025)}},
{"JPY-EYTIBOR-12M", FallbackData{"JPY-TONAR", 0.0018567, Date(1, Jan, 2025)}},
{"JPY-LIBOR-SN", FallbackData{"JPY-TONAR", -0.0001839, Date(1, Jan, 2022)}},
{"JPY-LIBOR-1W", FallbackData{"JPY-TONAR", -0.0001981, Date(1, Jan, 2022)}},
{"JPY-LIBOR-1M", FallbackData{"JPY-TONAR", -0.0002923, Date(1, Jan, 2022)}},
{"JPY-LIBOR-2M", FallbackData{"JPY-TONAR", -0.0000449, Date(1, Jan, 2022)}},
{"JPY-LIBOR-3M", FallbackData{"JPY-TONAR", 0.0000835, Date(1, Jan, 2022)}},
{"JPY-LIBOR-6M", FallbackData{"JPY-TONAR", 0.0005809, Date(1, Jan, 2022)}},
{"JPY-LIBOR-12M", FallbackData{"JPY-TONAR", 0.00166, Date(1, Jan, 2022)}},
{"AUD-BBSW-1M", FallbackData{"AUD-AONIA", 0.001191, Date(1, Jan, 2100)}},
{"AUD-BBSW-2M", FallbackData{"AUD-AONIA", 0.002132, Date(1, Jan, 2100)}},
{"AUD-BBSW-3M", FallbackData{"AUD-AONIA", 0.002623, Date(1, Jan, 2100)}},
{"AUD-BBSW-4M", FallbackData{"AUD-AONIA", 0.003313, Date(1, Jan, 2100)}},
{"AUD-BBSW-5M", FallbackData{"AUD-AONIA", 0.004104, Date(1, Jan, 2100)}},
{"AUD-BBSW-6M", FallbackData{"AUD-AONIA", 0.004845, Date(1, Jan, 2100)}},
{"HKD-HIBOR-ON", FallbackData{"HKD-HONIA", 0.0003219, Date(1, Jan, 2100)}},
{"HKD-HIBOR-1W", FallbackData{"HKD-HONIA", 0.001698, Date(1, Jan, 2100)}},
{"HKD-HIBOR-2W", FallbackData{"HKD-HONIA", 0.002370, Date(1, Jan, 2100)}},
{"HKD-HIBOR-1M", FallbackData{"HKD-HONIA", 0.0039396, Date(1, Jan, 2100)}},
{"HKD-HIBOR-2M", FallbackData{"HKD-HONIA", 0.0056768, Date(1, Jan, 2100)}},
{"HKD-HIBOR-3M", FallbackData{"HKD-HONIA", 0.0072642, Date(1, Jan, 2100)}},
{"HKD-HIBOR-6M", FallbackData{"HKD-HONIA", 0.0093495, Date(1, Jan, 2100)}},
{"HKD-HIBOR-12M", FallbackData{"HKD-HONIA", 0.0121231, Date(1, Jan, 2100)}},
{"CAD-CDOR-1M", FallbackData{"CAD-CORRA", 0.0033033, Date(1, Jan, 2100)}},
{"CAD-CDOR-2M", FallbackData{"CAD-CORRA", 0.0035822, Date(1, Jan, 2100)}},
{"CAD-CDOR-3M", FallbackData{"CAD-CORRA", 0.0037292, Date(1, Jan, 2100)}},
{"CAD-CDOR-6M", FallbackData{"CAD-CORRA", 0.0049323, Date(17, May, 2021)}},
{"CAD-CDOR-12M", FallbackData{"CAD-CORRA", 0.005479, Date(17, May, 2021)}},
{"GBP-LIBOR-ON", FallbackData{"GBP-SONIA", -0.000024, Date(1, Jan, 2022)}},
{"GBP-LIBOR-1W", FallbackData{"GBP-SONIA", 0.000168, Date(1, Jan, 2022)}},
{"GBP-LIBOR-1M", FallbackData{"GBP-SONIA", 0.000326, Date(1, Jan, 2022)}},
{"GBP-LIBOR-2M", FallbackData{"GBP-SONIA", 0.000633, Date(1, Jan, 2022)}},
{"GBP-LIBOR-3M", FallbackData{"GBP-SONIA", 0.001193, Date(1, Jan, 2022)}},
{"GBP-LIBOR-6M", FallbackData{"GBP-SONIA", 0.002766, Date(1, Jan, 2022)}},
{"GBP-LIBOR-12M", FallbackData{"GBP-SONIA", 0.004644, Date(1, Jan, 2022)}},
{"USD-LIBOR-ON", FallbackData{"USD-SOFR", 0.0000644, Date(1, Jul, 2023)}},
{"USD-LIBOR-1W", FallbackData{"USD-SOFR", 0.0003839, Date(1, Jan, 2023)}},
{"USD-LIBOR-1M", FallbackData{"USD-SOFR", 0.0011448, Date(1, Jul, 2023)}},
{"USD-LIBOR-2M", FallbackData{"USD-SOFR", 0.0018456, Date(1, Jan, 2023)}},
{"USD-LIBOR-3M", FallbackData{"USD-SOFR", 0.0026161, Date(1, Jul, 2023)}},
{"USD-LIBOR-6M", FallbackData{"USD-SOFR", 0.0042826, Date(1, Jul, 2023)}},
{"USD-LIBOR-12M", FallbackData{"USD-SOFR", 0.0071513, Date(1, Jul, 2023)}}}};
return c;
}
} // namespace data
} // namespace ore
| 7,127 |
679 | <reponame>denisgotthans/togglz
package org.togglz.spring.activation;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.togglz.core.activation.AbstractTokenizedActivationStrategy;
import org.togglz.core.activation.Parameter;
import org.togglz.core.activation.ParameterBuilder;
import org.togglz.core.repository.FeatureState;
import org.togglz.core.user.FeatureUser;
import org.togglz.spring.util.ContextClassLoaderApplicationContextHolder;
/**
* <p>
* An activation strategy based on the profiles that are active within the Spring environment.
* </p>
* <p>
* One or more profiles can be specified in a comma-separated value via the "{@value #PARAM_PROFILES}" parameter. This
* strategy works by only activating the feature if at least one of the profiles are currently active. Profile names are
* not case sensitive.
* </p>
* <p>
* If a given profile is prefixed with the NOT operator ({@code !}), the feature will only be active if the profile is
* <b>not</b> active. If the value of the "{@value #PARAM_PROFILES}" parameter was {@code "p1,!p2"}, the feature would
* only be active if "p1" is active or if "p2" is not active.
* </p>
*
* @author <NAME>
* @see AbstractTokenizedActivationStrategy
*/
public class SpringProfileActivationStrategy extends AbstractTokenizedActivationStrategy {
public static final String ID = "spring-profile";
public static final String PARAM_PROFILES = "profiles";
private static List<String> getActiveProfileNames(ApplicationContext applicationContext) {
String[] names = applicationContext.getEnvironment().getActiveProfiles();
List<String> result = new ArrayList<>(names.length);
for (String name : names) {
result.add(name.toLowerCase());
}
return result;
}
@Override
public String getId() {
return ID;
}
@Override
public String getName() {
return "Spring Profile";
}
@Override
public boolean isActive(FeatureState featureState, FeatureUser user, List<Token> tokens) {
ApplicationContext applicationContext = ContextClassLoaderApplicationContextHolder.get();
if (applicationContext == null) {
throw new IllegalStateException("ApplicationContext could not be found, which can occur if there is no "
+ "bean for TogglzApplicationContextBinderApplicationListener when TogglzAutoConfiguration is not "
+ "being used");
}
List<String> activeProfileNames = getActiveProfileNames(applicationContext);
for (Token token : tokens) {
if (activeProfileNames.contains(token.getValue()) != token.isNegated()) {
return true;
}
}
return false;
}
@Override
public Parameter[] getParameters() {
return new Parameter[] {
ParameterBuilder.create(PARAM_PROFILES)
.label("Profile Names")
.description("A comma-separated list of profile names for which the feature should be active. A "
+ "profile can be negated by prefixing the name with the NOT operator (!).")
};
}
@Override
public String getTokenParameterName() {
return PARAM_PROFILES;
}
@Override
public TokenTransformer getTokenParameterTransformer() {
return new TokenTransformer() {
@Override
public String transform(String value) {
return value.toLowerCase();
}
};
}
}
| 1,281 |
601 | package com.java3y.austin.stream.utils;
import com.java3y.austin.stream.callback.RedisPipelineCallBack;
import com.java3y.austin.stream.constants.AustinFlinkConstant;
import io.lettuce.core.LettuceFutures;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.codec.ByteArrayCodec;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author 3y
* @date 2022/2/22
* 无Spring环境下使用Redis,基于Lettuce封装
*/
public class LettuceRedisUtils {
/**
* 初始化 redisClient
*/
private static RedisClient redisClient;
static {
RedisURI redisUri = RedisURI.Builder.redis(AustinFlinkConstant.REDIS_IP)
.withPort(Integer.valueOf(AustinFlinkConstant.REDIS_PORT))
.withPassword(<PASSWORD>linkConstant.REDIS_PASSWORD.toCharArray())
.build();
redisClient = RedisClient.create(redisUri);
}
/**
* 封装pipeline操作
*/
public static void pipeline(RedisPipelineCallBack pipelineCallBack) {
StatefulRedisConnection<byte[], byte[]> connect = redisClient.connect(new ByteArrayCodec());
RedisAsyncCommands<byte[], byte[]> commands = connect.async();
List<RedisFuture<?>> futures = pipelineCallBack.invoke(commands);
commands.flushCommands();
LettuceFutures.awaitAll(10, TimeUnit.SECONDS,
futures.toArray(new RedisFuture[futures.size()]));
connect.close();
}
}
| 696 |
446 | /* ========================================
* PurestAir - PurestAir.h
* Copyright (c) 2016 airwindows, All rights reserved
* ======================================== */
#ifndef __PurestAir_H
#include "PurestAir.h"
#endif
void PurestAir::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames)
{
float* in1 = inputs[0];
float* in2 = inputs[1];
float* out1 = outputs[0];
float* out2 = outputs[1];
double applyTarget = (A*2.0)-1.0;
double threshold = pow((1-fabs(applyTarget)),3);
if (applyTarget > 0) applyTarget *= 3;
double intensity = pow(B,2)*5.0;
double wet = C;
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-37) inputSampleL = fpd * 1.18e-37;
if (fabs(inputSampleR)<1.18e-37) inputSampleR = fpd * 1.18e-37;
long double drySampleL = inputSampleL;
long double drySampleR = inputSampleR;
halfDrySampleL = halfwaySampleL = (inputSampleL + last1SampleL) / 2.0;
last1SampleL = inputSampleL;
s3L = s2L;
s2L = s1L;
s1L = inputSampleL;
double m1 = (s1L-s2L)*((s1L-s2L)/1.3);
double m2 = (s2L-s3L)*((s1L-s2L)/1.3);
double sense = fabs((m1-m2)*((m1-m2)/1.3))*intensity;
//this will be 0 for smooth, high for SSS
applyL += applyTarget - sense;
applyL *= 0.5;
if (applyL < -1.0) applyL = -1.0;
double clamp = halfwaySampleL - halfDrySampleL;
if (clamp > threshold) halfwaySampleL = lastSampleL + threshold;
if (-clamp > threshold) halfwaySampleL = lastSampleL - threshold;
lastSampleL = halfwaySampleL;
clamp = inputSampleL - lastSampleL;
if (clamp > threshold) inputSampleL = lastSampleL + threshold;
if (-clamp > threshold) inputSampleL = lastSampleL - threshold;
lastSampleL = inputSampleL;
diffSampleL = *in1 - inputSampleL;
halfDiffSampleL = halfDrySampleL - halfwaySampleL;
inputSampleL = *in1 + ((diffSampleL + halfDiffSampleL)*applyL);
//done with left channel
halfDrySampleR = halfwaySampleR = (inputSampleR + last1SampleR) / 2.0;
last1SampleR = inputSampleR;
s3R = s2R;
s2R = s1R;
s1R = inputSampleR;
m1 = (s1R-s2R)*((s1R-s2R)/1.3);
m2 = (s2R-s3R)*((s1R-s2R)/1.3);
sense = fabs((m1-m2)*((m1-m2)/1.3))*intensity;
//this will be 0 for smooth, high for SSS
applyR += applyTarget - sense;
applyR *= 0.5;
if (applyR < -1.0) applyR = -1.0;
clamp = halfwaySampleR - halfDrySampleR;
if (clamp > threshold) halfwaySampleR = lastSampleR + threshold;
if (-clamp > threshold) halfwaySampleR = lastSampleR - threshold;
lastSampleR = halfwaySampleR;
clamp = inputSampleR - lastSampleR;
if (clamp > threshold) inputSampleR = lastSampleR + threshold;
if (-clamp > threshold) inputSampleR = lastSampleR - threshold;
lastSampleR = inputSampleR;
diffSampleR = *in2 - inputSampleR;
halfDiffSampleR = halfDrySampleR - halfwaySampleR;
inputSampleR = *in2 + ((diffSampleR + halfDiffSampleR)*applyR);
//done with right channel
if (wet !=1.0) {
inputSampleL = (inputSampleL * wet) + (drySampleL * (1.0-wet));
inputSampleR = (inputSampleR * wet) + (drySampleR * (1.0-wet));
}
//begin 32 bit stereo floating point dither
int expon; frexpf((float)inputSampleL, &expon);
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
inputSampleL += ((double(fpd)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62));
frexpf((float)inputSampleR, &expon);
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
inputSampleR += ((double(fpd)-uint32_t(0x7fffffff)) * 5.5e-36l * pow(2,expon+62));
//end 32 bit stereo floating point dither
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
void PurestAir::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames)
{
double* in1 = inputs[0];
double* in2 = inputs[1];
double* out1 = outputs[0];
double* out2 = outputs[1];
double applyTarget = (A*2.0)-1.0;
double threshold = pow((1-fabs(applyTarget)),3);
if (applyTarget > 0) applyTarget *= 3;
double intensity = pow(B,2)*5.0;
double wet = C;
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpd * 1.18e-43;
if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpd * 1.18e-43;
long double drySampleL = inputSampleL;
long double drySampleR = inputSampleR;
halfDrySampleL = halfwaySampleL = (inputSampleL + last1SampleL) / 2.0;
last1SampleL = inputSampleL;
s3L = s2L;
s2L = s1L;
s1L = inputSampleL;
double m1 = (s1L-s2L)*((s1L-s2L)/1.3);
double m2 = (s2L-s3L)*((s1L-s2L)/1.3);
double sense = fabs((m1-m2)*((m1-m2)/1.3))*intensity;
//this will be 0 for smooth, high for SSS
applyL += applyTarget - sense;
applyL *= 0.5;
if (applyL < -1.0) applyL = -1.0;
double clamp = halfwaySampleL - halfDrySampleL;
if (clamp > threshold) halfwaySampleL = lastSampleL + threshold;
if (-clamp > threshold) halfwaySampleL = lastSampleL - threshold;
lastSampleL = halfwaySampleL;
clamp = inputSampleL - lastSampleL;
if (clamp > threshold) inputSampleL = lastSampleL + threshold;
if (-clamp > threshold) inputSampleL = lastSampleL - threshold;
lastSampleL = inputSampleL;
diffSampleL = *in1 - inputSampleL;
halfDiffSampleL = halfDrySampleL - halfwaySampleL;
inputSampleL = *in1 + ((diffSampleL + halfDiffSampleL)*applyL);
//done with left channel
halfDrySampleR = halfwaySampleR = (inputSampleR + last1SampleR) / 2.0;
last1SampleR = inputSampleR;
s3R = s2R;
s2R = s1R;
s1R = inputSampleR;
m1 = (s1R-s2R)*((s1R-s2R)/1.3);
m2 = (s2R-s3R)*((s1R-s2R)/1.3);
sense = fabs((m1-m2)*((m1-m2)/1.3))*intensity;
//this will be 0 for smooth, high for SSS
applyR += applyTarget - sense;
applyR *= 0.5;
if (applyR < -1.0) applyR = -1.0;
clamp = halfwaySampleR - halfDrySampleR;
if (clamp > threshold) halfwaySampleR = lastSampleR + threshold;
if (-clamp > threshold) halfwaySampleR = lastSampleR - threshold;
lastSampleR = halfwaySampleR;
clamp = inputSampleR - lastSampleR;
if (clamp > threshold) inputSampleR = lastSampleR + threshold;
if (-clamp > threshold) inputSampleR = lastSampleR - threshold;
lastSampleR = inputSampleR;
diffSampleR = *in2 - inputSampleR;
halfDiffSampleR = halfDrySampleR - halfwaySampleR;
inputSampleR = *in2 + ((diffSampleR + halfDiffSampleR)*applyR);
//done with right channel
if (wet !=1.0) {
inputSampleL = (inputSampleL * wet) + (drySampleL * (1.0-wet));
inputSampleR = (inputSampleR * wet) + (drySampleR * (1.0-wet));
}
//begin 64 bit stereo floating point dither
int expon; frexp((double)inputSampleL, &expon);
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
inputSampleL += ((double(fpd)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62));
frexp((double)inputSampleR, &expon);
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
inputSampleR += ((double(fpd)-uint32_t(0x7fffffff)) * 1.1e-44l * pow(2,expon+62));
//end 64 bit stereo floating point dither
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
| 3,072 |
14,668 | // Copyright 2018 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 "device/bluetooth/bluetooth_pairing_winrt.h"
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "base/strings/string_piece.h"
#include "base/task/thread_pool.h"
#include "base/win/com_init_util.h"
#include "base/win/post_async_results.h"
#include "base/win/scoped_hstring.h"
#include "device/bluetooth/bluetooth_device_winrt.h"
#include "device/bluetooth/event_utils_winrt.h"
namespace device {
namespace {
using ABI::Windows::Devices::Enumeration::DevicePairingKinds;
using ABI::Windows::Devices::Enumeration::DevicePairingKinds_ConfirmOnly;
using ABI::Windows::Devices::Enumeration::DevicePairingKinds_ConfirmPinMatch;
using ABI::Windows::Devices::Enumeration::DevicePairingKinds_DisplayPin;
using ABI::Windows::Devices::Enumeration::DevicePairingKinds_ProvidePin;
using ABI::Windows::Devices::Enumeration::DevicePairingResult;
using ABI::Windows::Devices::Enumeration::DevicePairingResultStatus;
using ABI::Windows::Devices::Enumeration::
DevicePairingResultStatus_AlreadyPaired;
using ABI::Windows::Devices::Enumeration::
DevicePairingResultStatus_AuthenticationFailure;
using ABI::Windows::Devices::Enumeration::
DevicePairingResultStatus_AuthenticationTimeout;
using ABI::Windows::Devices::Enumeration::
DevicePairingResultStatus_ConnectionRejected;
using ABI::Windows::Devices::Enumeration::DevicePairingResultStatus_Failed;
using ABI::Windows::Devices::Enumeration::
DevicePairingResultStatus_OperationAlreadyInProgress;
using ABI::Windows::Devices::Enumeration::DevicePairingResultStatus_Paired;
using ABI::Windows::Devices::Enumeration::
DevicePairingResultStatus_PairingCanceled;
using ABI::Windows::Devices::Enumeration::
DevicePairingResultStatus_RejectedByHandler;
using CompletionCallback = base::OnceCallback<void(HRESULT hr)>;
using ConnectErrorCode = BluetoothDevice::ConnectErrorCode;
using ABI::Windows::Devices::Enumeration::IDeviceInformationCustomPairing;
using ABI::Windows::Devices::Enumeration::IDevicePairingRequestedEventArgs;
using ABI::Windows::Devices::Enumeration::IDevicePairingResult;
using ABI::Windows::Foundation::IAsyncOperation;
using Microsoft::WRL::ComPtr;
void PostTask(BluetoothPairingWinrt::ConnectCallback callback,
absl::optional<BluetoothDevice::ConnectErrorCode> error_code) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), error_code));
}
HRESULT CompleteDeferral(
Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IDeferral> deferral) {
// Apparently deferrals may be created (aka obtained) on the main thread
// initialized for STA, but must be completed on a thread with COM initialized
// for MTA. If the deferral is completed on the main thread then the
// Complete() call will succeed, i.e return S_OK, but the Windows Device
// Association Service will be hung and all Bluetooth association changes
// (system wide) will fail.
base::win::AssertComApartmentType(base::win::ComApartmentType::MTA);
return deferral->Complete();
}
} // namespace
BluetoothPairingWinrt::BluetoothPairingWinrt(
BluetoothDeviceWinrt* device,
BluetoothDevice::PairingDelegate* pairing_delegate,
ComPtr<IDeviceInformationCustomPairing> custom_pairing,
ConnectCallback callback)
: device_(device),
pairing_delegate_(pairing_delegate),
custom_pairing_(std::move(custom_pairing)),
callback_(std::move(callback)) {
DCHECK(device_);
DCHECK(pairing_delegate_);
DCHECK(custom_pairing_);
}
BluetoothPairingWinrt::~BluetoothPairingWinrt() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!pairing_requested_token_)
return;
HRESULT hr =
custom_pairing_->remove_PairingRequested(*pairing_requested_token_);
if (FAILED(hr)) {
DVLOG(2) << "Removing PairingRequested Handler failed: "
<< logging::SystemErrorCodeToString(hr);
}
}
void BluetoothPairingWinrt::StartPairing() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
pairing_requested_token_ = AddTypedEventHandler(
custom_pairing_.Get(),
&IDeviceInformationCustomPairing::add_PairingRequested,
base::BindRepeating(&BluetoothPairingWinrt::OnPairingRequested,
weak_ptr_factory_.GetWeakPtr()));
if (!pairing_requested_token_) {
PostTask(std::move(callback_),
BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
ComPtr<IAsyncOperation<DevicePairingResult*>> pair_op;
HRESULT hr = custom_pairing_->PairAsync(
DevicePairingKinds_ConfirmOnly | DevicePairingKinds_ProvidePin |
DevicePairingKinds_ConfirmPinMatch,
&pair_op);
if (FAILED(hr)) {
DVLOG(2) << "DeviceInformationCustomPairing::PairAsync() failed: "
<< logging::SystemErrorCodeToString(hr);
PostTask(std::move(callback_),
BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
hr = base::win::PostAsyncResults(
std::move(pair_op), base::BindOnce(&BluetoothPairingWinrt::OnPair,
weak_ptr_factory_.GetWeakPtr()));
if (FAILED(hr)) {
DVLOG(2) << "PostAsyncResults failed: "
<< logging::SystemErrorCodeToString(hr);
PostTask(std::move(callback_),
BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
}
bool BluetoothPairingWinrt::ExpectingPinCode() const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return expecting_pin_code_;
}
void BluetoothPairingWinrt::OnSetPinCodeDeferralCompletion(HRESULT hr) {
if (FAILED(hr)) {
DVLOG(2) << "Completing Deferred Pairing Request failed: "
<< logging::SystemErrorCodeToString(hr);
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
}
}
void BluetoothPairingWinrt::SetPinCode(base::StringPiece pin_code) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(2) << "BluetoothPairingWinrt::SetPinCode(" << pin_code << ")";
auto pin_hstring = base::win::ScopedHString::Create(pin_code);
DCHECK(expecting_pin_code_);
expecting_pin_code_ = false;
DCHECK(pairing_requested_);
HRESULT hr = pairing_requested_->AcceptWithPin(pin_hstring.get());
if (FAILED(hr)) {
DVLOG(2) << "Accepting Pairing Request With Pin failed: "
<< logging::SystemErrorCodeToString(hr);
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
DCHECK(pairing_deferral_);
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&CompleteDeferral, std::move(pairing_deferral_)),
base::BindOnce(&BluetoothPairingWinrt::OnSetPinCodeDeferralCompletion,
weak_ptr_factory_.GetWeakPtr()));
}
void BluetoothPairingWinrt::OnRejectPairing(HRESULT hr) {
if (FAILED(hr)) {
DVLOG(2) << "Completing Deferred Pairing Request failed: "
<< logging::SystemErrorCodeToString(hr);
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
std::move(callback_).Run(
BluetoothDevice::ConnectErrorCode::ERROR_AUTH_REJECTED);
}
void BluetoothPairingWinrt::RejectPairing() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(2) << "BluetoothPairingWinrt::RejectPairing()";
DCHECK(pairing_deferral_);
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&CompleteDeferral, std::move(pairing_deferral_)),
base::BindOnce(&BluetoothPairingWinrt::OnRejectPairing,
weak_ptr_factory_.GetWeakPtr()));
}
void BluetoothPairingWinrt::OnCancelPairing(HRESULT hr) {
// This method is normally never called. Usually when CancelPairing() is
// invoked the deferral is completed, which immediately calls OnPair(), which
// runs |callback_| and destroys this object before this method can be
// executed. However, if the deferral fails to complete, this will be run.
if (FAILED(hr)) {
DVLOG(2) << "Completing Deferred Pairing Request failed: "
<< logging::SystemErrorCodeToString(hr);
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
std::move(callback_).Run(
BluetoothDevice::ConnectErrorCode::ERROR_AUTH_CANCELED);
}
void BluetoothPairingWinrt::CancelPairing() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(2) << "BluetoothPairingWinrt::CancelPairing()";
DCHECK(pairing_deferral_);
// There is no way to explicitly cancel an in-progress pairing as
// DevicePairingRequestedEventArgs has no Cancel() method. Our approach is to
// complete the deferral, without accepting, which results in a
// RejectedByHandler result status. |was_cancelled_| is set so that OnPair(),
// which is called when the deferral is completed, will know that cancellation
// was the actual result.
was_cancelled_ = true;
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&CompleteDeferral, std::move(pairing_deferral_)),
base::BindOnce(&BluetoothPairingWinrt::OnCancelPairing,
weak_ptr_factory_.GetWeakPtr()));
}
void BluetoothPairingWinrt::OnPairingRequested(
IDeviceInformationCustomPairing* custom_pairing,
IDevicePairingRequestedEventArgs* pairing_requested) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(2) << "BluetoothPairingWinrt::OnPairingRequested()";
DevicePairingKinds pairing_kind;
HRESULT hr = pairing_requested->get_PairingKind(&pairing_kind);
if (FAILED(hr)) {
DVLOG(2) << "Getting Pairing Kind failed: "
<< logging::SystemErrorCodeToString(hr);
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
DVLOG(2) << "DevicePairingKind: " << static_cast<int>(pairing_kind);
if (pairing_kind != DevicePairingKinds_ProvidePin) {
DVLOG(2) << "Unexpected DevicePairingKind.";
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
hr = pairing_requested->GetDeferral(&pairing_deferral_);
if (FAILED(hr)) {
DVLOG(2) << "Getting Pairing Deferral failed: "
<< logging::SystemErrorCodeToString(hr);
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
pairing_requested_ = pairing_requested;
expecting_pin_code_ = true;
pairing_delegate_->RequestPinCode(device_);
}
void BluetoothPairingWinrt::OnPair(
ComPtr<IDevicePairingResult> pairing_result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DevicePairingResultStatus status;
HRESULT hr = pairing_result->get_Status(&status);
if (FAILED(hr)) {
DVLOG(2) << "Getting Pairing Result Status failed: "
<< logging::SystemErrorCodeToString(hr);
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
if (was_cancelled_ && status == DevicePairingResultStatus_RejectedByHandler) {
// See comment in CancelPairing() for explanation of why was_cancelled_
// is used.
status = DevicePairingResultStatus_PairingCanceled;
}
DVLOG(2) << "Pairing Result Status: " << static_cast<int>(status);
switch (status) {
case DevicePairingResultStatus_AlreadyPaired:
case DevicePairingResultStatus_Paired:
std::move(callback_).Run(/*error_code=*/absl::nullopt);
return;
case DevicePairingResultStatus_PairingCanceled:
std::move(callback_).Run(
BluetoothDevice::ConnectErrorCode::ERROR_AUTH_CANCELED);
return;
case DevicePairingResultStatus_AuthenticationFailure:
std::move(callback_).Run(
BluetoothDevice::ConnectErrorCode::ERROR_AUTH_FAILED);
return;
case DevicePairingResultStatus_ConnectionRejected:
case DevicePairingResultStatus_RejectedByHandler:
std::move(callback_).Run(
BluetoothDevice::ConnectErrorCode::ERROR_AUTH_REJECTED);
return;
case DevicePairingResultStatus_AuthenticationTimeout:
std::move(callback_).Run(
BluetoothDevice::ConnectErrorCode::ERROR_AUTH_TIMEOUT);
return;
case DevicePairingResultStatus_Failed:
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
case DevicePairingResultStatus_OperationAlreadyInProgress:
std::move(callback_).Run(
BluetoothDevice::ConnectErrorCode::ERROR_INPROGRESS);
return;
default:
std::move(callback_).Run(BluetoothDevice::ConnectErrorCode::ERROR_FAILED);
return;
}
}
} // namespace device
| 4,728 |
3,212 | <gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.snmp.helper;
import org.apache.nifi.snmp.configuration.V1TrapConfiguration;
import org.apache.nifi.snmp.configuration.V2TrapConfiguration;
import org.snmp4j.PDUv1;
public class TrapConfigurationFactory {
// v1 specific
private static final String ENTERPRISE_OID = "1.3.5.7.11";
private static final String AGENT_ADDRESS = "1.2.3.4";
private static final String GENERIC_TRAP_TYPE = String.valueOf(PDUv1.ENTERPRISE_SPECIFIC);
private static final String SPECIFIC_TRAP_TYPE = "2";
// v2c/v3 specific
private static final String TRAP_OID_VALUE = "testTrapOidValue";
public static V1TrapConfiguration getV1TrapConfiguration() {
return V1TrapConfiguration.builder()
.enterpriseOid(ENTERPRISE_OID)
.agentAddress(AGENT_ADDRESS)
.genericTrapType(GENERIC_TRAP_TYPE)
.specificTrapType(SPECIFIC_TRAP_TYPE)
.build();
}
public static V2TrapConfiguration getV2TrapConfiguration() {
return new V2TrapConfiguration(TRAP_OID_VALUE);
}
}
| 656 |
648 | <gh_stars>100-1000
{"resourceType":"SearchParameter","id":"Immunization-vaccine-code","url":"http://hl7.org/fhir/SearchParameter/Immunization-vaccine-code","name":"vaccine-code","publisher":"Health Level Seven International (Public Health and Emergency Response)","contact":[{"telecom":[{"system":"other","value":"http://hl7.org/fhir"}]},{"telecom":[{"system":"other","value":"http://www.hl7.org/Special/committees/pher/index.cfm"}]}],"date":"2015-10-24T07:41:03+11:00","code":"vaccine-code","base":"Immunization","type":"token","description":"Vaccine Product Administered","xpath":"f:Immunization/f:vaccineCode","xpathUsage":"normal"} | 195 |
8,772 | package org.apereo.cas.notifications.push;
import org.apereo.cas.authentication.principal.Principal;
import org.springframework.core.Ordered;
import java.util.Map;
/**
* This is {@link NotificationSender}.
*
* @author <NAME>
* @since 6.3.0
*/
@FunctionalInterface
public interface NotificationSender extends Ordered {
@Override
default int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
/**
* Whether it can send a notification.
*
* @return whether it can send an notification
*/
default boolean canSend() {
return true;
}
/**
* Notify.
*
* @param principal the principal
* @param messageData the message data
* @return true/false
*/
boolean notify(Principal principal, Map<String, String> messageData);
/**
* No op notification sender.
*
* @return the notification sender
*/
static NotificationSender noOp() {
return (principal, messageData) -> true;
}
}
| 380 |
629 | <gh_stars>100-1000
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <unordered_map>
#include "flags.h"
#include "module.h"
#include "state.h"
#include "unitsinfo.h"
#include "utils.h"
class RuleModule : public cherrypi::Module {
public:
long currentFrame_ = 0;
std::unordered_map<cherrypi::Unit*, cherrypi::Unit*> attacks_;
RuleModule() : Module() {
setName("Rule");
}
void step(cherrypi::State* state) override {
auto& allies = state->unitsInfo().myUnits();
auto& enemies = state->unitsInfo().enemyUnits();
if (currentFrame_ % 100 == 0) {
attacks_.clear();
}
if (currentFrame_ % FLAGS_frame_skip == 0) { // Frame skip
for (auto& ally : allies) {
cherrypi::Unit* target = nullptr;
if (FLAGS_opponent == "attack_move") {
// To make episodes end faster and so our models don't just learn to
// run, we attack move idle units towards our enemy
if (ally->idle() && enemies.size() > 0) {
auto upc = cherrypi::utils::makeSharpUPC(
ally,
cherrypi::Position{enemies[0]},
cherrypi::Command::Delete);
state->board()->postUPC(std::move(upc), cherrypi::kRootUpcId, this);
}
} else if (FLAGS_opponent == "closest") {
int x = ally->unit.x;
int y = ally->unit.y;
target = enemies[0];
float nearestDist = 1e9;
for (auto& enemy : enemies) {
int eX = enemy->unit.x;
int eY = enemy->unit.y;
float dist =
std::pow(float(x - eX), 2.) + std::pow(float(y - eY), 2.);
if (dist < nearestDist) {
nearestDist = dist;
target = enemy;
}
}
} else if (FLAGS_opponent == "weakest") {
int x = ally->unit.x;
int y = ally->unit.y;
target = enemies[0];
float weakest = 1e9;
for (auto& enemy : enemies) {
int eX = enemy->unit.x;
int eY = enemy->unit.y;
float dist =
std::pow(float(x - eX), 2.) + std::pow(float(y - eY), 2.);
float score = enemy->unit.health + enemy->unit.shield + dist / 1024;
if (score < weakest) {
weakest = score;
target = enemy;
}
}
} else {
throw std::runtime_error("No such opponent: " + FLAGS_opponent);
}
// Sending same attack command can "cancel" attacks, so check first
if (target && attacks_[ally] != target) {
attacks_[ally] = target;
auto upc = cherrypi::utils::makeSharpUPC(
ally, target, cherrypi::Command::Delete);
state->board()->postUPC(std::move(upc), cherrypi::kRootUpcId, this);
}
}
}
currentFrame_++;
}
};
| 1,420 |
471 | package org.plantuml.idea.grammar;
import com.intellij.lang.refactoring.NamesValidator;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import static org.apache.commons.lang.StringUtils.containsNone;
public class PumlNamesValidator implements NamesValidator {
@Override
public boolean isKeyword(@NotNull String name, Project project) {
return false;
}
@Override
public boolean isIdentifier(@NotNull String name, Project project) {
return (!name.isEmpty() && containsNone(name, new char[]{' ', '\t'}))
|| (name.startsWith("[") && name.endsWith("]"))
|| (name.startsWith("\"") && name.endsWith("\""))
|| (name.startsWith("(") && name.endsWith(")"));
}
} | 308 |
568 | package com.novoda.simonsaysandroidthings;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.things.pio.PeripheralManagerService;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.novoda.simonsaysandroidthings.game.Score;
import com.novoda.simonsaysandroidthings.game.SimonSays;
import com.novoda.simonsaysandroidthings.hw.board.BoardFactory;
import com.novoda.simonsaysandroidthings.hw.io.Button;
import com.novoda.simonsaysandroidthings.hw.io.Buzzer;
import com.novoda.simonsaysandroidthings.hw.io.GpioButton;
import com.novoda.simonsaysandroidthings.hw.io.GpioLed;
import com.novoda.simonsaysandroidthings.hw.io.Group;
import com.novoda.simonsaysandroidthings.hw.io.Led;
import com.novoda.simonsaysandroidthings.hw.io.PwmBuzzer;
import java.util.Arrays;
public class HomeActivity extends Activity {
private SimonSays game;
private Button toggleButton;
private ValueEventListener valueEventListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BoardFactory boardFactory = BoardFactory.getBoardFactory();
PeripheralManagerService service = new PeripheralManagerService();
Buzzer buzzer = PwmBuzzer.create(boardFactory.getBuzzerPwm(), service);
Group green = createGroup(service, boardFactory.getGreenButtonGpio(), boardFactory.getGreenLedGpio(), buzzer, 500);
Group red = createGroup(service, boardFactory.getRedButtonGpio(), boardFactory.getRedLedGpio(), buzzer, 1000);
Group blue = createGroup(service, boardFactory.getBlueButtonGpio(), boardFactory.getBlueLedGpio(), buzzer, 1500);
Group yellow = createGroup(service, boardFactory.getYellowButtonGpio(), boardFactory.getYellowLedGpio(), buzzer, 2000);
// Highscore highscore = new SharedPrefsHighscore(this);
Score score = new FirebaseScore(FirebaseDatabase.getInstance().getReference());
game = new SimonSays(Arrays.asList(green, red, blue, yellow), score, buzzer);
game.start();
toggleButton = GpioButton.create(boardFactory.getToggleGpio(), service);
toggleButton.setListener(new Button.Listener() {
@Override
public void onButtonPressed(Button button) {
// not used
}
@Override
public void onButtonReleased(Button button) {
game.toggle();
}
});
final TextView hishcore = (TextView) findViewById(R.id.highscore);
final TextView currentRound = (TextView) findViewById(R.id.current_round);
valueEventListener = FirebaseDatabase.getInstance().getReference().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
hishcore.setText(dataSnapshot.child("highscore").getValue(Long.class).toString());
currentRound.setText(dataSnapshot.child("current_score").getValue(Long.class).toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
// nothing to do
}
});
}
private Group createGroup(PeripheralManagerService service, String buttonPinName, String ledPinName, Buzzer buzzer, int frequency) {
Button button = GpioButton.create(buttonPinName, service);
Led led = GpioLed.create(ledPinName, service);
return new Group(led, button, buzzer, frequency);
}
@Override
protected void onDestroy() {
super.onDestroy();
FirebaseDatabase.getInstance().getReference().removeEventListener(valueEventListener);
try {
game.close();
toggleButton.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 1,534 |
566 | <filename>args4j/test/org/kohsuke/args4j/ExplicitBooleanOptionTest.java
package org.kohsuke.args4j;
import org.kohsuke.args4j.ExplicitBooleanOptionTest.BooleanOptionHolder;
import org.kohsuke.args4j.spi.ExplicitBooleanOptionHandler;
public class ExplicitBooleanOptionTest extends Args4JTestBase<BooleanOptionHolder> {
public static class BooleanOptionHolder {
@Option(name = "-booleanOpt", handler = ExplicitBooleanOptionHandler.class, usage = "Set a boolean value")
boolean booleanOpt;
@Option(name = "-nextArg")
boolean nextArg;
}
@Override
public BooleanOptionHolder getTestObject() {
return new BooleanOptionHolder();
}
public void testSetBooleanTrue() throws CmdLineException {
args = new String[] { "-booleanOpt", "true" };
parser.parseArgument(args);
assertTrue(testObject.booleanOpt);
}
public void testSetBooleanOn() throws CmdLineException {
args = new String[] { "-booleanOpt", "on" };
parser.parseArgument(args);
assertTrue(testObject.booleanOpt);
}
public void testSetBooleanYes() throws CmdLineException {
args = new String[] { "-booleanOpt", "yes" };
parser.parseArgument(args);
assertTrue(testObject.booleanOpt);
}
public void testSetBooleanTrueCaseInsensitive() throws CmdLineException {
args = new String[] { "-booleanOpt", "tRuE" };
parser.parseArgument(args);
assertTrue(testObject.booleanOpt);
}
public void testSetBoolean1() throws CmdLineException {
args = new String[] { "-booleanOpt", "1" };
parser.parseArgument(args);
assertTrue(testObject.booleanOpt);
}
public void testSetBooleanFalse() throws CmdLineException {
args = new String[] { "-booleanOpt", "false" };
parser.parseArgument(args);
assertFalse(testObject.booleanOpt);
}
public void testSetBooleanOff() throws CmdLineException {
args = new String[] { "-booleanOpt", "off" };
parser.parseArgument(args);
assertFalse(testObject.booleanOpt);
}
public void testSetBooleanNo() throws CmdLineException {
args = new String[] { "-booleanOpt", "no" };
parser.parseArgument(args);
assertFalse(testObject.booleanOpt);
}
public void testSetBoolean0() throws CmdLineException {
args = new String[] { "-booleanOpt", "0" };
parser.parseArgument(args);
assertFalse(testObject.booleanOpt);
}
public void testSetBooleanFalseCaseInsensitive() throws CmdLineException {
args = new String[] { "-booleanOpt", "FaLsE" };
parser.parseArgument(args);
assertFalse(testObject.booleanOpt);
}
public void testSetBooleanLastArgIsTrue() throws CmdLineException {
args = new String[] { "-booleanOpt" };
parser.parseArgument(args);
assertTrue(testObject.booleanOpt);
}
public void testSetBooleanWithoutParamIsTrue() throws CmdLineException {
args = new String[] { "-booleanOpt", "-nextArg" };
parser.parseArgument(args);
assertTrue(testObject.booleanOpt);
}
public void testIllegalBoolean() {
args = new String[] { "-booleanOpt", "ILLEGAL_BOOLEAN" };
try {
parser.parseArgument(args);
fail("Can't set ILLEGAL_BOOLEAN as value.");
} catch (CmdLineException expected) {}
}
public void testUsage() {
args = new String[] { "-wrong" };
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
assertUsageContains("Usage message should contain 'VAL'", "VAL");
}
}
}
| 1,504 |
703 | #include <GameEngine/GameEnginePCH.h>
#include <GameEngine/VisualScript/VisualScriptInstance.h>
#include <GameEngine/VisualScript/VisualScriptNode.h>
// clang-format off
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezVisualScriptNode, 1, ezRTTINoAllocator)
EZ_END_DYNAMIC_REFLECTED_TYPE;
// clang-format on
ezVisualScriptNode::ezVisualScriptNode() {}
ezVisualScriptNode::~ezVisualScriptNode() {}
ezInt32 ezVisualScriptNode::HandlesMessagesWithID() const
{
return -1;
}
void ezVisualScriptNode::HandleMessage(ezMessage* pMsg) {}
bool ezVisualScriptNode::IsManuallyStepped() const
{
ezHybridArray<ezAbstractProperty*, 32> properties;
GetDynamicRTTI()->GetAllProperties(properties);
for (auto prop : properties)
{
if (prop->GetAttributeByType<ezVisScriptExecPinOutAttribute>() != nullptr)
return true;
if (prop->GetAttributeByType<ezVisScriptExecPinInAttribute>() != nullptr)
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
// clang-format off
EZ_BEGIN_STATIC_REFLECTED_ENUM(ezVisualScriptDataPinType, 1)
EZ_ENUM_CONSTANTS(ezVisualScriptDataPinType::None, ezVisualScriptDataPinType::Number, ezVisualScriptDataPinType::Boolean, ezVisualScriptDataPinType::Vec3, ezVisualScriptDataPinType::String)
EZ_ENUM_CONSTANTS(ezVisualScriptDataPinType::GameObjectHandle, ezVisualScriptDataPinType::ComponentHandle, ezVisualScriptDataPinType::Variant)
EZ_END_STATIC_REFLECTED_ENUM;
// clang-format on
// static
ezVisualScriptDataPinType::Enum ezVisualScriptDataPinType::GetDataPinTypeForType(const ezRTTI* pType)
{
auto varType = pType->GetVariantType();
if (varType >= ezVariant::Type::Int8 && varType <= ezVariant::Type::Double)
{
return ezVisualScriptDataPinType::Number;
}
switch (varType)
{
case ezVariantType::Bool:
return ezVisualScriptDataPinType::Boolean;
case ezVariantType::Vector3:
return ezVisualScriptDataPinType::Vec3;
case ezVariantType::String:
return ezVisualScriptDataPinType::String;
default:
return pType == ezGetStaticRTTI<ezVariant>() ? ezVisualScriptDataPinType::Variant : ezVisualScriptDataPinType::None;
}
}
// static
void ezVisualScriptDataPinType::EnforceSupportedType(ezVariant& var)
{
switch (var.GetType())
{
case ezVariantType::Int8:
case ezVariantType::UInt8:
case ezVariantType::Int16:
case ezVariantType::UInt16:
case ezVariantType::Int32:
case ezVariantType::UInt32:
case ezVariantType::Int64:
case ezVariantType::UInt64:
case ezVariantType::Float:
{
const double value = var.ConvertTo<double>();
var = value;
return;
}
default:
return;
}
}
static ezUInt32 s_StorageSizes[] = {
ezInvalidIndex, // None
sizeof(double), // Number
sizeof(bool), // Boolean
sizeof(ezVec3), // Vec3
sizeof(ezString), // String
sizeof(ezGameObjectHandle), // GameObjectHandle
sizeof(ezComponentHandle), // ComponentHandle
sizeof(ezVariant), // Variant
};
// static
ezUInt32 ezVisualScriptDataPinType::GetStorageByteSize(Enum dataPinType)
{
if (dataPinType >= Number && dataPinType <= Variant)
{
EZ_CHECK_AT_COMPILETIME(EZ_ARRAY_SIZE(s_StorageSizes) == Variant + 1);
return s_StorageSizes[dataPinType];
}
EZ_ASSERT_NOT_IMPLEMENTED;
return ezInvalidIndex;
}
//////////////////////////////////////////////////////////////////////////
// clang-format off
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezVisScriptExecPinOutAttribute, 1, ezRTTIDefaultAllocator<ezVisScriptExecPinOutAttribute>)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("Slot", m_uiPinSlot)
}
EZ_END_PROPERTIES;
}
EZ_END_DYNAMIC_REFLECTED_TYPE;
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezVisScriptExecPinInAttribute, 1, ezRTTIDefaultAllocator<ezVisScriptExecPinInAttribute>)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("Slot", m_uiPinSlot)
}
EZ_END_PROPERTIES;
}
EZ_END_DYNAMIC_REFLECTED_TYPE;
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezVisScriptDataPinInAttribute, 1, ezRTTIDefaultAllocator<ezVisScriptDataPinInAttribute>)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("Slot", m_uiPinSlot),
EZ_ENUM_MEMBER_PROPERTY("Type", ezVisualScriptDataPinType, m_DataType)
}
EZ_END_PROPERTIES;
}
EZ_END_DYNAMIC_REFLECTED_TYPE;
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezVisScriptDataPinOutAttribute, 1, ezRTTIDefaultAllocator<ezVisScriptDataPinOutAttribute>)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("Slot", m_uiPinSlot),
EZ_ENUM_MEMBER_PROPERTY("Type", ezVisualScriptDataPinType, m_DataType)
}
EZ_END_PROPERTIES;
}
EZ_END_DYNAMIC_REFLECTED_TYPE;
// clang-format on
//////////////////////////////////////////////////////////////////////////
EZ_STATICLINK_FILE(GameEngine, GameEngine_VisualScript_Implementation_VisualScriptNode);
| 1,896 |
518 | {
"name": "<NAME>",
"category": "Task & Project Management",
"start_url": "https://www.pivotaltracker.com/signin",
"icons": [
{
"src": "https://cdn.filestackcontent.com/BNGXjp8iQjGjJu7vvUJm",
"platform": "browserx"
}
],
"theme_color": "#ED7D1A",
"scope": "https://www.pivotaltracker.com",
"bx_legacy_service_id": "pivotal-tracker"
}
| 170 |
11,094 | <gh_stars>1000+
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
import math
from torch.utils.data import TensorDataset, DataLoader
from HelperClass.NeuralNet_1_2 import *
from HelperClass.Visualizer_1_0 import *
from Level2_ShowMultipleResult import ShowData
import torch.nn as nn
import torch.nn.functional as F
import torch
from torch.optim import Adam
import warnings
warnings.filterwarnings('ignore')
file_name = "../../data/ch07.npz"
def ShowResult(W, B, X, Y, xt, yt):
fig = plt.figure(figsize=(6,6))
DrawThreeCategoryPoints(X[:,0], X[:,1], Y[:], xlabel="x1", ylabel="x2", show=False)
b13 = (B[0,0] - B[0,2])/(W[1,2] - W[1,0])
w13 = (W[0,0] - W[0,2])/(W[1,2] - W[1,0])
b23 = (B[0,2] - B[0,1])/(W[1,1] - W[1,2])
w23 = (W[0,2] - W[0,1])/(W[1,1] - W[1,2])
b12 = (B[0,1] - B[0,0])/(W[1,0] - W[1,1])
w12 = (W[0,1] - W[0,0])/(W[1,0] - W[1,1])
x = np.linspace(0,1,2)
y = w13 * x + b13
p13, = plt.plot(x,y,c='r')
x = np.linspace(0,1,2)
y = w23 * x + b23
p23, = plt.plot(x,y,c='b')
x = np.linspace(0,1,2)
y = w12 * x + b12
p12, = plt.plot(x,y,c='g')
plt.legend([p13,p23,p12], ["13","23","12"])
plt.axis([-0.1,1.1,-0.1,1.1])
DrawThreeCategoryPoints(xt[:,0], xt[:,1], yt[:], xlabel="x1", ylabel="x2", show=True, isPredicate=True)
class Model(nn.Module):
def __init__(self, input_size, class_num):
super(Model, self).__init__()
self.fc = nn.Linear(input_size, class_num)
def forward(self, x):
x = self.fc(x)
x = F.softmax(x)
return x
if __name__ == '__main__':
max_epoch = 500
num_category = 3
reader = DataReader_1_3(file_name)
reader.ReadData()
# show raw data before normalization
reader.NormalizeX()
num_input = 2 # input size
# get numpy form data
XTrain, YTrain = reader.XTrain, reader.YTrain - 1
torch_dataset = TensorDataset(torch.FloatTensor(XTrain), torch.LongTensor(YTrain.reshape(-1,)))
reader.ToOneHot(num_category, base=1) # transform to one-hot
ShowData(reader.XRaw, reader.YTrain)
train_loader = DataLoader( # data loader class
dataset=torch_dataset,
batch_size=32,
shuffle=False,
)
loss_func = nn.CrossEntropyLoss()
model = Model(num_input,num_category)
optimizer = Adam(model.parameters(), lr=1e-2)
e_loss = [] # mean loss at every epoch
for epoch in range(max_epoch):
b_loss = [] # mean loss at every batch
for step, (batch_x, batch_y) in enumerate(train_loader):
optimizer.zero_grad()
pred = model(batch_x)
loss = loss_func(pred,batch_y)
loss.backward()
optimizer.step()
b_loss.append(loss.cpu().data.numpy())
print("Epoch: %d, Loss: %.5f" % (epoch, np.mean(b_loss)))
xt_raw = np.array([5, 1, 7, 6, 5, 6, 2, 7]).reshape(4, 2)
xt = reader.NormalizePredicateData(xt_raw)
xt = torch.FloatTensor(xt)
output = model(xt).cpu().data.numpy()
ShowResult(model.fc.weight.data.numpy().transpose(), model.fc.bias.data.numpy().reshape(1, 3),
reader.XTrain, reader.YTrain, xt, output)
| 1,557 |
578 | <reponame>GerHobbelt/CacheLib
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#include <memory>
#include <string>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#include <folly/Format.h>
#pragma GCC diagnostic pop
#include "cachelib/allocator/CacheDetails.h"
#include "cachelib/shm/ShmManager.h"
namespace facebook {
namespace cachelib {
// used as a read only into a shared cache. The cache is owned by another
// process and we peek into the items in the cache based on their offsets.
class ReadOnlySharedCacheView {
public:
// tries to attach to an existing cache with the cacheDir if present under
// the correct shm mode.
//
// @param cacheDir the directory that identifies the cache
// @param usePosix the posix compatbility status of original cache. This
// would be part of the config that was used to
// initialize the cache
// @param addr starting address that this segment should be mapped to
// (exception will be thrown if it is not mounted to the
// given address)
// if nullptr, the segment will be mapped to a random
// address chosen by the kernel
explicit ReadOnlySharedCacheView(const std::string& cacheDir,
bool usePosixShm,
void* addr = nullptr)
: shm_(ShmManager::attachShmReadOnly(
cacheDir, detail::kShmCacheName, usePosixShm, addr)) {}
// returns the absolute address at which the shared memory mapping is mounted.
// The caller can add a relative offset obtained from
// CacheAllocator::getItemPtrAsOffset to this address in order to compute the
// address at which that item is stored (within the process which manages this
// ReadOnlySharedCacheView).
uintptr_t getShmMappingAddress() const noexcept {
auto mapping = shm_->getCurrentMapping();
return reinterpret_cast<uintptr_t>(mapping.addr);
}
// computes an aboslute address in the cache, given a relative offset that
// was obtained from CacheAllocator::getItemPtrAsOffset. It is the caller's
// responsibility to ensure the memory backing the offset corresponds to an
// active ItemHandle in the system.
//
// Returns a valid pointer if the offset is valid. Returns nullptr if no
// shared memory mapping is mounted. Throws if the given offset is invalid.
const void* getItemPtrFromOffset(uintptr_t offset) {
auto mapping = shm_->getCurrentMapping();
if (mapping.addr == nullptr) {
return nullptr;
}
if (offset >= mapping.size) {
throw std::invalid_argument(folly::sformat(
"Invalid offset {} with mapping of size {}", offset, mapping.size));
}
return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(mapping.addr) +
offset);
}
private:
// the segment backing the cache
std::unique_ptr<ShmSegment> shm_;
};
} // namespace cachelib
} // namespace facebook
| 1,229 |
771 | <reponame>noitcudni/tiny-helpers<filename>helpers/regular-expresssions-101.json
{
"name": "regular expresssions 101",
"url": "https://regex101.com/",
"desc": "Learn, build, & test Regular Expressions",
"tags": [
"Regular Expressions"
],
"maintainers": [
"firasdib"
],
"addedAt": "2019-12-29"
}
| 131 |
356 | <reponame>hardeepnagi/java-util
package com.cedarsoftware.util;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
/**
* useful InetAddress Utilities
*
* @author <NAME>
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* 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
* <br><br>
* http://www.apache.org/licenses/LICENSE-2.0
* <br><br>
* 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.
*/
public class TestInetAddressUtilities
{
@Test
public void testMapUtilitiesConstructor() throws Exception
{
Constructor<InetAddressUtilities> con = InetAddressUtilities.class.getDeclaredConstructor();
Assert.assertEquals(Modifier.PRIVATE, con.getModifiers() & Modifier.PRIVATE);
con.setAccessible(true);
Assert.assertNotNull(con.newInstance());
}
@Test
public void testGetIpAddress() throws Exception {
byte[] bytes = InetAddress.getLocalHost().getAddress();
Assert.assertArrayEquals(bytes, InetAddressUtilities.getIpAddress());
}
@Test
public void testGetLocalHost() throws Exception {
String name = InetAddress.getLocalHost().getHostName();
Assert.assertEquals(name, InetAddressUtilities.getHostName());
}
}
| 681 |
5,169 | {
"name": "CategorySpecDemo",
"version": "0.0.1",
"summary": "A short description of CategorySpecDemo.",
"description": "这是一个分类的podspec的demo测试",
"homepage": "https://github.com/MrLuanJX/CategoryDemo",
"authors": {
"luanjinxin": "<EMAIL>"
},
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/MrLuanJX/CategoryDemo.git",
"tag": "0.0.1"
},
"source_files": [
"CategoryFile",
"CategoryFile/**/*.{h,m}"
],
"frameworks": [
"Foundation",
"UIKit"
]
}
| 248 |
1,844 | /*
* Copyright 2010-2013 Ning, Inc.
* Copyright 2014-2018 Groupon, Inc
* Copyright 2014-2018 The Billing Project, LLC
*
* The Billing Project 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.killbill.billing.jaxrs.resources;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.killbill.billing.ObjectType;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.account.api.AccountApiException;
import org.killbill.billing.account.api.AccountUserApi;
import org.killbill.billing.catalog.api.Currency;
import org.killbill.billing.invoice.api.InvoicePayment;
import org.killbill.billing.invoice.api.InvoicePaymentType;
import org.killbill.billing.invoice.api.InvoiceUserApi;
import org.killbill.billing.jaxrs.json.AuditLogJson;
import org.killbill.billing.jaxrs.json.CustomFieldJson;
import org.killbill.billing.jaxrs.json.InvoiceItemJson;
import org.killbill.billing.jaxrs.json.InvoicePaymentJson;
import org.killbill.billing.jaxrs.json.InvoicePaymentTransactionJson;
import org.killbill.billing.jaxrs.json.PaymentTransactionJson;
import org.killbill.billing.jaxrs.json.TagJson;
import org.killbill.billing.jaxrs.util.Context;
import org.killbill.billing.jaxrs.util.JaxrsUriBuilder;
import org.killbill.billing.payment.api.InvoicePaymentApi;
import org.killbill.billing.payment.api.Payment;
import org.killbill.billing.payment.api.PaymentApi;
import org.killbill.billing.payment.api.PaymentApiException;
import org.killbill.billing.payment.api.PaymentOptions;
import org.killbill.billing.payment.api.PaymentTransaction;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.payment.api.TransactionStatus;
import org.killbill.billing.util.UUIDs;
import org.killbill.billing.util.api.AuditLevel;
import org.killbill.billing.util.api.AuditUserApi;
import org.killbill.billing.util.api.CustomFieldApiException;
import org.killbill.billing.util.api.CustomFieldUserApi;
import org.killbill.billing.util.api.TagApiException;
import org.killbill.billing.util.api.TagDefinitionApiException;
import org.killbill.billing.util.api.TagUserApi;
import org.killbill.billing.util.audit.AccountAuditLogs;
import org.killbill.billing.util.audit.AuditLogWithHistory;
import org.killbill.billing.util.callcontext.CallContext;
import org.killbill.billing.util.callcontext.TenantContext;
import org.killbill.billing.util.customfield.CustomField;
import org.killbill.clock.Clock;
import org.killbill.commons.metrics.TimedResource;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@Singleton
@Path(JaxrsResource.INVOICE_PAYMENTS_PATH)
@Api(value = JaxrsResource.INVOICE_PAYMENTS_PATH, description = "Operations on invoice payments", tags = "InvoicePayment")
public class InvoicePaymentResource extends JaxRsResourceBase {
private static final String ID_PARAM_NAME = "paymentId";
private final InvoicePaymentApi invoicePaymentApi;
private final InvoiceUserApi invoiceApi;
@Inject
public InvoicePaymentResource(final AccountUserApi accountUserApi,
final PaymentApi paymentApi,
final JaxrsUriBuilder uriBuilder,
final TagUserApi tagUserApi,
final CustomFieldUserApi customFieldUserApi,
final AuditUserApi auditUserApi,
final InvoicePaymentApi invoicePaymentApi,
final InvoiceUserApi invoiceApi,
final Clock clock,
final Context context) {
super(uriBuilder, tagUserApi, customFieldUserApi, auditUserApi, accountUserApi, paymentApi, invoicePaymentApi, null, clock, context);
this.invoicePaymentApi = invoicePaymentApi;
this.invoiceApi = invoiceApi;
}
@TimedResource
@GET
@Path("/{paymentId:" + UUID_PATTERN + "}/")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Retrieve a payment by id", response = InvoicePaymentJson.class)
@ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid payment id supplied"),
@ApiResponse(code = 404, message = "Payment not found")})
public Response getInvoicePayment(@PathParam("paymentId") final UUID paymentId,
@QueryParam(QUERY_WITH_PLUGIN_INFO) @DefaultValue("false") final Boolean withPluginInfo,
@QueryParam(QUERY_WITH_ATTEMPTS) @DefaultValue("false") final Boolean withAttempts,
@QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
@QueryParam(QUERY_AUDIT) @DefaultValue("NONE") final AuditMode auditMode,
@javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException {
final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Payment payment = paymentApi.getPayment(paymentId, withPluginInfo, withAttempts, pluginProperties, tenantContext);
final AccountAuditLogs accountAuditLogs = auditUserApi.getAccountAuditLogs(payment.getAccountId(), auditMode.getLevel(), tenantContext);
final List<InvoicePayment> invoicePayments = invoicePaymentApi.getInvoicePayments(paymentId, tenantContext);
final InvoicePayment invoicePayment = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {
@Override
public boolean apply(final InvoicePayment input) {
return input.getType() == InvoicePaymentType.ATTEMPT;
}
}).orNull();
final UUID invoiceId = invoicePayment != null ? invoicePayment.getInvoiceId() : null;
final InvoicePaymentJson result = new InvoicePaymentJson(payment, invoiceId, accountAuditLogs);
return Response.status(Response.Status.OK).entity(result).build();
}
@TimedResource
@GET
@Path("/{invoicePaymentId:" + UUID_PATTERN + "}/" + AUDIT_LOG_WITH_HISTORY)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Retrieve invoice payment audit logs with history by id", response = AuditLogJson.class, responseContainer = "List")
@ApiResponses(value = {@ApiResponse(code = 404, message = "Invoice payment not found")})
public Response getInvoicePaymentAuditLogsWithHistory(@PathParam("invoicePaymentId") final UUID invoicePaymentId,
@javax.ws.rs.core.Context final HttpServletRequest request) {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final List<AuditLogWithHistory> auditLogWithHistory = invoiceApi.getInvoicePaymentAuditLogsWithHistoryForId(invoicePaymentId, AuditLevel.FULL, tenantContext);
return Response.status(Status.OK).entity(getAuditLogsWithHistory(auditLogWithHistory)).build();
}
@TimedResource
@POST
@Path("/{paymentId:" + UUID_PATTERN + "}/" + REFUNDS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Refund a payment, and adjust the invoice if needed", response = InvoicePaymentJson.class)
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created refund successfully"),
@ApiResponse(code = 400, message = "Invalid payment id supplied"),
@ApiResponse(code = 404, message = "Account or payment not found")})
public Response createRefundWithAdjustments(@PathParam("paymentId") final UUID paymentId,
final InvoicePaymentTransactionJson json,
@QueryParam(QUERY_PAYMENT_EXTERNAL) @DefaultValue("false") final Boolean externalPayment,
@QueryParam(QUERY_PAYMENT_METHOD_ID) final UUID paymentMethodId,
@QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final UriInfo uriInfo,
@javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException, AccountApiException {
verifyNonNullOrEmpty(json, "InvoicePaymentTransactionJson body should be specified");
final CallContext callContextNoAccountId = context.createCallContextNoAccountId(createdBy, reason, comment, request);
final Payment payment = paymentApi.getPayment(paymentId, false, false, ImmutableList.<PluginProperty>of(), callContextNoAccountId);
final Account account = accountUserApi.getAccountById(payment.getAccountId(), callContextNoAccountId);
final CallContext callContext = context.createCallContextWithAccountId(account.getId(), createdBy, reason, comment, request);
final Iterable<PluginProperty> pluginProperties;
final String transactionExternalKey = json.getTransactionExternalKey() != null ? json.getTransactionExternalKey() : UUIDs.randomUUID().toString();
final String paymentExternalKey = json.getPaymentExternalKey() != null ? json.getPaymentExternalKey() : UUIDs.randomUUID().toString();
final boolean isAdjusted = json.isAdjusted() != null && json.isAdjusted();
final Map<UUID, BigDecimal> adjustments = new HashMap<UUID, BigDecimal>();
if (isAdjusted) {
if (json.getAdjustments() != null && !json.getAdjustments().isEmpty()) {
for (final InvoiceItemJson item : json.getAdjustments()) {
adjustments.put(item.getInvoiceItemId(), item.getAmount());
}
pluginProperties = extractPluginProperties(pluginPropertiesString);
} else {
pluginProperties = extractPluginProperties(pluginPropertiesString);
}
} else {
pluginProperties = extractPluginProperties(pluginPropertiesString);
}
final UUID paymentIdToRedirectTo;
if (externalPayment) {
invoicePaymentApi.createCreditForInvoicePayment(isAdjusted,
adjustments,
account,
paymentId,
paymentMethodId,
null,
json.getAmount(),
account.getCurrency(),
json.getEffectiveDate(),
paymentExternalKey,
transactionExternalKey,
pluginProperties,
createInvoicePaymentControlPluginApiPaymentOptions(true),
callContext);
// /!\ Note! The invoicePayment#paymentId points to the original payment (PURCHASE) here, NOT the new one (CREDIT)
paymentIdToRedirectTo = paymentApi.getPaymentByTransactionExternalKey(transactionExternalKey, false, false, ImmutableList.<PluginProperty>of(), callContext).getId();
} else {
invoicePaymentApi.createRefundForInvoicePayment(isAdjusted,
adjustments,
account,
payment.getId(),
json.getAmount(),
account.getCurrency(),
json.getEffectiveDate(),
transactionExternalKey,
pluginProperties,
createInvoicePaymentControlPluginApiPaymentOptions(false),
callContext);
// Note that the InvoicePayment may not be created (i.e. return null), even though the refund went through (wrong item adjustments for instance)
paymentIdToRedirectTo = payment.getId();
}
return uriBuilder.buildResponse(uriInfo, InvoicePaymentResource.class, "getInvoicePayment", paymentIdToRedirectTo, request);
}
@TimedResource
@POST
@Path("/{paymentId:" + UUID_PATTERN + "}/" + CHARGEBACKS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Record a chargeback", response = InvoicePaymentJson.class)
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created chargeback successfully"),
@ApiResponse(code = 400, message = "Invalid payment id supplied"),
@ApiResponse(code = 404, message = "Account or payment not found")})
public Response createChargeback(@PathParam("paymentId") final UUID paymentId,
final InvoicePaymentTransactionJson json,
@QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final UriInfo uriInfo,
@javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException, AccountApiException {
verifyNonNullOrEmpty(json, "InvoicePaymentTransactionJson body should be specified");
verifyNonNullOrEmpty(json.getAmount(), "InvoicePaymentTransactionJson amount needs to be set");
final CallContext callContextNoAccountId = context.createCallContextNoAccountId(createdBy, reason, comment, request);
final Payment payment = paymentApi.getPayment(paymentId, false, false, ImmutableList.<PluginProperty>of(), callContextNoAccountId);
final Account account = accountUserApi.getAccountById(payment.getAccountId(), callContextNoAccountId);
final CallContext callContext = context.createCallContextWithAccountId(account.getId(), createdBy, reason, comment, request);
final String transactionExternalKey = json.getTransactionExternalKey() != null ? json.getTransactionExternalKey() : UUIDs.randomUUID().toString();
invoicePaymentApi.createChargebackForInvoicePayment(account,
payment.getId(),
json.getAmount(),
account.getCurrency(),
json.getEffectiveDate(),
transactionExternalKey,
extractPluginProperties(pluginPropertiesString),
createInvoicePaymentControlPluginApiPaymentOptions(false),
callContext);
return uriBuilder.buildResponse(uriInfo, InvoicePaymentResource.class, "getInvoicePayment", payment.getId(), request);
}
@TimedResource
@POST
@Path("/{paymentId:" + UUID_PATTERN + "}/" + CHARGEBACK_REVERSALS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Record a chargebackReversal", response = InvoicePaymentJson.class)
@ApiResponses(value = {@ApiResponse(code = 201, message = "Created chargeback reversal successfully"),
@ApiResponse(code = 400, message = "Invalid payment id supplied"),
@ApiResponse(code = 404, message = "Account or payment not found")})
public Response createChargebackReversal(@PathParam("paymentId") final UUID paymentId,
final InvoicePaymentTransactionJson json,
@QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final UriInfo uriInfo,
@javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException, AccountApiException {
verifyNonNullOrEmpty(json, "InvoicePaymentTransactionJson body should be specified");
verifyNonNullOrEmpty(json.getTransactionExternalKey(), "InvoicePaymentTransactionJson transactionExternalKey needs to be set");
final CallContext callContextNoAccountId = context.createCallContextNoAccountId(createdBy, reason, comment, request);
final Payment payment = paymentApi.getPayment(paymentId, false, false, ImmutableList.<PluginProperty>of(), callContextNoAccountId);
final Account account = accountUserApi.getAccountById(payment.getAccountId(), callContextNoAccountId);
final CallContext callContext = context.createCallContextWithAccountId(account.getId(), createdBy, reason, comment, request);
invoicePaymentApi.createChargebackReversalForInvoicePayment(account,
payment.getId(),
json.getEffectiveDate(),
json.getTransactionExternalKey(),
extractPluginProperties(pluginPropertiesString),
createInvoicePaymentControlPluginApiPaymentOptions(false),
callContext);
return uriBuilder.buildResponse(uriInfo, InvoicePaymentResource.class, "getInvoicePayment", paymentId, request);
}
@TimedResource(name = "completeInvoicePaymentTransaction")
@PUT
@Path("/{paymentId:" + UUID_PATTERN + "}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Complete an existing transaction")
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successful operation"),
@ApiResponse(code = 400, message = "Invalid paymentId supplied"),
@ApiResponse(code = 404, message = "Account or payment not found"),
@ApiResponse(code = 402, message = "Transaction declined by gateway"),
@ApiResponse(code = 422, message = "Payment is aborted by a control plugin"),
@ApiResponse(code = 502, message = "Failed to submit payment transaction"),
@ApiResponse(code = 503, message = "Payment in unknown status, failed to receive gateway response"),
@ApiResponse(code = 504, message = "Payment operation timeout")})
public Response completeInvoicePaymentTransaction(@PathParam("paymentId") final UUID paymentId,
final PaymentTransactionJson json,
@QueryParam(QUERY_PAYMENT_CONTROL_PLUGIN_NAME) final List<String> paymentControlPluginNames,
@QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final UriInfo uriInfo,
@javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException, AccountApiException {
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Payment payment = paymentApi.getPayment(paymentId, false, false, ImmutableList.<PluginProperty>of(), tenantContext);
final List<InvoicePayment> invoicePayments = invoicePaymentApi.getInvoicePayments(paymentId, tenantContext);
final InvoicePayment originalInvoicePaymentAttempt = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {
@Override
public boolean apply(final InvoicePayment input) {
return input.getType() == InvoicePaymentType.ATTEMPT && !input.isSuccess();
}
}).orNull();
final UUID invoiceId = originalInvoicePaymentAttempt != null ? originalInvoicePaymentAttempt.getInvoiceId() : null;
if (invoiceId == null) {
return Response.status(Status.NOT_FOUND).build();
}
final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
final List<String> controlPluginNames = new ArrayList<String>();
controlPluginNames.addAll(paymentControlPluginNames);
final Account account = accountUserApi.getAccountById(payment.getAccountId(), tenantContext);
final BigDecimal amount = json == null ? null : json.getAmount();
final Currency currency = json == null ? null : json.getCurrency();
final CallContext callContext = context.createCallContextWithAccountId(account.getId(), createdBy, reason, comment, request);
final PaymentTransaction pendingOrSuccessTransaction = lookupPendingOrSuccessTransaction(payment,
json != null ? json.getTransactionId() : null,
json != null ? json.getTransactionExternalKey() : null,
json != null ? json.getTransactionType() : null);
// If transaction was already completed, return early (See #626)
if (pendingOrSuccessTransaction.getTransactionStatus() == TransactionStatus.SUCCESS) {
return Response.status(Status.NO_CONTENT).build();
}
final PaymentOptions paymentOptions = createControlPluginApiPaymentOptions(paymentControlPluginNames);
invoicePaymentApi.createPurchaseForInvoicePayment(account, invoiceId, payment.getPaymentMethodId(), payment.getId(), amount, currency, null,
payment.getExternalKey(), pendingOrSuccessTransaction.getExternalKey(),
pluginProperties, paymentOptions, callContext);
return Response.status(Status.NO_CONTENT).build();
}
@TimedResource
@GET
@Path("/{paymentId:" + UUID_PATTERN + "}/" + CUSTOM_FIELDS)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Retrieve payment custom fields", response = CustomFieldJson.class, responseContainer = "List", nickname = "getInvoicePaymentCustomFields")
@ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid payment id supplied")})
public Response getCustomFields(@PathParam(ID_PARAM_NAME) final UUID id,
@QueryParam(QUERY_AUDIT) @DefaultValue("NONE") final AuditMode auditMode,
@javax.ws.rs.core.Context final HttpServletRequest request) {
return super.getCustomFields(id, auditMode, context.createTenantContextNoAccountId(request));
}
@TimedResource
@POST
@Path("/{paymentId:" + UUID_PATTERN + "}/" + CUSTOM_FIELDS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Add custom fields to payment", response = CustomField.class, responseContainer = "List")
@ApiResponses(value = {@ApiResponse(code = 201, message = "Custom field created successfully"),
@ApiResponse(code = 400, message = "Invalid payment id supplied")})
public Response createInvoicePaymentCustomFields(@PathParam(ID_PARAM_NAME) final UUID id,
final List<CustomFieldJson> customFields,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final HttpServletRequest request,
@javax.ws.rs.core.Context final UriInfo uriInfo) throws CustomFieldApiException {
return super.createCustomFields(id, customFields,
context.createCallContextNoAccountId(createdBy, reason, comment, request), uriInfo, request);
}
@TimedResource
@PUT
@Path("/{paymentId:" + UUID_PATTERN + "}/" + CUSTOM_FIELDS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Modify custom fields to payment")
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successful operation"),
@ApiResponse(code = 400, message = "Invalid payment id supplied")})
public Response modifyInvoicePaymentCustomFields(@PathParam(ID_PARAM_NAME) final UUID id,
final List<CustomFieldJson> customFields,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException {
return super.modifyCustomFields(id, customFields,
context.createCallContextNoAccountId(createdBy, reason, comment, request));
}
@TimedResource
@DELETE
@Path("/{paymentId:" + UUID_PATTERN + "}/" + CUSTOM_FIELDS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Remove custom fields from payment")
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successful operation"),
@ApiResponse(code = 400, message = "Invalid payment id supplied")})
public Response deleteInvoicePaymentCustomFields(@PathParam(ID_PARAM_NAME) final UUID id,
@QueryParam(QUERY_CUSTOM_FIELD) final List<UUID> customFieldList,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final HttpServletRequest request) throws CustomFieldApiException {
return super.deleteCustomFields(id, customFieldList,
context.createCallContextNoAccountId(createdBy, reason, comment, request));
}
@TimedResource
@GET
@Path("/{paymentId:" + UUID_PATTERN + "}/" + TAGS)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Retrieve payment tags", response = TagJson.class, responseContainer = "List", nickname = "getInvoicePaymentTags")
@ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid payment id supplied"),
@ApiResponse(code = 404, message = "Payment not found")})
public Response getTags(@PathParam(ID_PARAM_NAME) final UUID paymentId,
@QueryParam(QUERY_INCLUDED_DELETED) @DefaultValue("false") final Boolean includedDeleted,
@QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
@QueryParam(QUERY_AUDIT) @DefaultValue("NONE") final AuditMode auditMode,
@javax.ws.rs.core.Context final HttpServletRequest request) throws TagDefinitionApiException, PaymentApiException {
final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
final TenantContext tenantContext = context.createTenantContextNoAccountId(request);
final Payment payment = paymentApi.getPayment(paymentId, false, false, pluginProperties, tenantContext);
return super.getTags(payment.getAccountId(), paymentId, auditMode, includedDeleted, tenantContext);
}
@TimedResource
@POST
@Path("/{paymentId:" + UUID_PATTERN + "}/" + TAGS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Add tags to payment", response = TagJson.class, responseContainer = "List")
@ApiResponses(value = {@ApiResponse(code = 201, message = "Tag created successfully"),
@ApiResponse(code = 400, message = "Invalid payment id supplied")})
public Response createInvoicePaymentTags(@PathParam(ID_PARAM_NAME) final UUID id,
final List<UUID> tagList,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final UriInfo uriInfo,
@javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException {
return super.createTags(id, tagList, uriInfo,
context.createCallContextNoAccountId(createdBy, reason, comment, request), request);
}
@TimedResource
@DELETE
@Path("/{paymentId:" + UUID_PATTERN + "}/" + TAGS)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Remove tags from payment")
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successful operation"),
@ApiResponse(code = 400, message = "Invalid payment id supplied")})
public Response deleteInvoicePaymentTags(@PathParam(ID_PARAM_NAME) final UUID id,
@QueryParam(QUERY_TAG) final List<UUID> tagList,
@HeaderParam(HDR_CREATED_BY) final String createdBy,
@HeaderParam(HDR_REASON) final String reason,
@HeaderParam(HDR_COMMENT) final String comment,
@javax.ws.rs.core.Context final HttpServletRequest request) throws TagApiException {
return super.deleteTags(id, tagList,
context.createCallContextNoAccountId(createdBy, reason, comment, request));
}
@Override
protected ObjectType getObjectType() {
return ObjectType.PAYMENT;
}
}
| 15,942 |
763 | <reponame>zabrewer/batfish<filename>projects/batfish/src/main/java/org/batfish/representation/cisco_nxos/RouteDistinguisherOrAuto.java
package org.batfish.representation.cisco_nxos;
import java.io.Serializable;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.batfish.datamodel.bgp.RouteDistinguisher;
/** Either {@code auto} or an explicit {@link RouteDistinguisher}. */
public final class RouteDistinguisherOrAuto implements Serializable {
private static final RouteDistinguisherOrAuto AUTO = new RouteDistinguisherOrAuto(null);
public static RouteDistinguisherOrAuto auto() {
return AUTO;
}
public static RouteDistinguisherOrAuto of(@Nonnull RouteDistinguisher rd) {
return new RouteDistinguisherOrAuto(rd);
}
public boolean isAuto() {
return _routeDistinguisher == null;
}
@Nullable
public RouteDistinguisher getRouteDistinguisher() {
return _routeDistinguisher;
}
//////////////////////////////////////////
///// Private implementation details /////
//////////////////////////////////////////
private RouteDistinguisherOrAuto(@Nullable RouteDistinguisher rd) {
_routeDistinguisher = rd;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (!(o instanceof RouteDistinguisherOrAuto)) {
return false;
}
RouteDistinguisherOrAuto that = (RouteDistinguisherOrAuto) o;
return Objects.equals(_routeDistinguisher, that._routeDistinguisher);
}
@Override
public int hashCode() {
return Objects.hashCode(_routeDistinguisher);
}
@Nullable private final RouteDistinguisher _routeDistinguisher;
}
| 531 |
878 | <gh_stars>100-1000
package com.lfk.justweengine.drawable.Button;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.renderscript.Float2;
import com.lfk.justweengine.engine.Engine;
import com.lfk.justweengine.utils.tools.DisplayUtils;
/**
* TextButton
*
* @author liufengkai
* Created by liufengkai on 15/12/12.
*/
public class TextButton extends BaseButton {
// text color / button color
private int b_text_Color, b_button_Color;
// text
private String b_text;
// zoom in center
private boolean b_zoomCenter, b_firstInit;
private Paint b_textPaint;
private float b_textWidth, b_singleWidth;
/**
* TextButton
*
* @param b_engine engine context
* @param name textButton name
*/
public TextButton(Engine b_engine, String name) {
super(b_engine, name);
init();
}
/**
* TextButton
*
* @param b_engine engine context
* @param b_width w
* @param b_height h
* @param name textButton name
*/
public TextButton(Engine b_engine, int b_width, int b_height, String name) {
super(b_engine, b_width, b_height, name);
init();
}
private void init() {
b_text = "";
b_text_Color = Color.WHITE;
b_button_Color = Color.TRANSPARENT;
b_zoomCenter = false;
b_firstInit = false;
b_position = new Point(110, 110);
b_scale = new Float2(1.0f, 1.0f);
b_textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
b_textPaint.setColor(b_text_Color);
b_textPaint.setTextSize(40);
paint.setColor(b_button_Color);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
}
@Override
public void draw() {
e_canvas = b_engine.getCanvas();
if (b_width == 0 || b_height == 0) {
float[] widths = new float[1];
// 获取单个汉字的宽度
b_textPaint.getTextWidths("蛤", widths);
b_text = b_text != null ? b_text : "";
b_textWidth = widths[0] * b_text.length();
b_singleWidth = widths[0];
b_width = (int) (b_text.length() * widths[0] + 2 * DisplayUtils.dip2px(16));
b_height = (int) (widths[0] + 2 * DisplayUtils.dip2px(8));
}
int x = b_position.x;
int y = b_position.y;
int w = (int) (b_width * b_scale.x);
int h = (int) (b_height * b_scale.y);
if (!b_firstInit) {
b_rect = new Rect(x, y, x + w, y + h);
b_firstInit = true;
}
if (!b_zoomCenter) {
b_rect = new Rect(x, y, x + w, y + h);
}
e_canvas.drawRect(b_rect, paint);
e_canvas.drawText(b_text, x + (b_width / 2 - b_textWidth / 2),
y + (b_height / 2 + b_singleWidth / 2), b_textPaint);
}
@Override
public void animation() {
if (b_baseAnim != null && b_baseAnim.animating) {
doAnimation();
}
}
private void doAnimation() {
switch (b_baseAnim.animType) {
case COLOR:
paint.setColor(b_baseAnim.adjustButtonBackGround(b_button_Color, b_normal));
break;
}
}
public void setZoomCenter(boolean zoomCenter) {
this.b_zoomCenter = zoomCenter;
}
public void setTextColor(int text_Color) {
if (b_textPaint != null) b_textPaint.setColor(text_Color);
this.b_text_Color = text_Color;
}
public void setButtonColor(int button_Color) {
this.b_button_Color = button_Color;
this.paint.setColor(button_Color);
}
@Override
public void setNormal(boolean b_normal) {
if (b_baseAnim != null) {
this.b_baseAnim.animating = true;
this.b_normal = b_normal;
}
}
public void setAnimation(BaseButtonAnimation anim) {
this.b_baseAnim = anim;
}
@Override
public void setText(String b_text) {
this.b_text = b_text;
}
public void setPosition(int x, int y) {
this.b_position.x = x;
this.b_position.y = y;
}
}
| 2,014 |
1,741 | from .shim import *
from .util import get_dpi_scale
import logging
logger = logging.getLogger("Lighthouse.Qt.WaitBox")
#--------------------------------------------------------------------------
# Qt WaitBox
#--------------------------------------------------------------------------
class WaitBox(QtWidgets.QDialog):
"""
A Generic Qt WaitBox Dialog.
"""
def __init__(self, text, title="Please wait...", abort=None):
super(WaitBox, self).__init__()
# dialog text & window title
self._text = text
self._title = title
# abort routine (optional)
self._abort = abort
# initialize the dialog UI
self._ui_init()
def set_text(self, text):
"""
Change the waitbox text.
"""
self._text = text
self._text_label.setText(text)
qta = QtCore.QCoreApplication.instance()
qta.processEvents()
def show(self, modal=True):
self.setModal(modal)
result = super(WaitBox, self).show()
qta = QtCore.QCoreApplication.instance()
qta.processEvents()
#--------------------------------------------------------------------------
# Initialization - UI
#--------------------------------------------------------------------------
def _ui_init(self):
"""
Initialize UI elements.
"""
self.setWindowFlags(
self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint
)
self.setWindowFlags(
self.windowFlags() | QtCore.Qt.MSWindowsFixedSizeDialogHint
)
self.setWindowFlags(
self.windowFlags() & ~QtCore.Qt.WindowCloseButtonHint
)
# configure the main widget / form
self.setSizeGripEnabled(False)
self.setModal(True)
self._dpi_scale = get_dpi_scale()*5.0
# initialize abort button
self._abort_button = QtWidgets.QPushButton("Cancel")
# layout the populated UI just before showing it
self._ui_layout()
def _ui_layout(self):
"""
Layout the major UI elements of the widget.
"""
self.setWindowTitle(self._title)
self._text_label = QtWidgets.QLabel(self._text)
self._text_label.setAlignment(QtCore.Qt.AlignHCenter)
# vertical layout (whole widget)
v_layout = QtWidgets.QVBoxLayout()
v_layout.setAlignment(QtCore.Qt.AlignCenter)
v_layout.addWidget(self._text_label)
if self._abort:
self._abort_button.clicked.connect(abort)
v_layout.addWidget(self._abort_button)
v_layout.setSpacing(self._dpi_scale*3)
v_layout.setContentsMargins(
self._dpi_scale*5,
self._dpi_scale,
self._dpi_scale*5,
self._dpi_scale
)
# scale widget dimensions based on DPI
height = self._dpi_scale * 15
self.setMinimumHeight(height)
# compute the dialog layout
self.setLayout(v_layout)
| 1,282 |
852 | /*
* GoldenPatternBase.cpp
*
* Created on: Oct 3, 2017
* Author: kbunkow
*/
#include "L1Trigger/L1TMuonOverlapPhase1/interface/Omtf/GoldenPatternBase.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <iomanip>
std::ostream& operator<<(std::ostream& out, const Key& o) {
out << "Key_" << std::setw(2) << o.theNumber << " hwNum " << std::setw(2) << o.getHwPatternNumber() << " group "
<< std::setw(2) << o.theGroup << ":" << o.theIndexInGroup << " : (eta=" << o.theEtaCode << ", pt=" << std::setw(3)
<< o.thePt << ", charge=" << setw(2) << o.theCharge << ")";
return out;
}
GoldenPatternBase::GoldenPatternBase(const Key& aKey) : theKey(aKey), myOmtfConfig(nullptr) {}
GoldenPatternBase::GoldenPatternBase(const Key& aKey, const OMTFConfiguration* omtfConfig)
: theKey(aKey),
myOmtfConfig(omtfConfig),
results(boost::extents[myOmtfConfig->processorCnt()][myOmtfConfig->nTestRefHits()]) {
for (unsigned int iProc = 0; iProc < results.size(); iProc++) {
for (unsigned int iTestRefHit = 0; iTestRefHit < results[iProc].size(); iTestRefHit++) {
results[iProc][iTestRefHit].init(omtfConfig);
}
}
}
void GoldenPatternBase::setConfig(const OMTFConfiguration* omtfConfig) {
myOmtfConfig = omtfConfig;
results.resize(boost::extents[myOmtfConfig->processorCnt()][myOmtfConfig->nTestRefHits()]);
for (unsigned int iProc = 0; iProc < results.size(); iProc++) {
for (unsigned int iTestRefHit = 0; iTestRefHit < results[iProc].size(); iTestRefHit++) {
results[iProc][iTestRefHit].init(omtfConfig);
}
}
}
////////////////////////////////////////////////////
////////////////////////////////////////////////////
StubResult GoldenPatternBase::process1Layer1RefLayer(unsigned int iRefLayer,
unsigned int iLayer,
MuonStubPtrs1D layerStubs,
const MuonStubPtr refStub) {
//if (this->getDistPhiBitShift(iLayer, iRefLayer) != 0) LogTrace("l1tOmtfEventPrint")<<__FUNCTION__<<":"<<__LINE__<<key()<<this->getDistPhiBitShift(iLayer, iRefLayer)<<std::endl;
int phiMean = this->meanDistPhiValue(iLayer, iRefLayer, refStub->phiBHw);
int phiDistMin = myOmtfConfig->nPhiBins(); //1<<(myOmtfConfig->nPdfAddrBits()); //"infinite" value for the beginning
///Select hit closest to the mean of probability
///distribution in given layer
MuonStubPtr selectedStub;
int phiRefHit = 0;
if (refStub)
phiRefHit = refStub->phiHw;
if (this->myOmtfConfig->isBendingLayer(iLayer)) {
phiRefHit = 0; //phi ref hit for the bending layer set to 0, since it should not be included in the phiDist
}
for (auto& stub : layerStubs) {
if (!stub) //empty pointer
continue;
int hitPhi = stub->phiHw;
if (this->myOmtfConfig->isBendingLayer(iLayer)) {
//rejecting phiB of the low quality DT stubs is done in the OMTFInputMaker
hitPhi = stub->phiBHw;
}
if (hitPhi >= (int)myOmtfConfig->nPhiBins()) //TODO is this needed now? the empty hit will be empty stub
continue; //empty itHits are marked with nPhiBins() in OMTFProcessor::restrictInput
int phiDist = this->myOmtfConfig->foldPhi(hitPhi - phiMean - phiRefHit);
//for standard omtf foldPhi is not needed, but if one processor works for full phi then it is
//if (this->getDistPhiBitShift(iLayer, iRefLayer) != 0)
/*LogTrace("l1tOmtfEventPrint") <<"\n"<<__FUNCTION__<<":"<<__LINE__<<" "<<theKey<<std::endl;
LogTrace("l1tOmtfEventPrint") <<__FUNCTION__<<":"<<__LINE__
<<" iRefLayer "<<iRefLayer<<" iLayer "<<iLayer
<<" hitPhi "<<hitPhi<<" phiMean "<<phiMean<<" phiRefHit "<<phiRefHit<<" phiDist "<<phiDist<<std::endl;*/
//firmware works on the sign-value, shift must be done on abs(phiDist)
int sign = phiDist < 0 ? -1 : 1;
phiDist = abs(phiDist) >> this->getDistPhiBitShift(iLayer, iRefLayer);
phiDist *= sign;
//if the shift is done here, it means that the phiMean in the xml should be the same as without shift
//if (this->getDistPhiBitShift(iLayer, iRefLayer) != 0) std::cout<<__FUNCTION__<<":"<<__LINE__<<" phiDist "<<phiDist<<std::endl;
if (abs(phiDist) < abs(phiDistMin)) {
phiDistMin = phiDist;
selectedStub = stub;
}
}
if (!selectedStub) {
if (this->myOmtfConfig->isNoHitValueInPdf()) {
PdfValueType pdfVal = this->pdfValue(iLayer, iRefLayer, 0);
return StubResult(pdfVal, false, myOmtfConfig->nPhiBins(), iLayer, selectedStub);
} else {
return StubResult(0, false, myOmtfConfig->nPhiBins(), iLayer, selectedStub); //2018 version
}
}
int pdfMiddle = 1 << (myOmtfConfig->nPdfAddrBits() - 1);
/* debug
if(phiDistMin != 128 && iRefLayer == 0 && iLayer == 1)*/
/*LogTrace("l1tOmtfEventPrint")<<__FUNCTION__<<":"<<__LINE__<<" iRefLayer "<<iRefLayer<<" iLayer "<<iLayer<<" selectedStub "<<*selectedStub
<<" phiDistMin "<<phiDistMin<<" phiMean "<<phiMean<<" shift "<<this->getDistPhiBitShift(iLayer, iRefLayer)<<std::endl;*/
///Check if phiDistMin is within pdf range -63 +63
///in firmware here the arithmetic "value and sign" is used, therefore the range is -63 +63, and not -64 +63
if (abs(phiDistMin) > ((1 << (myOmtfConfig->nPdfAddrBits() - 1)) - 1)) {
return StubResult(0, false, phiDistMin + pdfMiddle, iLayer, selectedStub);
//return GoldenPatternResult::LayerResult(this->pdfValue(iLayer, iRefLayer, 0), false, phiDistMin + pdfMiddle, selHit);
//in some algorithms versions with thresholds we use the bin 0 to store the pdf value returned when there was no hit.
//in the version without thresholds, the value in the bin 0 should be 0
}
///Shift phidist, so 0 is at the middle of the range
phiDistMin += pdfMiddle;
//if (this->getDistPhiBitShift(iLayer, iRefLayer) != 0) LogTrace("l1tOmtfEventPrint")<<__FUNCTION__<<":"<<__LINE__<<" phiDistMin "<<phiDistMin<<std::endl;
PdfValueType pdfVal = this->pdfValue(iLayer, iRefLayer, phiDistMin);
if (pdfVal <= 0) {
return StubResult(0, false, phiDistMin, iLayer, selectedStub);
}
return StubResult(pdfVal, true, phiDistMin, iLayer, selectedStub);
}
////////////////////////////////////////////////////
////////////////////////////////////////////////////
void GoldenPatternBase::finalise(unsigned int procIndx) {
for (auto& result : getResults()[procIndx]) {
result.finalise();
}
}
| 2,548 |
804 | package com.example.abner.stickerdemo.view;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.abner.stickerdemo.R;
import com.example.abner.stickerdemo.utils.CommonUtils;
/**
* Created by Abner on 15/6/12.
* QQ 230877476
* Email <EMAIL>
*/
public class BubbleInputDialog extends Dialog {
private final String defaultStr;
private EditText et_bubble_input;
private TextView tv_show_count;
private TextView tv_action_done;
private static final int MAX_COUNT = 33; //字数最大限制33个
private Context mContext;
private BubbleTextView bubbleTextView;
public BubbleInputDialog(Context context) {
super(context, android.R.style.Theme_Translucent_NoTitleBar);
mContext = context;
defaultStr = context.getString(R.string.double_click_input_text);
initView();
}
public BubbleInputDialog(Context context, BubbleTextView view) {
super(context, android.R.style.Theme_Translucent_NoTitleBar);
mContext = context;
defaultStr = context.getString(R.string.double_click_input_text);
bubbleTextView = view;
initView();
}
public void setBubbleTextView(BubbleTextView bubbleTextView) {
this.bubbleTextView = bubbleTextView;
if (defaultStr.equals(bubbleTextView.getmStr())) {
et_bubble_input.setText("");
} else {
et_bubble_input.setText(bubbleTextView.getmStr());
et_bubble_input.setSelection(bubbleTextView.getmStr().length());
}
}
private void initView() {
setContentView(R.layout.view_input_dialog);
tv_action_done = (TextView) findViewById(R.id.tv_action_done);
et_bubble_input = (EditText) findViewById(R.id.et_bubble_input);
tv_show_count = (TextView) findViewById(R.id.tv_show_count);
et_bubble_input.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
long textLength = CommonUtils.calculateLength(s);
tv_show_count.setText(String.valueOf(MAX_COUNT - textLength));
if (textLength > MAX_COUNT) {
tv_show_count.setTextColor(mContext.getResources().getColor(R.color.red_e73a3d));
} else {
tv_show_count.setTextColor(mContext.getResources().getColor(R.color.grey_8b8b8b));
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
et_bubble_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
done();
return true;
}
return false;
}
});
tv_action_done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
done();
}
});
}
@Override
public void show() {
super.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager m = (InputMethodManager) et_bubble_input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
m.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
}
}, 500);
}
@Override
public void dismiss() {
super.dismiss();
InputMethodManager m = (InputMethodManager) et_bubble_input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
m.hideSoftInputFromWindow(et_bubble_input.getWindowToken(), 0);
}
public interface CompleteCallBack {
void onComplete(View bubbleTextView, String str);
}
private CompleteCallBack mCompleteCallBack;
public void setCompleteCallBack(CompleteCallBack completeCallBack) {
this.mCompleteCallBack = completeCallBack;
}
private void done() {
if (Integer.valueOf(tv_show_count.getText().toString()) < 0) {
Toast.makeText(mContext, mContext.getString(R.string.over_text_limit), Toast.LENGTH_SHORT).show();
return;
}
dismiss();
if (mCompleteCallBack != null) {
String str;
if (TextUtils.isEmpty(et_bubble_input.getText())) {
str = "";
} else {
str = et_bubble_input.getText().toString();
}
mCompleteCallBack.onComplete(bubbleTextView, str);
}
}
}
| 2,313 |
377 | # PYAF_URL="http://pyaf.herokuapp.com/model"
PYAF_URL="http://0.0.0.0:8081/model"
def test_heroku_pyaf(data):
url = PYAF_URL
header = {"Content-Type":"application/json"}
import httplib2
http = httplib2.Http()
response, send = http.request(url, "POST", headers=header, body=data)
content = response.read()
return content;
def test_heroku_pyaf_2(data):
import json, urllib3
http = urllib3.PoolManager()
r = http.request('POST', PYAF_URL,
headers={'Content-Type': 'application/json'},
body=json.dumps(data))
content = r.data
return content;
CSV="https://raw.githubusercontent.com/antoinecarme/TimeSeriesData/master/ozone-la.csv"
data={"Name":"model1", "CSVFile":CSV, "DateFormat":"%Y-%m"}
cont = test_heroku_pyaf_2(data);
print(cont);
data2={"CSVFile":CSV, "DateFormat":"%Y-%m"}
cont1 = test_heroku_pyaf_2(data2);
print(cont1);
| 410 |
1,916 | /* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2014 Stanford University and the Authors. *
* Authors: <NAME> *
* 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. *
* -------------------------------------------------------------------------- */
/* Implementation of non-inline methods of the handle class
Constraint::LineOnLineContact, and its implementation class
Constraint::LineOnLineContactImpl. */
#include "SimTKcommon.h"
#include "simbody/internal/common.h"
#include "simbody/internal/Constraint.h"
#include "simbody/internal/Constraint_LineOnLineContact.h"
#include "Constraint_LineOnLineContactImpl.h"
#include "SimbodyMatterSubsystemRep.h"
namespace SimTK {
//==============================================================================
// LINE ON LINE CONTACT
//==============================================================================
SimTK_INSERT_DERIVED_HANDLE_DEFINITIONS(Constraint::LineOnLineContact,
Constraint::LineOnLineContactImpl,
Constraint);
Constraint::LineOnLineContact::LineOnLineContact
(MobilizedBody& mobod_F,
const Transform& defaultEdgeFrameF,
Real defaultHalfLengthF,
MobilizedBody& mobod_B,
const Transform& defaultEdgeFrameB,
Real defaultHalfLengthB,
bool enforceRolling)
: Constraint(new LineOnLineContactImpl(enforceRolling))
{
SimTK_APIARGCHECK_ALWAYS(mobod_F.isInSubsystem() && mobod_B.isInSubsystem(),
"Constraint::LineOnLineContact","LineOnLineContact",
"Both mobilized bodies must already be in a SimbodyMatterSubsystem.");
SimTK_APIARGCHECK_ALWAYS(mobod_F.isInSameSubsystem(mobod_B),
"Constraint::LineOnLineContact","LineOnLineContact",
"The two mobilized bodies to be connected must be in the same "
"SimbodyMatterSubsystem.");
mobod_F.updMatterSubsystem().adoptConstraint(*this);
updImpl().m_mobod_F = updImpl().addConstrainedBody(mobod_F);
updImpl().m_mobod_B = updImpl().addConstrainedBody(mobod_B);
updImpl().m_def_X_FEf = defaultEdgeFrameF;
updImpl().m_def_hf = defaultHalfLengthF;
updImpl().m_def_X_BEb = defaultEdgeFrameB;
updImpl().m_def_hb = defaultHalfLengthB;
}
Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setDefaultEdgeFrameF(const Transform& defaultEdgeFrameF) {
getImpl().invalidateTopologyCache();
updImpl().m_def_X_FEf = defaultEdgeFrameF;
return *this;
}
Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setDefaultHalfLengthF(Real defaultHalfLengthF) {
getImpl().invalidateTopologyCache();
updImpl().m_def_hf = defaultHalfLengthF;
return *this;
}
Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setDefaultEdgeFrameB(const Transform& defaultEdgeFrameB) {
getImpl().invalidateTopologyCache();
updImpl().m_def_X_BEb = defaultEdgeFrameB;
return *this;
}
Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setDefaultHalfLengthB(Real defaultHalfLengthB) {
getImpl().invalidateTopologyCache();
updImpl().m_def_hb = defaultHalfLengthB;
return *this;
}
const MobilizedBody& Constraint::LineOnLineContact::
getMobilizedBodyF() const {
const LineOnLineContactImpl& impl = getImpl();
return impl.getMobilizedBodyFromConstrainedBody(impl.m_mobod_F);
}
const MobilizedBody& Constraint::LineOnLineContact::
getMobilizedBodyB() const {
const LineOnLineContactImpl& impl = getImpl();
return impl.getMobilizedBodyFromConstrainedBody(impl.m_mobod_B);
}
bool Constraint::LineOnLineContact::isEnforcingRolling() const
{ return getImpl().m_enforceRolling; }
const Transform& Constraint::LineOnLineContact::
getDefaultEdgeFrameF() const {return getImpl().m_def_X_FEf;}
Real Constraint::LineOnLineContact::
getDefaultHalfLengthF() const {return getImpl().m_def_hf;}
const Transform& Constraint::LineOnLineContact::
getDefaultEdgeFrameB() const {return getImpl().m_def_X_BEb;}
Real Constraint::LineOnLineContact::
getDefaultHalfLengthB() const {return getImpl().m_def_hb;}
const Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setEdgeFrameF(State& state, const Transform& edgeFrameF) const {
getImpl().updParameters(state).X_FEf = edgeFrameF;
return *this;
}
const Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setHalfLengthF(State& state, Real halfLengthF) const {
getImpl().updParameters(state).hf = halfLengthF;
return *this;
}
const Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setEdgeFrameB(State& state, const Transform& edgeFrameB) const {
getImpl().updParameters(state).X_BEb = edgeFrameB;
return *this;
}
const Constraint::LineOnLineContact& Constraint::LineOnLineContact::
setHalfLengthB(State& state, Real halfLengthB) const {
getImpl().updParameters(state).hb = halfLengthB;
return *this;
}
const Transform& Constraint::LineOnLineContact::
getEdgeFrameF(const State& state) const
{ return getImpl().getParameters(state).X_FEf; }
Real Constraint::LineOnLineContact::
getHalfLengthF(const State& state) const
{ return getImpl().getParameters(state).hf; }
const Transform& Constraint::LineOnLineContact::
getEdgeFrameB(const State& state) const
{ return getImpl().getParameters(state).X_BEb; }
Real Constraint::LineOnLineContact::
getHalfLengthB(const State& state) const
{ return getImpl().getParameters(state).hb; }
Real Constraint::LineOnLineContact::getPositionError(const State& s) const {
Real perr;
getImpl().getPositionErrors(s, 1, &perr);
return perr;
}
Vec3 Constraint::LineOnLineContact::getVelocityErrors(const State& s) const {
const LineOnLineContactImpl& impl = getImpl();
Vec3 verr_PC; // result is velocity error in P frame
if (impl.m_enforceRolling) {
Real verr[3];
impl.getVelocityErrors(s, 3, verr);
verr_PC = Vec3(verr[1],verr[2],verr[0]); // switch to x,y,z order
} else {
Real pverr;
getImpl().getVelocityErrors(s, 1, &pverr);
verr_PC = Vec3(0,0,pverr); // lone error is in z direction
}
return verr_PC;
}
Vec3 Constraint::LineOnLineContact::getAccelerationErrors(const State& s) const {
const LineOnLineContactImpl& impl = getImpl();
Vec3 aerr_PC; // result is acceleration error in P frame
if (impl.m_enforceRolling) {
Real aerr[3];
impl.getAccelerationErrors(s, 3, aerr);
aerr_PC = Vec3(aerr[1],aerr[2],aerr[0]); // switch to x,y,z order
} else {
Real paerr;
getImpl().getAccelerationErrors(s, 1, &paerr);
aerr_PC = Vec3(0,0,paerr); // lone error is in z direction
}
return aerr_PC;
}
Vec3 Constraint::LineOnLineContact::getMultipliers(const State& s) const {
const LineOnLineContactImpl& impl = getImpl();
Vec3 lambda_PC; // result is -force on point F in P frame
if (impl.m_enforceRolling) {
Real lambda[3];
impl.getMultipliers(s, 3, lambda);
lambda_PC = Vec3(lambda[1],lambda[2],lambda[0]); //switch to x,y,z order
} else {
Real lambda;
getImpl().getMultipliers(s, 1, &lambda);
lambda_PC = Vec3(0,0,lambda); // lone force is in z direction
}
return lambda_PC;
}
Vec3 Constraint::LineOnLineContact::
findForceOnBodyBInG(const State& s) const {
const LineOnLineContactImpl& impl = getImpl();
if (impl.isDisabled(s))
return Vec3(0);
const Transform X_GC = findContactFrameInG(s);
const Vec3 f_C = -getMultipliers(s); // watch sign convention
return X_GC.R()*f_C;
}
Transform Constraint::LineOnLineContact::
findContactFrameInG(const State& s) const {
const LineOnLineContactImpl& impl = getImpl();
const LineOnLineContactImpl::PositionCache& pc =
impl.ensurePositionCacheRealized(s);
const MobilizedBody& mobod_A = impl.getAncestorMobilizedBody();
if (mobod_A.isGround())
return pc.X_AC; // == X_GC
const Transform& X_GA = mobod_A.getBodyTransform(s);
return X_GA * pc.X_AC; // 63 flops
}
void Constraint::LineOnLineContact::
findClosestPointsInG(const State& s, Vec3& Qf_G, Vec3& Qb_G,
bool& linesAreParallel) const {
const LineOnLineContactImpl& impl = getImpl();
const LineOnLineContactImpl::PositionCache& pc =
impl.ensurePositionCacheRealized(s);
const MobilizedBody& mobod_A = impl.getAncestorMobilizedBody();
if (mobod_A.isGround()) {
Qf_G = pc.p_AQf;
Qb_G = pc.p_AQb;
} else {
const Transform& X_GA = mobod_A.getBodyTransform(s);
Qf_G = X_GA * pc.p_AQf; // 18 flops
Qb_G = X_GA * pc.p_AQb; // 18 flops
}
}
// The separation is the signed distance between the lines' closest points.
// Same as perr routine, but works when constraint is disabled.
Real Constraint::LineOnLineContact::
findSeparation(const State& s) const {
const LineOnLineContactImpl::PositionCache& pc =
getImpl().ensurePositionCacheRealized(s);
const Real r = ~pc.p_PfPb_A * pc.n_A; // 5 flops
return r;
}
//==============================================================================
// LINE ON LINE CONTACT IMPL
//==============================================================================
// The default parameters may be overridden by setting a discrete variable in
// the state, and we need a couple of cache entries to hold expensive
// computations. We allocate the state resources here.
void Constraint::LineOnLineContactImpl::
realizeTopologyVirtual(State& state) const {
m_parametersIx = getMyMatterSubsystemRep().
allocateDiscreteVariable(state, Stage::Position,
new Value<Parameters>(Parameters(m_def_X_FEf, m_def_hf,
m_def_X_BEb, m_def_hb)));
m_posCacheIx = getMyMatterSubsystemRep().
allocateLazyCacheEntry(state, Stage::Position,
new Value<PositionCache>());
m_velCacheIx = getMyMatterSubsystemRep().
allocateLazyCacheEntry(state, Stage::Velocity,
new Value<VelocityCache>());
}
const Constraint::LineOnLineContactImpl::Parameters&
Constraint::LineOnLineContactImpl::
getParameters(const State& state) const {
return Value<Parameters>::downcast
(getMyMatterSubsystemRep().getDiscreteVariable(state,m_parametersIx));
}
Constraint::LineOnLineContactImpl::Parameters&
Constraint::LineOnLineContactImpl::
updParameters(State& state) const {
return Value<Parameters>::updDowncast
(getMyMatterSubsystemRep().updDiscreteVariable(state,m_parametersIx));
}
const Constraint::LineOnLineContactImpl::PositionCache&
Constraint::LineOnLineContactImpl::
getPositionCache(const State& state) const {
return Value<PositionCache>::downcast
(getMyMatterSubsystemRep().getCacheEntry(state,m_posCacheIx));
}
Constraint::LineOnLineContactImpl::PositionCache&
Constraint::LineOnLineContactImpl::
updPositionCache(const State& state) const {
return Value<PositionCache>::updDowncast
(getMyMatterSubsystemRep().updCacheEntry(state,m_posCacheIx));
}
const Constraint::LineOnLineContactImpl::VelocityCache&
Constraint::LineOnLineContactImpl::
getVelocityCache(const State& state) const {
return Value<VelocityCache>::downcast
(getMyMatterSubsystemRep().getCacheEntry(state,m_velCacheIx));
}
Constraint::LineOnLineContactImpl::VelocityCache&
Constraint::LineOnLineContactImpl::
updVelocityCache(const State& state) const {
return Value<VelocityCache>::updDowncast
(getMyMatterSubsystemRep().updCacheEntry(state,m_velCacheIx));
}
// This costs about 213 flops.
void Constraint::LineOnLineContactImpl::
calcPositionInfo(const State& state,
const Transform& X_AF, const Transform& X_AB,
PositionCache& pc) const
{
const Parameters& params = getParameters(state);
const UnitVec3& df_F = params.X_FEf.x();
const UnitVec3& db_B = params.X_BEb.x();
const UnitVec3& sf_F = params.X_FEf.z(); // outward normal
const UnitVec3& sb_B = params.X_BEb.z();
const Vec3& p_FPf = params.X_FEf.p();
const Vec3& p_BPb = params.X_BEb.p();
pc.df_A = X_AF.R() * df_F; // 15 flops
pc.db_A = X_AB.R() * db_B; // 15
pc.p_FPf_A = X_AF.R() * p_FPf; // 15
pc.p_BPb_A = X_AB.R() * p_BPb; // 15
const Vec3 p_APf = X_AF.p() + pc.p_FPf_A; // 3
const Vec3 p_APb = X_AB.p() + pc.p_BPb_A; // 3
pc.p_PfPb_A = p_APb - p_APf; // 3
const UnitVec3 sf_A = X_AF.R() * sf_F; // 15 flops
const UnitVec3 sb_A = X_AB.R() * sb_B; // 15
const Vec3 wraw_A = pc.df_A % pc.db_A; // 9
// Use whichever of the outward normal directions gives a clearer signal.
// We want w point out from F or into B. ~12 flops
const Real wsf = ~wraw_A*sf_A, wsb = ~wraw_A*sb_A;
if (std::abs(wsf) > std::abs(wsb)) pc.sense = (wsf >= 0 ? 1 : -1);
else pc.sense = (wsb >= 0 ? -1 : 1);
pc.w_A = pc.sense * wraw_A; // 3 flops
const Real sinTheta = pc.w_A.norm(); //~20
//TODO: should do something better than this for parallel edges. Not clear
// that an exception is best though since this might occur prior to an
// assembly analysis that would fix the problem. Also consider if we're
// doing event-driven contact we may need to catch the event of edges
// going from crossed to parallel to turn off the edge/edge contact.
if (sinTheta < SignificantReal) { // 1 flop
pc.edgesAreParallel = true;
pc.oos = 1/SignificantReal; // just to avoid NaN-ing if sinTheta==0
} else {
pc.edgesAreParallel = false;
pc.oos = 1/sinTheta; //~10
}
pc.n_A = UnitVec3(pc.w_A * pc.oos, true); // 3
pc.pXn = pc.p_PfPb_A % pc.n_A; // 9 flops
const Real f = -pc.sense*pc.oos; // 2 flops
pc.tf = f*dot(pc.db_A, pc.pXn); // 6
pc.tb = f*dot(pc.df_A, pc.pXn); // 6
// Create the contact frame C. The origin should be half way between
// Qf and Qb. The z axis is the contact normal n. x is along edge Ef, in
// direction df. y = z X x = n X df.
pc.p_AQf = p_APf + pc.tf * pc.df_A; // 6 flops
pc.p_AQb = p_APb + pc.tb * pc.db_A; // 6
const Vec3 p_ACo = 0.5*(pc.p_AQf + pc.p_AQb); // 6
pc.X_AC.updP() = p_ACo;
// Since unit vector n is perpendicular to df (and db), n X df
// is already a unit vector without normalizing.
const UnitVec3 nXdf(pc.n_A % pc.df_A, true); // 9 flops
pc.X_AC.updR().setRotationFromUnitVecsTrustMe(pc.df_A, nXdf, pc.n_A);
// Vectors from F and B body origins to contact point, expressed in A.
// These are the station locations at which forces are applied.
pc.p_FCo_A = p_ACo - X_AF.p(); // 3 flops
pc.p_BCo_A = p_ACo - X_AB.p(); // 3
}
const Constraint::LineOnLineContactImpl::PositionCache&
Constraint::LineOnLineContactImpl::
ensurePositionCacheRealized(const State& s) const {
if (getMyMatterSubsystemRep().isCacheValueRealized(s, m_posCacheIx))
return getPositionCache(s);
PositionCache& pc = updPositionCache(s);
const Transform& X_AF = getBodyTransformFromState(s, m_mobod_F);
const Transform& X_AB = getBodyTransformFromState(s, m_mobod_B);
calcPositionInfo(s, X_AF, X_AB, pc);
getMyMatterSubsystemRep().markCacheValueRealized(s, m_posCacheIx);
return pc;
}
// This costs about 340 flops if position info has already been calculated,
// otherwise we also pay for ensurePositionCacheRealized().
void Constraint::LineOnLineContactImpl::
calcVelocityInfo(const State& state,
const SpatialVec& V_AF, const SpatialVec& V_AB,
VelocityCache& vc) const
{
const PositionCache& pc = ensurePositionCacheRealized(state);
if (pc.edgesAreParallel)
return;
const Vec3& w_AF = V_AF[0]; // handy abbreviations
const Vec3& v_AF = V_AF[1];
const Vec3& w_AB = V_AB[0];
const Vec3& v_AB = V_AB[1];
// These are d/dt_A p_FPf and d/dt_A p_BPb
const Vec3 wX_p_FPf_A = w_AF % pc.p_FPf_A; // 9 flops
const Vec3 wX_p_BPb_A = w_AB % pc.p_BPb_A; // 9
const Vec3 v_APf = v_AF + wX_p_FPf_A; // 3
const Vec3 v_APb = v_AB + wX_p_BPb_A; // 3
vc.dp_PfPb_A = v_APb - v_APf; // 3
vc.ddf_A = w_AF % pc.df_A; // 9 flops
vc.ddb_A = w_AB % pc.db_A; // 9
vc.dw_A = pc.sense*(vc.ddf_A % pc.db_A + pc.df_A % vc.ddb_A);//24
vc.dn_A = pc.oos * (vc.dw_A - (~pc.n_A*vc.dw_A)*pc.n_A); // 14
// Calculate the velocity of B's material point (station) at Co,
// measured in the F frame and expressed in A.
const Vec3 vA_BCo_A = v_AB + w_AB % pc.p_BCo_A; // 12 flops
const Vec3 vA_FCo_A = v_AF + w_AF % pc.p_FCo_A; // 12
vc.vF_BCo_A = vA_BCo_A - vA_FCo_A; // 3
// We have s=||w||, oos=1/s. We want doos = d/dt oos.
vc.doos = -square(pc.oos) * dot(pc.n_A, vc.dw_A); // 8 flops
const Vec3 nXdb = pc.n_A % pc.db_A; // 9 flops
const Vec3 nXdf = pc.n_A % pc.df_A; // 9
const Vec3 d_nXdb = vc.dn_A % pc.db_A + pc.n_A % vc.ddb_A; // 21
const Vec3 d_nXdf = vc.dn_A % pc.df_A + pc.n_A % vc.ddf_A; // 21
const Real dtf = -pc.sense * ( // 20
pc.oos * (~vc.dp_PfPb_A*nXdb + ~pc.p_PfPb_A*d_nXdb)
+ vc.doos * (~pc.p_PfPb_A*nXdb) );
const Real dtb = -pc.sense * ( // 20
pc.oos * (~vc.dp_PfPb_A*nXdf + ~pc.p_PfPb_A*d_nXdf)
+ vc.doos * (~pc.p_PfPb_A*nXdf) );
const Vec3 dQf = v_APf + dtf * pc.df_A + pc.tf * vc.ddf_A; // 12 flops
const Vec3 dQb = v_APb + dtb * pc.db_A + pc.tb * vc.ddb_A; // 12
const Vec3 dCo = 0.5*(dQf + dQb); // 6
const Vec3 dp_FCo = dCo - v_AF; // 3
const Vec3 dp_BCo = dCo - v_AB; // 3
vc.wXdp_FCo_A = w_AF % dp_FCo; // 9 flops
vc.wXdp_BCo_A = w_AB % dp_BCo; // 9
vc.ddfXddb2 = 2.*(vc.ddf_A % vc.ddb_A); // 12
vc.wXddf_A = w_AF % vc.ddf_A; // 9
vc.wXddb_A = w_AB % vc.ddb_A; // 9
// These are the Coriolis accelerations of Pf and Pb, needed later.
vc.wXwX_p_FPf_A = w_AF % wX_p_FPf_A; // 9 flops
vc.wXwX_p_BPb_A = w_AB % wX_p_BPb_A; // 9
// Record derivative of the contact frame.
// We have Cx=df, Cz=n, Cy=n x df. Want derivatives in A.
vc.dCx_A = vc.ddf_A;
vc.dCz_A = vc.dn_A;
vc.dCy_A = d_nXdf;
vc.dCo_A = dCo;
}
const Constraint::LineOnLineContactImpl::VelocityCache&
Constraint::LineOnLineContactImpl::
ensureVelocityCacheRealized(const State& s) const {
if (getMyMatterSubsystemRep().isCacheValueRealized(s, m_velCacheIx))
return getVelocityCache(s);
VelocityCache& vc = updVelocityCache(s);
const SpatialVec& V_AF = getBodyVelocityFromState(s, m_mobod_F);
const SpatialVec& V_AB = getBodyVelocityFromState(s, m_mobod_B);
calcVelocityInfo(s, V_AF, V_AB, vc);
getMyMatterSubsystemRep().markCacheValueRealized(s, m_velCacheIx);
return vc;
}
void Constraint::LineOnLineContactImpl::
calcDecorativeGeometryAndAppendVirtual
(const State& s, Stage stage, Array_<DecorativeGeometry>& geom) const
{
// We can't generate the artwork until we know the lines' placements,
// which might not be until Position stage.
if ( stage != Stage::Position
|| !getMyMatterSubsystemRep().getShowDefaultGeometry())
return;
const Parameters& params = getParameters(s);
const Real hf = params.hf;
const Real hb = params.hb;
const PositionCache& pc = ensurePositionCacheRealized(s);
const Transform& X_AC = pc.X_AC;
const MobilizedBody& mobod_A = getAncestorMobilizedBody();
const Transform& X_GA = mobod_A.getBodyTransform(s);
const Rotation& R_GA = X_GA.R();
const Transform X_GC = X_GA * X_AC;
// Convert interesting stuff from A to G.
const UnitVec3 df_G = R_GA * X_AC.x();
const UnitVec3 db_G = R_GA * pc.db_A;
const Vec3 p_GQf = X_GA * pc.p_AQf;
const Vec3 p_GQb = X_GA * pc.p_AQb;
const Vec3 half_Lf = hf * df_G;
const Vec3 half_Lb = hb * db_G;
const MobilizedBody& bodyF = getMobilizedBodyFromConstrainedBody(m_mobod_F);
const MobilizedBody& bodyB = getMobilizedBodyFromConstrainedBody(m_mobod_B);
const Transform& X_GF = bodyF.getBodyTransform(s);
const Transform& X_GB = bodyB.getBodyTransform(s);
const Transform X_GEf = X_GF * params.X_FEf;
const Transform X_GEb = X_GB * params.X_BEb;
// On body F draw a green line segment around the orange closest point.
geom.push_back(DecorativeLine(p_GQf-half_Lf, p_GQf+half_Lf)
.setColor(Green));
geom.push_back(DecorativeFrame().setTransform(X_GEf)
.setColor(Green*.9).setLineThickness(1).setScale(0.5)); // F color
geom.push_back(DecorativePoint(p_GQf)
.setColor(Orange).setLineThickness(2)); // B color
// On body B draw an orange line segment around the green closest point.
geom.push_back(DecorativeLine(p_GQb-half_Lb, p_GQb+half_Lb)
.setColor(Orange));
geom.push_back(DecorativeFrame().setTransform(X_GEb)
.setColor(Orange*.9).setLineThickness(1).setScale(0.5)); // B color
geom.push_back(DecorativePoint(p_GQb)
.setColor(Green).setLineThickness(2)); // F color
// Show the contact frame in red.
geom.push_back(DecorativeFrame().setTransform(X_GC)
.setColor(Red));
}
} // namespace SimTK
| 10,794 |
377 | #pragma once
#ifndef DEBUG_SVGTESTPAGEHANDLER_H
#define DEBUG_SVGTESTPAGEHANDLER_H
//------------------------------------------------------------------------------
/**
@class Debug::SvgTestPageHandler
A HTTP test page handler to test SVG rendering functionality.
@copyright
(C) 2008 Radon Labs GmbH
(C) 2013-2020 Individual contributors, see AUTHORS file
*/
#include "http/httprequesthandler.h"
//------------------------------------------------------------------------------
namespace Debug
{
class SvgTestPageHandler : public Http::HttpRequestHandler
{
__DeclareClass(SvgTestPageHandler);
public:
/// constructor
SvgTestPageHandler();
/// handle a http request, the handler is expected to fill the content stream with response data
virtual void HandleRequest(const Ptr<Http::HttpRequest>& request);
private:
/// test shape rendering
bool TestShapeRendering(const Ptr<Http::HttpRequest>& request);
/// test line chart rendering
bool TestLineChartRendering(const Ptr<Http::HttpRequest>& request);
};
} // namespace Debug
//------------------------------------------------------------------------------
#endif
| 330 |
1,019 | /*
* Copyright 2016 The Cartographer 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.
*/
#include "cartographer_ros/time_conversion.h"
#include "cartographer/common/time.h"
#include "ros/ros.h"
namespace cartographer_ros {
::ros::Time ToRos(::cartographer::common::Time time) {
int64_t uts_timestamp = ::cartographer::common::ToUniversal(time);
int64_t ns_since_unix_epoch =
(uts_timestamp -
::cartographer::common::kUtsEpochOffsetFromUnixEpochInSeconds *
10000000ll) *
100ll;
::ros::Time ros_time;
ros_time.fromNSec(ns_since_unix_epoch);
return ros_time;
}
// TODO(pedrofernandez): Write test.
::cartographer::common::Time FromRos(const ::ros::Time& time) {
// The epoch of the ICU Universal Time Scale is "0001-01-01 00:00:00.0 +0000",
// exactly 719162 days before the Unix epoch.
return ::cartographer::common::FromUniversal(
(time.sec +
::cartographer::common::kUtsEpochOffsetFromUnixEpochInSeconds) *
10000000ll +
(time.nsec + 50) / 100); // + 50 to get the rounding correct.
}
} // namespace cartographer_ros
| 549 |
5,964 | <filename>third_party/WebKit/Source/core/plugins/testing/DictionaryPluginPlaceholder.h
// Copyright 2014 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 DictionaryPluginPlaceholder_h
#define DictionaryPluginPlaceholder_h
#include "core/html/shadow/PluginPlaceholderElement.h"
#include "core/plugins/PluginPlaceholder.h"
#include "core/testing/PluginPlaceholderOptions.h"
#include "wtf/text/WTFString.h"
namespace blink {
// Manipulates a plugin placeholder element based on a fixed dictionary given.
// Used for layout tests that examine the formatting of structured placeholders.
class DictionaryPluginPlaceholder : public NoBaseWillBeGarbageCollected<DictionaryPluginPlaceholder>, public PluginPlaceholder {
WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(DictionaryPluginPlaceholder);
public:
static PassOwnPtrWillBeRawPtr<DictionaryPluginPlaceholder> create(Document& document, const PluginPlaceholderOptions& options)
{
RefPtrWillBeRawPtr<PluginPlaceholderElement> placeholder = PluginPlaceholderElement::create(document);
if (options.hasMessage())
placeholder->setMessage(options.message());
if (options.hasCloseable())
placeholder->setIsCloseable(options.closeable());
return adoptPtrWillBeNoop(new DictionaryPluginPlaceholder(placeholder.release()));
}
#if !ENABLE(OILPAN)
virtual ~DictionaryPluginPlaceholder() override { }
#endif
DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_pluginPlaceholderElement); }
virtual void loadIntoContainer(ContainerNode& container) override
{
container.removeChildren();
container.appendChild(m_pluginPlaceholderElement, ASSERT_NO_EXCEPTION);
}
private:
DictionaryPluginPlaceholder(PassRefPtrWillBeRawPtr<PluginPlaceholderElement> element) : m_pluginPlaceholderElement(element) { }
RefPtrWillBeMember<PluginPlaceholderElement> m_pluginPlaceholderElement;
};
} // namespace blink
#endif // DictionaryPluginPlaceholder_h
| 636 |
488 | /*******************************************************************************
* Copyright 2012 University of Southern California
*
* 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.
*
* This code was developed by the Information Integration Group as part
* of the Karma project at the Information Sciences Institute of the
* University of Southern California. For more information, publications,
* and related projects, please see: http://www.isi.edu/integration
******************************************************************************/
package edu.isi.karma.model.serialization;
import java.util.List;
import com.hp.hpl.jena.rdf.model.Model;
import edu.isi.karma.rep.sources.Source;
public abstract class SourceLoader {
public abstract Source getSourceByUri(String uri);
public abstract void deleteSourceByUri(String uri);
public abstract List<Source> getSourcesAbstractInfo(Integer sourceLimit);
public abstract List<Source> getSourcesDetailedInfo(Integer sourceLimit);
public abstract Source importSourceFromJenaModel(Model model);
public Model getSourceJenaModel(String uri) {
Model m = Repository.Instance().getNamedModel(uri);
if (m == null)
return null;
return m;
}
}
| 442 |
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 CHROME_BROWSER_VR_ELEMENTS_LASER_H_
#define CHROME_BROWSER_VR_ELEMENTS_LASER_H_
#include "chrome/browser/vr/elements/ui_element.h"
#include "chrome/browser/vr/renderers/base_quad_renderer.h"
#include "ui/gfx/geometry/point3_f.h"
namespace vr {
struct Model;
class Laser : public UiElement {
public:
explicit Laser(Model* model);
~Laser() override;
class Renderer : public BaseQuadRenderer {
public:
Renderer();
~Renderer() override;
void Draw(float opacity, const gfx::Transform& view_proj_matrix);
private:
GLuint model_view_proj_matrix_handle_;
GLuint texture_unit_handle_;
GLuint texture_data_handle_;
GLuint color_handle_;
GLuint fade_point_handle_;
GLuint fade_end_handle_;
GLuint opacity_handle_;
DISALLOW_COPY_AND_ASSIGN(Renderer);
};
private:
void Render(UiElementRenderer* renderer,
const CameraModel& model) const final;
// Since the laser needs to render in response to model changes that occur
// after the scene update (i.e., after input), we cannot rely on the usual
// data binding flow since that would result in a frame of latency. Opacity
// changes, however, are not latency sensitive and are bound in the usual way
// (they also do not update due to input).
Model* model_;
DISALLOW_COPY_AND_ASSIGN(Laser);
};
} // namespace vr
#endif // CHROME_BROWSER_VR_ELEMENTS_LASER_H_
| 561 |
539 | # Copyright 2018-2021 Xanadu Quantum Technologies 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.
"""Contains transforms and helpers functions for decomposing arbitrary unitary
operations into elementary gates.
"""
import pennylane as qml
from pennylane import math
def _convert_to_su2(U):
r"""Convert a 2x2 unitary matrix to :math:`SU(2)`.
Args:
U (array[complex]): A matrix, presumed to be :math:`2 \times 2` and unitary.
Returns:
array[complex]: A :math:`2 \times 2` matrix in :math:`SU(2)` that is
equivalent to U up to a global phase.
"""
# Compute the determinant
det = U[0, 0] * U[1, 1] - U[0, 1] * U[1, 0]
exp_angle = -1j * math.cast_like(math.angle(det), 1j) / 2
return U * math.exp(exp_angle)
def zyz_decomposition(U, wire):
r"""Recover the decomposition of a single-qubit matrix :math:`U` in terms of
elementary operations.
Diagonal operations can be converted to a single :class:`.RZ` gate, while non-diagonal
operations will be converted to a :class:`.Rot` gate that implements the original operation
up to a global phase in the form :math:`RZ(\omega) RY(\theta) RZ(\phi)`.
.. warning::
When used with ``jax.jit``, all unitaries will be converted to :class:`.Rot` gates,
including those that are diagonal.
Args:
U (tensor): A 2 x 2 unitary matrix.
wire (Union[Wires, Sequence[int] or int]): The wire on which to apply the operation.
Returns:
list[qml.Operation]: A ``Rot`` gate on the specified wire that implements ``U``
up to a global phase, or an equivalent ``RZ`` gate if ``U`` is diagonal.
**Example**
Suppose we would like to apply the following unitary operation:
.. code-block:: python3
U = np.array([
[-0.28829348-0.78829734j, 0.30364367+0.45085995j],
[ 0.53396245-0.10177564j, 0.76279558-0.35024096j]
])
For PennyLane devices that cannot natively implement ``QubitUnitary``, we
can instead recover a ``Rot`` gate that implements the same operation, up
to a global phase:
>>> decomp = zyz_decomposition(U, 0)
>>> decomp
[Rot(-0.24209529417800013, 1.14938178234275, 1.7330581433950871, wires=[0])]
"""
U = _convert_to_su2(U)
# If the value of U is not abstract, we can include a conditional statement
# that will check if the off-diagonal elements are 0; if so, just use one RZ
if not math.is_abstract(U):
if math.allclose(U[0, 1], 0.0):
return [qml.RZ(2 * math.angle(U[1, 1]), wires=wire)]
# Derive theta from the off-diagonal element. Clip to ensure valid arcsin input
element = math.clip(math.abs(U[0, 1]), 0, 1)
theta = 2 * math.arcsin(element)
# Compute phi and omega from the angles of the top row; use atan2 to keep
# the angle within -np.pi and np.pi, and add very small values to avoid the
# undefined case of 0/0. We add a smaller value to the imaginary part than
# the real part because it is imag / real in the definition of atan2.
angle_U00 = math.arctan2(math.imag(U[0, 0]) + 1e-128, math.real(U[0, 0]) + 1e-64)
angle_U10 = math.arctan2(math.imag(U[1, 0]) + 1e-128, math.real(U[1, 0]) + 1e-64)
phi = -angle_U10 - angle_U00
omega = angle_U10 - angle_U00
return [qml.Rot(phi, theta, omega, wires=wire)]
| 1,436 |
377 | #include "Exception.h"
MPFD::Exception::Exception(const std::string& error) {
Error = error;
}
MPFD::Exception::Exception(const MPFD::Exception& orig) {
if (&orig != this) {
Error = orig.Error;
}
}
const std::string& MPFD::Exception::GetError() const {
return Error;
} | 110 |
8,805 | {
"name": "react-native-geolocation",
"version": "2.0.2",
"summary": "React Native Geolocation Module for iOS and Android",
"license": "MIT",
"authors": "React Native Community",
"homepage": "https://github.com/react-native-community/react-native-geolocation#README.md",
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/react-native-community/react-native-geolocation.git",
"tag": "2.0.2"
},
"source_files": "ios/**/*.{h,m}",
"dependencies": {
"React": [
]
}
}
| 216 |
345 | <gh_stars>100-1000
import tensorflow as tf
import sonnet as snt
# from sonnet.python.modules.base import AbstractModule
# from sonnet.python.modules.basic import Linear as snt.Linear
# from sonnet.python.modules.gated_rnn import LSTM as snt.LSTM
# from sonnet.python.modules.basic_rnn import DeepRNN as snt.DeepRNN
# from sonnet.python.modules.basic import BatchApply as snt.BatchApply
def swich(inputs):
return inputs * tf.nn.sigmoid(inputs)
def Linear(name, output_size):
initializers = {"w": tf.truncated_normal_initializer(stddev=0.1),
"b": tf.constant_initializer(value=0.1)}
regularizers = {"w": tf.contrib.layers.l2_regularizer(scale=0.1),
"b": tf.contrib.layers.l2_regularizer(scale=0.1)}
return snt.Linear(output_size,
initializers=initializers,
regularizers=regularizers,
name=name)
# def build_common_network(inputs):
# """common network
# :param inputs: [Time, Batch, state_size]
# :return: [Time, Batch, hidden_size]
# """
# # build rnn
# batch_size = inputs.get_shape().as_list()[1]
# l1 = snt..LSTM(128, name='rnn_first')
# l2 = snt..LSTM(64, name='rnn_second')
# l3 = snt..LSTM(32, name='rnn_third')
# rnn = snt..DeepRNN([l1, l2, l3])
# initial_state = rnn.initial_state(batch_size)
# # looping
# output_sequence, final_state = tf.nn.dynamic_rnn(
# rnn, inputs, initial_state=initial_state, time_major=True)
# return output_sequence
def build_common_network(inputs):
"""common network
:param inputs: [Time, Batch, state_size]
:return: [Time, Batch, hidden_size]
"""
# build rnn
batch_size = inputs.get_shape().as_list()[1]
l1 = snt.LSTM(64, name='rnn_first')
l2 = snt.LSTM(32, name='rnn_second')
rnn = snt.DeepRNN([l1, l2])
initial_state = rnn.initial_state(batch_size)
# looping
output_sequence, final_state = tf.nn.dynamic_rnn(
rnn, inputs, initial_state=initial_state, time_major=True)
return output_sequence
class ActorNet(snt.AbstractModule):
"""actor network
"""
def __init__(self, name='Actor'):
super().__init__(name=name)
def _build(self, output_size, inputs):
# loop net -> [Time, Batch, hidden_size]
net = build_common_network(inputs) # rnn output (-1, 1)
# linear net
net = snt.BatchApply(Linear('input_layer', 64))(net)
net = swich(net)
net = snt.BatchApply(Linear('output_layer', output_size))(net)
return tf.nn.softmax(net) # [Time, Batch, output_size]
def get_regularization(self):
return self.get_variables(tf.GraphKeys.REGULARIZATION_LOSSES)
class CriticNet(snt.AbstractModule):
"""critic network
"""
def __init__(self, name='critic'):
super().__init__(name=name)
def _build(self, inputs):
# loop net -> [Time, Batch, hidden_size]
net = build_common_network(inputs) # range (-1, 1)
# linear net
net = snt.BatchApply(Linear('input_layer', 64))(net)
net = swich(net)
net = snt.BatchApply(Linear('output_layer', 1))(net)
net = tf.squeeze(net, axis=2)
# net = tf.nn.tanh(net)
return tf.reduce_mean(net, axis=1) # [Time]
def get_regularization(self):
return self.get_variables(tf.GraphKeys.REGULARIZATION_LOSSES) | 1,533 |
1,414 | /*---------------------------------------------------------------------------
//
// 3 Band EQ :)
//
// EQ.H - Header file for 3 band EQ
//
// (c) <NAME> / Etanza Systems / 2K6
//
// Shouts / Loves / Moans = etanza at lycos dot co dot uk
//
// This work is hereby placed in the public domain for all purposes, including
// use in commercial applications.
//
// The author assumes NO RESPONSIBILITY for any problems caused by the use of
// this software.
//
//----------------------------------------------------------------------------*/
#ifndef __EQ3BAND__
#define __EQ3BAND__
/* ------------
//| Structures |
// ------------*/
typedef struct {
/* Filter #1 (Low band) */
double lf; /* Frequency */
double f1p0; /* Poles ... */
double f1p1;
double f1p2;
double f1p3;
/* Filter #2 (High band) */
double hf; /* Frequency */
double f2p0; /* Poles ... */
double f2p1;
double f2p2;
double f2p3;
/* Sample history buffer */
double sdm1; /* Sample data minus 1 */
double sdm2; /* 2 */
double sdm3; /* 3 */
/* Gain Controls */
double lg; /* low gain */
double mg; /* mid gain */
double hg; /* high gain */
} EQSTATE;
/* ---------
//| Exports |
// ---------*/
extern void init_3band_state(EQSTATE * es, int lowfreq, int highfreq,
int mixfreq);
extern double do_3band(EQSTATE * es, int sample);
#endif /* #ifndef __EQ3BAND__ */
| 623 |
315 | package no.nordicsemi.android.mesh.transport;
import no.nordicsemi.android.mesh.opcodes.ConfigMessageOpCodes;
/**
* Creates the ConfigDefaultTtlGet message.
*/
@SuppressWarnings("unused")
public class ConfigDefaultTtlGet extends ConfigMessage {
private static final String TAG = ConfigDefaultTtlGet.class.getSimpleName();
private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_DEFAULT_TTL_GET;
/**
* Constructs ConfigDefaultTtlGet message.
*/
public ConfigDefaultTtlGet() {
assembleMessageParameters();
}
@Override
public int getOpCode() {
return OP_CODE;
}
@Override
void assembleMessageParameters() {
//Do nothing as ConfigNodeReset message does not have parameters
}
}
| 270 |
1,503 | <filename>greykite/tests/sklearn/uncertainty/test_base_uncertainty_model.py
import pandas as pd
import pytest
from greykite.sklearn.uncertainty.base_uncertainty_model import BaseUncertaintyModel
from greykite.sklearn.uncertainty.uncertainty_methods import UncertaintyMethodEnum
@pytest.fixture
def uncertainty_dict():
uncertainty_dict = dict(
uncertainty_method=UncertaintyMethodEnum.simple_conditional_residuals.name,
params=dict()
)
return uncertainty_dict
def test_init(uncertainty_dict):
model = BaseUncertaintyModel(
uncertainty_dict=uncertainty_dict,
a=1,
b="2"
)
assert model .uncertainty_dict == uncertainty_dict
assert model.a == 1
assert model.b == "2"
assert model.uncertainty_method is None
assert model.params is None
assert model.train_df is None
assert model.uncertainty_model is None
assert model.pred_df is None
def test_check_input():
model = BaseUncertaintyModel(uncertainty_dict=None)
model._check_input()
assert model.uncertainty_dict == {}
def test_fit():
model = BaseUncertaintyModel(
uncertainty_dict={}
)
model.fit(train_df=pd.DataFrame({}))
assert model.train_df is not None
| 466 |
348 | {"nom":"Podensac","circ":"9ème circonscription","dpt":"Gironde","inscrits":1975,"abs":1002,"votants":973,"blancs":10,"nuls":5,"exp":958,"res":[{"nuance":"MDM","nom":"Mme <NAME>","voix":296},{"nuance":"SOC","nom":"M. <NAME>","voix":187},{"nuance":"FI","nom":"<NAME>","voix":153},{"nuance":"FN","nom":"Mme <NAME>","voix":140},{"nuance":"LR","nom":"M. <NAME>","voix":83},{"nuance":"ECO","nom":"M. <NAME>","voix":35},{"nuance":"DLF","nom":"M. <NAME>","voix":22},{"nuance":"COM","nom":"Mme <NAME>","voix":16},{"nuance":"EXG","nom":"M. <NAME>","voix":10},{"nuance":"DIV","nom":"Mme <NAME>","voix":8},{"nuance":"DIV","nom":"M. <NAME>","voix":7},{"nuance":"DVG","nom":"M. <NAME>","voix":1},{"nuance":"ECO","nom":"M. <NAME>","voix":0}]} | 299 |
909 | public class InstanceMethod {
public boolean <caret>foo(int i) {
return i == 0;
}
public void test() {
foo(1)
}
} | 52 |
850 | <gh_stars>100-1000
import unittest
from .utils import adjust, cleanse_java, cleanse_python, TranspileTestCase
class AdjustTests(unittest.TestCase):
def assertEqualOutput(self, actual, expected):
self.assertEqual(adjust(actual), adjust(expected))
def test_adjust(self):
"Test input can be stripped of leading spaces."
self.assertEqual("""for i in range(0, 10):
print('hello, world')
print('Done.')
""", adjust("""
for i in range(0, 10):
print('hello, world')
print('Done.')
"""))
def test_adjust_no_leading_space(self):
self.assertEqual("""for i in range(0, 10):
print('hello, world')
print('Done.')
""", adjust("""for i in range(0, 10):
print('hello, world')
print('Done.')
"""))
class AssertCodeExecutionTests(TranspileTestCase):
@unittest.expectedFailure
def test_fail_unexpected_exception(self):
self.assertCodeExecution("""
raise ValueError
""")
def test_allow_expected_exception(self):
self.assertCodeExecution("""
raise ValueError
""", exits_early=True)
@unittest.expectedFailure
def test_fail_missing_expected_exception(self):
self.assertCodeExecution("""
print('Done.')
""", exits_early=True)
class JavaNormalizationTests(unittest.TestCase):
def assertNormalized(self, actual, expected):
self.assertEqual(cleanse_java(adjust(actual), None), adjust(expected))
def test_no_exception(self):
self.assertNormalized(
"""
Hello, world.
""",
"""
Hello, world.
"""
)
def test_exception_in_clinit(self):
self.assertNormalized(
"""
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: IndexError: list index out of range
at org.python.types.List.__getitem__(List.java:100)
at org.python.types.List.__getitem__(List.java:85)
at python.test.<clinit>(test.py:2)
""",
"""
### EXCEPTION ###
IndexError: list index out of range
test.py:2
"""
)
def test_exception_in_module_init(self):
self.assertNormalized(
"""
Exception in thread "main" NameError: name 'y' is not defined
at org.python.types.Module.__getattribute__(Module.java:32)
at python.example.__init__.module$import(example.py:2)
at python.example.__init__.main(example.py)
""",
"""
### EXCEPTION ###
NameError: name 'y' is not defined
example.py:2
"""
)
def test_exception_in_clinit_after_output(self):
self.assertNormalized(
"""
Hello, world.
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: IndexError: list index out of range
at org.python.types.List.__getitem__(List.java:100)
at org.python.types.List.__getitem__(List.java:85)
at python.test.<clinit>(test.py:2)
""",
"""
Hello, world.
### EXCEPTION ###
IndexError: list index out of range
test.py:2
"""
)
def test_exception_in_clinit_after_output_windows(self):
self.assertNormalized(
"""
Hello, world.
java.lang.ExceptionInInitializerError
Caused by: IndexError: list index out of range
at org.python.types.List.__getitem__(List.java:100)
at org.python.types.List.__getitem__(List.java:85)
at python.test.<clinit>(test.py:2)
""",
"""
Hello, world.
### EXCEPTION ###
IndexError: list index out of range
test.py:2
"""
)
def test_exception_in_clinit_after_output_testdaemon(self):
self.assertNormalized(
"""
False
True
Exception in thread "main" java.lang.ExceptionInInitializerError
\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
\tat java.lang.reflect.Method.invoke(Method.java:497)
\tat python.testdaemon.TestDaemon.main(TestDaemon.java:66)
Caused by: KeyError: 'c'
at org.python.types.Dict.__getitem__(Dict.java:142)
at python.test.__init__.<clinit>(test.py:4)
... 5 more
""",
"""
False
True
### EXCEPTION ###
KeyError: 'c'
test.py:4
"""
)
def test_exception_in_method(self):
self.assertNormalized(
"""
Exception in thread "main" IndexError: list index out of range
at org.python.types.List.__getitem__(List.java:100)
at org.python.types.List.__getitem__(List.java:85)
at python.test.main(test.py:3)
""",
"""
### EXCEPTION ###
IndexError: list index out of range
test.py:3
"""
)
def test_exception_in_method_windows(self):
self.assertNormalized(
"""
IndexError: list index out of range
at org.python.types.List.__getitem__(List.java:100)
at org.python.types.List.__getitem__(List.java:85)
at python.test.main(test.py:3)
""",
"""
### EXCEPTION ###
IndexError: list index out of range
test.py:3
"""
)
def test_exception_in_method_after_output(self):
self.assertNormalized(
"""
Hello, world.
Exception in thread "main" IndexError: list index out of range
at org.python.types.List.__getitem__(List.java:100)
at org.python.types.List.__getitem__(List.java:85)
at python.test.main(test.py:3)
""",
"""
Hello, world.
### EXCEPTION ###
IndexError: list index out of range
test.py:3
"""
)
def test_exception_in_method_after_output_windows(self):
self.assertNormalized(
"""
Hello, world.
IndexError: list index out of range
at org.python.types.List.__getitem__(List.java:100)
at org.python.types.List.__getitem__(List.java:85)
at python.test.main(test.py:3)
""",
"""
Hello, world.
### EXCEPTION ###
IndexError: list index out of range
test.py:3
"""
)
def test_exception_in_constructor(self):
self.assertNormalized(
"""
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: UnboundLocalError: local variable 'x' referenced before assignment
at python.example.Foo.__init__(example.py:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.python.types.Method.invoke(Method.java:66)
at python.example.Foo.<init>(example.py)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.python.types.Constructor.invoke(Constructor.java:25)
at python.example.<clinit>(example.py:51)
""",
"""
### EXCEPTION ###
UnboundLocalError: local variable 'x' referenced before assignment
example.py:51
example.py:44
"""
)
def test_memory_reference(self):
self.assertNormalized(
"""
Class is <class 'com.example.MyClass'>
Method is <native function com.example.MyClass.method>
Method from instance is <bound native method com.example.MyClass.method of <Native class com.example.MyClass object at 0x1eb19f4e>>
Hello from the instance!
Done.
""", # noqa
"""
Class is <class 'com.example.MyClass'>
Method is <native function com.example.MyClass.method>
Method from instance is <bound native method com.example.MyClass.method of <Native class com.example.MyClass object at 0xXXXXXXXX>>
Hello from the instance!
Done.
""" # noqa
)
class PythonNormalizationTests(unittest.TestCase):
def assertNormalized(self, actual, expected):
self.assertEqual(cleanse_python(adjust(actual), None), adjust(expected))
def test_no_exception(self):
self.assertNormalized(
"""
Hello, world.
""",
"""
Hello, world.
"""
)
def test_exception(self):
self.assertNormalized(
"""
Traceback (most recent call last):
File "test.py", line 3, in <module>
print(x & y)
TypeError: unsupported operand type(s) for &: 'float' and 'bool'
""",
"""
### EXCEPTION ###
TypeError: unsupported operand type(s) for &: 'float' and 'bool'
test.py:3
"""
)
def test_exception_with_other_text(self):
self.assertNormalized(
"""
Hello, world.
Traceback (most recent call last):
File "test.py", line 3, in <module>
print(x & y)
TypeError: unsupported operand type(s) for &: 'float' and 'bool'
""",
"""
Hello, world.
### EXCEPTION ###
TypeError: unsupported operand type(s) for &: 'float' and 'bool'
test.py:3
"""
)
def test_memory_reference(self):
self.assertNormalized(
"""
Class is <class 'com.example.MyClass'>
Method is <native function com.example.MyClass.method>
Method from instance is <bound native method com.example.MyClass.method of <Native class com.example.MyClass object at 0x1eb19f4e>>
Hello from the instance!
Done.
""", # noqa
"""
Class is <class 'com.example.MyClass'>
Method is <native function com.example.MyClass.method>
Method from instance is <bound native method com.example.MyClass.method of <Native class com.example.MyClass object at 0xXXXXXXXX>>
Hello from the instance!
Done.
""" # noqa
)
class JavaBootstrapTests(TranspileTestCase):
def test_java_code(self):
"You can supply Java code and use it from within Python"
self.assertJavaExecution(
"""
from com.example import MyClass
obj = MyClass()
obj.doStuff()
print("Done.")
""",
java={
'com/example/MyClass': """
package com.example;
public class MyClass {
public void doStuff() {
System.out.println("Hello from Java");
}
}
"""
},
out="""
Hello from Java
Done.
""",
)
| 6,264 |
364 | <reponame>mbw-ahc/hapi-fhir
package ca.uhn.fhir.rest.api;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2021 Smile CDR, 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.
* #L%
*/
import ca.uhn.fhir.context.api.BundleInclusionRule;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* This interface should be considered experimental and will likely change in future releases of HAPI. Use with caution!
*/
public interface IVersionSpecificBundleFactory {
void addResourcesToBundle(List<IBaseResource> theResult, BundleTypeEnum theBundleType, String theServerBase, BundleInclusionRule theBundleInclusionRule, Set<Include> theIncludes);
void addRootPropertiesToBundle(String theId, @Nonnull BundleLinks theBundleLinks, Integer theTotalResults, IPrimitiveType<Date> theLastUpdated);
IBaseResource getResourceBundle();
/**
* @deprecated This was deprecated in HAPI FHIR 4.1.0 as it provides duplicate functionality to the {@link #addRootPropertiesToBundle(String, BundleLinks, Integer, IPrimitiveType<Date>)}
* and {@link #addResourcesToBundle(List, BundleTypeEnum, String, BundleInclusionRule, Set)} methods
*/
@Deprecated
default void initializeBundleFromResourceList(String theAuthor, List<? extends IBaseResource> theResult, String theServerBase, String theCompleteUrl, int theTotalResults, BundleTypeEnum theBundleType) {
addTotalResultsToBundle(theResult.size(), theBundleType);
addResourcesToBundle(new ArrayList<>(theResult), theBundleType, null, null, null);
}
void initializeWithBundleResource(IBaseResource theResource);
List<IBaseResource> toListOfResources();
void addTotalResultsToBundle(Integer theTotalResults, BundleTypeEnum theBundleType);
}
| 762 |
4,036 | package typeaccesses;
public class Arrays {
String[] ss;
java.util.List<String>[] sls;
} | 34 |
30,023 | <filename>homeassistant/components/uscis/__init__.py
"""The uscis component."""
| 28 |
1,247 | package org.seckill.api.service;
import org.seckill.entity.Goods;
import java.io.Serializable;
import java.util.List;
/**
*
* @author heng
* @date 2017/1/7
*/
public interface GoodsService {
/**
* @param goodsId
* @param bytes
*/
void uploadGoodsPhoto(long goodsId, byte[] bytes);
/**
* @param goods
* @param bytes
*/
void addGoods(Goods goods, byte[] bytes);
List<Goods> list();
Goods getById(Serializable goodsId);
}
| 192 |
14,668 | {
"name": "options_ui with chrome_style in manifest v3",
"description": "Tests that specifying chrome_style=true is invalid for manifest v3",
"version": "1",
"manifest_version": 3,
"options_ui": {
"page": "options.html",
"chrome_style": true
}
}
| 95 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Saint-Aigulin","circ":"4ème circonscription","dpt":"Charente-Maritime","inscrits":1578,"abs":887,"votants":691,"blancs":48,"nuls":24,"exp":619,"res":[{"nuance":"LR","nom":"<NAME>","voix":350},{"nuance":"REM","nom":"<NAME>","voix":269}]} | 115 |
553 | package com.muses.taoshop.item.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
/**
* <pre>
* 商品品类
* </pre>
* @author nicky
* @version 1.00.00
* <pre>
* 修改记录
* 修改后版本: 修改人: 修改日期: 2018.06.09 21:49 修改内容:
* </pre>
*/
@Data
public class ItemCategory {
/**
* 商品品类id
*/
private Long id;
/**
* 商品品类名称
*/
private String categoryName;
/**
* 上级id
*/
private Long sjid;
/**
* 上次修改时间
*/
@JSONField(format ="yyyy-MM-dd HH:mm:ss")
private Date lastModifyTime;
/**
* 创建时间
*/
@JSONField(format ="yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 子菜单
*/
private List<ItemCategory> subCategorys;
} | 577 |
677 | <reponame>InfiniteSynthesis/lynx-native
#ifndef LYNX_LEPUS_MATH_API_H_
#define LYNX_LEPUS_MATH_API_H_
#include <time.h>
namespace lepus {
Value Sin(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(sin(arg->number_));
}
Value Acos(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(acos(arg->number_));
}
Value Asin(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(asin(arg->number_));
}
Value Abs(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(fabs(arg->number_));
}
Value Atan(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(atan(arg->number_));
}
Value Ceil(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(ceil(arg->number_));
}
Value Cos(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(cos(arg->number_));
}
Value Exp(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(exp(arg->number_));
}
Value Floor(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(floor(arg->number_));
}
Value Log(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(log(arg->number_));
}
Value Max(Context* context) {
Value* arg1 = context->GetParam(1);
Value* arg2 = context->GetParam(2);
if(arg1->type_ != Value_Number||arg2->type_ != Value_Number){
return Value();
}
return Value(fmax(arg1->number_, arg2->number_));
}
Value Min(Context* context) {
Value* arg1 = context->GetParam(1);
Value* arg2 = context->GetParam(2);
if(arg1->type_ != Value_Number||arg2->type_ != Value_Number){
return Value();
}
return Value(fmin(arg1->number_, arg2->number_));
}
Value Pow(Context* context) {
Value* arg1 = context->GetParam(1);
Value* arg2 = context->GetParam(2);
if(arg1->type_ != Value_Number||arg2->type_ != Value_Number){
return Value();
}
return Value(pow(arg1->number_, arg2->number_));
}
Value Random(Context* context) {
static bool seeded = false;
if (!seeded) {
seeded = true;
srand(static_cast<unsigned int>(time(NULL)));
}
return Value((float)rand()/RAND_MAX);
}
Value Round(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(round(arg->number_));
}
Value Sqrt(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(sqrt(arg->number_));
}
Value Tan(Context* context) {
Value* arg = context->GetParam(1);
if(arg->type_ != Value_Number){
return Value();
}
return Value(tan(arg->number_));
}
void RegisterMathAPI(Context* ctx) {
Dictonary* table = lynx_new Dictonary;
RegisterTableFunction(ctx, table, "sin", &Sin);
RegisterTableFunction(ctx, table, "abs", &Abs);
RegisterTableFunction(ctx, table, "acos", &Acos);
RegisterTableFunction(ctx, table, "atan", &Atan);
RegisterTableFunction(ctx, table, "asin", &Asin);
RegisterTableFunction(ctx, table, "ceil", &Ceil);
RegisterTableFunction(ctx, table, "cos", &Cos);
RegisterTableFunction(ctx, table, "exp", &Exp);
RegisterTableFunction(ctx, table, "floor", &Floor);
RegisterTableFunction(ctx, table, "log", &Log);
RegisterTableFunction(ctx, table, "max", &Max);
RegisterTableFunction(ctx, table, "min", &Min);
RegisterTableFunction(ctx, table, "pow", &Pow);
RegisterTableFunction(ctx, table, "random", &Random);
RegisterTableFunction(ctx, table, "round", &Round);
RegisterTableFunction(ctx, table, "sqrt", &Sqrt);
RegisterTableFunction(ctx, table, "tan", &Tan);
RegisterFunctionTable(ctx, "Math", table);
}
}
#endif
| 2,356 |
337 | <filename>challenges/platformids.py
platforms = {
"UA": "usaco.org",
"CC": "codechef.com",
"EOL":"e-olimp.com",
"CH24": "ch24.org",
"HR": "hackerrank.com",
"HE": "hackerearth.com",
"ICPC": "icfpcontest.org",
"GCJ": "google.com/codejam",
"DE24": "deadline24.pl",
"IOI": "stats.ioinformatics.org",
"PE": "projecteuler.net",
"SN": "contests.snarknews.info",
"CG": "codingame.com",
"CF": "codeforces.com",
"ELY": "e-olymp.com",
"DMOJ": "dmoj.ca",
"MARA": "marathon24.com",
"IPSC": "ipsc.ksp.sk",
"UVA": "uva.onlinejudge.org",
"OPEN": "opener.itransition.com",
"HSIN": "hsin.hr/coci",
"CFT": "ctftime.org",
"KA": "kaggle.com",
"TC": "topcoder.com",
"FBHC": "facebook.com/hackercup"
} | 368 |
1,444 |
package mage.cards.d;
import mage.abilities.Ability;
import mage.abilities.dynamicvalue.common.ManacostVariableValue;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.DamageTargetControllerEffect;
import mage.abilities.effects.common.DestroyTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.ComparisonType;
import mage.filter.common.FilterArtifactPermanent;
import mage.filter.predicate.mageobject.ManaValuePredicate;
import mage.game.Game;
import mage.target.common.TargetArtifactPermanent;
import mage.target.targetadjustment.TargetAdjuster;
import java.util.UUID;
/**
* @author LoneFox
*/
public final class Detonate extends CardImpl {
public Detonate(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{X}{R}");
// Destroy target artifact with converted mana cost X. It can't be regenerated. Detonate deals X damage to that artifact's controller.
this.getSpellAbility().addEffect(new DestroyTargetEffect(true));
this.getSpellAbility().addTarget(new TargetArtifactPermanent(new FilterArtifactPermanent("artifact with mana value X")));
Effect effect = new DamageTargetControllerEffect(ManacostVariableValue.REGULAR);
effect.setText("{this} deals X damage to that artifact's controller");
this.getSpellAbility().addEffect(effect);
this.getSpellAbility().setTargetAdjuster(DetonateAdjuster.instance);
}
private Detonate(final Detonate card) {
super(card);
}
@Override
public Detonate copy() {
return new Detonate(this);
}
}
enum DetonateAdjuster implements TargetAdjuster {
instance;
@Override
public void adjustTargets(Ability ability, Game game) {
ability.getTargets().clear();
int xValue = ability.getManaCostsToPay().getX();
FilterArtifactPermanent filter = new FilterArtifactPermanent("artifact with mana value X");
filter.add(new ManaValuePredicate(ComparisonType.EQUAL_TO, xValue));
ability.addTarget(new TargetArtifactPermanent(filter));
}
} | 719 |
846 | <filename>components/dynamic-icon/component.json<gh_stars>100-1000
{
"component": "dynamic-icon",
"status": "prod",
"display-name": "Dynamic Icon",
"classKey": "DynamicIcon",
"SLDS-component-path": "/components/dynamic-icon",
"site-stories": [
{
"heading": "Ellie",
"path": "/__examples__/ellie.jsx"
},
{
"heading": "Eq",
"path": "/__examples__/eq.jsx"
},
{
"heading": "Score",
"path": "/__examples__/score.jsx"
},
{
"heading": "Strength",
"path": "/__examples__/strength.jsx"
},
{
"heading": "Trend",
"path": "/__examples__/trend.jsx"
},
{
"heading": "Typing",
"path": "/__examples__/typing.jsx"
},
{
"heading": "Waffle",
"path": "/__examples__/waffle.jsx"
}
],
"url-slug": "dynamic-icon"
}
| 372 |
5,169 | <gh_stars>1000+
{
"name": "BecmPod",
"version": "0.1.0",
"summary": "BecmPod.",
"description": "Pod Becm",
"homepage": "https://github.com/grupobecm/BecmPod.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"vadue": "<EMAIL>"
},
"source": {
"git": "https://github.com/grupobecm/BecmPod.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "10.0"
},
"source_files": "BecmPod/Classes/**/*",
"pushed_with_swift_version": "3.0"
}
| 238 |
1,042 | /*
* Copyright (c) scott.cgi All Rights Reserved.
*
* This source code belongs to project Mojoc, which is a pure C Game Engine hosted on GitHub.
* The Mojoc Game Engine is licensed under the MIT License, and will continue to be iterated with coding passion.
*
* License : https://github.com/scottcgi/Mojoc/blob/master/LICENSE
* GitHub : https://github.com/scottcgi/Mojoc
* CodeStyle: https://github.com/scottcgi/Mojoc/blob/master/Docs/CodeStyle.md
*
* Since : 2013-1-24
* Update : 2019-1-18
* Author : scott.cgi
*/
#include "Engine/Toolkit/Platform/Log.h"
#include "Engine/Toolkit/Math/Math.h"
/**
* Test polygon contains 2D point(x, y).
*
* first — foreach vector(preX - curX, preY - curY) of polygon
* second — check the point's y on the y area of vector
* third — cross product between vector(x - curX, y - curY) and vector(preX - curX, preY - curY)
* fourth — get the result is (x - curX) * (preY - curY) - (y - curY) * (preX - curX) = 0
* then —
*
* if result zero means point on the vector
* if result positive means point on the right of vector
* if result negative means point on the left of vector
*/
#define TestPolygonXY(polygon, x, y, pointOnRight, pointOnLeft) \
float* points = polygon->data; \
int preIndex = polygon->length - 2; \
\
for (int i = 0; i < polygon->length; i += 2) \
{ \
float curY = points[i + 1]; \
float preY = points[preIndex + 1]; \
\
if ((curY < y && preY >= y) || (preY < y && curY >= y)) \
{ \
float curX = points[i]; \
\
if (curX + (y - curY) / (preY - curY) * (points[preIndex] - curX) <= x) \
{ \
pointOnRight; \
} \
else \
{ \
pointOnLeft; \
} \
} \
\
preIndex = i; \
} \
static bool TestPolygonPoint(Array(float)* polygon, float x, float y)
{
bool inside = false;
TestPolygonXY
(
polygon,
x,
y,
// point on the right of polygon vector
inside = !inside,
);
return inside;
}
static bool TestPolygonAB(Array(float)* polygonA, Array(float)* polygonB)
{
bool inside = false;
for (int i = 0; i < polygonA->length; i += 2)
{
float x = AArray_Get(polygonA, i, float);
float y = AArray_Get(polygonA, i + 1, float);
TestPolygonXY
(
polygonB,
x,
y,
// point on the right of polygon vector
inside = !inside,
);
if (inside)
{
return true;
}
}
return inside;
}
static bool TestPolygonPolygon(Array(float)* polygonA, Array(float)* polygonB)
{
return TestPolygonAB(polygonA, polygonB) || TestPolygonAB(polygonB, polygonA);
}
static bool TestPolygonABStrict(Array(float)* polygonA, Array(float)* polygonB)
{
int leftCount = 0;
int rightCount = 0;
for (int i = 0; i < polygonA->length; i += 2)
{
float x = AArray_Get(polygonA, i, float);
float y = AArray_Get(polygonA, i + 1, float);
TestPolygonXY
(
polygonB,
x,
y,
// count point on the right of polygon vector
++rightCount,
// count point on the left of polygon vector
++leftCount
);
if (rightCount % 2 != 0)
{
return true;
}
}
return rightCount != 0 && leftCount == rightCount;
}
static bool TestPolygonPolygonStrict(Array(float)* polygonA, Array(float)* polygonB)
{
return TestPolygonABStrict(polygonA, polygonB) || TestPolygonABStrict(polygonB, polygonA);
}
static bool TestLineAB(Array(float)* lineA, Array(float)* lineB)
{
bool flags[2] = {false, false};
for (int i = 0; i < lineA->length; i += 2)
{
float x = AArray_Get(lineA, i, float);
float y = AArray_Get(lineA, i + 1, float);
TestPolygonXY
(
lineB,
x,
y,
// flag point on the right of line vector
flags[(unsigned int) i >> 1] = true,
// flag point on the left of line vector
flags[(unsigned int) i >> 1] = true
);
}
// test lineA two points both sides of lineB
return flags[0] && flags[1];
}
static bool TestLineLine(Array(float)* lineA, Array(float)* lineB)
{
return TestLineAB(lineA, lineB) || TestLineAB(lineB, lineA);
}
static void RotatePoints(Array(float)* pointArr, float angle, Array(float)* outRotatedPointArr)
{
ALog_A
(
outRotatedPointArr->length >= pointArr->length,
"AMath RotatePoints2 outRotatedPointArr length must larger than pointArr."
);
float cos = AMath_Cos(angle);
float sin = AMath_Sin(angle);
float* arr1 = (float*) pointArr->data;
float* arr2 = (float*) outRotatedPointArr->data;
for (int i = 0; i < pointArr->length; i += 2)
{
float x = arr1[i];
float y = arr1[i + 1];
arr2[i] = x * cos - y * sin;
arr2[i + 1] = x * sin + y * cos;
}
}
struct AMath AMath[1] =
{{
TestPolygonPoint,
TestPolygonAB,
TestPolygonPolygon,
TestPolygonABStrict,
TestPolygonPolygonStrict,
TestLineAB,
TestLineLine,
RotatePoints,
}};
| 3,891 |
1,491 | import unittest
import os
import mock
import torchtext
from seq2seq.dataset import SourceField, TargetField
from seq2seq.trainer import SupervisedTrainer
class TestSupervisedTrainer(unittest.TestCase):
def setUp(self):
test_path = os.path.dirname(os.path.realpath(__file__))
src = SourceField()
tgt = TargetField()
self.dataset = torchtext.data.TabularDataset(
path=os.path.join(test_path, 'data/eng-fra.txt'), format='tsv',
fields=[('src', src), ('tgt', tgt)],
)
src.build_vocab(self.dataset)
tgt.build_vocab(self.dataset)
@mock.patch('seq2seq.trainer.SupervisedTrainer._train_batch', return_value=0)
@mock.patch('seq2seq.util.checkpoint.Checkpoint.save')
def test_batch_num_when_resuming(self, mock_checkpoint, mock_func):
mock_model = mock.Mock()
mock_optim = mock.Mock()
trainer = SupervisedTrainer(batch_size=16)
trainer.optimizer = mock_optim
n_epoches = 1
start_epoch = 1
steps_per_epoch = 7
step = 3
trainer._train_epoches(self.dataset, mock_model, n_epoches, start_epoch, step)
self.assertEqual(steps_per_epoch - step, mock_func.call_count)
@mock.patch('seq2seq.trainer.SupervisedTrainer._train_batch', return_value=0)
@mock.patch('seq2seq.util.checkpoint.Checkpoint.save')
def test_resume_from_multiple_of_epoches(self, mock_checkpoint, mock_func):
mock_model = mock.Mock()
mock_optim = mock.Mock()
trainer = SupervisedTrainer(batch_size=16)
trainer.optimizer = mock_optim
n_epoches = 1
start_epoch = 1
step = 7
trainer._train_epoches(self.dataset, mock_model, n_epoches, start_epoch, step)
if __name__ == '__main__':
unittest.main()
| 810 |
658 | #include <stdint.h>
#include <stddef.h>
#include <tinf/tinf.h>
__attribute__((noreturn))
void entry(uint8_t *compressed_stage2, size_t stage2_size, uint8_t boot_drive, int pxe) {
// The decompressor should decompress compressed_stage2 to address 0x8000.
uint8_t *dest = (uint8_t *)0x8000;
tinf_gzip_uncompress(dest, compressed_stage2, stage2_size);
asm volatile (
"movl $0x7c00, %%esp\n\t"
"xorl %%ebp, %%ebp\n\t"
"pushl %1\n\t"
"pushl %0\n\t"
"pushl $0\n\t"
"pushl $0x8000\n\t"
"ret\n\t"
:
: "r" ((uint32_t)boot_drive), "r" (pxe)
: "memory"
);
__builtin_unreachable();
}
| 361 |
1,681 | # -*- coding: utf-8 -*-
"""
=============================
Using describe to evaluate the integrity of your visualization
=============================
The downside to using dimensionality reduction to visualize your data is that
some variance will likely be removed. To help get a sense for the integrity of your low
dimensional visualizations, we built the `describe` function, which computes
the covariance (samples by samples) of both the raw and reduced datasets, and
plots their correlation.
"""
# Code source: <NAME>
# License: MIT
# import
import hypertools as hyp
import numpy as np
# load example data
geo = hyp.load('weights_sample')
data = geo.get_data()
# plot
hyp.describe(data)
| 181 |
342 | /*
* Copyright 2009,2015-2016 BitMover, 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.
*/
#include "../sccs.h"
#ifndef WIN32
private void
reject(void)
{
fprintf(stderr, "_startmenu: not supported on this platform.\n");
exit(1);
}
int
__startmenu_generic(void)
{
reject();
return (0);
}
void *
__startmenu_generic_ptr(void)
{
reject();
return (0);
}
#else
#include <shlobj.h>
/*
* List of start menu items
*
* This list should never shrink (because the uninstall function will
* attempt to remove each one in turn.)
*
* When a release decides to remove a menu item, switch the enabled
* field to 0 and the menu item will not be created by install.
*/
private struct smenu {
char *menuname;
char *target;
char *icon;
char *cmd;
char *wdenv;
int enabled;
} menulist[] = {
{
.menuname = "BitKeeper",
.target = "http://bitkeeper.com/start",
.icon = "%s/bk.ico",
.cmd = "",
.wdenv = "HOMEPATH",
.enabled = 1
},
{
.menuname = "BitKeeper Documentation",
.target = "%s/bkg.exe",
.icon = "%s/bk.ico",
.cmd = "helptool",
.wdenv = 0,
.enabled = 1
},
/* things from bk-7.0-alpha to delete */
{
.menuname = "../BitKeeper",
.target = "%s/bk.exe",
.icon = "%s/bk.ico",
.cmd = "explorer",
.wdenv = "HOMEPATH",
.enabled = 0
},
{
.menuname = "../BitKeeper Documentation",
.target = "%s/bk.exe",
.icon = "%s/bk.ico",
.cmd = "helptool",
.wdenv = 0,
.enabled = 0
},
{
.menuname = 0
}
};
char *
bkmenupath(u32 user, int create, int isthere)
{
LPITEMIDLIST id;
int flag;
char *mpath;
char pmenupath[MAX_PATH];
if (user) {
flag = CSIDL_PROGRAMS;
} else {
flag = CSIDL_COMMON_PROGRAMS;
}
unless (SHGetSpecialFolderLocation(NULL, flag, &id) == S_OK) {
fprintf(stderr, "_startmenu: could not find your %s menu.\n",
user ? "user start" : "start");
return (0);
}
/* API fills a buffer of minimum Windows MAX_PATH size (260) */
unless (SHGetPathFromIDList(id, pmenupath)) {
return (0);
}
mpath = aprintf("%s/BitKeeper", pmenupath);
localName2bkName(mpath, mpath);
if (create && !exists(mpath) && mkdirp(mpath)) {
fprintf(stderr, "_startmenu: could not create %s\n", mpath);
free(mpath);
return (0);
}
if (isthere && !exists(mpath)) {
free(mpath);
return (0);
}
return (mpath);
}
int
startmenu_set(u32 user, char *menupath, char *target, char *icon, char *args,
char *cwd)
{
int ret = 0;
char *tpath = 0, *linkpath = 0;
IShellLink *sl = 0;
IPersistFile *pf = 0;
WCHAR wpath[MAX_PATH];
CoInitialize(NULL);
unless (tpath = bkmenupath(user, 1, 1)) return (1);
linkpath = aprintf("%s/%s.lnk", tpath, menupath);
if (exists(linkpath)) {
fprintf(stderr, "_startmenu: %s already exists\n", linkpath);
ret = 1;
goto out;
}
if (CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
&IID_IShellLink, (LPVOID *) &sl) != S_OK) {
fprintf(stderr,
"_startmenu: CoCreateInstance fails, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
if (sl->lpVtbl->QueryInterface(sl,
&IID_IPersistFile, (void **)&pf) != S_OK) {
fprintf(stderr,
"_startmenu: QueryInterface failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
sl->lpVtbl->SetPath(sl, target);
sl->lpVtbl->SetArguments(sl, args);
sl->lpVtbl->SetIconLocation(sl, icon, 0);
if (cwd) sl->lpVtbl->SetWorkingDirectory(sl, cwd);
MultiByteToWideChar(CP_ACP, 0, linkpath, -1, wpath, MAX_PATH);
if (pf->lpVtbl->Save(pf, wpath, TRUE) != S_OK) {
fprintf(stderr,
"_startmenu: Save failed, error %ld\n", GetLastError());
ret = 1;
goto out;
}
out:
if (pf) pf->lpVtbl->Release(pf);
if (sl) sl->lpVtbl->Release(sl);
if (tpath) free(tpath);
if (linkpath) free(linkpath);
CoUninitialize();
return (ret);
}
int
startmenu_get(u32 user, char *menu)
{
HRESULT res;
int idx, ret = 0;
char *tpath = 0, *linkpath = 0;
IShellLink *sl = 0;
IPersistFile *pf = 0;
WCHAR wpath[MAX_PATH];
char target[MAX_PATH];
char iconpath[MAX_PATH];
char args[MAX_PATH];
CoInitialize(NULL);
unless (tpath = bkmenupath(user, 0, 1)) return (1);
linkpath = aprintf("%s/%s.lnk", tpath, menu);
if (!exists(linkpath)) {
fprintf(stderr, "_startmenu: %s not found\n", linkpath);
ret = 1;
goto out;
}
if (CoCreateInstance(&CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, &IID_IShellLink, (LPVOID *) &sl) != S_OK) {
fprintf(stderr,
"_startmenu: CoCreateInstance failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
if (sl->lpVtbl->QueryInterface(sl,
&IID_IPersistFile, (void **)&pf) != S_OK) {
fprintf(stderr,
"_startmenu: QueryInterface failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
MultiByteToWideChar(CP_ACP, 0, linkpath, -1, wpath, MAX_PATH);
if (pf->lpVtbl->Load(pf, wpath, STGM_READ) != S_OK) {
fprintf(stderr, "_startmenu: Load failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
#if 0
res = sl->lpVtbl->Resolve(sl, 0, SLR_NO_UI);
if (res != S_OK) {
fprintf(stderr, "_startmenu: Resolve failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
#endif
/*
* Ugh... this will get the target if it's a file but not an URL
* if the target is an URL then GetPath() returns S_FALSE and a
* null string. Sigh.
*/
res = sl->lpVtbl->GetPath(sl, target, MAX_PATH, NULL, SLGP_UNCPRIORITY);
if (res == S_FALSE) {
printf("\"%s\" points at a URL which we cannot extract\n", menu);
/* not an error, no need to set ret */
goto out;
} else if (res != S_OK) {
fprintf(stderr, "_startmenu: GetPath failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
if (sl->lpVtbl->GetIconLocation(sl, iconpath, MAX_PATH, &idx) != S_OK){
fprintf(stderr,
"_startmenu: GetIconLocation failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
if (sl->lpVtbl->GetArguments(sl, args, MAX_PATH) != S_OK) {
fprintf(stderr,
"_startmenu: GetArguments failed, error %ld\n",
GetLastError());
ret = 1;
goto out;
}
if (user) printf("-u ");
if (iconpath && strlen(iconpath)) printf("-i\"%s\" ", iconpath);
printf("\"%s\" ", menu);
printf("\"%s\" ", target);
if (strlen(args)) printf("\"%s\"", args);
printf("\n");
out:
if (pf) pf->lpVtbl->Release(pf);
if (sl) sl->lpVtbl->Release(sl);
if (tpath) free(tpath);
if (linkpath) free(linkpath);
CoUninitialize();
return (ret);
}
int
startmenu_rm(u32 user, char *menu)
{
int ret = 0;
char *tpath = 0, *linkpath = 0;
CoInitialize(NULL);
assert(menu);
unless (tpath = bkmenupath(user, 0, 1)) {
ret = 1;
goto out;
}
linkpath = aprintf("%s/%s.lnk", tpath, menu);
if (exists(linkpath) && unlink(linkpath)) {
fprintf(stderr,
"_startmenu: %s: unlink failed, error %ld\n",
linkpath, GetLastError());
ret = 1;
}
out:
if (linkpath) free(linkpath);
if (tpath) free(tpath);
CoUninitialize();
return (ret);
}
int
startmenu_list(u32 user, char *menu)
{
char **files;
int i;
int ret = 0;
char *tpath = 0, *dirpath = 0, *linkpath = 0;
CoInitialize(NULL);
unless (tpath = bkmenupath(user, 0, 1)) return (1);
if (menu) {
dirpath = aprintf("%s/%s", tpath, menu);
} else {
dirpath = strdup(tpath);
}
linkpath = aprintf("%s.lnk", dirpath);
if (exists(linkpath)) {
printf("%s\n", linkpath);
ret = 1;
goto out;
} else if (!exists(dirpath)) {
fprintf(stderr, "_startmenu: %s: not found\n", dirpath);
ret = 1;
goto out;
} if (!isdir(dirpath)) {
fprintf(stderr,
"_startmenu: %s: exists but is not a directory\n",
dirpath);
ret = 1;
goto out;
}
files = getdir(dirpath);
EACH (files) {
printf("%s\n", files[i]);
}
freeLines(files, free);
out:
if (tpath) free(tpath);
if (dirpath) free(dirpath);
if (linkpath) free(linkpath);
CoUninitialize();
return (ret);
}
void
startmenu_install(char *dest)
{
struct smenu *smp;
char *target, *icon, *t, *home = 0;
char buf[MAXPATH];
/*
* This hack is necessary because our MSYS mashes
* HOMEPATH to be \
*
* If, in a command prompt window:
*
* echo %HOMEPATH%
* bk sh -c "echo $HOMEPATH"
*
* yield similar results then it may be OK to remove.
*/
if (SUCCEEDED(SHGetFolderPath(0, CSIDL_PROFILE, 0, 0, buf))) {
home = buf;
}
for (smp = menulist; smp->menuname; smp++) {
unless (smp->enabled) continue;
target = aprintf(smp->target, dest);
icon = aprintf(smp->icon, dest);
if (smp->wdenv && streq(smp->wdenv, "HOMEPATH")) {
t = home;
} else if (smp->wdenv) {
t = getenv(smp->wdenv);
} else {
t = 0;
}
startmenu_set(0, smp->menuname, target, icon, smp->cmd, t);
free(icon);
free(target);
}
}
void
startmenu_uninstall(FILE *log)
{
int i;
char *bkmenu;
struct smenu *smp;
char buf[MAXPATH];
/* Make win32 layer be quiet and not retry */
win32flags_clear(WIN32_RETRY | WIN32_NOISY);
/*
* Remove *all* Start Menu shortcuts
* (including any legacy items)
*/
for (i = 0; i < 2; i++) {
/*
* Remove everything in our list
* (there may be items outside our BitKeeper
* subdir)
*/
for (smp = menulist; smp->menuname; smp++) {
startmenu_rm(i, smp->menuname);
}
/*
* Prior to 7.0 alpha, and now, things go in a
* BitKeeper subdir; nuke it -- should get anything
* missed by the above loop (which will be a bunch
* of things from bk versions <= 6)
*/
unless (bkmenu = bkmenupath(i, 0, 1)) continue;
if (!isdir(bkmenu) || !rmtree(bkmenu)) goto next;
/* rmtree failed; try renaming and deleting on reboot */
sprintf(buf, "%s.old%d", bkmenu, getpid());
if (rename(bkmenu, buf)) {
/* hmm, rename failed too */
fprintf(stderr,
"Could not delete or rename BitKeeper "
"start menu directory:\n%s\n",
bkmenu);
if (log) fprintf(log,
"Could not delete or rename BitKeeper "
"start menu directory:\n%s\n",
bkmenu);
goto next;
}
fprintf(stderr,
"Could not delete BitKeeper start menus:\n"
"\t%s\nWill be deleted on next reboot.\n",
buf);
if (log) fprintf(log,
"Could not delete BitKeeper start menus:\n"
"\t%s\nWill be deleted on next reboot.\n",
buf);
delete_onReboot(buf);
next: free(bkmenu);
}
}
#endif /* WIN32 */
| 4,739 |
648 | <filename>spec/hl7.fhir.core/1.0.2/package/SearchParameter-Condition-onset-info.json
{"resourceType":"SearchParameter","id":"Condition-onset-info","url":"http://hl7.org/fhir/SearchParameter/Condition-onset-info","name":"onset-info","publisher":"Health Level Seven International (Patient Care)","contact":[{"telecom":[{"system":"other","value":"http://hl7.org/fhir"}]},{"telecom":[{"system":"other","value":"http://www.hl7.org/Special/committees/patientcare/index.cfm"}]}],"date":"2015-10-24T07:41:03+11:00","code":"onset-info","base":"Condition","type":"string","description":"Other onsets (boolean, age, range, string)","xpath":"f:Condition/f:onsetDateTime | f:Condition/f:onsetAge | f:Condition/f:onsetPeriod | f:Condition/f:onsetRange | f:Condition/f:onsetString","xpathUsage":"normal"} | 260 |
452 | <reponame>umautobots/pytorch_wavelets
# coding: utf-8
h0, g0, h1, g1 = level1('near_sym_a', True)
h0 = np.array([[0, -.05, 0.25, 0.5, 0.25, -0.05, 0]]).T
g1 = np.array([[0 -.05, -.25, .6, -.25, -.05, 0]]).T
h0 *= 1/np.sqrt(np.sum(h0**2))
h1 *= 1/np.sqrt(np.sum(h1**2))
g0 *= 1/np.sqrt(np.sum(g0**2))
g1 *= 1/np.sqrt(np.sum(g1**2))
h0a = np.concatenate((h0, [[0]]), axis=0)
h1a = np.concatenate(([[0]], h1), axis=0)
h0b = np.concatenate(([[0]], h0), axis=0)
h1b = np.concatenate((h1, [[0]]), axis=0)
g0a = np.concatenate(([[0]], g0), axis=0)
g1a = np.concatenate((g1, [[0]]), axis=0)
g0b = np.concatenate((g0, [[0]]), axis=0)
g1b = np.concatenate(([[0]], g1), axis=0)
np.savez('/scratch/fbc23/repos/fbcotter/pytorch_wavelets/pytorch_wavelets/dtcwt/data/near_sym_a2.npz', h0a=h0a, h1a=h1a, h0b=h0b, h1b=h1b, g0a=g0a, g1a=g1a, g0b=g0b,g1b=g1b)
| 502 |
778 | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: structural_mechanics_application/license.txt
//
// Main authors: <NAME>
//
#if !defined(KRATOS_UPDATED_LAGRANGIAN_H_INCLUDED )
#define KRATOS_UPDATED_LAGRANGIAN_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "custom_elements/base_solid_element.h"
#include "includes/variables.h"
#include "includes/constitutive_law.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class UpdatedLagrangian
* @ingroup StructuralMechanicsApplication
* @brief Updated Lagrangian element for 2D and 3D geometries.
* @details Implements an Updated Lagrangian definition for structural analysis. This works for arbitrary geometries in 2D and 3D
* @author <NAME>
* @author <NAME>
*/
class KRATOS_API(STRUCTURAL_MECHANICS_APPLICATION) UpdatedLagrangian
: public BaseSolidElement
{
public:
///@name Type Definitions
///@{
///Reference type definition for constitutive laws
typedef ConstitutiveLaw ConstitutiveLawType;
///Pointer type for constitutive laws
typedef ConstitutiveLawType::Pointer ConstitutiveLawPointerType;
///Type definition for integration methods
typedef GeometryData::IntegrationMethod IntegrationMethod;
/// The base element type
typedef BaseSolidElement BaseType;
/// The definition of the index type
typedef std::size_t IndexType;
/// The definition of the sizetype
typedef std::size_t SizeType;
/// Counted pointer of UpdatedLagrangian
KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION(UpdatedLagrangian);
///@}
///@name Life Cycle
///@{
/// Default constructor.
UpdatedLagrangian(IndexType NewId, GeometryType::Pointer pGeometry);
UpdatedLagrangian(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties);
// Copy constructor
UpdatedLagrangian(UpdatedLagrangian const& rOther)
:BaseType(rOther)
,mF0Computed(rOther.mF0Computed)
,mDetF0(rOther.mDetF0)
,mF0(rOther.mF0)
{};
/// Destructor.
~UpdatedLagrangian() override;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief Called to initialize the element.
* Must be called before any calculation is done
*/
void Initialize(const ProcessInfo& rCurrentProcessInfo) override;
/**
* @brief Called at the beginning of each solution step
* @param rCurrentProcessInfo the current process info instance
*/
void InitializeSolutionStep(const ProcessInfo& rCurrentProcessInfo) override;
/**
* @brief Called at the end of eahc solution step
* @param rCurrentProcessInfo the current process info instance
*/
void FinalizeSolutionStep(const ProcessInfo& rCurrentProcessInfo) override;
/**
* @brief It creates a new element pointer and clones the previous element data
* @param NewId the ID of the new element
* @param ThisNodes the nodes of the new element
* @param pProperties the properties assigned to the new element
* @return a Pointer to the new element
*/
Element::Pointer Clone (
IndexType NewId,
NodesArrayType const& rThisNodes
) const override;
/**
* @brief Creates a new element
* @param NewId The Id of the new created element
* @param pGeom The pointer to the geometry of the element
* @param pProperties The pointer to property
* @return The pointer to the created element
*/
Element::Pointer Create(
IndexType NewId,
GeometryType::Pointer pGeom,
PropertiesType::Pointer pProperties
) const override;
/**
* @brief Creates a new element
* @param NewId The Id of the new created element
* @param ThisNodes The array containing nodes
* @param pProperties The pointer to property
* @return The pointer to the created element
*/
Element::Pointer Create(
IndexType NewId,
NodesArrayType const& ThisNodes,
PropertiesType::Pointer pProperties
) const override;
/**
* @brief Calculate a boolean Variable on the Element Constitutive Law
* @param rVariable The variable we want to get
* @param rOutput The values obtained in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void CalculateOnIntegrationPoints(
const Variable<bool>& rVariable,
std::vector<bool>& rOutput,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Calculate a integer Variable on the Element Constitutive Law
* @param rVariable The variable we want to get
* @param rOutput The values obtained in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void CalculateOnIntegrationPoints(
const Variable<int>& rVariable,
std::vector<int>& rOutput,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Calculate a double Variable on the Element Constitutive Law
* @param rVariable The variable we want to get
* @param rOutput The values obtained in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void CalculateOnIntegrationPoints(
const Variable<double>& rVariable,
std::vector<double>& rOutput,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Calculate a 3 components array_1d on the Element Constitutive Law
* @param rVariable The variable we want to get
* @param rOutput The values obtained in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void CalculateOnIntegrationPoints(
const Variable<array_1d<double, 3>>& rVariable,
std::vector<array_1d<double, 3>>& rOutput,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Calculate a 6 components array_1d on the Element Constitutive Law
* @param rVariable The variable we want to get
* @param rOutput The values obtained in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void CalculateOnIntegrationPoints(
const Variable<array_1d<double, 6>>& rVariable,
std::vector<array_1d<double, 6>>& rOutput,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Calculate a Vector Variable on the Element Constitutive Law
* @param rVariable The variable we want to get
* @param rOutput The values obtained in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void CalculateOnIntegrationPoints(
const Variable<Vector>& rVariable,
std::vector<Vector>& rOutput,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Calculate a Matrix Variable on the Element Constitutive Law
* @param rVariable The variable we want to get
* @param rOutput The values obtained in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void CalculateOnIntegrationPoints(
const Variable<Matrix>& rVariable,
std::vector<Matrix>& rOutput,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Set a double Value on the Element Constitutive Law
* @param rVariable The variable we want to set
* @param rValues The values to set in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void SetValuesOnIntegrationPoints(
const Variable<double>& rVariable,
const std::vector<double>& rValues,
const ProcessInfo& rCurrentProcessInfo
) override;
/**
* @brief Set a Matrix Value on the Element Constitutive Law
* @param rVariable The variable we want to set
* @param rValues The values to set in the integration points
* @param rCurrentProcessInfo the current process info instance
*/
void SetValuesOnIntegrationPoints(
const Variable<Matrix>& rVariable,
const std::vector<Matrix>& rValues,
const ProcessInfo& rCurrentProcessInfo
) override;
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
std::stringstream buffer;
buffer << "Updated Lagrangian Solid Element #" << Id() << "\nConstitutive law: " << BaseType::mConstitutiveLawVector[0]->Info();
return buffer.str();
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << "Updated Lagrangian Solid Element #" << Id() << "\nConstitutive law: " << BaseType::mConstitutiveLawVector[0]->Info();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
pGetGeometry()->PrintData(rOStream);
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
/* Historical total elastic deformation measure */
bool mF0Computed; // To avoid computing more than once the historical total elastic deformation measure
std::vector<double> mDetF0; // The historical total elastic deformation measure determinant
std::vector<Matrix> mF0; // The historical total elastic deformation measure
///@}
///@name Protected Operators
///@{
UpdatedLagrangian() : BaseSolidElement()
{
}
/**
* @brief This method clones the element database
* @param rF0Computed To avoid computing more than once the historical total elastic deformation measure
* @param rDetF0 The historical total elastic deformation measure determinant
* @param rF0 The historical total elastic deformation measure
*/
void CloneUpdatedLagrangianDatabase(
const bool rF0Computed,
const std::vector<double>& rDetF0,
const std::vector<Matrix>& rF0
)
{
mF0Computed = rF0Computed;
mDetF0 = rDetF0;
mF0 = rF0;
}
/**
* Gives the StressMeasure used
*/
ConstitutiveLaw::StressMeasure GetStressMeasure() const override;
/**
* @brief It updates the historical database
* @param rThisKinematicVariables The kinematic variables to be calculated
* @param PointNumber The integration point considered
*/
void UpdateHistoricalDatabase(
KinematicVariables& rThisKinematicVariables,
const IndexType PointNumber
);
/**
* @brief This functions calculates both the RHS and the LHS
* @param rLeftHandSideMatrix The LHS
* @param rRightHandSideVector The RHS
* @param rCurrentProcessInfo The current process info instance
* @param CalculateStiffnessMatrixFlag The flag to set if compute the LHS
* @param CalculateResidualVectorFlag The flag to set if compute the RHS
*/
void CalculateAll(
MatrixType& rLeftHandSideMatrix,
VectorType& rRightHandSideVector,
const ProcessInfo& rCurrentProcessInfo,
const bool CalculateStiffnessMatrixFlag,
const bool CalculateResidualVectorFlag
) override;
/**
* @brief This functions updates the kinematics variables
* @param rThisKinematicVariables The kinematic variables to be calculated
* @param PointNumber The integration point considered
* @param rIntegrationMethod The integration method considered
*/
void CalculateKinematicVariables(
KinematicVariables& rThisKinematicVariables,
const IndexType PointNumber,
const GeometryType::IntegrationMethod& rIntegrationMethod
) override;
/**
* @brief This functions calculate the derivatives in the reference frame
* @param J0 The jacobian in the reference configuration
* @param InvJ0 The inverse of the jacobian in the reference configuration
* @param DN_DX The gradient derivative of the shape function
* @param PointNumber The id of the integration point considered
* @param ThisIntegrationMethod The integration method considered
* @return The determinant of the jacobian in the reference configuration
*/
double CalculateDerivativesOnReferenceConfiguration(
Matrix& J0,
Matrix& InvJ0,
Matrix& DN_DX,
const IndexType PointNumber,
IntegrationMethod ThisIntegrationMethod
) const override;
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
/**
* @brief This method computes the deformation matrix B
* @param rB The deformation matrix
* @param rDN_DX The gradient derivative of the shape function
* @param StrainSize The size of the Voigt notation stress vector
* @param PointNumber The integration point considered
*/
void CalculateB(
Matrix& rB,
const Matrix& rDN_DX,
const SizeType StrainSize,
const IndexType PointNumber
);
/**
* It returns the reference configuration deformation gradient determinant
* @param PointNumber The integration point considered
* @return The reference configuration deformation gradient determinant
*/
double ReferenceConfigurationDeformationGradientDeterminant(const IndexType PointNumber) const;
/**
* It returns the reference configuration deformation gradient
* @param PointNumber The integration point considered
* @return The reference configuration deformation gradient
*/
Matrix ReferenceConfigurationDeformationGradient(const IndexType PointNumber) const;
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
friend class Serializer;
// A private default constructor necessary for serialization
void save(Serializer& rSerializer) const override;
void load(Serializer& rSerializer) override;
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
/// Assignment operator.
//UpdatedLagrangian& operator=(const UpdatedLagrangian& rOther);
/// Copy constructor.
//UpdatedLagrangian(const UpdatedLagrangian& rOther);
///@}
}; // Class UpdatedLagrangian
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
} // namespace Kratos.
#endif // KRATOS_UPDATED_LAGRANGIAN_H_INCLUDED defined
| 5,549 |
1,405 | package com.lenovo.safecenter.HealthCheck;
public interface HealthCheckCallback {
void onFinished(int i);
void onOneItemProcess(HealthItemResult healthItemResult);
void onProgressChanged(int i);
void onResult(HealthItemResult healthItemResult);
void onScoreChanged(int i);
void onStarted(int i, int i2);
void onStatusChanged(int i);
void setProgressBarIndeterminate(boolean z);
}
| 136 |
1,350 | <reponame>Shashi-rk/azure-sdk-for-java<filename>sdk/avs/azure-resourcemanager-avs/src/main/java/com/azure/resourcemanager/avs/fluent/HcxEnterpriseSitesClient.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.avs.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.avs.fluent.models.HcxEnterpriseSiteInner;
/** An instance of this class provides access to all the operations defined in HcxEnterpriseSitesClient. */
public interface HcxEnterpriseSitesClient {
/**
* List HCX Enterprise Sites in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a paged list of HCX Enterprise Sites.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<HcxEnterpriseSiteInner> list(String resourceGroupName, String privateCloudName);
/**
* List HCX Enterprise Sites in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a paged list of HCX Enterprise Sites.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<HcxEnterpriseSiteInner> list(String resourceGroupName, String privateCloudName, Context context);
/**
* Get an HCX Enterprise Site by name in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an HCX Enterprise Site by name in a private cloud.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
HcxEnterpriseSiteInner get(String resourceGroupName, String privateCloudName, String hcxEnterpriseSiteName);
/**
* Get an HCX Enterprise Site by name in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an HCX Enterprise Site by name in a private cloud.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<HcxEnterpriseSiteInner> getWithResponse(
String resourceGroupName, String privateCloudName, String hcxEnterpriseSiteName, Context context);
/**
* Create or update an HCX Enterprise Site in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName The name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud.
* @param hcxEnterpriseSite The HCX Enterprise Site.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an HCX Enterprise Site resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
HcxEnterpriseSiteInner createOrUpdate(
String resourceGroupName,
String privateCloudName,
String hcxEnterpriseSiteName,
HcxEnterpriseSiteInner hcxEnterpriseSite);
/**
* Create or update an HCX Enterprise Site in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName The name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud.
* @param hcxEnterpriseSite The HCX Enterprise Site.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return an HCX Enterprise Site resource.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<HcxEnterpriseSiteInner> createOrUpdateWithResponse(
String resourceGroupName,
String privateCloudName,
String hcxEnterpriseSiteName,
HcxEnterpriseSiteInner hcxEnterpriseSite,
Context context);
/**
* Delete an HCX Enterprise Site in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String privateCloudName, String hcxEnterpriseSiteName);
/**
* Delete an HCX Enterprise Site in a private cloud.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> deleteWithResponse(
String resourceGroupName, String privateCloudName, String hcxEnterpriseSiteName, Context context);
}
| 2,406 |
2,255 | // Copyright (C) 2006-2010, Rapid7, Inc
// 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.
//
// * Neither the name of Rapid7, Inc nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 _VNCDLL_LOADER_INJECT_H
#define _VNCDLL_LOADER_INJECT_H
//===============================================================================================//
#include <Windows.h>
#define COMMANDLINE_LENGTH 1024
//===============================================================================================//
// Definition of ntdll!NtQueueApcThread
typedef DWORD(NTAPI * NTQUEUEAPCTHREAD)(HANDLE hThreadHandle, LPVOID lpApcRoutine, LPVOID lpApcRoutineContext, LPVOID lpApcStatusBlock, LPVOID lpApcReserved);
// Definitions used for running native x64 code from a wow64 process (see executex64.asm)
typedef BOOL(WINAPI * X64FUNCTION)(DWORD dwParameter);
typedef DWORD(WINAPI * EXECUTEX64)(X64FUNCTION pFunction, DWORD dwParameter);
//===============================================================================================//
// The context used for injection via migrate_via_apcthread
typedef struct _APCCONTEXT
{
union
{
LPVOID lpStartAddress;
BYTE bPadding1[8];
} s;
union
{
LPVOID lpParameter;
BYTE bPadding2[8];
} p;
BYTE bExecuted;
} APCCONTEXT, *LPAPCCONTEXT;
// The context used for injection via migrate_via_remotethread_wow64
typedef struct _WOW64CONTEXT
{
union
{
HANDLE hProcess;
BYTE bPadding2[8];
} h;
union
{
LPVOID lpStartAddress;
BYTE bPadding1[8];
} s;
union
{
LPVOID lpParameter;
BYTE bPadding2[8];
} p;
union
{
HANDLE hThread;
BYTE bPadding2[8];
} t;
} WOW64CONTEXT, *LPWOW64CONTEXT;
//===============================================================================================//
DWORD inject_via_apcthread(HANDLE hProcess, DWORD dwProcessID, DWORD dwDestinationArch, LPVOID lpStartAddress, LPVOID lpParameter);
DWORD inject_via_remotethread(HANDLE hProcess, DWORD dwDestinationArch, LPVOID lpStartAddress, LPVOID lpParameter);
DWORD inject_dll(DWORD dwPid, LPVOID lpDllBuffer, DWORD dwDllLenght, DWORD dwReflectiveOffset, LPVOID lpParam);
//===============================================================================================//
#endif
//===============================================================================================// | 1,267 |
348 | {"nom":"Serra-di-Ferro","circ":"2ème circonscription","dpt":"Corse-du-Sud","inscrits":514,"abs":145,"votants":369,"blancs":8,"nuls":0,"exp":361,"res":[{"nuance":"LR","nom":"<NAME>","voix":192},{"nuance":"REG","nom":"<NAME>","voix":169}]} | 97 |
7,194 | <gh_stars>1000+
{
"type": "none",
"comment": "Updating outdated fixtures now that makeStyles no longer supports functions.",
"packageName": "@fluentui/make-styles-webpack-loader",
"email": "<EMAIL>",
"dependentChangeType": "none"
}
| 80 |
454 | <filename>c/pahelix/toolkit/linear_rna/linear_rna/utils/energy_parameter.cpp
#include "utils/energy_parameter.h"
double g_lxc37 = 107.856;
int g_ml_intern37 = -90;
int g_ml_closing37 = 930;
int g_ml_base37 = 0;
int g_max_ninio = 300;
int g_ninio37 = 60;
int g_terminal_au37 = 50; // lhuang: outermost pair is AU or GU; also used in tetra_loop triloop
char g_triloops[241] =
"CAACG "
"GUUAC "
;
int g_triloop37[2] = {680, 690};
char g_tetraloops[281] =
"CAACGG "
"CCAAGG "
"CCACGG "
"CCCAGG "
"CCGAGG "
"CCGCGG "
"CCUAGG "
"CCUCGG "
"CUAAGG "
"CUACGG "
"CUCAGG "
"CUCCGG "
"CUGCGG "
"CUUAGG "
"CUUCGG "
"CUUUGG "
;
int g_tetraloop37[16] = {550, 330, 370, 340, 350, 360, 370, 250, 360, 280, 370, 270, 280, 350, 370, 370};
char g_hexaloops[361] =
"ACAGUACU "
"ACAGUGAU "
"ACAGUGCU "
"ACAGUGUU "
;
int g_hexaloop37[4] = { 280, 360, 290, 180};
int g_stack37[NBPAIRS+1][NBPAIRS+1] =
// CG GC GU UG AU UA NN
{{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, -240, -330, -210, -140, -210, -210, -140} /*CG*/
,{ VIE_INF, -330, -340, -250, -150, -220, -240, -150} /*GC*/
,{ VIE_INF, -210, -250, 130, -50, -140, -130, 130} /*GU*/
,{ VIE_INF, -140, -150, -50, 30, -60, -100, 30} /*UG*/
,{ VIE_INF, -210, -220, -140, -60, -110, -90, -60} /*AU*/
,{ VIE_INF, -210, -240, -130, -100, -90, -130, -90} /*UA*/
,{ VIE_INF, -140, -150, 130, 30, -60, -90, 130}}; /*NN*/
int g_hairpin37[31] =
{VIE_INF, VIE_INF, VIE_INF, 540, 560, 570, 540, 600, 550, 640,
650, 660, 670, 680, 690, 690, 700, 710, 710, 720,
720, 730, 730, 740, 740, 750, 750, 750, 760, 760, 770};
int g_bulge37[31] =
{VIE_INF, 380, 280, 320, 360, 400, 440, 460, 470, 480,
490, 500, 510, 520, 530, 540, 540, 550, 550, 560,
570, 570, 580, 580, 580, 590, 590, 600, 600, 600, 610};
int g_internal_loop37[31] =
{VIE_INF, VIE_INF, 100, 100, 110, 200, 200, 210, 230, 240,
250, 260, 270, 280, 290, 290, 300, 310, 310, 320,
330, 330, 340, 340, 350, 350, 350, 360, 360, 370, 370};
int g_mismatch_i37[NBPAIRS+1][5][5] =
{{{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
}
,{{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, -80, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, -100, 0, -100, 0}
,{ 0, 0, 0, 0, -60}
}
,{{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, -80, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, -100, 0, -100, 0}
,{ 0, 0, 0, 0, -60}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, -10, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -30, 70, -30, 70}
,{ 70, 70, 70, 70, 10}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, -10, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -30, 70, -30, 70}
,{ 70, 70, 70, 70, 10}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, -10, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -30, 70, -30, 70}
,{ 70, 70, 70, 70, 10}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, -10, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -30, 70, -30, 70}
,{ 70, 70, 70, 70, 10}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, -10, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -30, 70, -30, 70}
,{ 70, 70, 70, 70, 10}
}};
int g_mismatch_h37[NBPAIRS+1][5][5] =
{{{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
}
// lhuang: CG..
,{{ -80, -100, -110, -100, -80}
,{ -140, -150, -150, -140, -150}
,{ -80, -100, -110, -100, -80}
,{ -150, -230, -150, -240, -150}
,{ -100, -100, -140, -100, -210}
}
// lhuang: GC..
,{{ -50, -110, -70, -110, -50}
,{ -110, -110, -150, -130, -150}
,{ -50, -110, -70, -110, -50}
,{ -150, -250, -150, -220, -150}
,{ -100, -110, -100, -110, -160}
}
,{{ 20, 20, -20, -10, -20}
,{ 20, 20, -50, -30, -50}
,{ -10, -10, -20, -10, -20}
,{ -50, -100, -50, -110, -50}
,{ -10, -10, -30, -10, -100}
}
,{{ 0, -20, -10, -20, 0}
,{ -30, -50, -30, -60, -30}
,{ 0, -20, -10, -20, 0}
,{ -30, -90, -30, -110, -30}
,{ -10, -20, -10, -20, -90}
}
,{{ -10, -10, -20, -10, -20}
,{ -30, -30, -50, -30, -50}
,{ -10, -10, -20, -10, -20}
,{ -50, -120, -50, -110, -50}
,{ -10, -10, -30, -10, -120}
}
,{{ 0, -20, -10, -20, 0}
,{ -30, -50, -30, -50, -30}
,{ 0, -20, -10, -20, 0}
,{ -30, -150, -30, -150, -30}
,{ -10, -20, -10, -20, -90}
}
,{{ 20, 20, -10, -10, 0}
,{ 20, 20, -30, -30, -30}
,{ 0, -10, -10, -10, 0}
,{ -30, -90, -30, -110, -30}
,{ -10, -10, -10, -10, -90}
}};
int g_mismatch_m37[NBPAIRS+1][5][5] =
{{ /* NP.. */
{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
},
{ /* CG.. */
{ -50, -110, -50, -140, -70}
,{ -110, -110, -110, -160, -110}
,{ -70, -150, -70, -150, -100}
,{ -110, -130, -110, -140, -110}
,{ -50, -150, -50, -150, -70}
},
{ /* GC.. */
{ -80, -140, -80, -140, -100}
,{ -100, -150, -100, -140, -100}
,{ -110, -150, -110, -150, -140}
,{ -100, -140, -100, -160, -100}
,{ -80, -150, -80, -150, -120}
},
{ /* GU.. */
{ -50, -80, -50, -50, -50}
,{ -50, -100, -70, -50, -70}
,{ -60, -80, -60, -80, -60}
,{ -70, -110, -70, -80, -70}
,{ -50, -80, -50, -80, -50}
},
{ /* UG.. */
{ -30, -30, -60, -60, -60}
,{ -30, -30, -60, -60, -60}
,{ -70, -100, -70, -100, -80}
,{ -60, -80, -60, -80, -60}
,{ -60, -100, -70, -100, -60}
},
{ /* AU.. */
{ -50, -80, -50, -80, -50}
,{ -70, -100, -70, -110, -70}
,{ -60, -80, -60, -80, -60}
,{ -70, -110, -70, -120, -70}
,{ -50, -80, -50, -80, -50}
},
{ /* UA.. */
{ -60, -80, -60, -80, -60}
,{ -60, -80, -60, -80, -60}
,{ -70, -100, -70, -100, -80}
,{ -60, -80, -60, -80, -60}
,{ -70, -100, -70, -100, -80}
},
{ /* NN.. */
{ -30, -30, -50, -50, -50}
,{ -30, -30, -60, -50, -60}
,{ -60, -80, -60, -80, -60}
,{ -60, -80, -60, -80, -60}
,{ -50, -80, -50, -80, -50}
}};
int g_mismatch_1ni37[NBPAIRS+1][5][5] =
{{{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
}
,{{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
}
,{{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
}};
int g_mismatch_23i37[NBPAIRS+1][5][5] =
{{{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
}
,{{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, -50, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, -110, 0, -70, 0}
,{ 0, 0, 0, 0, -30}
}
,{{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, 0, 0, 0, 0}
,{ 0, -120, 0, -70, 0}
,{ 0, 0, 0, 0, -30}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -40, 70, 0, 70}
,{ 70, 70, 70, 70, 40}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 20, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -40, 70, 0, 70}
,{ 70, 70, 70, 70, 40}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -40, 70, 0, 70}
,{ 70, 70, 70, 70, 40}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 20, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -40, 70, 0, 70}
,{ 70, 70, 70, 70, 40}
}
,{{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, 70, 70, 70, 70}
,{ 70, -40, 70, 0, 70}
,{ 70, 70, 70, 70, 40}
}};
int g_mismatch_ext37[NBPAIRS+1][5][5] =
{{ /* NP.. */
{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
,{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}
},
{ /* CG.. */
{ -50, -110, -50, -140, -70}
,{ -110, -110, -110, -160, -110}
,{ -70, -150, -70, -150, -100}
,{ -110, -130, -110, -140, -110}
,{ -50, -150, -50, -150, -70}
},
{ /* GC.. */
{ -80, -140, -80, -140, -100}
,{ -100, -150, -100, -140, -100}
,{ -110, -150, -110, -150, -140}
,{ -100, -140, -100, -160, -100}
,{ -80, -150, -80, -150, -120}
},
{ /* GU.. */
{ -50, -80, -50, -50, -50}
,{ -50, -100, -70, -50, -70}
,{ -60, -80, -60, -80, -60}
,{ -70, -110, -70, -80, -70}
,{ -50, -80, -50, -80, -50}
},
{ /* UG.. */
{ -30, -30, -60, -60, -60}
,{ -30, -30, -60, -60, -60}
,{ -70, -100, -70, -100, -80}
,{ -60, -80, -60, -80, -60}
,{ -60, -100, -70, -100, -60}
},
{ /* AU.. */
{ -50, -80, -50, -80, -50}
,{ -70, -100, -70, -110, -70}
,{ -60, -80, -60, -80, -60}
,{ -70, -110, -70, -120, -70}
,{ -50, -80, -50, -80, -50}
},
{ /* UA.. */
{ -60, -80, -60, -80, -60}
,{ -60, -80, -60, -80, -60}
,{ -70, -100, -70, -100, -80}
,{ -60, -80, -60, -80, -60}
,{ -70, -100, -70, -100, -80}
},
{ /* NN.. */
{ -30, -30, -50, -50, -50}
,{ -30, -30, -60, -50, -60}
,{ -60, -80, -60, -80, -60}
,{ -60, -80, -60, -80, -60}
,{ -50, -80, -50, -80, -50}
}};
/* dangle5 */
int g_dangle5_37[NBPAIRS+1][5] =
{ /* N A C G U */
{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}, /* NP */
{ -10, -50, -30, -20, -10}, /* CG */
{ -0, -20, -30, -0, -0}, /* GC */
{ -20, -30, -30, -40, -20}, /* GU */
{ -10, -30, -10, -20, -20}, /* UG */
{ -20, -30, -30, -40, -20}, /* AU */
{ -10, -30, -10, -20, -20}, /* UA */
{ -0, -20, -10, -0, -0} /* NN */
};
/* dangle3 */
int g_dangle3_37[NBPAIRS+1][5] =
{ /* N A C G U */
{ VIE_INF, VIE_INF, VIE_INF, VIE_INF, VIE_INF}, /* NP */
{ -40, -110, -40, -130, -60}, /* CG */
{ -80, -170, -80, -170, -120}, /* GC */
{ -10, -70, -10, -70, -10}, /* GU */
{ -50, -80, -50, -80, -60}, /* UG */
{ -10, -70, -10, -70, -10}, /* AU */
{ -50, -80, -50, -80, -60}, /* UA */
{ -10, -70, -10, -70, -10} /* NN */
};
| 10,496 |
610 | <reponame>niunno/leanback-showcase
/*
* Copyright (C) 2017 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.support.v17.leanback.supportleanbackshowcase.app.room.viewmodel;
import android.app.Application;
import android.arch.core.util.Function;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.support.v17.leanback.supportleanbackshowcase.app.room.db.repo.VideosRepository;
import android.support.v17.leanback.supportleanbackshowcase.app.room.db.entity.CategoryEntity;
import android.support.v17.leanback.supportleanbackshowcase.app.room.db.entity.VideoEntity;
import java.util.List;
import javax.inject.Inject;
public class VideosViewModel extends AndroidViewModel {
// live data connect to database
private final LiveData<List<CategoryEntity>> mAllCategories;
private final LiveData<List<VideoEntity>> mSearchResults;
private final LiveData<VideoEntity> mVideoById;
private final LiveData<List<VideoEntity>> mAllVideosByCategory;
// mutable live data can be changed by ui controllers through setter
private final MutableLiveData<String> mQuery = new MutableLiveData<>();
private final MutableLiveData<Long> mVideoId = new MutableLiveData<>();
private final MutableLiveData<String> mVideoCategory = new MutableLiveData<>();
private final VideosRepository mRepository;
@Inject
public VideosViewModel(Application application, VideosRepository repository) {
super(application);
mRepository = repository;
mAllCategories = mRepository.getAllCategories();
mSearchResults = Transformations.switchMap(
mQuery, new Function<String, LiveData<List<VideoEntity>>>() {
@Override
public LiveData<List<VideoEntity>> apply(final String queryMessage) {
return mRepository.getSearchResult(queryMessage);
}
});
mVideoById = Transformations.switchMap(
mVideoId, new Function<Long, LiveData<VideoEntity>>() {
@Override
public LiveData<VideoEntity> apply(final Long videoId) {
return mRepository.getVideoById(videoId);
}
});
/**
* Using switch map function to react to the change of observed variable, the benefits of
* this mapping method is we don't have to re-create the live data every time.
*/
mAllVideosByCategory = Transformations.switchMap(mVideoCategory, new Function<String, LiveData<List<VideoEntity>>>() {
@Override
public LiveData<List<VideoEntity>> apply(String category) {
return mRepository.getVideosInSameCategoryLiveData(category);
}
});
}
public LiveData<List<VideoEntity>> getSearchResult() {
return mSearchResults;
}
public LiveData<VideoEntity> getVideoById() {
return mVideoById;
}
public LiveData<List<VideoEntity>> getVideosInSameCategory() {
return mAllVideosByCategory;
}
public LiveData<List<CategoryEntity>> getAllCategories() {
return mAllCategories;
}
public void setQueryMessage(String queryMessage) {
mQuery.setValue(queryMessage);
}
public void setVideoId(Long videoIdVal) {
mVideoId.setValue(videoIdVal);
}
public void setCategory(String category) {
mVideoCategory.setValue(category);
}
public void updateDatabase(VideoEntity video, String category, String value) {
mRepository.updateDatabase(video, category, value);
}
}
| 1,549 |
3,428 | {"id":"00937","group":"easy-ham-1","checksum":{"type":"MD5","value":"1442bfa30552275d60548860104339c3"},"text":"From <EMAIL> Wed Aug 28 10:51:16 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 43AC144155\n\tfor <jm@localhost>; Wed, 28 Aug 2002 05:51:15 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 28 Aug 2002 10:51:15 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g7S0T9Z03618 for <<EMAIL>>;\n Wed, 28 Aug 2002 01:29:09 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id D6E5A294220; Tue, 27 Aug 2002 17:21:09 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from mithral.com (watcher.mithral.com [204.153.244.1]) by\n xent.com (Postfix) with SMTP id 3F0BC294220 for <<EMAIL>>;\n Tue, 27 Aug 2002 17:20:25 -0700 (PDT)\nReceived: (qmail 10891 invoked by uid 1111); 28 Aug 2002 00:22:01 -0000\nFrom: \"<NAME>\" <<EMAIL>>\nTo: <NAME> <<EMAIL>>\nCc: <<EMAIL>>\nSubject: Re: DataPower announces XML-in-silicon\nIn-Reply-To: <<EMAIL>-<EMAIL>>\nMessage-Id: <<EMAIL>-<EMAIL>>\nMIME-Version: 1.0\nContent-Type: TEXT/PLAIN; charset=US-ASCII\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: [email protected]\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of Rohit Khare <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Tue, 27 Aug 2002 17:22:01 -0700 (PDT)\n\nOn Tue, 27 Aug 2002, <NAME> wrote:\n\n> DATAPOWER TECHNOLOGY ON Monday unveiled its network device designed\n> specifically to process XML data. Unlike competing solutions that\n> process XML data in software, DataPower's device processes the data in\n> hardware -- a technology achievement that provides greater performance,\n> according to company officials.\n\nNow, to do this, we all know they have to be cracking the strong crypto used\non all transaction in order to process them... So this has some preaty heavy\nimplications, unless it's just BS.\n\n> Kelly explained that converting data into XML increases the file size up\n> to 20 times. This, he said, makes processing the data very taxing on\n> application servers; DataPower believes an inline device is the best\n> alternative.\n\nOr.... you could just not bloat it 20x to begin with. Nah! (that was the\nwhole point of XML afterall, to sell more CPUs - much like Oracle's use of\nJava allows them to sell 3x more CPU licenses due to the performance hit)\n\n> In addition to the large file sizes, security is also of paramount\n> importance in the world of XML.\n>\n> \"Today's firewalls are designed to inspect HTTP traffic only,\" Kelly\n> said. \"A SOAP packet with XML will go straight through a firewall.\n> Firewalls are blind to XML today.\"\n\nAgain, see above... they _are_ claiming to decode the crypto...\n\n> \"Our XG3 execution core converts XML to machine code,\" said Kelly,\n\nMmmmmmmmmmm, machine code, never a good idea ;)\n\n- <NAME>. \"Duncan\" Beberg\n http://www.mithral.com/~beberg/\n <EMAIL>\n\n\n"} | 1,278 |
476 | #include <stdbool.h>
#include <stdio.h>
#include <xtables.h>
#include <linux/netfilter/xt_mark.h>
struct xt_mark_info {
unsigned long mark, mask;
uint8_t invert;
};
enum {
O_MARK = 0,
};
static void mark_mt_help(void)
{
printf(
"mark match options:\n"
"[!] --mark value[/mask] Match nfmark value with optional mask\n");
}
static const struct xt_option_entry mark_mt_opts[] = {
{.name = "mark", .id = O_MARK, .type = XTTYPE_MARKMASK32,
.flags = XTOPT_MAND | XTOPT_INVERT},
XTOPT_TABLEEND,
};
static void mark_mt_parse(struct xt_option_call *cb)
{
struct xt_mark_mtinfo1 *info = cb->data;
xtables_option_parse(cb);
if (cb->invert)
info->invert = true;
info->mark = cb->val.mark;
info->mask = cb->val.mask;
}
static void mark_parse(struct xt_option_call *cb)
{
struct xt_mark_info *markinfo = cb->data;
xtables_option_parse(cb);
if (cb->invert)
markinfo->invert = 1;
markinfo->mark = cb->val.mark;
markinfo->mask = cb->val.mask;
}
static void print_mark(unsigned int mark, unsigned int mask)
{
if (mask != 0xffffffffU)
printf(" 0x%x/0x%x", mark, mask);
else
printf(" 0x%x", mark);
}
static void
mark_mt_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_mark_mtinfo1 *info = (const void *)match->data;
printf(" mark match");
if (info->invert)
printf(" !");
print_mark(info->mark, info->mask);
}
static void
mark_print(const void *ip, const struct xt_entry_match *match, int numeric)
{
const struct xt_mark_info *info = (const void *)match->data;
printf(" MARK match");
if (info->invert)
printf(" !");
print_mark(info->mark, info->mask);
}
static void mark_mt_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_mark_mtinfo1 *info = (const void *)match->data;
if (info->invert)
printf(" !");
printf(" --mark");
print_mark(info->mark, info->mask);
}
static void
mark_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_mark_info *info = (const void *)match->data;
if (info->invert)
printf(" !");
printf(" --mark");
print_mark(info->mark, info->mask);
}
static struct xtables_match mark_mt_reg[] = {
{
.family = NFPROTO_UNSPEC,
.name = "mark",
.revision = 0,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_mark_info)),
.userspacesize = XT_ALIGN(sizeof(struct xt_mark_info)),
.help = mark_mt_help,
.print = mark_print,
.save = mark_save,
.x6_parse = mark_parse,
.x6_options = mark_mt_opts,
},
{
.version = XTABLES_VERSION,
.name = "mark",
.revision = 1,
.family = NFPROTO_UNSPEC,
.size = XT_ALIGN(sizeof(struct xt_mark_mtinfo1)),
.userspacesize = XT_ALIGN(sizeof(struct xt_mark_mtinfo1)),
.help = mark_mt_help,
.print = mark_mt_print,
.save = mark_mt_save,
.x6_parse = mark_mt_parse,
.x6_options = mark_mt_opts,
},
};
void _init(void)
{
xtables_register_matches(mark_mt_reg, ARRAY_SIZE(mark_mt_reg));
}
| 1,372 |
323 | <reponame>dparalen/libsolv
int read_installed_debian(struct repoinfo *cinfo);
void commit_transactionelement_debian(Pool *pool, Id type, Id p, FILE *fp);
| 54 |
379 | <filename>src/vcfprimers.cpp
/*
vcflib C++ library for parsing and manipulating VCF files
Copyright © 2010-2020 <NAME>
Copyright © 2020 <NAME>
This software is published under the MIT License. See the LICENSE file.
*/
#include "Variant.h"
#include "split.h"
#include "Fasta.h"
#include <getopt.h>
using namespace std;
using namespace vcflib;
void printSummary(char** argv) {
cerr << "usage: " << argv[0] << " [options] <vcf file>" << endl
<< endl
<< "For each VCF record, extract the flanking sequences, and write them to stdout as FASTA" << endl
<< "records suitable for alignment." << endl
<< "options:" << endl
<< " -f, --fasta-reference FASTA reference file to use to obtain primer sequences" << endl
<< " -l, --primer-length The length of the primer sequences on each side of the variant" << endl
<< endl
<< "This tool is intended for use in designing validation" << endl
<< "experiments. Primers extracted which would flank all of the alleles at multi-allelic" << endl
<< "sites. The name of the FASTA \"reads\" indicates the VCF record which they apply to." << endl
<< "The form is >CHROM_POS_LEFT for the 3' primer and >CHROM_POS_RIGHT for the 5' primer," << endl
<< "for example:" << endl
<< endl
<< ">20_233255_LEFT" << endl
<< "CCATTGTATATATAGACCATAATTTCTTTATCCAATCATCTGTTGATGGA" << endl
<< ">20_233255_RIGHT" << endl
<< "ACTCAGTTGATTCCATACCTTTGCCATCATGAATCATGTTGTAATAAACA" << endl
<< endl;
cerr << endl << "Type: transformation" << endl << endl;
exit(0);
}
int main(int argc, char** argv) {
int c;
string fastaRef;
int primerLength = 0;
if (argc == 1)
printSummary(argv);
while (true) {
static struct option long_options[] =
{
/* These options set a flag. */
//{"verbose", no_argument, &verbose_flag, 1},
{"help", no_argument, 0, 'h'},
{"fasta-reference", required_argument, 0, 'f'},
{"primer-length", required_argument, 0, 'l'},
//{"length", no_argument, &printLength, true},
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "hf:l:",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c)
{
case 0:
/* If this option set a flag, do nothing else now. */
if (long_options[option_index].flag != 0)
break;
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s", optarg);
printf ("\n");
break;
case 'f':
fastaRef = optarg;
break;
case 'l':
primerLength = atoi(optarg);
break;
case 'h':
printSummary(argv);
exit(0);
break;
case '?':
/* getopt_long already printed an error message. */
printSummary(argv);
exit(1);
break;
default:
abort ();
}
}
if (primerLength == 0) {
cerr << "a primer length must be specified" << endl;
exit(1);
}
if (fastaRef.empty()) {
cerr << "a FASTA reference sequence must be specified" << endl;
exit(1);
}
FastaReference ref;
ref.open(fastaRef);
VariantCallFile variantFile;
string inputFilename;
if (optind == argc - 1) {
inputFilename = argv[optind];
variantFile.open(inputFilename);
} else {
variantFile.open(std::cin);
}
if (!variantFile.is_open()) {
return 1;
}
Variant var(variantFile);
while (variantFile.getNextVariant(var)) {
// get the ref start and end positions
int refstart = var.position - 1; // convert to 0-based
int refend = var.position + var.ref.size() - 1;
string leftprimer = ref.getSubSequence(var.sequenceName, refstart - primerLength, primerLength);
string rightprimer = ref.getSubSequence(var.sequenceName, refend, primerLength);
//cout << var << endl;
cout << ">" << var.sequenceName << "_" << var.position << "_LEFT" << endl
<< leftprimer << endl
<< ">" << var.sequenceName << "_" << var.position << "_RIGHT" << endl
<< rightprimer << endl;
}
return 0;
}
| 2,183 |
4,973 | # set empty string to the third column to use the first section title to document title
latex_documents = [
('index', 'test.tex', '', 'Sphinx', 'report')
]
| 50 |
464 | <reponame>mmvanheusden/ForgeHax
package dev.fiki.forgehax.main.mods.player;
import dev.fiki.forgehax.api.cmd.flag.EnumFlag;
import dev.fiki.forgehax.api.cmd.settings.BooleanSetting;
import dev.fiki.forgehax.api.cmd.settings.IntegerSetting;
import dev.fiki.forgehax.api.event.SubscribeListener;
import dev.fiki.forgehax.api.events.game.PreGameTickEvent;
import dev.fiki.forgehax.api.extension.GeneralEx;
import dev.fiki.forgehax.api.extension.ItemEx;
import dev.fiki.forgehax.api.extension.LocalPlayerEx;
import dev.fiki.forgehax.api.mod.Category;
import dev.fiki.forgehax.api.mod.ToggleMod;
import dev.fiki.forgehax.api.modloader.RegisterMod;
import dev.fiki.forgehax.api.modloader.di.Injected;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import net.minecraft.inventory.container.ClickType;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import java.util.Comparator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import static dev.fiki.forgehax.main.Common.*;
@RegisterMod(
name = "AutoHotbarReplenish",
description = "Will replenish tools or block stacks automatically",
category = Category.PLAYER,
flags = EnumFlag.EXECUTOR_MAIN_THREAD
)
@RequiredArgsConstructor
@ExtensionMethod({GeneralEx.class, ItemEx.class, LocalPlayerEx.class})
public class AutoHotbarReplenish extends ToggleMod {
@Injected
private final Executor main;
@Injected("async")
private final Executor async;
private final IntegerSetting durability_threshold = newIntegerSetting()
.name("durability-threshold")
.description("Will auto replace tools when they hit this damage value")
.defaultTo(5)
.min(0)
.max((int) Short.MAX_VALUE)
.build();
private final IntegerSetting stack_threshold = newIntegerSetting()
.name("stack-threshold")
.description("Will replace stacks when there only remains this many")
.defaultTo(10)
.min(1)
.max((int) Short.MAX_VALUE)
.build();
private final IntegerSetting tick_delay = newIntegerSetting()
.name("tick-delay")
.description("Number of ticks between each window click packet. 0 will have no limit and a negative value will send n packets per tick")
.defaultTo(1)
.build();
private final BooleanSetting noGui = newBooleanSetting()
.name("no-gui")
.description("Don't run when a gui is open")
.defaultTo(true)
.build();
private AtomicReference<CompletableFuture<?>> worker = new AtomicReference<>(CompletableFuture.completedFuture(null));
private boolean isMonitoring(Slot slot) {
ItemStack stack = slot.getItem();
return stack.canBeDamaged() || stack.isStackable();
}
private boolean isAboveThreshold(ItemStack stack) {
return stack.canBeDamaged()
? stack.getDurability() > durability_threshold.getValue()
: stack.getStackCount() > stack_threshold.getValue();
}
private boolean isAboveThreshold(Slot slot) {
return isAboveThreshold(slot.getItem());
}
private boolean isExchangeable(ItemStack stack) {
return !stack.canBeDamaged() || isAboveThreshold(stack);
}
private boolean isExchangeable(Slot slot) {
return isExchangeable(slot.getItem());
}
@SneakyThrows
private void sleepTicks(int ticks) {
// 20 ticks a second = 1 tick every 50ms
Thread.sleep(50L * Math.max(ticks, 0));
}
private Executor asyncExecutor() {
return tick_delay.intValue() <= 0 ? Runnable::run : async;
}
private void stopWorker() {
val w = worker.getAndSet(CompletableFuture.completedFuture(null));
if (w != null) {
w.cancel(true);
}
}
@Override
protected void onDisabled() {
stopWorker();
}
@SubscribeListener
public void onTick(PreGameTickEvent event) {
// only process when a gui isn't opened by the player
if (!isInWorld() || (getDisplayScreen() != null && noGui.getValue())) {
return;
}
if (worker.get().isDone()) {
val lp = getLocalPlayer();
// get all items in hotbar
worker.set(lp.getHotbarSlots().stream()
// only track the ones that can be replaced or filtered
.filter(this::isMonitoring)
// filter out items that are not ready to be replenished
.negated(this::isAboveThreshold)
// filter out items that do not have replenishments
.filter(slot -> lp.getTopSlots().stream()
.filter(this::isMonitoring)
// all stackables and tools above threshold
.filter(this::isExchangeable)
.map(Slot::getItem)
.anyMatch(slot.getItem()::sameItemStackIgnoreDurability))
.min(Comparator.comparingInt(ItemEx::getDistanceFromSelected))
.map(hotbarSlot -> {
final ItemStack stack = hotbarSlot.getItem();
// if the item can be damaged then it is a tool
if (stack.canBeDamaged()) {
return lp.getTopSlots().stream()
.filter(this::isMonitoring)
.filter(this::isExchangeable)
.filter(s -> stack.sameItemStackIgnoreDurability(s.getItem()))
// get the item with the best matching enchantments
.max(Comparator.comparing(Slot::getItem, ItemEx::compareEnchantments))
.map(slot -> CompletableFuture.runAsync(() -> {
}, main)
.thenRun(() -> slot.click(ClickType.SWAP, hotbarSlot.getHotbarIndex()))
.waitTicks(tick_delay.intValue(), asyncExecutor(), main))
.orElse(null);
} else {
return lp.getTopSlots().stream()
.filter(this::isMonitoring)
.filter(this::isExchangeable)
.filter(s -> stack.sameItemStackIgnoreDurability(s.getItem()))
// get the slot with the least amount of items in the stack because
// this may require the fewest clicks to complete
.min(Comparator.comparing(Slot::getItem, Comparator.comparingInt(ItemStack::getCount)))
.map(slot -> CompletableFuture.supplyAsync(() -> slot.click(ClickType.PICKUP, 0), main)
.waitTicks(tick_delay.intValue(), asyncExecutor(), main)
// this will place the item into the hotbar
.thenApply(itemStack -> hotbarSlot.click(ClickType.PICKUP, 0))
// cleanup
.thenCompose(stack1 -> {
// if we dont get an empty item stack result, then we are still carrying an item
// and need to deposit it back to where it was
if (!stack1.isEmpty()) {
return CompletableFuture.runAsync(() -> {
}, main)
.waitTicks(tick_delay.intValue(), asyncExecutor(), main)
.thenApply(o -> slot.click(ClickType.PICKUP, 0))
.thenCompose(stack2 -> {
// we picked up something that managed to get in our inventory
// time to dumpster it
if (!stack2.isEmpty()) {
return CompletableFuture.runAsync(() -> {
}, main)
.waitTicks(tick_delay.intValue(), asyncExecutor(), main)
.thenRun(() -> lp.throwHeldItem());
}
return CompletableFuture.completedFuture(null);
});
} else {
// otherwise we don't have to care
return CompletableFuture.completedFuture(null);
}
})
.waitTicks(tick_delay.intValue(), asyncExecutor(), main)
)
.orElse(null);
}
})
.orElse(CompletableFuture.completedFuture(null)));
}
}
}
| 3,689 |
997 | <reponame>mkannwischer/PQClean<gh_stars>100-1000
#ifndef _RAINBOW_BLAS_H_
#define _RAINBOW_BLAS_H_
/// @file rainbow_blas.h
/// @brief Defining the functions used in rainbow.c acconding to the definitions in rainbow_config.h
///
/// Defining the functions used in rainbow.c acconding to the definitions in rainbow_config.h
#include "blas.h"
#include "blas_comm.h"
#include "parallel_matrix_op.h"
#include "rainbow_config.h"
#define gfv_get_ele PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_gf16v_get_ele
#define gfv_mul_scalar PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_gf16v_mul_scalar
#define gfv_madd PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_gf16v_madd
#define gfmat_prod PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_gf16mat_prod
#define gfmat_inv PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_gf16mat_inv
#define batch_trimat_madd PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_trimat_madd_gf16
#define batch_trimatTr_madd PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_trimatTr_madd_gf16
#define batch_2trimat_madd PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_2trimat_madd_gf16
#define batch_matTr_madd PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_matTr_madd_gf16
#define batch_bmatTr_madd PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_bmatTr_madd_gf16
#define batch_mat_madd PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_mat_madd_gf16
#define batch_quad_trimat_eval PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_quad_trimat_eval_gf16
#define batch_quad_recmat_eval PQCLEAN_RAINBOWICIRCUMZENITHAL_CLEAN_batch_quad_recmat_eval_gf16
#endif // _RAINBOW_BLAS_H_
| 710 |
12,252 | <gh_stars>1000+
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.representations.idm;
import java.util.Objects;
import org.keycloak.common.util.ObjectUtil;
/**
* Value object to represent an OID (object identifier) as used to describe LDAP schema, extension and features.
* See <a href="https://ldap.com/ldap-oid-reference-guide/">LDAP OID Reference Guide</a>.
*
* @author <NAME>, 2020-05-13
* @since 11.0
*/
public class LDAPCapabilityRepresentation {
public enum CapabilityType {
CONTROL,
EXTENSION,
FEATURE,
UNKNOWN;
public static CapabilityType fromRootDseAttributeName(String attributeName) {
switch (attributeName) {
case "supportedExtension": return CapabilityType.EXTENSION;
case "supportedControl": return CapabilityType.CONTROL;
case "supportedFeatures": return CapabilityType.FEATURE;
default: return CapabilityType.UNKNOWN;
}
}
};
private Object oid;
private CapabilityType type;
public LDAPCapabilityRepresentation() {
}
public LDAPCapabilityRepresentation(Object oidValue, CapabilityType type) {
this.oid = Objects.requireNonNull(oidValue);
this.type = type;
}
public String getOid() {
return oid instanceof String ? (String) oid : String.valueOf(oid);
}
public CapabilityType getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LDAPCapabilityRepresentation ldapOid = (LDAPCapabilityRepresentation) o;
return ObjectUtil.isEqualOrBothNull(oid, ldapOid.oid) && ObjectUtil.isEqualOrBothNull(type, ldapOid.type);
}
@Override
public int hashCode() {
return oid.hashCode();
}
@Override
public String toString() {
return new StringBuilder(LDAPCapabilityRepresentation.class.getSimpleName() + "[ ")
.append("oid=" + oid + ", ")
.append("type=" + type + " ]")
.toString();
}
}
| 1,083 |
743 | <filename>guacamole/src/main/java/org/apache/guacamole/tunnel/StreamInterceptingFilter.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.guacamole.tunnel;
import java.io.Closeable;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.io.GuacamoleWriter;
import org.apache.guacamole.net.GuacamoleTunnel;
import org.apache.guacamole.protocol.GuacamoleFilter;
import org.apache.guacamole.protocol.GuacamoleInstruction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Filter which selectively intercepts stream-related instructions,
* automatically writing to, reading from, or closing the stream given with
* interceptStream(). Any instructions required by the Guacamole protocol to be
* sent in response to intercepted instructions will be sent automatically.
*
* @param <T>
* The type of object which will produce or consume the data sent over the
* intercepted Guacamole stream. Usually, this will be either InputStream
* or OutputStream.
*/
public abstract class StreamInterceptingFilter<T extends Closeable>
implements GuacamoleFilter {
/**
* Logger for this class.
*/
private static final Logger logger =
LoggerFactory.getLogger(StreamInterceptingFilter.class);
/**
* Mapping of the all streams whose related instructions should be
* intercepted.
*/
private final InterceptedStreamMap<T> streams = new InterceptedStreamMap<T>();
/**
* The tunnel over which any required instructions should be sent.
*/
private final GuacamoleTunnel tunnel;
/**
* Creates a new StreamInterceptingFilter which selectively intercepts
* stream-related instructions. Any instructions required by the Guacamole
* protocol to be sent in response to intercepted instructions will be sent
* automatically over the given tunnel.
*
* @param tunnel
* The GuacamoleTunnel over which any required instructions should be
* sent.
*/
public StreamInterceptingFilter(GuacamoleTunnel tunnel) {
this.tunnel = tunnel;
}
/**
* Injects an arbitrary Guacamole instruction into the outbound Guacamole
* protocol stream (GuacamoleWriter) of the tunnel associated with this
* StreamInterceptingFilter, as if the instruction was sent by the connected
* client.
*
* @param instruction
* The Guacamole instruction to inject.
*/
protected void sendInstruction(GuacamoleInstruction instruction) {
// Temporarily acquire writer to send "ack" instruction
GuacamoleWriter writer = tunnel.acquireWriter();
// Send successful "ack"
try {
writer.writeInstruction(instruction);
}
catch (GuacamoleException e) {
logger.debug("Unable to send \"{}\" for intercepted stream.",
instruction.getOpcode(), e);
}
// Done writing
tunnel.releaseWriter();
}
/**
* Returns the stream having the given index and currently being intercepted
* by this filter.
*
* @param index
* The index of the stream to return.
*
* @return
* The stream having the given index, or null if no such stream is
* being intercepted.
*/
protected InterceptedStream<T> getInterceptedStream(String index) {
return streams.get(index);
}
/**
* Closes the stream having the given index and currently being intercepted
* by this filter, if any. If no such stream is being intercepted, then this
* function has no effect.
*
* @param index
* The index of the stream to close.
*
* @return
* The stream associated with the given index, if the stream is being
* intercepted, or null if no such stream exists.
*/
protected InterceptedStream<T> closeInterceptedStream(String index) {
return streams.close(index);
}
/**
* Closes the given stream.
*
* @param stream
* The stream to close.
*
* @return
* true if the given stream was being intercepted, false otherwise.
*/
protected boolean closeInterceptedStream(InterceptedStream<T> stream) {
return streams.close(stream);
}
/**
* Closes all streams being intercepted by this filter.
*/
public void closeAllInterceptedStreams() {
streams.closeAll();
}
/**
* Begins handling the data of the given intercepted stream. This function
* will automatically be invoked by interceptStream() for any valid stream.
* It is not required that this function block until all data is handled;
* interceptStream() will do this automatically. Implementations are free
* to use asynchronous approaches to data handling.
*
* @param stream
* The stream being intercepted.
*/
protected abstract void handleInterceptedStream(InterceptedStream<T> stream);
/**
* Intercept the stream having the given index, producing or consuming its
* data as appropriate. The given stream object will automatically be closed
* when the stream ends. If there is no stream having the given index, then
* the stream object will be closed immediately. This function will block
* until all data has been handled and the stream is ended.
*
* @param index
* The index of the stream to intercept.
*
* @param stream
* The stream object which will produce or consume all data for the
* stream having the given index.
*
* @throws GuacamoleException
* If an error occurs while intercepting the stream, or if the stream
* itself reports an error.
*/
public void interceptStream(int index, T stream) throws GuacamoleException {
InterceptedStream<T> interceptedStream;
String indexString = Integer.toString(index);
// Atomically verify tunnel is open and add the given stream
synchronized (tunnel) {
// Do nothing if tunnel is not open
if (!tunnel.isOpen())
return;
// Wrap stream
interceptedStream = new InterceptedStream<T>(indexString, stream);
// Replace any existing stream
streams.put(interceptedStream);
}
// Produce/consume all stream data
handleInterceptedStream(interceptedStream);
// Wait for stream to close
streams.waitFor(interceptedStream);
// Throw any asynchronously-provided exception
if (interceptedStream.hasStreamError())
throw interceptedStream.getStreamError();
}
}
| 2,534 |
5,250 | <reponame>jiandiao/flowable-engine
/* 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.flowable.rest.service.api.history;
import org.flowable.common.rest.api.PaginateRequest;
/**
* @author <NAME>
*/
public class HistoricActivityInstanceQueryRequest extends PaginateRequest {
private String activityId;
private String activityInstanceId;
private String activityName;
private String activityType;
private String executionId;
private Boolean finished;
private String taskAssignee;
private String processInstanceId;
private String processDefinitionId;
private String tenantId;
private String tenantIdLike;
private Boolean withoutTenantId;
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public Boolean getFinished() {
return finished;
}
public void setFinished(Boolean finished) {
this.finished = finished;
}
public String getTaskAssignee() {
return taskAssignee;
}
public void setTaskAssignee(String taskAssignee) {
this.taskAssignee = taskAssignee;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
}
| 1,159 |
3,269 | # Time: O(n)
# Space: O(n)
class UndirectedGraphNode(object):
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution(object):
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if node is None:
return None
cloned_node = UndirectedGraphNode(node.label)
cloned, queue = {node:cloned_node}, [node]
while queue:
current = queue.pop()
for neighbor in current.neighbors:
if neighbor not in cloned:
queue.append(neighbor)
cloned_neighbor = UndirectedGraphNode(neighbor.label)
cloned[neighbor] = cloned_neighbor
cloned[current].neighbors.append(cloned[neighbor])
return cloned[node]
| 412 |
398 | package com.ruiyun.example;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.browser.BrowserFetcher;
import com.ruiyun.jvppeteer.core.page.Page;
import org.junit.Test;
import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;
public class LaunchExample {
@Test
public void test1() throws Exception {
//自动下载722234版本的浏览器,第一次下载后不会再下载
BrowserFetcher.downloadIfNotExist();
LaunchOptions launchOptions = new LaunchOptionsBuilder().withIgnoreDefaultArgs(Arrays.asList("--enable-automation")).withHeadless(false).build();
Browser browser = Puppeteer.launch(launchOptions);
Page page = browser.newPage();
page.goTo("https://www.baidu.com/?tn=98012088_10_dg&ch=3");
// 做一些其他操作
browser.close();
}
public static void main(String[] args) {
Method[] declaredMethods = LaunchExample.class.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod.toGenericString());
}
}
}
| 485 |
665 | /*
* 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.isis.viewer.restfulobjects.rendering.domainobjects;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.node.NullNode;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.commons.internal.collections._Lists;
import org.apache.isis.commons.internal.collections._Maps;
import org.apache.isis.core.metamodel.interactions.managed.ManagedAction;
import org.apache.isis.core.metamodel.interactions.managed.ManagedParameter;
import org.apache.isis.core.metamodel.interactions.managed.ParameterNegotiationModel;
import org.apache.isis.core.metamodel.spec.ManagedObjects;
import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.Rel;
import org.apache.isis.viewer.restfulobjects.applib.RepresentationType;
import org.apache.isis.viewer.restfulobjects.rendering.IResourceContext;
import org.apache.isis.viewer.restfulobjects.rendering.LinkFollowSpecs;
import org.apache.isis.viewer.restfulobjects.rendering.domaintypes.ActionDescriptionReprRenderer;
import lombok.val;
public class ObjectActionReprRenderer
extends AbstractObjectMemberReprRenderer<ObjectAction> {
public ObjectActionReprRenderer(final IResourceContext resourceContext) {
this(resourceContext, null, null, JsonRepresentation.newMap());
}
public ObjectActionReprRenderer(
final IResourceContext resourceContext,
final LinkFollowSpecs linkFollowSpecs,
final String actionId,
final JsonRepresentation representation) {
super(resourceContext, linkFollowSpecs, actionId, RepresentationType.OBJECT_ACTION, representation,
Where.OBJECT_FORMS);
}
@Override
public JsonRepresentation render() {
renderMemberContent();
putDisabledReasonIfDisabled();
if (mode.isStandalone() || mode.isMutated()) {
addParameterDetails();
}
return representation;
}
// ///////////////////////////////////////////////////
// details link
// ///////////////////////////////////////////////////
/**
* Mandatory hook method to support x-ro-follow-links
*/
@Override
protected void followDetailsLink(final JsonRepresentation detailsLink) {
val where = resourceContext.getWhere();
final ObjectActionReprRenderer renderer = new ObjectActionReprRenderer(getResourceContext(), getLinkFollowSpecs(), null, JsonRepresentation.newMap());
renderer.with(ManagedAction.of(objectAdapter, objectMember, where)).usingLinkTo(linkTo).asFollowed();
detailsLink.mapPut("value", renderer.render());
}
// ///////////////////////////////////////////////////
// mutators
// ///////////////////////////////////////////////////
@Override
protected void addMutatorLinksIfEnabled() {
if (usability().isVetoed()) {
return;
}
final Map<String, MutatorSpec> mutators = objectMemberType.getMutators();
final SemanticsOf actionSemantics = objectMember.getSemantics();
final String mutator = InvokeKeys.getKeyFor(actionSemantics);
final MutatorSpec mutatorSpec = mutators.get(mutator);
addLinkFor(mutatorSpec);
}
@Override
protected ObjectAdapterLinkTo linkToForMutatorInvoke() {
return super.linkToForMutatorInvoke();
}
@Override
protected JsonRepresentation mutatorArgs(final MutatorSpec mutatorSpec) {
final JsonRepresentation argMap = JsonRepresentation.newMap();
val parameters = objectMember.getParameters();
for (int i = 0; i < objectMember.getParameterCount(); i++) {
argMap.mapPut(parameters.getElseFail(i).getId() + ".value", argValueFor(i));
}
return argMap;
}
private Object argValueFor(final int i) {
// force a null into the map
return NullNode.getInstance();
}
// ///////////////////////////////////////////////////
// parameter details
// ///////////////////////////////////////////////////
private ObjectActionReprRenderer addParameterDetails() {
final Map<String,Object> parameters = _Maps.newLinkedHashMap();
if(objectMember.getParameterCount()>0) {
val act = ManagedAction.of(objectAdapter, objectMember, Where.ANYWHERE);
val paramNeg = act.startParameterNegotiation();
for(val paramMod : paramNeg.getParamModels()) {
val paramMeta = paramMod.getMetaModel();
final Object paramDetails = paramDetails(paramMod, paramNeg);
parameters.put(paramMeta.getId(), paramDetails);
}
}
representation.mapPut("parameters", parameters);
return this;
}
private Object paramDetails(final ManagedParameter paramMod, final ParameterNegotiationModel paramNeg) {
val paramMeta = paramMod.getMetaModel();
final JsonRepresentation paramRep = JsonRepresentation.newMap();
paramRep.mapPut("num", paramMeta.getNumber());
paramRep.mapPut("id", paramMeta.getId());
paramRep.mapPut("name", paramMeta.getFriendlyName(objectAdapter.asProvider()));
paramRep.mapPut("description", paramMeta.getDescription(objectAdapter.asProvider()));
final Object paramChoices = choicesFor(paramMod, paramNeg);
if (paramChoices != null) {
paramRep.mapPut("choices", paramChoices);
}
final Object paramDefault = defaultFor(paramMod);
if (paramDefault != null) {
paramRep.mapPut("default", paramDefault);
}
return paramRep;
}
private Object choicesFor(
final ManagedParameter paramMod,
final ParameterNegotiationModel paramNeg) {
val paramMeta = paramMod.getMetaModel();
val choiceAdapters = paramMeta.getChoices(paramNeg, getInteractionInitiatedBy());
if (choiceAdapters == null || choiceAdapters.isEmpty()) {
return null;
}
final List<Object> list = _Lists.newArrayList();
for (val choiceAdapter : choiceAdapters) {
// REVIEW: previously was using the spec of the parameter, but think instead it should be the spec of the adapter itself
// final ObjectSpecification choiceSpec = param.getSpecification();
list.add(DomainObjectReprRenderer.valueOrRef(resourceContext, super.getJsonValueEncoder(), choiceAdapter));
}
return list;
}
private Object defaultFor(final ManagedParameter paramMod) {
val defaultAdapter = paramMod.getValue().getValue();
if (ManagedObjects.isNullOrUnspecifiedOrEmpty(defaultAdapter)) {
return null;
}
// REVIEW: previously was using the spec of the parameter, but think instead it should be the spec of the adapter itself
// final ObjectSpecification defaultSpec = param.getSpecification();
return DomainObjectReprRenderer.valueOrRef(resourceContext, super.getJsonValueEncoder(), defaultAdapter);
}
// ///////////////////////////////////////////////////
// extensions and links
// ///////////////////////////////////////////////////
@Override
protected void addLinksToFormalDomainModel() {
if(resourceContext.suppressDescribedByLinks()) {
return;
}
final JsonRepresentation link = ActionDescriptionReprRenderer.newLinkToBuilder(resourceContext, Rel.DESCRIBEDBY, objectAdapter.getSpecification(), objectMember).build();
getLinks().arrayAdd(link);
}
@Override
protected void putExtensionsIsisProprietary() {
getExtensions().mapPut("actionType", objectMember.getType().name().toLowerCase());
final SemanticsOf semantics = objectMember.getSemantics();
getExtensions().mapPut("actionSemantics", semantics.getCamelCaseName());
}
}
| 3,067 |
434 | #pragma once
#include "Base/Mesh.h"
#include "Base/Texture2D.h"
#include <string>
class Model
{
public:
Model(std::string name);
~Model();
void Update();
void SetupMeshOnGPU();
void UploadToGPU();
void Render();
glm::vec3 position = glm::vec3(0.0f);
glm::vec3 rotation = glm::vec3(0.0f);
glm::vec3 scale = glm::vec3(1.0f);
glm::mat4 modelMatrix = glm::mat4(1.0f);
Mesh *mesh;
std::string name;
uint32_t vao;
uint32_t vbo;
uint32_t ebo;
std::string path = "";
Texture2D *diffuse;
}; | 225 |
1,350 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.avs.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for ScriptExecutionParameterType. */
public final class ScriptExecutionParameterType extends ExpandableStringEnum<ScriptExecutionParameterType> {
/** Static value Value for ScriptExecutionParameterType. */
public static final ScriptExecutionParameterType VALUE = fromString("Value");
/** Static value SecureValue for ScriptExecutionParameterType. */
public static final ScriptExecutionParameterType SECURE_VALUE = fromString("SecureValue");
/** Static value Credential for ScriptExecutionParameterType. */
public static final ScriptExecutionParameterType CREDENTIAL = fromString("Credential");
/**
* Creates or finds a ScriptExecutionParameterType from its string representation.
*
* @param name a name to look for.
* @return the corresponding ScriptExecutionParameterType.
*/
@JsonCreator
public static ScriptExecutionParameterType fromString(String name) {
return fromString(name, ScriptExecutionParameterType.class);
}
/** @return known ScriptExecutionParameterType values. */
public static Collection<ScriptExecutionParameterType> values() {
return values(ScriptExecutionParameterType.class);
}
}
| 442 |
756 | <reponame>jonfung-scale/jonfung-httpcomponents-client
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.client5.http.utils;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.HeaderGroup;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link DateUtils}.
*/
public class TestDateUtils {
private static Instant createInstant(final int year, final Month month, final int day) {
return LocalDate.of(year, month, day).atStartOfDay(ZoneId.of("GMT")).toInstant();
}
private static Date createDate(final int year, final Month month, final int day) {
final Instant instant = createInstant(year, month, day);
return new Date(instant.toEpochMilli());
}
@Test
public void testBasicDateParse() throws Exception {
final Instant instant = createInstant(2005, Month.OCTOBER, 14);
Assertions.assertEquals(instant, DateUtils.parseDate("Fri, 14 Oct 2005 00:00:00 GMT", DateUtils.FORMATTER_RFC1123));
Assertions.assertEquals(instant, DateUtils.parseDate("Friday, 14 Oct 2005 00:00:00 GMT", DateUtils.FORMATTER_RFC1123));
Assertions.assertEquals(instant, DateUtils.parseDate("Fri, 14-Oct-2005 00:00:00 GMT", DateUtils.FORMATTER_RFC1036));
Assertions.assertEquals(instant, DateUtils.parseDate("Friday, 14-Oct-2005 00:00:00 GMT", DateUtils.FORMATTER_RFC1036));
Assertions.assertEquals(instant.minus(2, ChronoUnit.HOURS),
DateUtils.parseDate("Fri, 14 Oct 2005 00:00:00 CET", DateUtils.FORMATTER_RFC1123));
Assertions.assertEquals(instant.minus(2, ChronoUnit.HOURS),
DateUtils.parseDate("Fri, 14-Oct-05 00:00:00 CET", DateUtils.FORMATTER_RFC1036));
Assertions.assertEquals(instant, DateUtils.parseStandardDate("Fri, 14 Oct 2005 00:00:00 GMT"));
}
@Test
public void testDateParseMessage() throws Exception {
final HeaderGroup message1 = new HeaderGroup();
message1.setHeader(new BasicHeader(HttpHeaders.DATE, "Fri, 14 Oct 2005 00:00:00 GMT"));
Assertions.assertEquals(createInstant(2005, Month.OCTOBER, 14), DateUtils.parseStandardDate(message1, HttpHeaders.DATE));
final HeaderGroup message2 = new HeaderGroup();
message2.addHeader(new BasicHeader(HttpHeaders.DATE, "Fri, 14 Oct 2005 00:00:00 GMT"));
message2.addHeader(new BasicHeader(HttpHeaders.DATE, "Fri, 21 Oct 2005 00:00:00 GMT"));
Assertions.assertEquals(createInstant(2005, Month.OCTOBER, 14), DateUtils.parseStandardDate(message2, HttpHeaders.DATE));
}
@Test
public void testMalformedDate() {
Assertions.assertNull(DateUtils.parseDate("Fri, 14 Oct 2005 00:00:00 GMT", new DateTimeFormatter[] {}));
}
@Test
public void testInvalidInput() throws Exception {
Assertions.assertThrows(NullPointerException.class, () -> DateUtils.parseStandardDate(null));
Assertions.assertThrows(NullPointerException.class, () -> DateUtils.formatStandardDate(null));
}
@Test
public void testTwoDigitYearDateParse() throws Exception {
Assertions.assertEquals(createInstant(2005, Month.OCTOBER, 14),
DateUtils.parseDate("Friday, 14-Oct-05 00:00:00 GMT", DateUtils.FORMATTER_RFC1036));
}
@Test
public void testParseQuotedDate() throws Exception {
Assertions.assertEquals(createInstant(2005, Month.OCTOBER, 14),
DateUtils.parseDate("'Fri, 14 Oct 2005 00:00:00 GMT'", DateUtils.FORMATTER_RFC1123));
}
@Test
public void testBasicDateFormat() throws Exception {
final Instant instant = createInstant(2005, Month.OCTOBER, 14);
Assertions.assertEquals("Fri, 14 Oct 2005 00:00:00 GMT", DateUtils.formatStandardDate(instant));
Assertions.assertEquals("Fri, 14 Oct 2005 00:00:00 GMT", DateUtils.formatDate(instant, DateUtils.FORMATTER_RFC1123));
Assertions.assertEquals("Fri, 14-Oct-05 00:00:00 GMT", DateUtils.formatDate(instant, DateUtils.FORMATTER_RFC1036));
Assertions.assertEquals("Fri Oct 14 00:00:00 2005", DateUtils.formatDate(instant, DateUtils.FORMATTER_ASCTIME));
}
}
| 1,955 |
3,212 | /*
* 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.nifi.schema.access;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.SchemaIdentifier;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
public class HortonworksEncodedSchemaReferenceWriter implements SchemaAccessWriter {
private final int protocolVersion;
public HortonworksEncodedSchemaReferenceWriter(final int protocolVersion) {
this.protocolVersion = protocolVersion;
if (this.protocolVersion < HortonworksProtocolVersions.MIN_VERSION || this.protocolVersion > HortonworksProtocolVersions.MAX_VERSION) {
throw new IllegalArgumentException("Unknown Protocol Version '" + this.protocolVersion + "'. Protocol Version must be a value between "
+ HortonworksProtocolVersions.MIN_VERSION + " and " + HortonworksProtocolVersions.MAX_VERSION + ".");
}
}
@Override
public void writeHeader(final RecordSchema schema, final OutputStream out) throws IOException {
final SchemaIdentifier identifier = schema.getIdentifier();
// This encoding follows the pattern that is provided for serializing data by the Hortonworks Schema Registry serializer
// See: https://registry-project.readthedocs.io/en/latest/serdes.html#
switch(protocolVersion) {
case 1:
final Long id = identifier.getIdentifier().getAsLong();
final Integer version = identifier.getVersion().getAsInt();
final ByteBuffer bbv1 = ByteBuffer.allocate(13);
bbv1.put((byte) 1);
bbv1.putLong(id);
bbv1.putInt(version);
out.write(bbv1.array());
return;
case 2:
final Long sviV2 = identifier.getSchemaVersionId().getAsLong();
final ByteBuffer bbv2 = ByteBuffer.allocate(9);
bbv2.put((byte) 2);
bbv2.putLong(sviV2);
out.write(bbv2.array());
return;
case 3:
final Long sviV3 = identifier.getSchemaVersionId().getAsLong();
final ByteBuffer bbv3 = ByteBuffer.allocate(5);
bbv3.put((byte) 3);
bbv3.putInt(sviV3.intValue());
out.write(bbv3.array());
return;
default:
// Can't reach this point
throw new IllegalStateException("Unknown Protocol Version: " + this.protocolVersion);
}
}
@Override
public Map<String, String> getAttributes(final RecordSchema schema) {
return Collections.emptyMap();
}
@Override
public void validateSchema(RecordSchema schema) throws SchemaNotFoundException {
final SchemaIdentifier identifier = schema.getIdentifier();
switch (protocolVersion) {
case 1:
if (!identifier.getIdentifier().isPresent()) {
throw new SchemaNotFoundException("Cannot write Encoded Schema Reference because the Schema Identifier " +
"is not known and is required for Protocol Version " + protocolVersion);
}
if (!identifier.getVersion().isPresent()) {
throw new SchemaNotFoundException("Cannot write Encoded Schema Reference because the Schema Version " +
"is not known and is required for Protocol Version " + protocolVersion);
}
break;
case 2:
case 3:
if (!identifier.getSchemaVersionId().isPresent()) {
throw new SchemaNotFoundException("Cannot write Encoded Schema Reference because the Schema Version Identifier " +
"is not known and is required for Protocol Version " + protocolVersion);
}
break;
default:
// Can't reach this point
throw new SchemaNotFoundException("Unknown Protocol Version: " + protocolVersion);
}
}
@Override
public Set<SchemaField> getRequiredSchemaFields() {
return HortonworksProtocolVersions.getRequiredSchemaFields(protocolVersion);
}
}
| 2,054 |
2,499 | <filename>qmq-backup/src/main/java/qunar/tc/qmq/backup/store/impl/HBaseRecordStore.java
/*
* Copyright 2018 Qunar, 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 qunar.tc.qmq.backup.store.impl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.hbase.async.HBaseClient;
import org.hbase.async.KeyValue;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import qunar.tc.qmq.backup.base.*;
import qunar.tc.qmq.backup.service.BackupKeyGenerator;
import qunar.tc.qmq.backup.service.DicService;
import qunar.tc.qmq.backup.store.RecordStore;
import qunar.tc.qmq.backup.util.BackupMessageKeyRangeBuilder;
import qunar.tc.qmq.backup.util.BackupMessageKeyRegexpBuilder;
import qunar.tc.qmq.backup.util.KeyValueList;
import qunar.tc.qmq.backup.util.KeyValueListImpl;
import qunar.tc.qmq.utils.Bytes;
import qunar.tc.qmq.utils.CharsetUtils;
import qunar.tc.qmq.utils.RetrySubjectUtils;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static qunar.tc.qmq.backup.service.BackupKeyGenerator.*;
import static qunar.tc.qmq.backup.util.DateTimeUtils.localDateTime2Date;
import static qunar.tc.qmq.backup.util.HBaseValueDecoder.getRecord;
import static qunar.tc.qmq.backup.util.KeyTools.generateDecimalFormatKey19;
/**
* @author xufeng.deng <EMAIL>
* @since 2019/5/29
*/
public class HBaseRecordStore extends HBaseStore implements RecordStore {
private static final Logger LOG = LoggerFactory.getLogger(HBaseRecordStore.class);
private static final RecordQueryResult EMPTY_RECORD_RESULT = new RecordQueryResult(Collections.emptyList());
private static final int CONSUMER_GROUP_INDEX_IN_RETRY_MESSAGE = MESSAGE_SUBJECT_LENGTH + MESSAGE_ID_LENGTH + CREATE_TIME_LENGTH + BROKER_GROUP_LENGTH;
private byte[] indexTable;
private DicService dicService;
private BackupKeyGenerator keyGenerator;
HBaseRecordStore(byte[] table, byte[] indexTable, byte[] family, byte[][] qualifiers, HBaseClient client
, DicService dicService, BackupKeyGenerator keyGenerator) {
super(table, family, qualifiers, client);
this.indexTable = indexTable;
this.dicService = dicService;
this.keyGenerator = keyGenerator;
}
@Override
public RecordQueryResult findRecords(RecordQuery query) {
final String subject = query.getSubject();
if (Strings.isNullOrEmpty(subject)) return EMPTY_RECORD_RESULT;
final byte recordCode = query.getRecordCode();
if (recordCode == RecordEnum.RECORD.getCode()) {
final String brokerGroup = query.getBrokerGroup();
if (Strings.isNullOrEmpty(brokerGroup)) return EMPTY_RECORD_RESULT;
final List<RecordQueryResult.Record> records = findRecords(subject, new BackupMessageMeta(query.getSequence(), query.getBrokerGroup()), recordCode);
return retResult(records);
} else if (recordCode == RecordEnum.RETRY_RECORD.getCode()) {
final String messageId = query.getMessageId();
if (Strings.isNullOrEmpty(messageId)) return EMPTY_RECORD_RESULT;
return findRetryRecord(RetrySubjectUtils.buildRetrySubject(subject), messageId);
} else if (recordCode == RecordEnum.DEAD_RECORD.getCode()) {
final String messageId = query.getMessageId();
if (Strings.isNullOrEmpty(messageId)) return EMPTY_RECORD_RESULT;
final List<RecordQueryResult.Record> deads = findDeadRecord(subject, messageId);
if (CollectionUtils.isEmpty(deads)) return EMPTY_RECORD_RESULT;
return retResult(deads);
}
return null;
}
private List<RecordQueryResult.Record> findDeadRecord(final String subject, final String messageId) {
final String subjectId = dicService.name2Id(subject);
final String keyRegexp = BackupMessageKeyRegexpBuilder.buildDeadRecordRegexp(subjectId, messageId);
final String startKey = BackupMessageKeyRangeBuilder.buildDeadRecordStartKey(subjectId, messageId);
final String endKey = BackupMessageKeyRangeBuilder.buildDeadRecordEndKey(subjectId, messageId);
try {
return scan(table, keyRegexp, startKey, endKey, 100, 0, R_FAMILY, B_RECORD_QUALIFIERS, kvs -> {
final KeyValueList<KeyValue> kvl = new KeyValueListImpl(kvs);
final byte[] value = kvl.getValue(RECORDS);
final long sequence = Bytes.getLong(value, 0);
final long timestamp = Bytes.getLong(value, 8);
final int consumerGroupLength = value.length - 16;
final byte[] consumerGroupBytes = new byte[consumerGroupLength];
System.arraycopy(value, 16, consumerGroupBytes, 0, consumerGroupLength);
final String consumerGroup = CharsetUtils.toUTF8String(consumerGroupBytes);
return new RecordQueryResult.Record(consumerGroup, ActionEnum.OMIT.getCode(), RecordEnum.DEAD_RECORD.getCode(), timestamp, "", sequence);
});
} catch (Exception e) {
LOG.error("Failed to find dead records.", e);
return Collections.emptyList();
}
}
private RecordQueryResult findRetryRecord(final String subject, final String messageId) {
final List<BackupMessageMeta> metas = scanMessageMeta(subject, messageId);
final List<RecordQueryResult.Record> records = Lists.newArrayListWithCapacity(metas.size());
for (BackupMessageMeta meta : metas) {
final List<RecordQueryResult.Record> retryRecords = findRetryRecords(subject, meta, RecordEnum.RETRY_RECORD.getCode());
if (!CollectionUtils.isEmpty(retryRecords)) records.addAll(retryRecords);
}
return new RecordQueryResult(records);
}
private List<RecordQueryResult.Record> findRetryRecords(String subject, BackupMessageMeta meta, byte type) {
final List<RecordQueryResult.Record> records = Lists.newArrayList();
try {
final long sequence = meta.getSequence();
final String sequenceId = generateDecimalFormatKey19(sequence);
final String brokerGroup = meta.getBrokerGroup();
final String consumerGroupId = meta.getConsumerGroupId();
final String subjectId = dicService.name2Id(subject);
final String brokerGroupId = dicService.name2Id(brokerGroup);
final String pullAction = Byte.toString(ActionEnum.PULL.getCode());
final String ackAction = Byte.toString(ActionEnum.ACK.getCode());
final byte[] subjectBytes = toUtf8(subjectId);
final byte[] sequenceBytes = toUtf8(sequenceId);
final byte[] brokerGroupBytes = toUtf8(brokerGroupId);
final byte[] consumerGroupBytes = toUtf8(consumerGroupId);
final byte[] pullKey = keyGenerator.generateRecordKey(subjectBytes, sequenceBytes, brokerGroupBytes, consumerGroupBytes, toUtf8(pullAction));
final byte[] ackKey = keyGenerator.generateRecordKey(subjectBytes, sequenceBytes, brokerGroupBytes, consumerGroupBytes, toUtf8(ackAction));
final RecordQueryResult.Record pullRecord = get(table, pullKey, R_FAMILY, B_RECORD_QUALIFIERS, kvs -> getRecord(kvs, type));
if (pullRecord != null) records.add(pullRecord);
final RecordQueryResult.Record ackRecord = get(table, ackKey, R_FAMILY, B_RECORD_QUALIFIERS, kvs -> getRecord(kvs, type));
if (ackRecord != null) records.add(ackRecord);
} catch (Exception e) {
LOG.error("find retry records with meta: {} failed.", meta, e);
}
return records;
}
private List<BackupMessageMeta> scanMessageMeta(String subject, String messageId) {
final LocalDateTime now = LocalDateTime.now();
final Date createTimeEnd = localDateTime2Date(now);
final Date createTimeBegin = localDateTime2Date(now.minusDays(30));
try {
final String subjectId = dicService.name2Id(subject);
final String keyRegexp = BackupMessageKeyRegexpBuilder.buildRetryRegexp(subjectId, messageId);
final String startKey = BackupMessageKeyRangeBuilder.buildRetryRangeKey(subjectId, messageId, createTimeEnd);
final String endKey = BackupMessageKeyRangeBuilder.buildRetryRangeKey(subjectId, messageId, createTimeBegin);
final List<BackupMessageMeta> metas = scan(indexTable, keyRegexp, startKey, endKey, 1000, 0, B_FAMILY, B_MESSAGE_QUALIFIERS, kvs -> {
KeyValueList<KeyValue> kvl = new KeyValueListImpl(kvs);
byte[] value = kvl.getValue(CONTENT);
byte[] rowKey = kvl.getKey();
BackupMessageMeta meta = getMessageMeta(rowKey, value);
if (meta != null && rowKey.length > CONSUMER_GROUP_INDEX_IN_RETRY_MESSAGE) {
byte[] consumerGroupId = new byte[CONSUMER_GROUP_LENGTH];
System.arraycopy(rowKey, CONSUMER_GROUP_INDEX_IN_RETRY_MESSAGE, consumerGroupId, 0, CONSUMER_GROUP_LENGTH);
meta.setConsumerGroupId(new String(consumerGroupId, CharsetUtil.UTF_8));
}
return meta;
});
return Lists.newArrayList(Sets.newHashSet(metas));
} catch (Exception e) {
LOG.error("Failed to scan messages meta.", e);
return Lists.newArrayList();
}
}
@Override
protected BackupMessageMeta getMessageMeta(byte[] key, byte[] value) {
if (value == null || value.length <= 0) {
return null;
}
try {
long sequence = org.hbase.async.Bytes.getLong(value, 0);
long createTime = org.hbase.async.Bytes.getLong(value, 8);
int brokerGroupLength = org.hbase.async.Bytes.getInt(value, 16);
if (brokerGroupLength > 200) {
return null;
}
byte[] brokerGroupBytes = new byte[brokerGroupLength];
System.arraycopy(value, 20, brokerGroupBytes, 0, brokerGroupLength);
int messageIdLength = value.length - 20 - brokerGroupLength;
byte[] messageIdBytes = new byte[messageIdLength];
System.arraycopy(value, 20 + brokerGroupLength, messageIdBytes, 0, messageIdLength);
BackupMessageMeta meta = new BackupMessageMeta(sequence, new String(brokerGroupBytes, CharsetUtil.UTF_8), new String(messageIdBytes, CharsetUtil.UTF_8));
meta.setCreateTime(createTime);
return meta;
} catch (Exception ignored) {
}
return null;
}
private RecordQueryResult retResult(List<RecordQueryResult.Record> records) {
if (records != null && records.size() > 0) return new RecordQueryResult(records);
return new RecordQueryResult(Collections.emptyList());
}
// record && retry record && (resend record not included)
private List<RecordQueryResult.Record> findRecords(String subject, BackupMessageMeta meta, byte type) {
try {
final long sequence = meta.getSequence();
final String brokerGroup = meta.getBrokerGroup();
final String subjectId = dicService.name2Id(subject);
final String brokerGroupId = dicService.name2Id(brokerGroup);
final String recordRegexp = BackupMessageKeyRegexpBuilder.buildRecordRegexp(subjectId, sequence, brokerGroupId);
final String startKey = BackupMessageKeyRangeBuilder.buildRecordStartKey(subjectId, sequence, brokerGroupId);
final String endKey = BackupMessageKeyRangeBuilder.buildRecordEndKey(subjectId, sequence, brokerGroupId);
return scan(table, recordRegexp, startKey, endKey, 1000, 0, R_FAMILY, B_RECORD_QUALIFIERS, kvs -> getRecord(kvs, type));
} catch (Exception e) {
LOG.error("Failed to find records.", e);
return Collections.emptyList();
}
}
}
| 4,952 |
318 | <reponame>dicristina/baresip
/**
* @file ui.c User Interface
*
* Copyright (C) 2010 <NAME>
*/
#include <string.h>
#include <re.h>
#include <baresip.h>
#include "core.h"
static int stdout_handler(const char *p, size_t size, void *arg)
{
(void)arg;
if (1 != fwrite(p, size, 1, stdout))
return ENOMEM;
return 0;
}
/**
* Register a new User-Interface (UI) module
*
* @param uis UI Subsystem
* @param ui The User-Interface (UI) module to register
*/
void ui_register(struct ui_sub *uis, struct ui *ui)
{
if (!uis || !ui)
return;
list_append(&uis->uil, &ui->le, ui);
debug("ui: %s\n", ui->name);
}
/**
* Un-register a User-Interface (UI) module
*
* @param ui The User-Interface (UI) module to un-register
*/
void ui_unregister(struct ui *ui)
{
if (!ui)
return;
list_unlink(&ui->le);
}
/**
* Send an input key to the UI subsystem, with a print function for response
*
* @param uis UI Subsystem
* @param key Input character
* @param pf Print function for the response
*/
void ui_input_key(struct ui_sub *uis, char key, struct re_printf *pf)
{
if (!uis)
return;
(void)cmd_process(baresip_commands(), &uis->uictx, key, pf, NULL);
}
/**
* Send an input string to the UI subsystem
*
* @param str Input string
*/
void ui_input_str(const char *str)
{
struct re_printf pf;
struct pl pl;
if (!str)
return;
pf.vph = stdout_handler;
pf.arg = NULL;
pl_set_str(&pl, str);
(void)ui_input_pl(&pf, &pl);
}
/**
* Send an input pointer-length string to the UI subsystem
*
* @param pf Print function
* @param pl Input pointer-length string
*
* @return 0 if success, otherwise errorcode
*/
int ui_input_pl(struct re_printf *pf, const struct pl *pl)
{
struct cmd_ctx *ctx = NULL;
struct commands *commands = baresip_commands();
size_t i;
int err = 0;
if (!pf || !pl)
return EINVAL;
for (i=0; i<pl->l; i++) {
err |= cmd_process(commands, &ctx, pl->p[i], pf, NULL);
}
if (pl->l > 1 && ctx)
err |= cmd_process(commands, &ctx, '\n', pf, NULL);
mem_deref(ctx);
return err;
}
/**
* Send a long command with arguments to the UI subsystem.
* The slash prefix is optional.
*
* @param pf Print function for the response
* @param pl Long command with or without '/' prefix
*
* @return 0 if success, otherwise errorcode
*/
int ui_input_long_command(struct re_printf *pf, const struct pl *pl)
{
size_t offset;
int err;
if (!pl)
return EINVAL;
/* strip the prefix, if present */
if (pl->l > 1 && pl->p[0] == '/')
offset = 1;
else
offset = 0;
err = cmd_process_long(baresip_commands(),
pl->p + offset,
pl->l - offset, pf, NULL);
return err;
}
/**
* Send output to all modules registered in the UI subsystem
*
* @param uis UI Subsystem
* @param fmt Formatted output string
*/
void ui_output(struct ui_sub *uis, const char *fmt, ...)
{
char buf[512];
struct le *le;
va_list ap;
int n;
if (!uis)
return;
va_start(ap, fmt);
n = re_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
if (n < 0)
return;
for (le = uis->uil.head; le; le = le->next) {
const struct ui *ui = le->data;
if (ui->outputh)
ui->outputh(buf);
}
}
/**
* Reset the state of the UI subsystem, free resources
*
* @param uis UI Subsystem
*/
void ui_reset(struct ui_sub *uis)
{
if (!uis)
return;
uis->uictx = mem_deref(uis->uictx);
}
/**
* Check if the UI is in editor mode
*
* @param uis UI Subsystem
*
* @return True if editing, otherwise false
*/
bool ui_isediting(const struct ui_sub *uis)
{
if (!uis)
return false;
return uis->uictx != NULL;
}
/**
* Prompt the user interactively for a password
*
* NOTE: This function is blocking and should not be called from
* any re_main event handlers.
*
* @param passwordp Pointer to allocated password string
*
* @return 0 if success, otherwise errorcode
*/
int ui_password_prompt(char **passwordp)
{
char pwd[64];
const char *p;
char *nl;
int err;
if (!passwordp)
return EINVAL;
/* note: blocking UI call */
memset(pwd, 0, sizeof(pwd));
p = fgets(pwd, sizeof(pwd), stdin);
pwd[sizeof(pwd) - 1] = '\0';
nl = strchr(pwd, '\n');
if (!p || nl == NULL) {
(void)re_printf("Invalid password (0 - 63 characters"
" followed by newline)\n");
return EINVAL;
}
*nl = '\0';
err = str_dup(passwordp, pwd);
if (err)
return err;
return 0;
}
| 1,743 |
11,356 | <gh_stars>1000+
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: SoundAnalysisPreprocessing.proto
#ifndef PROTOBUF_SoundAnalysisPreprocessing_2eproto__INCLUDED
#define PROTOBUF_SoundAnalysisPreprocessing_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3003000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
// @@protoc_insertion_point(includes)
namespace CoreML {
namespace Specification {
namespace CoreMLModels {
class SoundAnalysisPreprocessing;
class SoundAnalysisPreprocessingDefaultTypeInternal;
extern SoundAnalysisPreprocessingDefaultTypeInternal _SoundAnalysisPreprocessing_default_instance_;
class SoundAnalysisPreprocessing_Vggish;
class SoundAnalysisPreprocessing_VggishDefaultTypeInternal;
extern SoundAnalysisPreprocessing_VggishDefaultTypeInternal _SoundAnalysisPreprocessing_Vggish_default_instance_;
} // namespace CoreMLModels
} // namespace Specification
} // namespace CoreML
namespace CoreML {
namespace Specification {
namespace CoreMLModels {
namespace protobuf_SoundAnalysisPreprocessing_2eproto {
// Internal implementation detail -- do not call these.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[];
static const ::google::protobuf::uint32 offsets[];
static void InitDefaultsImpl();
static void Shutdown();
};
void AddDescriptors();
void InitDefaults();
} // namespace protobuf_SoundAnalysisPreprocessing_2eproto
// ===================================================================
class SoundAnalysisPreprocessing_Vggish : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish) */ {
public:
SoundAnalysisPreprocessing_Vggish();
virtual ~SoundAnalysisPreprocessing_Vggish();
SoundAnalysisPreprocessing_Vggish(const SoundAnalysisPreprocessing_Vggish& from);
inline SoundAnalysisPreprocessing_Vggish& operator=(const SoundAnalysisPreprocessing_Vggish& from) {
CopyFrom(from);
return *this;
}
static const SoundAnalysisPreprocessing_Vggish& default_instance();
static inline const SoundAnalysisPreprocessing_Vggish* internal_default_instance() {
return reinterpret_cast<const SoundAnalysisPreprocessing_Vggish*>(
&_SoundAnalysisPreprocessing_Vggish_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
0;
void Swap(SoundAnalysisPreprocessing_Vggish* other);
// implements Message ----------------------------------------------
inline SoundAnalysisPreprocessing_Vggish* New() const PROTOBUF_FINAL { return New(NULL); }
SoundAnalysisPreprocessing_Vggish* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const SoundAnalysisPreprocessing_Vggish& from);
void MergeFrom(const SoundAnalysisPreprocessing_Vggish& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(SoundAnalysisPreprocessing_Vggish* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// @@protoc_insertion_point(class_scope:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish)
private:
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
mutable int _cached_size_;
friend struct protobuf_SoundAnalysisPreprocessing_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class SoundAnalysisPreprocessing : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing) */ {
public:
SoundAnalysisPreprocessing();
virtual ~SoundAnalysisPreprocessing();
SoundAnalysisPreprocessing(const SoundAnalysisPreprocessing& from);
inline SoundAnalysisPreprocessing& operator=(const SoundAnalysisPreprocessing& from) {
CopyFrom(from);
return *this;
}
static const SoundAnalysisPreprocessing& default_instance();
enum SoundAnalysisPreprocessingTypeCase {
kVggish = 20,
SOUNDANALYSISPREPROCESSINGTYPE_NOT_SET = 0,
};
static inline const SoundAnalysisPreprocessing* internal_default_instance() {
return reinterpret_cast<const SoundAnalysisPreprocessing*>(
&_SoundAnalysisPreprocessing_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
1;
void Swap(SoundAnalysisPreprocessing* other);
// implements Message ----------------------------------------------
inline SoundAnalysisPreprocessing* New() const PROTOBUF_FINAL { return New(NULL); }
SoundAnalysisPreprocessing* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const SoundAnalysisPreprocessing& from);
void MergeFrom(const SoundAnalysisPreprocessing& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(SoundAnalysisPreprocessing* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
typedef SoundAnalysisPreprocessing_Vggish Vggish;
// accessors -------------------------------------------------------
// .CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish vggish = 20;
bool has_vggish() const;
void clear_vggish();
static const int kVggishFieldNumber = 20;
const ::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish& vggish() const;
::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* mutable_vggish();
::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* release_vggish();
void set_allocated_vggish(::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* vggish);
SoundAnalysisPreprocessingTypeCase SoundAnalysisPreprocessingType_case() const;
// @@protoc_insertion_point(class_scope:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing)
private:
void set_has_vggish();
inline bool has_SoundAnalysisPreprocessingType() const;
void clear_SoundAnalysisPreprocessingType();
inline void clear_has_SoundAnalysisPreprocessingType();
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
union SoundAnalysisPreprocessingTypeUnion {
SoundAnalysisPreprocessingTypeUnion() {}
::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* vggish_;
} SoundAnalysisPreprocessingType_;
mutable int _cached_size_;
::google::protobuf::uint32 _oneof_case_[1];
friend struct protobuf_SoundAnalysisPreprocessing_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// SoundAnalysisPreprocessing_Vggish
// -------------------------------------------------------------------
// SoundAnalysisPreprocessing
// .CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.Vggish vggish = 20;
inline bool SoundAnalysisPreprocessing::has_vggish() const {
return SoundAnalysisPreprocessingType_case() == kVggish;
}
inline void SoundAnalysisPreprocessing::set_has_vggish() {
_oneof_case_[0] = kVggish;
}
inline void SoundAnalysisPreprocessing::clear_vggish() {
if (has_vggish()) {
delete SoundAnalysisPreprocessingType_.vggish_;
clear_has_SoundAnalysisPreprocessingType();
}
}
inline const ::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish& SoundAnalysisPreprocessing::vggish() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.vggish)
return has_vggish()
? *SoundAnalysisPreprocessingType_.vggish_
: ::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish::default_instance();
}
inline ::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* SoundAnalysisPreprocessing::mutable_vggish() {
if (!has_vggish()) {
clear_SoundAnalysisPreprocessingType();
set_has_vggish();
SoundAnalysisPreprocessingType_.vggish_ = new ::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish;
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.vggish)
return SoundAnalysisPreprocessingType_.vggish_;
}
inline ::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* SoundAnalysisPreprocessing::release_vggish() {
// @@protoc_insertion_point(field_release:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.vggish)
if (has_vggish()) {
clear_has_SoundAnalysisPreprocessingType();
::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* temp = SoundAnalysisPreprocessingType_.vggish_;
SoundAnalysisPreprocessingType_.vggish_ = NULL;
return temp;
} else {
return NULL;
}
}
inline void SoundAnalysisPreprocessing::set_allocated_vggish(::CoreML::Specification::CoreMLModels::SoundAnalysisPreprocessing_Vggish* vggish) {
clear_SoundAnalysisPreprocessingType();
if (vggish) {
set_has_vggish();
SoundAnalysisPreprocessingType_.vggish_ = vggish;
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.CoreMLModels.SoundAnalysisPreprocessing.vggish)
}
inline bool SoundAnalysisPreprocessing::has_SoundAnalysisPreprocessingType() const {
return SoundAnalysisPreprocessingType_case() != SOUNDANALYSISPREPROCESSINGTYPE_NOT_SET;
}
inline void SoundAnalysisPreprocessing::clear_has_SoundAnalysisPreprocessingType() {
_oneof_case_[0] = SOUNDANALYSISPREPROCESSINGTYPE_NOT_SET;
}
inline SoundAnalysisPreprocessing::SoundAnalysisPreprocessingTypeCase SoundAnalysisPreprocessing::SoundAnalysisPreprocessingType_case() const {
return SoundAnalysisPreprocessing::SoundAnalysisPreprocessingTypeCase(_oneof_case_[0]);
}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace CoreMLModels
} // namespace Specification
} // namespace CoreML
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_SoundAnalysisPreprocessing_2eproto__INCLUDED
| 3,801 |
591 | from typing import Iterator, Dict
class Offset2ID:
def __init__(self, ids=None):
self.ids = ids or []
def get_id(self, idx):
return self.ids[idx]
def append(self, data):
self.ids.append(data)
def extend(self, data):
self.ids.extend(data)
def update(self, position, data_id):
self.ids[position] = data_id
def delete_by_id(self, _id):
del self.ids[self.ids.index(_id)]
def index(self, _id):
return self.ids.index(_id)
def delete_by_offset(self, position):
del self.ids[position]
def insert(self, position, data_id):
self.ids.insert(position, data_id)
def clear(self):
self.ids.clear()
def delete_by_ids(self, ids):
ids = set(ids)
self.ids = list(filter(lambda _id: _id not in ids, self.ids))
def update_ids(self, _ids_map: Dict[str, str]):
for i in range(len(self.ids)):
if self.ids[i] in _ids_map:
self.ids[i] = _ids_map[self.ids[i]]
def save(self):
pass
def load(self):
pass
def __iter__(self) -> Iterator['str']:
yield from self.ids
def __eq__(self, other):
return self.ids == other.ids
def __len__(self):
return len(self.ids)
| 608 |
2,842 | <gh_stars>1000+
{
"name": "@wasm/arc_js",
"description": "",
"version": "1.0.0",
"scripts": {
"build": "gulp --gulpfile ./build.ts"
},
"devDependencies": {
},
"wasmStudio": {
"name": "ARCH JavaScript Project",
"description": "# ARCH JavaScript Project\n\nThis project comes with a small example to get started scripting the ARCH with JavaScript quickly.",
"icon": "js-lang-file-icon"
}
} | 156 |
331 | // Copyright © 2018 ChaiShushan <<EMAIL>>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
#include <stdio.h>
struct Int {
int Twice() {
const int* p = (int*)(this);
return (*p) * 2;
}
};
int main() {
int x = 42;
int v = ((Int*)(&x))->Twice();
printf("%d\n", v);
return 0;
}
| 138 |
777 | // Copyright 2014 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 IOS_WEB_PUBLIC_WEBUI_WEB_UI_IOS_CONTROLLER_FACTORY_H_
#define IOS_WEB_PUBLIC_WEBUI_WEB_UI_IOS_CONTROLLER_FACTORY_H_
#include "ios/web/public/webui/web_ui_ios.h"
class GURL;
namespace web {
class WebUIIOSController;
// Interface for an object that controls which URLs are considered WebUIIOS
// URLs and creates WebUIIOSController instances for given URLs.
class WebUIIOSControllerFactory {
public:
virtual ~WebUIIOSControllerFactory() {}
// Call to register a factory.
static void RegisterFactory(WebUIIOSControllerFactory* factory);
// Returns a WebUIIOSController instance for the given URL, or NULL if the URL
// doesn't correspond to a WebUIIOS.
virtual WebUIIOSController* CreateWebUIIOSControllerForURL(
WebUIIOS* web_ui,
const GURL& url) const = 0;
};
} // namespace web
#endif // IOS_WEB_PUBLIC_WEBUI_WEB_UI_IOS_CONTROLLER_FACTORY_H_
| 371 |
3,614 | package com.central.oauth.service.impl;
import com.central.oauth.service.ZltUserDetailsService;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.Assert;
/**
* 重写 UserDetailsByNameServiceWrapper 支持多帐户类型
*
* @author zlt
* @version 1.0
* @date 2021/7/24
* @see UserDetailsByNameServiceWrapper
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class UserDetailsByNameServiceFactoryWrapper <T extends Authentication> implements
AuthenticationUserDetailsService<T>, InitializingBean {
@Setter
private UserDetailServiceFactory userDetailServiceFactory;
public UserDetailsByNameServiceFactoryWrapper() {
}
public UserDetailsByNameServiceFactoryWrapper(final UserDetailServiceFactory userDetailServiceFactory) {
Assert.notNull(userDetailServiceFactory, "userDetailServiceFactory cannot be null.");
this.userDetailServiceFactory = userDetailServiceFactory;
}
/**
* Check whether all required properties have been set.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() {
Assert.notNull(this.userDetailServiceFactory, "UserDetailServiceFactory must be set");
}
/**
* Get the UserDetails object from the wrapped UserDetailsService implementation
*/
@Override
public UserDetails loadUserDetails(T authentication) throws UsernameNotFoundException {
ZltUserDetailsService userDetailsService;
if (authentication instanceof PreAuthenticatedAuthenticationToken) {
userDetailsService = this.userDetailServiceFactory.getService((Authentication)authentication.getPrincipal());
} else {
userDetailsService = this.userDetailServiceFactory.getService(authentication);
}
return userDetailsService.loadUserByUsername(authentication.getName());
}
}
| 720 |
370 | #define ZINT
#include <../Source/umf_garbage_collection.c>
| 22 |
701 |
#ifndef _Demo_Tutorial_SMAAGameState_H_
#define _Demo_Tutorial_SMAAGameState_H_
#include "OgrePrerequisites.h"
#include "TutorialGameState.h"
#include "OgreMesh2.h"
namespace Demo
{
class Tutorial_SMAAGameState : public TutorialGameState
{
private:
Ogre::SceneNode *mSceneNode[16];
Ogre::SceneNode *mLightNodes[3];
bool mAnimateObjects;
virtual void generateDebugText(float timeSinceLast, Ogre::String &outText);
public:
Tutorial_SMAAGameState( const Ogre::String &helpDescription );
virtual void createScene01();
virtual void update(float timeSinceLast);
virtual void keyReleased(const SDL_KeyboardEvent &arg);
};
}
#endif
| 266 |
313 | from common import *
# TODO: when introducing new encoder/decoder this needs to be updated consider
# using GRAPH.DEBUG command to be able to get this data
keys = {
b'x': b'\x07\x81\x82\xb6\xa9\x85\xd6\xadh\n\x05\x02x\x00\x02\x1e\x02\x00\x02\x01\x02\x00\x02\x03\x02\x01\x05\x02v\x00\x02\x01\x02\x00\x05\x02N\x00\x02\x01\x02\x01\x05\x02v\x00\x02\x00\x02\x01\x02\x01\x02\n\x02\x00\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x01\x02\x01\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x02\x02\x02\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x03\x02\x03\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x04\x02\x04\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x05\x02\x05\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x06\x02\x06\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x07\x02\x07\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x08\x02\x08\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\t\x02\t\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\n\x00\t\x00\x84\xf96Z\xd1\x98\xec\xc0',
b'{x}x_a244836f-fe81-4f8d-8ee2-83fc3fbcf102': b'\x07\x81\x82\xb6\xa9\x86g\xadh\n\x05\x02x\x00\x02\x1e\x02\x00\x02\x01\x02\x00\x02\x03\x02\x01\x05\x02v\x00\x02\x01\x02\x00\x05\x02N\x00\x02\x01\x02\x01\x05\x02v\x00\x02\x00\x02\x01\x02\x01\x02\n\x02\n\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x0b\x02\x0b\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x0c\x02\x0c\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\r\x02\r\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x0e\x02\x0e\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x0f\x02\x0f\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x10\x02\x10\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x11\x02\x11\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x12\x02\x12\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x13\x02\x13\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x14\x00\t\x00\x13H\x11\xb8\x15\xd3\xdc~',
b'{x}x_53ab30bb-1dbb-47b2-a41d-cac3acd68b8c': b'\x07\x81\x82\xb6\xa9\x86g\xadh\n\x05\x02x\x00\x02\x1e\x02\x00\x02\x01\x02\x00\x02\x03\x02\x01\x05\x02v\x00\x02\x01\x02\x00\x05\x02N\x00\x02\x01\x02\x01\x05\x02v\x00\x02\x00\x02\x05\x02\x01\x02\n\x02\x02\x02\x00\x02\x03\x02\x00\x02\x04\x02\x00\x02\x05\x02\x01\x02\x14\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x15\x02\x15\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x16\x02\x16\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x17\x02\x17\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x18\x02\x18\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x19\x02\x19\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x1a\x02\x1a\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x1b\x02\x1b\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x1c\x02\x1c\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x1d\x02\x1d\x02\x01\x02\x00\x02\x01\x02\x00\x02`\x00\x02\x1e\x00\t\x00\x1b\xa64\xd6\xf5\x0bk\xa6'
}
class testRdbLoad():
def __init__(self):
self.env = Env(decodeResponses=True, moduleArgs='VKEY_MAX_ENTITY_COUNT 10')
self.conn = self.env.getConnection()
# assert that |keyspace| == `n`
def validate_key_count(self, n):
keys = self.conn.keys('*')
self.env.assertEqual(len(keys), n)
# restore the key data
def restore_key(self, key):
self.conn.restore(key, '0', keys[key])
# validate that the imported data exists
def _test_data(self):
expected = [[i] for i in range(1, 31)]
q = "MATCH (n:N) RETURN n.v"
result = self.conn.execute_command("GRAPH.RO_QUERY", "x", q)
self.env.assertEqual(result[1], expected)
def test_rdb_load(self):
aux = self.conn.execute_command("GRAPH.DEBUG", "AUX", "START")
self.env.assertEqual(aux, 1)
self.restore_key(b'{<KEY>')
self.restore_key(b'{<KEY>')
self.conn.flushall()
self.validate_key_count(0)
aux = self.conn.execute_command("GRAPH.DEBUG", "AUX", "START")
self.env.assertEqual(aux, 1)
self.restore_key(b'{<KEY>')
self.restore_key(b'{<KEY>')
self.restore_key(b'x')
aux = self.conn.execute_command("GRAPH.DEBUG", "AUX", "END")
self.env.assertEqual(aux, 0)
self.validate_key_count(1)
self._test_data()
self.conn.save()
| 2,707 |
3,285 | <gh_stars>1000+
/*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ONEFLOW_API_PYTHON_UTIL_OF_API_REGISTRY_H_
#define ONEFLOW_API_PYTHON_UTIL_OF_API_REGISTRY_H_
#include <pybind11/pybind11.h>
#include <map>
#include <vector>
#include <functional>
#include "oneflow/core/common/preprocessor.h"
namespace oneflow {
class OneflowModuleRegistry {
public:
OneflowModuleRegistry() = default;
~OneflowModuleRegistry() = default;
void Register(std::string module_path, std::function<void(pybind11::module&)> BuildModule);
void ImportAll(pybind11::module& m);
private:
void BuildSubModule(const std::string& module_path, pybind11::module& m,
const std::function<void(pybind11::module&)>& BuildModule);
};
} // namespace oneflow
#define ONEFLOW_API_PYBIND11_MODULE(module_path, m) \
static void OF_PP_CAT(OneflowApiPythonModule, __LINE__)(pybind11::module&); \
namespace { \
struct OfApiRegistryInit { \
OfApiRegistryInit() { \
::oneflow::OneflowModuleRegistry().Register(module_path, \
&OF_PP_CAT(OneflowApiPythonModule, __LINE__)); \
} \
}; \
OfApiRegistryInit of_api_registry_init; \
} \
static void OF_PP_CAT(OneflowApiPythonModule, __LINE__)(pybind11::module & m)
#endif // ONEFLOW_API_PYTHON_UTIL_OF_API_REGISTRY_H_
| 1,345 |
725 | <reponame>vexofp/hyperion
// STL includes
#include <cstring>
#include <cstdio>
#include <iostream>
// hyperion local includes
#include "LedDeviceAmbiLed.h"
LedDeviceAmbiLed::LedDeviceAmbiLed(const std::string& outputDevice, const unsigned baudrate, int delayAfterConnect_ms) :
LedRs232Device(outputDevice, baudrate, delayAfterConnect_ms),
_ledBuffer(0),
_timer()
{
// setup the timer
_timer.setSingleShot(false);
_timer.setInterval(5000);
connect(&_timer, SIGNAL(timeout()), this, SLOT(rewriteLeds()));
// start the timer
_timer.start();
}
int LedDeviceAmbiLed::write(const std::vector<ColorRgb> & ledValues)
{
if (_ledBuffer.size() == 0)
{
_ledBuffer.resize(1 + 3*ledValues.size());
_ledBuffer[3*ledValues.size()] = 255;
}
// restart the timer
_timer.start();
// write data
memcpy( _ledBuffer.data(), ledValues.data(), ledValues.size() * 3);
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
int LedDeviceAmbiLed::switchOff()
{
// restart the timer
_timer.start();
// write data
memset(_ledBuffer.data(), 0, _ledBuffer.size()-6);
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
void LedDeviceAmbiLed::rewriteLeds()
{
writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
| 446 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.