max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
785
/* * Copyright © 2018, 2021 Apple Inc. and the ServiceTalk project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.servicetalk.opentracing.inmemory; import io.servicetalk.opentracing.inmemory.api.InMemoryReference; import io.servicetalk.opentracing.inmemory.api.InMemorySpan; import io.servicetalk.opentracing.inmemory.api.InMemorySpanContext; import io.opentracing.Span; import io.opentracing.SpanContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import javax.annotation.Nullable; import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; /** * Span object used by the {@link DefaultInMemoryTracer}. */ abstract class AbstractInMemorySpan implements InMemorySpan { private static final Logger logger = LoggerFactory.getLogger(AbstractInMemorySpan.class); private final InMemorySpanContext context; private final List<InMemoryReference> references; String operationName; /** * Instantiates a new {@link AbstractInMemorySpan}. * * @param operationName the operation name. * @param references a {@link List} of {@link InMemoryReference}s. * @param context the {@link SpanContext} associated with this {@link Span} */ AbstractInMemorySpan(String operationName, List<InMemoryReference> references, InMemorySpanContext context) { this.context = requireNonNull(context); this.operationName = operationName; this.references = references; } @Override public final InMemorySpanContext context() { return context; } @Override public final String operationName() { return operationName; } @Override public final List<InMemoryReference> references() { return unmodifiableList(references); } @Override public final Span setOperationName(String operationName) { this.operationName = operationName; return this; } @Override public final Span setBaggageItem(String key, String value) { // Not supported, silently ignore to avoid breaking third party code. logger.debug("setBaggageItem() is not supported"); return this; } @Nullable @Override public final String getBaggageItem(String key) { logger.debug("getBaggageItem() is not supported"); return null; } }
956
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/test_print_view_manager_for_request_preview.h" #include <memory> #include <utility> #include "base/callback.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/printing/print_view_manager.h" #include "components/printing/common/print.mojom.h" #include "content/public/browser/web_contents.h" using content::WebContents; namespace printing { // static void TestPrintViewManagerForRequestPreview::CreateForWebContents( WebContents* web_contents) { web_contents->SetUserData( PrintViewManager::UserDataKey(), std::make_unique<TestPrintViewManagerForRequestPreview>(web_contents)); } TestPrintViewManagerForRequestPreview::TestPrintViewManagerForRequestPreview( WebContents* web_contents) : PrintViewManager(web_contents) {} TestPrintViewManagerForRequestPreview:: ~TestPrintViewManagerForRequestPreview() = default; // static TestPrintViewManagerForRequestPreview* TestPrintViewManagerForRequestPreview::FromWebContents( WebContents* web_contents) { return static_cast<TestPrintViewManagerForRequestPreview*>( PrintViewManager::FromWebContents(web_contents)); } void TestPrintViewManagerForRequestPreview::set_quit_closure( base::OnceClosure quit_closure) { quit_closure_ = std::move(quit_closure); } void TestPrintViewManagerForRequestPreview::RequestPrintPreview( mojom::RequestPrintPreviewParamsPtr params) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(quit_closure_)); PrintViewManager::RequestPrintPreview(std::move(params)); } } // namespace printing
597
1,970
<reponame>liufangqi/hudi<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hudi.table.action.compact; import org.apache.hudi.avro.model.HoodieCompactionPlan; import org.apache.hudi.client.WriteStatus; import org.apache.hudi.common.data.HoodieData; import org.apache.hudi.common.model.HoodieCommitMetadata; import org.apache.hudi.common.model.HoodieRecordPayload; import org.apache.hudi.common.model.HoodieWriteStat; import org.apache.hudi.common.table.timeline.HoodieActiveTimeline; import org.apache.hudi.common.table.timeline.HoodieInstant; import org.apache.hudi.common.table.timeline.HoodieTimeline; import org.apache.hudi.common.table.timeline.TimelineMetadataUtils; import org.apache.hudi.common.util.Option; import org.apache.hudi.exception.HoodieCompactionException; import org.apache.hudi.table.HoodieTable; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; /** * Base class helps to perform compact. * * @param <T> Type of payload in {@link org.apache.hudi.common.model.HoodieRecord} * @param <I> Type of inputs * @param <K> Type of keys * @param <O> Type of outputs */ public class CompactHelpers<T extends HoodieRecordPayload, I, K, O> { private static final CompactHelpers SINGLETON_INSTANCE = new CompactHelpers(); private CompactHelpers() { } public static CompactHelpers getInstance() { return SINGLETON_INSTANCE; } public HoodieCommitMetadata createCompactionMetadata( HoodieTable table, String compactionInstantTime, HoodieData<WriteStatus> writeStatuses, String schema) throws IOException { byte[] planBytes = table.getActiveTimeline().readCompactionPlanAsBytes( HoodieTimeline.getCompactionRequestedInstant(compactionInstantTime)).get(); HoodieCompactionPlan compactionPlan = TimelineMetadataUtils.deserializeCompactionPlan(planBytes); List<HoodieWriteStat> updateStatusMap = writeStatuses.map(WriteStatus::getStat).collectAsList(); HoodieCommitMetadata metadata = new HoodieCommitMetadata(true); for (HoodieWriteStat stat : updateStatusMap) { metadata.addWriteStat(stat.getPartitionPath(), stat); } metadata.addMetadata(org.apache.hudi.common.model.HoodieCommitMetadata.SCHEMA_KEY, schema); if (compactionPlan.getExtraMetadata() != null) { compactionPlan.getExtraMetadata().forEach(metadata::addMetadata); } return metadata; } public void completeInflightCompaction(HoodieTable table, String compactionCommitTime, HoodieCommitMetadata commitMetadata) { HoodieActiveTimeline activeTimeline = table.getActiveTimeline(); try { activeTimeline.transitionCompactionInflightToComplete( new HoodieInstant(HoodieInstant.State.INFLIGHT, HoodieTimeline.COMPACTION_ACTION, compactionCommitTime), Option.of(commitMetadata.toJsonString().getBytes(StandardCharsets.UTF_8))); } catch (IOException e) { throw new HoodieCompactionException( "Failed to commit " + table.getMetaClient().getBasePath() + " at time " + compactionCommitTime, e); } } }
1,240
678
<filename>glean/lang/clang/preprocessor.cpp<gh_stars>100-1000 /* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "glean/lang/clang/preprocessor.h" #include <llvm/Config/llvm-config.h> namespace { using namespace facebook::glean::clangx; using namespace facebook::glean::cpp; struct PPCallbacks final : public clang::PPCallbacks { explicit PPCallbacks(ClangDB* d) : db(*d) {} Fact<Pp::Macro> macro(const clang::Token& name) { return db.fact<Pp::Macro>(static_cast<std::string>(name.getIdentifierInfo()->getName())); } // clang::PPCallbacks overrides void FileChanged( clang::SourceLocation loc, FileChangeReason reason, clang::SrcMgr::CharacteristicKind, clang::FileID) override { if (reason == clang::PPCallbacks::EnterFile) { db.enterFile(loc, last_include); last_include.reset(); } } #if LLVM_VERSION_MAJOR >= 11 void FileSkipped( const clang::FileEntryRef& entry, const clang::Token&, clang::SrcMgr::CharacteristicKind) override { db.skipFile(last_include, &entry.getFileEntry()); last_include.reset(); } #else void FileSkipped( const clang::FileEntry& entry, const clang::Token&, clang::SrcMgr::CharacteristicKind) override { db.skipFile(last_include, &entry); last_include.reset(); } #endif void InclusionDirective( clang::SourceLocation hashLoc, const clang::Token&, clang::StringRef, bool, clang::CharSourceRange filenameRange, const clang::FileEntry *file, clang::StringRef, clang::StringRef, const clang::Module * #if LLVM_VERSION_MAJOR >= 8 ,clang::SrcMgr::CharacteristicKind #endif ) override { last_include = ClangDB::Include{hashLoc, filenameRange, file}; } void Ifdef( clang::SourceLocation, const clang::Token& name, const clang::MacroDefinition& def) override { clang::SourceRange range(name.getLocation(), name.getEndLoc()); macroUsed(name, def, range, false); } void Ifndef( clang::SourceLocation, const clang::Token& name, const clang::MacroDefinition& def) override { clang::SourceRange range(name.getLocation(), name.getEndLoc()); macroUsed(name, def, range, false); } void MacroDefined( const clang::Token& name, const clang::MacroDirective *) override { auto src = db.srcRange(name.getLocation()); auto def = db.fact<Pp::Define>(macro(name), src.range); db.ppevent(Cxx::PPEvent::define(def), src); } void MacroUndefined( const clang::Token& name, const clang::MacroDefinition&, const clang::MacroDirective *) override { auto src = db.srcRange(name.getLocation()); auto undef = db.fact<Pp::Undef>(macro(name), src.range); db.ppevent(Cxx::PPEvent::undef(undef), src); } void macroUsed( const clang::Token& name, const clang::MacroDefinition& def, clang::SourceRange range, bool expand) { #define PROFILE_macroUsed 0 #if PROFILE_macroUsed using Clock = std::chrono::steady_clock; static std::chrono::microseconds time = std::chrono::microseconds::zero(); static size_t count = 0; const auto start = Clock::now(); #endif // Getting the location is expensive and there are a lot fewer macro // definition sites than there are macro expansions so let's cache those // locations. folly::Optional<Src::Loc> defloc; if (auto info = def.getMacroInfo()) { defloc = folly::get_optional(macros, info); if (!defloc.has_value()) { defloc = db.srcLoc(info->getDefinitionLoc()); macros.insert({info, defloc.value()}); } } // We absolutely don't want to let Clang resolve nested macro expansion // ranges here (via db.srcRange -> getExpansionRange) as doing so turned out // to be horrendously expensive. Instead, when we see a top-level expansion // (the range isn't isMacroID) we resolve it ourselves and store it in // 'expansion'. Subsequent nested expansions must be part of this top-level // expansion so we just use that range. There is a subtlety with how we // handle expansions in macro arguments, see comments below. This is a // massive win in performance - at one time, this function accounted for // >40% of the running time in Strobelight (cf. T59197014). const ClangDB::SourceRange src = (range.getBegin().isMacroID() && expansion.has_value()) // This is part of the current top-level expansion, just use its // range. ? expansion.value() // Manually convert this to a CharSourceRange and call the more // efficient immediateSourceRange rather than srcRange. : db.immediateSrcRange( clang::CharSourceRange::getCharRange( { // getBegin points at the start of the first token range.getBegin(), // getEnd points at the start of the last token. range.getEnd().getLocWithOffset( // Skip over the last token to make this an proper (exclusive) // char range. range.getBegin() == range.getEnd() // The macro expansion range is only one token which must be // the macro name. ? name.getLength() // Multiple tokens which means the last token must be the // closing parenthesis. : 1) })); if (range.getBegin().isMacroID() && !expansion.has_value()) { // This really shouldn't happen. LOG(ERROR) << "Unexpected nested macro expansion at " << range.printToString(db.sourceManager()); } // Don't update expansion if this is an expansion of a macro argument. // Consider: // // #define ONE 1 // #define TWO 2 // #define FOO ONE // #define MACRO(x) x+TWO // int y = MACRO(FOO); // // Here, we get the following calls: // // MACRO(...) - the outer expansion (not isMacroID) // FOO - argument (not isMacroID) // ONE - definition of FOO (isMacroID) // TWO - definition of MACRO(x) (isMacroID) // // We set expansion in the MACRO(...) call but if we then update it in // the FOO call, we'd assign the (nested) expansion of TWO to the range // of FOO. Instead, we don't update and assign the expansions of both // ONE and TWO (but not FOO!) to the range of MACRO(FOO). This is arguably // slightly less wrong. There doesn't seem to be an easy way to do better // without actually resolving the MacroID ranges. Perhaps we could hook // into the lexer somehow. if (!range.getBegin().isMacroID() && (!expansion.has_value() || src.file != expansion->file || src.span.start + src.span.length > expansion->span.start + expansion->span.length)) { expansion = src; } // Resolve the name range manually, too. For top-level expansions, it's // the (inclusive for now) range of the name token. For nested expansions // the current schema is broken anyway - we assign the range of the // top-level expansion (it should be spelling file + range). const auto name_r = name.getLocation().isMacroID() ? src : db.immediateSrcRange( clang::CharSourceRange::getCharRange({ name.getLocation(), name.getEndLoc() })); auto use = db.fact<Pp::Use>( macro(name), Src::ByteRange{name_r.span.start, name_r.span.start + name_r.span.length}, maybe(defloc), expand, src.range); db.ppevent(Cxx::PPEvent::use(use), src); #if PROFILE_macroUsed const auto end = Clock::now(); time += std::chrono::duration_cast<std::chrono::microseconds>(end - start); ++count; if ((count % 10000) == 0) { LOG(INFO) << "macroUsed " << time.count() << "us (" << count << ")"; } #endif } void MacroExpands( const clang::Token& name, const clang::MacroDefinition& def, clang::SourceRange range, const clang::MacroArgs *) override { macroUsed(name, def, range, true); } void Defined( const clang::Token& name, const clang::MacroDefinition& def, clang::SourceRange range) override { macroUsed(name, def, range, false); } ClangDB& db; folly::Optional<ClangDB::Include> last_include; // The range of the current top-level macro expansion (see comments in // macroUsed). folly::Optional<ClangDB::SourceRange> expansion; // Cached locations of macro definitions (see macroUsed). folly::F14FastMap<clang::MacroInfo *, Src::Loc> macros; }; } namespace facebook { namespace glean { namespace clangx { std::unique_ptr<clang::PPCallbacks> newPPCallbacks(ClangDB* db) { return std::make_unique<PPCallbacks>(db); } } } }
3,448
1,428
#include <iostream> using namespace std; int main(){ cout<< "Hello World!\n"; }
31
314
<reponame>DuncanBetts/morepath import morepath import dectate def test_cleanup(): class App(morepath.App): pass dectate.commit(App) # second commit should clean up after the first one, so we # expect no conflict errors dectate.commit(App)
101
1,909
<filename>xchange-cexio/src/main/java/info/bitrich/xchangestream/cexio/dto/CexioWebSocketPongMessage.java package info.bitrich.xchangestream.cexio.dto; import com.fasterxml.jackson.annotation.JsonProperty; import info.bitrich.xchangestream.cexio.CexioStreamingRawService; public class CexioWebSocketPongMessage { @JsonProperty("e") private final String e = CexioStreamingRawService.PONG; public CexioWebSocketPongMessage() {} public String getE() { return e; } @Override public String toString() { return "CexioWebSocketPongMessage{" + "e='" + e + '\'' + '}'; } }
227
988
<filename>deps/GraphBLAS/Source/GB_concat.c //------------------------------------------------------------------------------ // GB_concat: concatenate an array of matrices into a single matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #define GB_FREE_WORKSPACE \ GB_WERK_POP (Tile_cols, int64_t) ; \ GB_WERK_POP (Tile_rows, int64_t) ; #define GB_FREE_ALL \ GB_FREE_WORKSPACE ; \ GB_phbix_free (C) ; #include "GB_concat.h" GrB_Info GB_concat // concatenate a 2D array of matrices ( GrB_Matrix C, // input/output matrix for results const GrB_Matrix *Tiles, // 2D row-major array of size m-by-n const GrB_Index m, const GrB_Index n, GB_Context Context ) { //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- GB_WERK_DECLARE (Tile_rows, int64_t) ; GB_WERK_DECLARE (Tile_cols, int64_t) ; GB_WERK_PUSH (Tile_rows, m+1, int64_t) ; GB_WERK_PUSH (Tile_cols, n+1, int64_t) ; if (Tile_rows == NULL || Tile_cols == NULL) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; ASSERT_MATRIX_OK (C, "C input for GB_concat", GB0) ; for (int64_t k = 0 ; k < m*n ; k++) { GrB_Matrix A = Tiles [k] ; GB_RETURN_IF_NULL_OR_FAULTY (A) ; ASSERT_MATRIX_OK (A, "Tile[k] input for GB_concat", GB0) ; GB_MATRIX_WAIT (A) ; } //-------------------------------------------------------------------------- // check the sizes and types of each tile //-------------------------------------------------------------------------- bool csc = C->is_csc ; GrB_Type ctype = C->type ; for (int64_t i = 0 ; i < m ; i++) { GrB_Matrix A = GB_TILE (Tiles, i, 0) ; Tile_rows [i] = GB_NROWS (A) ; } for (int64_t j = 0 ; j < n ; j++) { GrB_Matrix A = GB_TILE (Tiles, 0, j) ; Tile_cols [j] = GB_NCOLS (A) ; } bool C_is_full = true ; bool C_iso = false ; const size_t csize = ctype->size ; const GB_Type_code ccode = ctype->code ; GB_void cscalar [GB_VLA(csize)] ; GB_void ascalar [GB_VLA(csize)] ; memset (cscalar, 0, csize) ; memset (ascalar, 0, csize) ; int64_t cnz = 0 ; int64_t cnvec_estimate = 0 ; // upper bound on C->nvec if hypersparse for (int64_t i = 0 ; i < m ; i++) { for (int64_t j = 0 ; j < n ; j++) { //------------------------------------------------------------------ // get the (i,j) tile //------------------------------------------------------------------ GrB_Matrix A = GB_TILE (Tiles, i, j) ; //------------------------------------------------------------------ // check the types and dimensions //------------------------------------------------------------------ int64_t nrows = GB_NROWS (A) ; int64_t ncols = GB_NCOLS (A) ; int64_t anz = GB_nnz (A) ; int A_sparsity = GB_sparsity (A) ; if (A_sparsity == GxB_HYPERSPARSE) { cnvec_estimate += A->nvec ; } else { int64_t n = csc ? ncols : nrows ; cnvec_estimate += GB_IMIN (n, anz) ; } GrB_Type atype = A->type ; #define offset (GB_Global_print_one_based_get ( ) ? 1 : 0) if (!GB_Type_compatible (ctype, atype)) { GB_FREE_WORKSPACE ; GB_ERROR (GrB_DOMAIN_MISMATCH, "Input matrix Tiles{" GBd "," GBd "} of type [%s]\n" "cannot be typecast to output of type [%s]\n", i+offset, j+offset, atype->name, ctype->name) ; } int64_t tile_rows = Tile_rows [i] ; if (tile_rows != nrows) { GB_FREE_WORKSPACE ; GB_ERROR (GrB_DIMENSION_MISMATCH, "Input matrix Tiles{" GBd "," GBd "} is " GBd "-by-" GBd "; its row\ndimension must match all other matrices Tiles{" GBd ",:}, which is " GBd "\n", i+offset, j+offset, nrows, ncols, i+offset, tile_rows) ; } int64_t tile_cols = Tile_cols [j] ; if (tile_cols != ncols) { GB_FREE_WORKSPACE ; GB_ERROR (GrB_DIMENSION_MISMATCH, "Input matrix Tiles{" GBd "," GBd "} is " GBd "-by-" GBd "; its column\ndimension must match all other matrices " "Tiles{:," GBd "}, which is " GBd "\n", i+offset, j+offset, nrows, ncols, j+offset, tile_cols) ; } //------------------------------------------------------------------ // check if C is iso, full, and/or empty //------------------------------------------------------------------ bool A_full = (A_sparsity == GxB_FULL) || (anz == GB_nnz_full (A)) ; bool A_empty = (anz == 0) ; bool A_iso = A->iso || (anz == 1 && A_sparsity != GxB_BITMAP) ; // C is full only if all tiles are full or as-if-full. A tile with // a zero dimension has no entries and is both as-if-full and // empty, but not iso. C_is_full = C_is_full && A_full ; // get the iso value of an iso tile, typecasted to C->type if (A_iso) { GB_cast_scalar (ascalar, ccode, A->x, A->type->code, csize) ; if (cnz == 0) { // A is the first non-empty iso tile seen while C is empty; // C becomes non-empty and iso, with the iso value from A. C_iso = true ; memcpy (cscalar, ascalar, csize) ; } } // C is iso only if at least one tile is iso, and all others empty // or iso with the same value as the first non-empty iso tile if (C_iso) { if (A_empty) { // C remains iso } else if (A_iso) { // C and A are both iso; check if iso values are the same C_iso = C_iso && (memcmp (cscalar, ascalar, csize) == 0) ; } else { // otherwise, C is non-iso C_iso = false ; } } cnz += anz ; } } //-------------------------------------------------------------------------- // replace Tile_rows and Tile_cols with their cumulative sum //-------------------------------------------------------------------------- GB_cumsum (Tile_rows, m, NULL, 1, Context) ; GB_cumsum (Tile_cols, n, NULL, 1, Context) ; int64_t cnrows = Tile_rows [m] ; int64_t cncols = Tile_cols [n] ; if (cnrows != GB_NROWS (C) || cncols != GB_NCOLS (C)) { GB_FREE_WORKSPACE ; GB_ERROR (GrB_DIMENSION_MISMATCH, "C is " GBd "-by-" GBd " but Tiles{:,:} is " GBd "-by-" GBd "\n", GB_NROWS (C), GB_NCOLS (C), cnrows, cncols) ; } //-------------------------------------------------------------------------- // C = concatenate (Tiles) //-------------------------------------------------------------------------- if (cnz == 0) { // construct C as an empty matrix GBURBLE ("(empty concat) ") ; GB_OK (GB_clear (C, Context)) ; } else if (C_is_full) { // construct C as full GBURBLE ("(%sfull concat) ", C_iso ? "iso " : "") ; GB_OK (GB_concat_full (C, C_iso, cscalar, Tiles, m, n, Tile_rows, Tile_cols, Context)) ; } else if (GB_convert_sparse_to_bitmap_test (C->bitmap_switch, cnz, cnrows, cncols)) { // construct C as bitmap GBURBLE ("(%sbitmap concat) ", C_iso ? "iso " : "") ; GB_OK (GB_concat_bitmap (C, C_iso, cscalar, cnz, Tiles, m, n, Tile_rows, Tile_cols, Context)) ; } else if (GB_convert_sparse_to_hyper_test (C->hyper_switch, cnvec_estimate, C->vdim)) { // construct C as hypersparse GBURBLE ("(%shyper concat) ", C_iso ? "iso " : "") ; GB_OK (GB_concat_hyper (C, C_iso, cscalar, cnz, Tiles, m, n, Tile_rows, Tile_cols, Context)) ; } else { // construct C as sparse GBURBLE ("(%ssparse concat) ", C_iso ? "iso " : "") ; GB_OK (GB_concat_sparse (C, C_iso, cscalar, cnz, Tiles, m, n, Tile_rows, Tile_cols, Context)) ; } //-------------------------------------------------------------------------- // conform C to its desired format and return result //-------------------------------------------------------------------------- GB_FREE_WORKSPACE ; ASSERT_MATRIX_OK (C, "C before conform for GB_concat", GB0) ; GB_OK (GB_conform (C, Context)) ; ASSERT_MATRIX_OK (C, "C output for GB_concat", GB0) ; return (GrB_SUCCESS) ; }
4,687
6,989
<reponame>HeyLey/catboost #include <stdlib.h> #include <stdio.h> #include "vars.h" #include <util/system/platform.h> #define main RealMain #include "Modules/python.c" #undef main int main(int argc, char** argv) { char* distArcPath = getenv("ARCADIA_ROOT_DISTBUILD"); char* pyPath = NULL; char* mx = 0; char* x = 0; int ret; putenv("PYTHONHOME="); putenv("PY_IGNORE_ENVIRONMENT="); putenv("PYTHONDONTWRITEBYTECODE=x"); if (distArcPath) { pyPath = malloc(strlen("PYTHONPATH=") + strlen(distArcPath) + strlen(GetPyLib()) + 2); if (!pyPath) abort(); mx = strdup(GetPyLib()); x = mx; if (!x) abort(); if (*x && *x == '"') { x += 1; x[strlen(x) - 1] = 0; } sprintf(pyPath, "PYTHONPATH=%s/%s", distArcPath, x); } else { pyPath = malloc(strlen("PYTHONPATH=") + strlen(GetLibDir()) + 1); sprintf(pyPath, "PYTHONPATH=%s", GetLibDir()); } putenv(pyPath); ret = RealMain(argc, argv); if (pyPath) free(pyPath); if (mx) free(mx); return ret; }
603
348
{"nom":"Conat","dpt":"Pyrénées-Orientales","inscrits":78,"abs":21,"votants":57,"blancs":11,"nuls":3,"exp":43,"res":[{"panneau":"1","voix":26},{"panneau":"2","voix":17}]}
73
758
import pytest import random import string import os import requests import boto3 from fixtures import get_order, get_product, iam_auth # pylint: disable=import-error,no-name-in-module from helpers import get_parameter # pylint: disable=import-error,no-name-in-module @pytest.fixture(scope="module") def products_table_name(): """ Products DynamoDB table name """ return get_parameter("/ecommerce/{Environment}/products/table/name") @pytest.fixture(scope="module") def orders_table_name(): """ Orders DynamoDB table name """ return get_parameter("/ecommerce/{Environment}/orders/table/name") @pytest.fixture(scope="module") def user_pool_id(): """ Cognito User Pool ID """ return get_parameter("/ecommerce/{Environment}/users/user-pool/id") @pytest.fixture(scope="module") def delivery_pricing_api_url(): """ Delivery Pricing API """ return get_parameter("/ecommerce/{Environment}/delivery-pricing/api/url") @pytest.fixture def api_id(): """ Frontend GraphQL API ID """ return get_parameter("/ecommerce/{Environment}/frontend-api/api/id") @pytest.fixture def api_url(): """ Frontend GraphQL API URL """ return get_parameter("/ecommerce/{Environment}/frontend-api/api/url") @pytest.fixture def payment_3p_api_url(): return get_parameter("/ecommerce/{Environment}/payment-3p/api/url") @pytest.fixture def api_key(api_id): """ API Key for AppSync """ appsync = boto3.client("appsync") response = appsync.create_api_key(apiId=api_id) yield response["apiKey"]["id"] appsync.delete_api_key(apiId=api_id, id=response["apiKey"]["id"]) @pytest.fixture(scope="module") def password(): """ Generate a unique password for the user """ return "".join( random.choices(string.ascii_uppercase, k=10) + random.choices(string.ascii_lowercase, k=10) + random.choices(string.digits, k=5) + random.choices(string.punctuation, k=3) ) @pytest.fixture(scope="module") def email(): """ Generate a unique email address for the user """ return "".join(random.choices(string.ascii_lowercase, k=20))+"@example.<EMAIL>" @pytest.fixture(scope="module") def client_id(user_pool_id): """ Return a user pool client """ cognito = boto3.client("cognito-idp") # Create a Cognito User Pool Client response = cognito.create_user_pool_client( UserPoolId=user_pool_id, ClientName="ecommerce-{}-frontend-api-test".format(os.environ["ECOM_ENVIRONMENT"]), GenerateSecret=False, ExplicitAuthFlows=["ADMIN_NO_SRP_AUTH"] ) # Return the client ID client_id = response["UserPoolClient"]["ClientId"] yield client_id # Delete the client cognito.delete_user_pool_client( UserPoolId=user_pool_id, ClientId=client_id ) @pytest.fixture(scope="module") def user_id(user_pool_id, email, password): """ User ID generated by Cognito """ cognito = boto3.client("cognito-idp") # Create a Cognito user response = cognito.admin_create_user( UserPoolId=user_pool_id, Username=email, UserAttributes=[{ "Name": "email", "Value": email }], MessageAction="SUPPRESS" ) user_id = response["User"]["Username"] cognito.admin_set_user_password( UserPoolId=user_pool_id, Username=user_id, Password=password, Permanent=True ) # Return the user ID yield user_id # Delete the user cognito.admin_delete_user( UserPoolId=user_pool_id, Username=user_id ) @pytest.fixture(scope="module") def jwt_token(user_pool_id, user_id, client_id, email, password): """ Returns a JWT token for API Gateway """ cognito = boto3.client("cognito-idp") response = cognito.admin_initiate_auth( UserPoolId=user_pool_id, ClientId=client_id, AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": email, "PASSWORD": password } ) return response["AuthenticationResult"]["IdToken"] @pytest.fixture(scope="function") def product(get_product, products_table_name): """ Product """ table = boto3.resource("dynamodb").Table(products_table_name) # pylint: disable=no-member product = get_product() table.put_item(Item=product) yield product table.delete_item(Key={"productId": product["productId"]}) @pytest.fixture(scope="function") def order_request(get_order, product, iam_auth, delivery_pricing_api_url, payment_3p_api_url): """ Order Request """ order = get_order() # Grab the correct delivery price from the backend res = requests.post( "{}/backend/pricing".format(delivery_pricing_api_url), auth=iam_auth(delivery_pricing_api_url), json={ "products": [product], "address": order["address"] } ) delivery_price = res.json()["pricing"] # Get a payment token total = delivery_price + sum([p["price"]*p.get("quantity", 1) for p in order["products"]]) res = requests.post( "{}/preauth".format(payment_3p_api_url), json={ "cardNumber": "1234567890123456", "amount": total } ) payment_token = res.json()["paymentToken"] return { "products": [product], "address": order["address"], "deliveryPrice": delivery_price, "paymentToken": payment_token } def test_create_order(jwt_token, api_url, order_request): """ Test createOrder """ headers = {"Authorization": jwt_token} query = """ mutation ($order: CreateOrderRequest!) { createOrder(order: $order) { success message errors order { orderId userId } } } """ variables = { "order": order_request } response = requests.post(api_url, json={"query": query, "variables": variables}, headers=headers) data = response.json() print(data) assert "data" in data assert data["data"] is not None assert "createOrder" in data["data"] result = data["data"]["createOrder"] assert result["success"] == True assert "order" in result def test_get_products(api_url, product, api_key): """ Test getProducts """ headers = {"X-Api-Key": api_key} query = """ query { getProducts { products { productId name } } } """ response = requests.post(api_url, json={"query": query}, headers=headers) data = response.json() assert "data" in data assert data["data"] is not None assert "getProducts" in data["data"] assert "products" in data["data"]["getProducts"] found = False for res_product in data["data"]["getProducts"]["products"]: if res_product["productId"] == product["productId"]: found = True assert found == True def test_get_product(api_url, product, api_key): """ Test getProduct """ headers = {"X-Api-Key": api_key} query = """ query ($productId: ID!) { getProduct(productId: $productId) { productId name } } """ variables = { "productId": product["productId"] } response = requests.post(api_url, json={"query": query, "variables": variables}, headers=headers) data = response.json() assert "data" in data assert data["data"] is not None assert "getProduct" in data["data"] assert data["data"]["getProduct"]["productId"] == product["productId"] assert data["data"]["getProduct"]["name"] == product["name"] def test_get_orders(jwt_token, api_url): """ Test getOrders """ headers = {"Authorization": jwt_token} query = """ query { getOrders { orders { orderId userId } } } """ response = requests.post(api_url, json={"query": query}, headers=headers) data = response.json() print(data) assert "data" in data assert "getOrders" in data["data"] assert "orders" in data["data"]["getOrders"] def test_get_delivery_pricing(get_order, jwt_token, api_url): """ Test getDeliveryPricing """ order = get_order() headers = {"Authorization": jwt_token} query = """ query($input: DeliveryPricingInput!) { getDeliveryPricing(input: $input) { pricing } } """ variables = { "input": { "products": order["products"], "address": order["address"] } } print("VARIABLES", variables) response = requests.post(api_url, json={"query": query, "variables": variables}, headers=headers) data = response.json() print(data) assert "data" in data assert "getDeliveryPricing" in data["data"] assert "pricing" in data["data"]["getDeliveryPricing"]
3,790
13,111
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.oap.server.receiver.zabbix.provider.protocol; import com.google.common.collect.ImmutableSet; import org.apache.skywalking.oap.server.library.module.ModuleStartException; import org.apache.skywalking.oap.server.receiver.zabbix.provider.ZabbixBaseTest; import org.apache.skywalking.oap.server.receiver.zabbix.provider.ZabbixMetrics; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ZabbixProtocolHandlerTest extends ZabbixBaseTest { @Override protected ZabbixMetrics buildZabbixMetrics() throws ModuleStartException, Exception { ZabbixMetrics metrics = mock(ZabbixMetrics.class); // mock zabbix metrics when(metrics.getAllMonitorMetricNames(any())).thenReturn(ImmutableSet.<String>builder().add("system.cpu.load[all,avg15]").build()); when(metrics.convertMetrics(any())).thenReturn(ZabbixMetrics.ConvertStatics.EMPTY); return metrics; } /** * Test active tasks and agent data request and response */ @Test public void testReceive() throws Throwable { // Verify Active Checks writeZabbixMessage("{\"request\":\"active checks\",\"host\":\"zabbix-test-agent\"}"); assertZabbixActiveChecksRequest(0, "zabbix-test-agent"); assertZabbixActiveChecksResponse(0, "system.cpu.load[all,avg15]"); // Verify Agent data writeZabbixMessage("{\"request\":\"agent data\",\"session\":\"f32425dc61971760bf791f731931a92e\",\"data\":[{\"host\":\"zabbix-test-agent\",\"key\":\"system.cpu.load[all,avg15]\",\"value\":\"1.123\",\"id\":2,\"clock\":1609588563,\"ns\":87682907}],\"clock\":1609588568,\"ns\":102244476}"); assertZabbixAgentDataRequest(1, "zabbix-test-agent", "system.cpu.load[all,avg15]"); assertZabbixAgentDataResponse(2); } /** * Test error protocol */ @Test public void testErrorProtocol() throws Throwable { // Simple header for (int i = 1; i < 4; i++) { assertNeedMoreInput(new byte[i]); } // Only header string assertNeedMoreInput(new byte[] {'Z', 'B', 'X', 'D'}); // Header error assertWriteErrorProtocol(new byte[] {'Z', 'B', 'X', 'D', 2, 0, 0, 0, 0}); assertWriteErrorProtocol(new byte[] {'Z', 'B', 'X', 'D', 2, 1, 0, 0, 0}); // Need more content assertNeedMoreInput(new byte[] {'Z', 'B', 'X', 'D', 1, 5, 0, 0, 0, 1, 1, 1}); // Empty data assertWriteErrorProtocol(buildZabbixRequestData("")); assertWriteErrorProtocol(buildZabbixRequestData("{}")); assertWriteErrorProtocol(buildZabbixRequestData("{\"test\": 1}")); } }
1,369
322
#!/usr/bin/env python """ safe2bin.py - Simple safe(hex) to binary format converter Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import binascii import re import string import os import sys from optparse import OptionError from optparse import OptionParser # Regex used for recognition of hex encoded characters HEX_ENCODED_CHAR_REGEX = r"(?P<result>\\x[0-9A-Fa-f]{2})" # Raw chars that will be safe encoded to their slash (\) representations (e.g. newline to \n) SAFE_ENCODE_SLASH_REPLACEMENTS = "\t\n\r\x0b\x0c" # Characters that don't need to be safe encoded SAFE_CHARS = "".join(filter(lambda _: _ not in SAFE_ENCODE_SLASH_REPLACEMENTS, string.printable.replace('\\', ''))) # Prefix used for hex encoded values HEX_ENCODED_PREFIX = r"\x" # Strings used for temporary marking of hex encoded prefixes (to prevent double encoding) HEX_ENCODED_PREFIX_MARKER = "__HEX_ENCODED_PREFIX__" # String used for temporary marking of slash characters SLASH_MARKER = "__SLASH__" def safecharencode(value): """ Returns safe representation of a given basestring value >>> safecharencode(u'test123') u'test123' >>> safecharencode(u'test\x01\x02\xff') u'test\\01\\02\\03\\ff' """ retVal = value if isinstance(value, basestring): if any([_ not in SAFE_CHARS for _ in value]): retVal = retVal.replace(HEX_ENCODED_PREFIX, HEX_ENCODED_PREFIX_MARKER) retVal = retVal.replace('\\', SLASH_MARKER) for char in SAFE_ENCODE_SLASH_REPLACEMENTS: retVal = retVal.replace(char, repr(char).strip('\'')) retVal = reduce(lambda x, y: x + (y if (y in string.printable or isinstance(value, unicode) and ord(y) >= 160) else '\\x%02x' % ord(y)), retVal, (unicode if isinstance(value, unicode) else str)()) retVal = retVal.replace(SLASH_MARKER, "\\\\") retVal = retVal.replace(HEX_ENCODED_PREFIX_MARKER, HEX_ENCODED_PREFIX) elif isinstance(value, list): for i in xrange(len(value)): retVal[i] = safecharencode(value[i]) return retVal def safechardecode(value, binary=False): """ Reverse function to safecharencode """ retVal = value if isinstance(value, basestring): retVal = retVal.replace('\\\\', SLASH_MARKER) while True: match = re.search(HEX_ENCODED_CHAR_REGEX, retVal) if match: retVal = retVal.replace(match.group("result"), (unichr if isinstance(value, unicode) else chr)(ord(binascii.unhexlify(match.group("result").lstrip("\\x"))))) else: break for char in SAFE_ENCODE_SLASH_REPLACEMENTS[::-1]: retVal = retVal.replace(repr(char).strip('\''), char) retVal = retVal.replace(SLASH_MARKER, '\\') if binary: if isinstance(retVal, unicode): retVal = retVal.encode("utf8") elif isinstance(value, (list, tuple)): for i in xrange(len(value)): retVal[i] = safechardecode(value[i]) return retVal def main(): usage = '%s -i <input file> [-o <output file>]' % sys.argv[0] parser = OptionParser(usage=usage, version='0.1') try: parser.add_option('-i', dest='inputFile', help='Input file') parser.add_option('-o', dest='outputFile', help='Output file') (args, _) = parser.parse_args() if not args.inputFile: parser.error('Missing the input file, -h for help') except (OptionError, TypeError), e: parser.error(e) if not os.path.isfile(args.inputFile): print 'ERROR: the provided input file \'%s\' is not a regular file' % args.inputFile sys.exit(1) f = open(args.inputFile, 'r') data = f.read() f.close() if not args.outputFile: args.outputFile = args.inputFile + '.bin' f = open(args.outputFile, 'wb') f.write(safechardecode(data)) f.close() if __name__ == '__main__': main()
1,726
1,073
// -flto causes a switch to llvm-bc object files. // RUN: %clang -ccc-print-phases -c %s -flto 2> %t // RUN: FileCheck -check-prefix=CHECK-COMPILE-ACTIONS < %t %s // // CHECK-COMPILE-ACTIONS: 2: compiler, {1}, ir // CHECK-COMPILE-ACTIONS: 3: backend, {2}, lto-bc // RUN: %clang -ccc-print-phases %s -flto 2> %t // RUN: FileCheck -check-prefix=CHECK-COMPILELINK-ACTIONS < %t %s // // CHECK-COMPILELINK-ACTIONS: 0: input, "{{.*}}lto.c", c // CHECK-COMPILELINK-ACTIONS: 1: preprocessor, {0}, cpp-output // CHECK-COMPILELINK-ACTIONS: 2: compiler, {1}, ir // CHECK-COMPILELINK-ACTIONS: 3: backend, {2}, lto-bc // CHECK-COMPILELINK-ACTIONS: 4: linker, {3}, image // llvm-bc and llvm-ll outputs need to match regular suffixes // (unfortunately). // RUN: %clang %s -flto -save-temps -### 2> %t // RUN: FileCheck -check-prefix=CHECK-COMPILELINK-SUFFIXES < %t %s // // CHECK-COMPILELINK-SUFFIXES: "-o" "{{.*}}lto.i" "-x" "c" "{{.*}}lto.c" // CHECK-COMPILELINK-SUFFIXES: "-o" "{{.*}}lto.bc" {{.*}}"{{.*}}lto.i" // CHECK-COMPILELINK-SUFFIXES: "-o" "{{.*}}lto.o" {{.*}}"{{.*}}lto.bc" // CHECK-COMPILELINK-SUFFIXES: "{{.*}}a.{{(out|exe)}}" {{.*}}"{{.*}}lto.o" // RUN: %clang %s -flto -S -### 2> %t // RUN: FileCheck -check-prefix=CHECK-COMPILE-SUFFIXES < %t %s // // CHECK-COMPILE-SUFFIXES: "-o" "{{.*}}lto.s" "-x" "c" "{{.*}}lto.c" // RUN: not %clang %s -emit-llvm 2>&1 | FileCheck --check-prefix=LLVM-LINK %s // LLVM-LINK: -emit-llvm cannot be used when linking // -flto should cause link using gold plugin // RUN: %clang -target x86_64-unknown-linux -### %s -flto 2> %t // RUN: FileCheck -check-prefix=CHECK-LINK-LTO-ACTION < %t %s // // CHECK-LINK-LTO-ACTION: "-plugin" "{{.*}}/LLVMgold.so" // -flto=full should cause link using gold plugin // RUN: %clang -target x86_64-unknown-linux -### %s -flto=full 2> %t // RUN: FileCheck -check-prefix=CHECK-LINK-FULL-ACTION < %t %s // // CHECK-LINK-FULL-ACTION: "-plugin" "{{.*}}/LLVMgold.so" // Check that subsequent -fno-lto takes precedence // RUN: %clang -target x86_64-unknown-linux -### %s -flto=full -fno-lto 2> %t // RUN: FileCheck -check-prefix=CHECK-LINK-NOLTO-ACTION < %t %s // // CHECK-LINK-NOLTO-ACTION-NOT: "-plugin" "{{.*}}/LLVMgold.so" // -flto passes along an explicit debugger tuning argument. // RUN: %clang -target x86_64-unknown-linux -### %s -flto -glldb 2> %t // RUN: FileCheck -check-prefix=CHECK-TUNING-LLDB < %t %s // RUN: %clang -target x86_64-unknown-linux -### %s -flto -g 2> %t // RUN: FileCheck -check-prefix=CHECK-NO-TUNING < %t %s // // CHECK-TUNING-LLDB: "-plugin-opt=-debugger-tune=lldb" // CHECK-NO-TUNING-NOT: "-plugin-opt=-debugger-tune
1,152
575
// Copyright (c) 2012 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 "remoting/host/linux/x_server_clipboard.h" #include <limits> #include "base/callback.h" #include "base/memory/ref_counted_memory.h" #include "base/memory/scoped_refptr.h" #include "base/stl_util.h" #include "remoting/base/constants.h" #include "remoting/base/logging.h" #include "remoting/base/util.h" #include "ui/gfx/x/extension_manager.h" #include "ui/gfx/x/future.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" namespace remoting { XServerClipboard::XServerClipboard() = default; XServerClipboard::~XServerClipboard() = default; void XServerClipboard::Init(x11::Connection* connection, const ClipboardChangedCallback& callback) { connection_ = connection; callback_ = callback; if (!connection_->xfixes().present()) { HOST_LOG << "X server does not support XFixes."; return; } // Let the server know the client version. connection_->xfixes().QueryVersion( {x11::XFixes::major_version, x11::XFixes::minor_version}); clipboard_window_ = connection_->GenerateId<x11::Window>(); connection_->CreateWindow({ .wid = clipboard_window_, .parent = connection_->default_root(), .width = 1, .height = 1, .override_redirect = x11::Bool32(true), }); // TODO(lambroslambrou): Use ui::X11AtomCache for this, either by adding a // dependency on ui/ or by moving X11AtomCache to base/. static const char* const kAtomNames[] = {"CLIPBOARD", "INCR", "SELECTION_STRING", "TARGETS", "TIMESTAMP", "UTF8_STRING"}; static const int kNumAtomNames = base::size(kAtomNames); x11::Future<x11::InternAtomReply> futures[kNumAtomNames]; for (size_t i = 0; i < kNumAtomNames; i++) futures[i] = connection_->InternAtom({false, kAtomNames[i]}); connection_->Flush(); x11::Atom atoms[kNumAtomNames]; memset(atoms, 0, sizeof(atoms)); for (size_t i = 0; i < kNumAtomNames; i++) { if (auto reply = futures[i].Sync()) { atoms[i] = reply->atom; } else { LOG(ERROR) << "Failed to intern atom(s)"; break; } } clipboard_atom_ = atoms[0]; large_selection_atom_ = atoms[1]; selection_string_atom_ = atoms[2]; targets_atom_ = atoms[3]; timestamp_atom_ = atoms[4]; utf8_string_atom_ = atoms[5]; static_assert(kNumAtomNames >= 6, "kAtomNames is too small"); connection_->xfixes().SelectSelectionInput( {static_cast<x11::Window>(clipboard_window_), static_cast<x11::Atom>(clipboard_atom_), x11::XFixes::SelectionEventMask::SetSelectionOwner}); connection_->Flush(); } void XServerClipboard::SetClipboard(const std::string& mime_type, const std::string& data) { DCHECK(connection_->Ready()); if (clipboard_window_ == x11::Window::None) return; // Currently only UTF-8 is supported. if (mime_type != kMimeTypeTextUtf8) return; if (!StringIsUtf8(data.c_str(), data.length())) { LOG(ERROR) << "ClipboardEvent: data is not UTF-8 encoded."; return; } data_ = data; AssertSelectionOwnership(x11::Atom::PRIMARY); AssertSelectionOwnership(clipboard_atom_); } void XServerClipboard::ProcessXEvent(const x11::Event& event) { if (clipboard_window_ == x11::Window::None || event.window() != clipboard_window_) { return; } if (auto* property_notify = event.As<x11::PropertyNotifyEvent>()) OnPropertyNotify(*property_notify); else if (auto* selection_notify = event.As<x11::SelectionNotifyEvent>()) OnSelectionNotify(*selection_notify); else if (auto* selection_request = event.As<x11::SelectionRequestEvent>()) OnSelectionRequest(*selection_request); else if (auto* selection_clear = event.As<x11::SelectionClearEvent>()) OnSelectionClear(*selection_clear); if (auto* xfixes_selection_notify = event.As<x11::XFixes::SelectionNotifyEvent>()) { OnSetSelectionOwnerNotify(xfixes_selection_notify->selection, xfixes_selection_notify->selection_timestamp); } } void XServerClipboard::OnSetSelectionOwnerNotify(x11::Atom selection, x11::Time timestamp) { // Protect against receiving new XFixes selection notifications whilst we're // in the middle of waiting for information from the current selection owner. // A reasonable timeout allows for misbehaving apps that don't respond // quickly to our requests. if (!get_selections_time_.is_null() && (base::TimeTicks::Now() - get_selections_time_) < base::TimeDelta::FromSeconds(5)) { // TODO(lambroslambrou): Instead of ignoring this notification, cancel any // pending request operations and ignore the resulting events, before // dispatching new requests here. return; } // Only process CLIPBOARD selections. if (selection != clipboard_atom_) return; // If we own the selection, don't request details for it. if (IsSelectionOwner(selection)) return; get_selections_time_ = base::TimeTicks::Now(); // Before getting the value of the chosen selection, request the list of // target formats it supports. RequestSelectionTargets(selection); } void XServerClipboard::OnPropertyNotify(const x11::PropertyNotifyEvent& event) { if (large_selection_property_ != x11::Atom::None && event.atom == large_selection_property_ && event.state == x11::Property::NewValue) { auto req = connection_->GetProperty({ .c_delete = true, .window = clipboard_window_, .property = large_selection_property_, .type = x11::Atom::Any, .long_length = std::numeric_limits<uint32_t>::max(), }); if (auto reply = req.Sync()) { if (reply->type != x11::Atom::None) { // TODO(lambroslambrou): Properly support large transfers - // http://crbug.com/151447. // If the property is zero-length then the large transfer is complete. if (reply->value_len == 0) large_selection_property_ = x11::Atom::None; } } } } void XServerClipboard::OnSelectionNotify( const x11::SelectionNotifyEvent& event) { if (event.property != x11::Atom::None) { auto req = connection_->GetProperty({ .c_delete = true, .window = clipboard_window_, .property = event.property, .type = x11::Atom::Any, .long_length = std::numeric_limits<uint32_t>::max(), }); if (auto reply = req.Sync()) { if (reply->type == large_selection_atom_) { // Large selection - just read and ignore these for now. large_selection_property_ = event.property; } else { // Standard selection - call the selection notifier. large_selection_property_ = x11::Atom::None; if (reply->type != x11::Atom::None) { HandleSelectionNotify(event, reply->type, reply->format, reply->value_len, reply->value->data()); return; } } } } HandleSelectionNotify(event, x11::Atom::None, 0, 0, nullptr); } void XServerClipboard::OnSelectionRequest( const x11::SelectionRequestEvent& event) { x11::SelectionNotifyEvent selection_event; selection_event.requestor = event.requestor; selection_event.selection = event.selection; selection_event.time = event.time; selection_event.target = event.target; auto property = event.property == x11::Atom::None ? event.target : event.property; if (!IsSelectionOwner(selection_event.selection)) { selection_event.property = x11::Atom::None; } else { selection_event.property = property; if (selection_event.target == static_cast<x11::Atom>(targets_atom_)) { SendTargetsResponse(selection_event.requestor, selection_event.property); } else if (selection_event.target == static_cast<x11::Atom>(timestamp_atom_)) { SendTimestampResponse(selection_event.requestor, selection_event.property); } else if (selection_event.target == static_cast<x11::Atom>(utf8_string_atom_) || selection_event.target == x11::Atom::STRING) { SendStringResponse(selection_event.requestor, selection_event.property, selection_event.target); } } x11::SendEvent(selection_event, selection_event.requestor, x11::EventMask::NoEvent, connection_); } void XServerClipboard::OnSelectionClear(const x11::SelectionClearEvent& event) { selections_owned_.erase(event.selection); } void XServerClipboard::SendTargetsResponse(x11::Window requestor, x11::Atom property) { // Respond advertising x11::Atom::STRING, UTF8_STRING and TIMESTAMP data for // the selection. x11::Atom targets[3] = { timestamp_atom_, utf8_string_atom_, x11::Atom::STRING, }; connection_->ChangeProperty({ .mode = x11::PropMode::Replace, .window = requestor, .property = property, .type = x11::Atom::ATOM, .format = CHAR_BIT * sizeof(x11::Atom), .data_len = base::size(targets), .data = base::MakeRefCounted<base::RefCountedStaticMemory>( &targets[0], sizeof(targets)), }); connection_->Flush(); } void XServerClipboard::SendTimestampResponse(x11::Window requestor, x11::Atom property) { // Respond with the timestamp of our selection; we always return // CurrentTime since our selections are set by remote clients, so there // is no associated local X event. // TODO(lambroslambrou): Should use a proper timestamp here instead of // CurrentTime. ICCCM recommends doing a zero-length property append, // and getting a timestamp from the subsequent PropertyNotify event. x11::Time time = x11::Time::CurrentTime; connection_->ChangeProperty({ .mode = x11::PropMode::Replace, .window = requestor, .property = property, .type = x11::Atom::INTEGER, .format = CHAR_BIT * sizeof(x11::Time), .data_len = 1, .data = base::MakeRefCounted<base::RefCountedStaticMemory>(&time, sizeof(time)), }); connection_->Flush(); } void XServerClipboard::SendStringResponse(x11::Window requestor, x11::Atom property, x11::Atom target) { if (!data_.empty()) { // Return the actual string data; we always return UTF8, regardless of // the configured locale. connection_->ChangeProperty({ .mode = x11::PropMode::Replace, .window = requestor, .property = property, .type = target, .format = 8, .data_len = data_.size(), .data = base::MakeRefCounted<base::RefCountedStaticMemory>( data_.data(), data_.size()), }); connection_->Flush(); } } void XServerClipboard::HandleSelectionNotify( const x11::SelectionNotifyEvent& event, x11::Atom type, int format, int item_count, const void* data) { bool finished = false; auto target = event.target; if (target == targets_atom_) finished = HandleSelectionTargetsEvent(event, format, item_count, data); else if (target == utf8_string_atom_ || target == x11::Atom::STRING) finished = HandleSelectionStringEvent(event, format, item_count, data); if (finished) get_selections_time_ = base::TimeTicks(); } bool XServerClipboard::HandleSelectionTargetsEvent( const x11::SelectionNotifyEvent& event, int format, int item_count, const void* data) { auto selection = event.selection; if (event.property == targets_atom_) { if (data && format == 32) { const uint32_t* targets = static_cast<const uint32_t*>(data); for (int i = 0; i < item_count; i++) { if (targets[i] == static_cast<uint32_t>(utf8_string_atom_)) { RequestSelectionString(selection, utf8_string_atom_); return false; } } } } RequestSelectionString(selection, x11::Atom::STRING); return false; } bool XServerClipboard::HandleSelectionStringEvent( const x11::SelectionNotifyEvent& event, int format, int item_count, const void* data) { auto property = event.property; auto target = event.target; if (property != selection_string_atom_ || !data || format != 8) return true; std::string text(static_cast<const char*>(data), item_count); if (target == x11::Atom::STRING || target == utf8_string_atom_) NotifyClipboardText(text); return true; } void XServerClipboard::NotifyClipboardText(const std::string& text) { data_ = text; callback_.Run(kMimeTypeTextUtf8, data_); } void XServerClipboard::RequestSelectionTargets(x11::Atom selection) { connection_->ConvertSelection({clipboard_window_, selection, targets_atom_, targets_atom_, x11::Time::CurrentTime}); } void XServerClipboard::RequestSelectionString(x11::Atom selection, x11::Atom target) { connection_->ConvertSelection({clipboard_window_, selection, target, selection_string_atom_, x11::Time::CurrentTime}); } void XServerClipboard::AssertSelectionOwnership(x11::Atom selection) { connection_->SetSelectionOwner( {clipboard_window_, selection, x11::Time::CurrentTime}); auto reply = connection_->GetSelectionOwner({selection}).Sync(); auto owner = reply ? reply->owner : x11::Window::None; if (owner == clipboard_window_) { selections_owned_.insert(selection); } else { LOG(ERROR) << "XSetSelectionOwner failed for selection " << static_cast<uint32_t>(selection); } } bool XServerClipboard::IsSelectionOwner(x11::Atom selection) { return selections_owned_.find(selection) != selections_owned_.end(); } } // namespace remoting
5,681
308
package org.getopentest.logging; import static org.testng.Assert.*; import org.testng.annotations.Test; public class BaseLoggerNGTest { public BaseLoggerNGTest() { } @Test public void addSecretContainingRegexpChars() { TestLogger testLogger = new TestLogger(); String regexSpecialChars = "[{}()\\\\[\\\\].+*?^$\\\\\\\\|]"; testLogger.addSecret("secret1"); testLogger.addSecret(regexSpecialChars); testLogger.addSecret("secret3"); testLogger.info("ABC secret1 DEF " + regexSpecialChars + " GHI secret3 JKL"); assertTrue(!testLogger.lastLogText.contains("secret1")); assertTrue(!testLogger.lastLogText.contains(regexSpecialChars)); assertTrue(!testLogger.lastLogText.contains("secret3")); } @Test public void addSecretByRegex() { TestLogger testLogger = new TestLogger(); testLogger.addSecret("secret1"); // Use a regex positive lookbehind testLogger.addSecretByRegex("(?<=prefix1 )regexp_secret\\d"); testLogger.info("ABC secret1 DEF prefix1 regexp_secret1 regexp_secret2"); assertTrue(!testLogger.lastLogText.contains("secret1")); assertTrue(!testLogger.lastLogText.contains("regexp_secret1")); assertTrue(testLogger.lastLogText.contains("regexp_secret2")); } @Test public void addSecretByRegex_multiple_regexes() { TestLogger testLogger = new TestLogger(); testLogger.addSecret("secret1"); // Use a regex positive lookbehind testLogger.addSecretByRegex("(?<=prefix )regexp_secret\\d"); testLogger.info("ABC secret1 DEF prefix regexp_secret1 prefix regexp_secret2"); assertTrue(!testLogger.lastLogText.contains("secret1")); assertTrue(!testLogger.lastLogText.contains("regexp_secret1")); assertTrue(!testLogger.lastLogText.contains("regexp_secret2")); } @Test public void clearSecrets() { TestLogger testLogger = new TestLogger(); testLogger.setLevel(LogLevel.INFO); testLogger.addSecret("secret1"); testLogger.info("ABC secret1 DEF"); assertTrue(!testLogger.lastLogText.contains("secret1")); testLogger.clearSecrets(); testLogger.info("ABC secret1 DEF"); assertTrue(testLogger.lastLogText.contains("secret1")); } @Test public void debug() { TestLogger testLogger = new TestLogger(); testLogger.setLevel(LogLevel.DEBUG); testLogger.addSecret("secret1"); testLogger.debug("ABC secret1 DEF"); assertTrue(!testLogger.lastLogText.contains("secret1")); } @Test public void error() { TestLogger testLogger = new TestLogger(); testLogger.setLevel(LogLevel.ERROR); testLogger.addSecret("secret1"); testLogger.error("ABC secret1 DEF"); assertTrue(!testLogger.lastLogText.contains("secret1")); } @Test public void info() { TestLogger testLogger = new TestLogger(); testLogger.setLevel(LogLevel.INFO); testLogger.addSecret("secret1"); testLogger.info("ABC secret1 DEF"); assertTrue(!testLogger.lastLogText.contains("secret1")); } @Test public void setMaskSecrets() { TestLogger testLogger = new TestLogger(); testLogger.setLevel(LogLevel.INFO); testLogger.addSecret("secret1"); testLogger.info("ABC secret1 DEF"); assertTrue(!testLogger.lastLogText.contains("secret1")); testLogger.setMaskSecrets(false); testLogger.info("ABC secret1 DEF"); assertTrue(testLogger.lastLogText.contains("secret1")); } @Test public void trace() { TestLogger testLogger = new TestLogger(); testLogger.setLevel(LogLevel.TRACE); testLogger.addSecret("secret1"); testLogger.trace("ABC secret1 DEF"); assertTrue(!testLogger.lastLogText.contains("secret1")); } @Test public void warning() { TestLogger testLogger = new TestLogger(); testLogger.setLevel(LogLevel.WARN); testLogger.addSecret("secret1"); testLogger.warning("ABC secret1 DEF"); assertTrue(!testLogger.lastLogText.contains("secret1")); } }
2,007
319
<filename>image/image-feature-extraction/src/main/java/org/openimaj/image/model/asm/datasets/ShapeModelDatasets.java /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openimaj.image.model.asm.datasets; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemManager; import org.apache.commons.vfs2.VFS; import org.openimaj.data.dataset.ListBackedDataset; import org.openimaj.data.dataset.VFSListDataset; import org.openimaj.image.Image; import org.openimaj.io.InputStreamObjectReader; import org.openimaj.io.ObjectReader; import org.openimaj.math.geometry.point.Point2dImpl; import org.openimaj.math.geometry.point.PointList; import org.openimaj.math.geometry.point.PointListConnections; import org.openimaj.util.pair.IndependentPair; /** * Utilities for creating with {@link ShapeModelDataset} instances. * * @author <NAME> (<EMAIL>) * */ public class ShapeModelDatasets { /** * Basic in memory dataset * * @author <NAME> (<EMAIL>) * * @param <IMAGE> * type of the images in the collection */ private static class BasicDataset<IMAGE extends Image<?, IMAGE>> extends ListBackedDataset<IndependentPair<PointList, IMAGE>> implements ShapeModelDataset<IMAGE> { private PointListConnections connections; public BasicDataset(List<IndependentPair<PointList, IMAGE>> data, PointListConnections connections) { this.data = data; this.connections = connections; } @Override public PointListConnections getConnections() { return connections; } @Override public List<PointList> getPointLists() { return IndependentPair.getFirst(this); } @Override public List<IMAGE> getImages() { return IndependentPair.getSecond(this); } } /** * File-backed dataset * * @author <NAME> (<EMAIL>) * * @param <IMAGE> * type of the images in the collection */ private abstract static class FileBackedDataset<IMAGE extends Image<?, IMAGE>> extends VFSListDataset<IndependentPair<PointList, IMAGE>> implements ShapeModelDataset<IMAGE> { protected PointListConnections connections; public FileBackedDataset(String path, ObjectReader<IndependentPair<PointList, IMAGE>, FileObject> reader, PointListConnections conns) throws IOException { super(path, reader); this.connections = conns; } @Override public PointListConnections getConnections() { return connections; } @Override public List<PointList> getPointLists() { return IndependentPair.getFirst(this); } @Override public List<IMAGE> getImages() { return IndependentPair.getSecond(this); } } private static class ASFDataset<IMAGE extends Image<?, IMAGE>> extends FileBackedDataset<IMAGE> { private static class ASFReader<IMAGE extends Image<?, IMAGE>> implements ObjectReader<IndependentPair<PointList, IMAGE>, FileObject> { private static String[] SUPPORTED_IMAGE_EXTS = { "jpg", "jpeg", "bmp", "png" }; private InputStreamObjectReader<IMAGE> imReader; public ASFReader(InputStreamObjectReader<IMAGE> reader) { this.imReader = reader; } @Override public IndependentPair<PointList, IMAGE> read(FileObject source) throws IOException { final PointList pl = new PointList(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(source.getContent().getInputStream())); String line; while ((line = br.readLine()) != null) { if (!line.startsWith("#")) { final String[] parts = line.split("\\s+"); if (parts.length < 7) continue; final float x = Float.parseFloat(parts[2].trim()); final float y = Float.parseFloat(parts[3].trim()); pl.points.add(new Point2dImpl(x, y)); } } } finally { if (br != null) try { br.close(); } catch (final IOException e) { // ignore } } IMAGE image = null; if (imReader != null) { for (final String ext : SUPPORTED_IMAGE_EXTS) { String name = source.getName().getBaseName(); name = name.substring(0, name.lastIndexOf(".") + 1) + ext; final FileObject file = source.getParent().getChild(name); if (file != null && file.exists()) { InputStream imstream = null; try { imstream = file.getContent().getInputStream(); image = imReader.read(imstream); break; } catch (final IOException e) { // ignore } finally { if (imstream != null) { try { imstream.close(); } catch (final IOException e) { // ignore } } } } } } if (image != null) pl.scaleXY(image.getWidth(), image.getHeight()); return new IndependentPair<PointList, IMAGE>(pl, image); } @Override public boolean canRead(FileObject source, String name) { return name.endsWith(".asf"); } } public ASFDataset(String path, InputStreamObjectReader<IMAGE> reader) throws IOException { super(path, new ASFReader<IMAGE>(reader), null); readConnections(); } void readConnections() throws IOException { connections = new PointListConnections(); final FileObject firstASF = this.getFileObject(0); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(firstASF.getContent().getInputStream())); String line; while ((line = br.readLine()) != null) { if (!line.startsWith("#")) { final String[] parts = line.split("\\s+"); if (parts.length < 7) continue; final int from = Integer.parseInt(parts[4].trim()); final int to = Integer.parseInt(parts[6].trim()); connections.addConnection(from, to); } } } finally { if (br != null) { try { br.close(); } catch (final IOException e) { // ignore } ; } } } } private static class PTSDataset<IMAGE extends Image<?, IMAGE>> extends FileBackedDataset<IMAGE> { private static class PTSReader<IMAGE extends Image<?, IMAGE>> implements ObjectReader<IndependentPair<PointList, IMAGE>, FileObject> { private static String[] SUPPORTED_IMAGE_EXTS = { "jpg", "jpeg", "bmp", "png" }; private InputStreamObjectReader<IMAGE> imReader; private FileObject ptsPath; private FileObject imgsPath; public PTSReader(InputStreamObjectReader<IMAGE> imReader, String ptsPath, String imgsPath) throws IOException { this.imReader = imReader; final FileSystemManager fsManager = VFS.getManager(); this.ptsPath = fsManager.resolveFile(ptsPath); this.imgsPath = fsManager.resolveFile(imgsPath); } @Override public IndependentPair<PointList, IMAGE> read(FileObject source) throws IOException { final PointList pl = new PointList(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(source.getContent().getInputStream())); br.readLine(); br.readLine(); br.readLine(); String line; while ((line = br.readLine()) != null) { if (!line.startsWith("}") && line.trim().length() > 0) { final String[] parts = line.split("\\s+"); final float x = Float.parseFloat(parts[0].trim()); final float y = Float.parseFloat(parts[1].trim()); pl.points.add(new Point2dImpl(x, y)); } } } finally { if (br != null) try { br.close(); } catch (final IOException e) { } } IMAGE image = null; if (this.imReader != null) { final String relPath = ptsPath.getName().getRelativeName(source.getName()); for (final String ext : SUPPORTED_IMAGE_EXTS) { final String imRelPath = relPath.substring(0, relPath.lastIndexOf(".") + 1) + ext; final FileObject imgPath = imgsPath.resolveFile(imRelPath); if (imgPath.exists()) { InputStream imstream = null; try { imstream = imgPath.getContent().getInputStream(); image = imReader.read(imstream); break; } catch (final IOException e) { // ignore } finally { if (imstream != null) { try { imstream.close(); } catch (final IOException e) { // ignore } } } break; } } } return IndependentPair.pair(pl, image); } @Override public boolean canRead(FileObject source, String name) { return name.endsWith(".pts") && !name.equals("dummy.pts"); } } public PTSDataset(String imgsPath, String ptsPath, String modelPath, InputStreamObjectReader<IMAGE> reader) throws IOException { super(ptsPath, new PTSReader<IMAGE>(reader, ptsPath, imgsPath), null); readConnections(modelPath); } void readConnections(String path) throws IOException { BufferedReader br = null; try { final FileSystemManager fsManager = VFS.getManager(); br = new BufferedReader(new InputStreamReader(fsManager.resolveFile(path).getContent().getInputStream())); this.connections = new PointListConnections(); String line; while ((line = br.readLine()) != null) { if (!line.trim().startsWith("indices")) continue; final String[] data = line.trim().replace("indices(", "").replace(")", "").split(","); final boolean isOpen = (br.readLine().contains("open_boundary")); int prev = Integer.parseInt(data[0]); for (int i = 1; i < data.length; i++) { final int next = Integer.parseInt(data[i]); connections.addConnection(prev, next); prev = next; } if (!isOpen) { connections.addConnection(Integer.parseInt(data[data.length - 1]), Integer.parseInt(data[0])); } } } finally { try { if (br != null) br.close(); } catch (final IOException e) { } } } } private ShapeModelDatasets() { } /** * Create a dataset with the given data. * * @param data * the image-pointset pairs * @param connections * the connections across the points * @return the dataset */ public static <IMAGE extends Image<?, IMAGE>> ShapeModelDataset<IMAGE> create( List<IndependentPair<PointList, IMAGE>> data, PointListConnections connections) { return new BasicDataset<IMAGE>(data, connections); } /** * Load a dataset from ASF format files as used by the IMM dataset. If the * images are present, they will also be loaded (images must have the same * name as the corresponding ASF files, but with a different extension). * * @see IMMFaceDatabase * @see "http://commons.apache.org/proper/commons-vfs/filesystems.html" * @param path * the file system path or uri. See the Apache Commons VFS2 * documentation for all the details. * @param reader * the reader with which to load the images * * @return the dataset * @throws IOException * if an error occurs */ public static <IMAGE extends Image<?, IMAGE>> ShapeModelDataset<IMAGE> loadASFDataset(String path, InputStreamObjectReader<IMAGE> reader) throws IOException { return new ASFDataset<IMAGE>(path, reader); } /** * Load a dataset from PTS format files as used by <NAME>'s ASM/AAM * tools. If the images are present, they will also be loaded (images must * have the same name as the corresponding PTS files, but with a different * extension). * * @param ptsDirPath * the directory containing the pts files * @param imgDirPath * the directory containing the images * @param modelFilePath * the path to the model (connections) file * * @see IMMFaceDatabase * @see "http://commons.apache.org/proper/commons-vfs/filesystems.html" * @param reader * the reader with which to load the images * * @return the dataset * @throws IOException * if an error occurs */ public static <IMAGE extends Image<?, IMAGE>> ShapeModelDataset<IMAGE> loadPTSDataset(String ptsDirPath, String imgDirPath, String modelFilePath, InputStreamObjectReader<IMAGE> reader) throws IOException { return new PTSDataset<IMAGE>(imgDirPath, ptsDirPath, modelFilePath, reader); } }
5,330
945
/* * 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.iotdb.tsfile.encoding.decoder; import org.apache.iotdb.tsfile.encoding.encoder.DoublePrecisionEncoderV1; import org.apache.iotdb.tsfile.encoding.encoder.Encoder; import org.apache.iotdb.tsfile.encoding.encoder.SinglePrecisionEncoderV1; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class GorillaDecoderV1Test { private static final Logger logger = LoggerFactory.getLogger(GorillaDecoderV1Test.class); private final double delta = 0.0000001; private final int floatMaxPointValue = 10000; private final long doubleMaxPointValue = 1000000000000000L; private List<Float> floatList; private List<Double> doubleList; @Before public void setUp() { floatList = new ArrayList<Float>(); int hybridCount = 11; int hybridNum = 50; int hybridStart = 2000; for (int i = 0; i < hybridNum; i++) { for (int j = 0; j < hybridCount; j++) { floatList.add((float) hybridStart / floatMaxPointValue); } for (int j = 0; j < hybridCount; j++) { floatList.add((float) hybridStart / floatMaxPointValue); hybridStart += 3; } hybridCount += 2; } doubleList = new ArrayList<Double>(); int hybridCountDouble = 11; int hybridNumDouble = 50; long hybridStartDouble = 2000; for (int i = 0; i < hybridNumDouble; i++) { for (int j = 0; j < hybridCountDouble; j++) { doubleList.add((double) hybridStartDouble / doubleMaxPointValue); } for (int j = 0; j < hybridCountDouble; j++) { doubleList.add((double) hybridStartDouble / doubleMaxPointValue); hybridStart += 3; } hybridCountDouble += 2; } } @After public void tearDown() {} @Test public void testNegativeNumber() throws IOException { Encoder encoder = new SinglePrecisionEncoderV1(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); float value = -7.101f; encoder.encode(value, baos); encoder.encode(value - 2, baos); encoder.encode(value - 4, baos); encoder.flush(baos); encoder.encode(value, baos); encoder.encode(value - 2, baos); encoder.encode(value - 4, baos); encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); for (int i = 0; i < 2; i++) { Decoder decoder = new SinglePrecisionDecoderV1(); if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readFloat(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value - 2, decoder.readFloat(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value - 4, decoder.readFloat(buffer), delta); } } } @Test public void testZeroNumber() throws IOException { Encoder encoder = new DoublePrecisionEncoderV1(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); double value = 0f; encoder.encode(value, baos); encoder.encode(value, baos); encoder.encode(value, baos); encoder.flush(baos); encoder.encode(value, baos); encoder.encode(value, baos); encoder.encode(value, baos); encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); for (int i = 0; i < 2; i++) { Decoder decoder = new DoublePrecisionDecoderV1(); if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readDouble(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readDouble(buffer), delta); } if (decoder.hasNext(buffer)) { assertEquals(value, decoder.readDouble(buffer), delta); } } } @Test public void testFloatRepeat() throws Exception { for (int i = 1; i <= 10; i++) { testFloatLength(floatList, false, i); } } @Test public void testDoubleRepeat() throws Exception { for (int i = 1; i <= 10; i++) { testDoubleLength(doubleList, false, i); } } @Test public void testFloat() throws IOException { Encoder encoder = new SinglePrecisionEncoderV1(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); float value = 7.101f; int num = 10000; for (int i = 0; i < num; i++) { encoder.encode(value + 2 * i, baos); } encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Decoder decoder = new SinglePrecisionDecoderV1(); for (int i = 0; i < num; i++) { if (decoder.hasNext(buffer)) { assertEquals(value + 2 * i, decoder.readFloat(buffer), delta); continue; } fail(); } } @Test public void testDouble() throws IOException { Encoder encoder = new DoublePrecisionEncoderV1(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); double value = 7.101f; int num = 1000; for (int i = 0; i < num; i++) { encoder.encode(value + 2 * i, baos); } encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Decoder decoder = new DoublePrecisionDecoderV1(); for (int i = 0; i < num; i++) { if (decoder.hasNext(buffer)) { // System.out.println("turn "+i); assertEquals(value + 2 * i, decoder.readDouble(buffer), delta); continue; } fail(); } } private void testFloatLength(List<Float> valueList, boolean isDebug, int repeatCount) throws Exception { Encoder encoder = new SinglePrecisionEncoderV1(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < repeatCount; i++) { for (float value : valueList) { encoder.encode(value, baos); } encoder.flush(baos); } ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); for (int i = 0; i < repeatCount; i++) { Decoder decoder = new SinglePrecisionDecoderV1(); for (float value : valueList) { // System.out.println("Repeat: "+i+" value: "+value); if (decoder.hasNext(buffer)) { float value_ = decoder.readFloat(buffer); if (isDebug) { logger.debug("{} // {}", value_, value); } assertEquals(value, value_, delta); continue; } fail(); } } } private void testDoubleLength(List<Double> valueList, boolean isDebug, int repeatCount) throws Exception { Encoder encoder = new DoublePrecisionEncoderV1(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < repeatCount; i++) { for (double value : valueList) { encoder.encode(value, baos); } encoder.flush(baos); } ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); for (int i = 0; i < repeatCount; i++) { Decoder decoder = new DoublePrecisionDecoderV1(); for (double value : valueList) { if (decoder.hasNext(buffer)) { double value_ = decoder.readDouble(buffer); if (isDebug) { logger.debug("{} // {}", value_, value); } assertEquals(value, value_, delta); continue; } fail(); } } } }
3,170
528
<reponame>anukaal/opytimizer """Flower Pollination Algorithm. """ import copy import opytimizer.math.distribution as d import opytimizer.math.random as r import opytimizer.utils.exception as e import opytimizer.utils.logging as log from opytimizer.core import Optimizer logger = log.get_logger(__name__) class FPA(Optimizer): """A FPA class, inherited from Optimizer. This is the designed class to define FPA-related variables and methods. References: <NAME>. Flower pollination algorithm for global optimization. International conference on unconventional computing and natural computation (2012). """ def __init__(self, params=None): """Initialization method. Args: params (dict): Contains key-value parameters to the meta-heuristics. """ # Overrides its parent class with the receiving params super(FPA, self).__init__() # Lévy flight control parameter self.beta = 1.5 # Lévy flight scaling factor self.eta = 0.2 # Probability of local pollination self.p = 0.8 # Builds the class self.build(params) logger.info('Class overrided.') @property def beta(self): """float: Lévy flight control parameter. """ return self._beta @beta.setter def beta(self, beta): if not isinstance(beta, (float, int)): raise e.TypeError('`beta` should be a float or integer') if beta <= 0 or beta > 2: raise e.ValueError('`beta` should be between 0 and 2') self._beta = beta @property def eta(self): """float: Lévy flight scaling factor. """ return self._eta @eta.setter def eta(self, eta): if not isinstance(eta, (float, int)): raise e.TypeError('`eta` should be a float or integer') if eta < 0: raise e.ValueError('`eta` should be >= 0') self._eta = eta @property def p(self): """float: Probability of local pollination. """ return self._p @p.setter def p(self, p): if not isinstance(p, (float, int)): raise e.TypeError('`p` should be a float or integer') if p < 0 or p > 1: raise e.ValueError('`p` should be between 0 and 1') self._p = p def _global_pollination(self, agent_position, best_position): """Updates the agent's position based on a global pollination (eq. 1). Args: agent_position (np.array): Agent's current position. best_position (np.array): Best agent's current position. Returns: A new position. """ # Generates a Lévy distribution step = d.generate_levy_distribution(self.beta) # Calculates the global pollination global_pollination = self.eta * step * (best_position - agent_position) # Calculates the new position based on previous global pollination new_position = agent_position + global_pollination return new_position def _local_pollination(self, agent_position, k_position, l_position, epsilon): """Updates the agent's position based on a local pollination (eq. 3). Args: agent_position (np.array): Agent's current position. k_position (np.array): Agent's (index k) current position. l_position (np.array): Agent's (index l) current position. epsilon (float): An uniform random generated number. Returns: A new position. """ # Calculates the local pollination local_pollination = epsilon * (k_position - l_position) # Calculates the new position based on previous local pollination new_position = agent_position + local_pollination return new_position def update(self, space, function): """Wraps Flower Pollination Algorithm over all agents and variables. Args: space (Space): Space containing agents and update-related information. function (Function): A Function object that will be used as the objective function. """ # Iterates through all agents for agent in space.agents: # Creates a temporary agent a = copy.deepcopy(agent) # Generates an uniform random number r1 = r.generate_uniform_random_number() # Check if generated random number is bigger than probability if r1 > self.p: # Updates a temporary position according to global pollination a.position = self._global_pollination( agent.position, space.best_agent.position) else: # Generates an uniform random number epsilon = r.generate_uniform_random_number() # Generates an index for flower `k` and flower `l` k = r.generate_integer_random_number(0, len(space.agents)) l = r.generate_integer_random_number(0, len(space.agents), exclude_value=k) # Updates a temporary position according to local pollination a.position = self._local_pollination(agent.position, space.agents[k].position, space.agents[l].position, epsilon) # Checks agent's limits a.clip_by_bound() # Calculates the fitness for the temporary position a.fit = function(a.position) # If new fitness is better than agent's fitness if a.fit < agent.fit: # Copies its position and fitness to the agent agent.position = copy.deepcopy(a.position) agent.fit = copy.deepcopy(a.fit)
2,442
351
<reponame>mgerdes/minigolf<filename>src/mcore/mcommon.h #ifndef _MCOMMON_H #define _MCOMMON_H #include <stdbool.h> void mstrncpy(char *dest, const char *src, int n); unsigned char *mbase64_decode(const char *src, int len, int *dec_len); char *mbase64_encode(const unsigned char *src, int len); bool mwrite_file(const char *path, unsigned char *data, int data_len); bool mread_file(const char *path, unsigned char **data, int *data_len); bool mstr_copy_line(char **str, char **line_buffer, int *line_buffer_cap); #endif
197
3,897
/** ****************************************************************************** * @file stm32u5xx_hal_tim_ex.h * @author MCD Application Team * @brief Header file of TIM HAL Extended module. ****************************************************************************** * @attention * * Copyright (c) 2021 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32U5xx_HAL_TIM_EX_H #define STM32U5xx_HAL_TIM_EX_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32u5xx_hal_def.h" /** @addtogroup STM32U5xx_HAL_Driver * @{ */ /** @addtogroup TIMEx * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Types TIM Extended Exported Types * @{ */ /** * @brief TIM Hall sensor Configuration Structure definition */ typedef struct { uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. This parameter can be a value of @ref TIM_Input_Capture_Polarity */ uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ uint32_t IC1Filter; /*!< Specifies the input capture filter. This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t Commutation_Delay; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ } TIM_HallSensor_InitTypeDef; /** * @brief TIM Break/Break2 input configuration */ typedef struct { uint32_t Source; /*!< Specifies the source of the timer break input. This parameter can be a value of @ref TIMEx_Break_Input_Source */ uint32_t Enable; /*!< Specifies whether or not the break input source is enabled. This parameter can be a value of @ref TIMEx_Break_Input_Source_Enable */ uint32_t Polarity; /*!< Specifies the break input source polarity. This parameter can be a value of @ref TIMEx_Break_Input_Source_Polarity */ } TIMEx_BreakInputConfigTypeDef; /** * @brief TIM Encoder index configuration */ typedef struct { uint32_t Polarity; /*!< TIM Encoder index polarity.This parameter can be a value of @ref TIMEx_Encoder_Index_Polarity */ uint32_t Prescaler; /*!< TIM Encoder index prescaler.This parameter can be a value of @ref TIMEx_Encoder_Index_Prescaler */ uint32_t Filter; /*!< TIM Encoder index filter.This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ uint32_t Blanking; /*!< Specifies whether or not the encoder index event is conditioned by TI3 or TI4 input.This parameter can be a value of @ref TIMEx_Encoder_Index_Blanking */ FunctionalState FirstIndexEnable; /*!< Specifies whether or not the encoder first index is enabled.This parameter value can be ENABLE or DISABLE. */ uint32_t Position; /*!< Specifies in which AB input configuration the index event resets the counter.This parameter can be a value of @ref TIMEx_Encoder_Index_Position */ uint32_t Direction; /*!< Specifies in which counter direction the index event resets the counter.This parameter can be a value of @ref TIMEx_Encoder_Index_Direction */ } TIMEx_EncoderIndexConfigTypeDef; /** * @} */ /* End of exported types -----------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Constants TIM Extended Exported Constants * @{ */ /** @defgroup TIMEx_Remap TIM Extended Remapping * @{ */ #define TIM_TIM1_ETR_GPIO 0x00000000UL /*!< TIM1_ETR is not connected to I/O */ #define TIM_TIM1_ETR_COMP1 TIM1_AF1_ETRSEL_0 /*!< TIM1_ETR is connected to COMP1 output */ #define TIM_TIM1_ETR_COMP2 TIM1_AF1_ETRSEL_1 /*!< TIM1_ETR is connected to COMP2 output */ #define TIM_TIM1_ETR_MSIK (TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM1_ETR is connected to MSIK */ #define TIM_TIM1_ETR_HSI TIM1_AF1_ETRSEL_2 /*!< TIM1_ETR is connected to HSI */ #define TIM_TIM1_ETR_MSIS (TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM1_ETR is connected to MSI */ #define TIM_TIM1_ETR_ADC1_AWD1 (TIM1_AF1_ETRSEL_3) /*!< TIM1_ETR is connected to ADC1 AWD1 */ #define TIM_TIM1_ETR_ADC1_AWD2 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_0) /*!< TIM1_ETR is connected to ADC1 AWD2 */ #define TIM_TIM1_ETR_ADC1_AWD3 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_1) /*!< TIM1_ETR is connected to ADC1 AWD3 */ #define TIM_TIM1_ETR_ADC4_AWD1 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM1_ETR is connected to ADC4 AWD1 */ #define TIM_TIM1_ETR_ADC4_AWD2 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_2) /*!< TIM1_ETR is connected to ADC4 AWD2 */ #define TIM_TIM1_ETR_ADC4_AWD3 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM1_ETR is connected to ADC4 AWD3 */ #define TIM_TIM2_ETR_GPIO 0x00000000UL /*!< TIM2_ETR is not connected to I/O */ #define TIM_TIM2_ETR_COMP1 TIM1_AF1_ETRSEL_0 /*!< TIM2_ETR is connected to COMP1 output */ #define TIM_TIM2_ETR_COMP2 TIM1_AF1_ETRSEL_1 /*!< TIM2_ETR is connected to COMP2 output */ #define TIM_TIM2_ETR_MSIK (TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM2_ETR is connected to MSIK */ #define TIM_TIM2_ETR_HSI TIM1_AF1_ETRSEL_2 /*!< TIM2_ETR is connected to HSI */ #define TIM_TIM2_ETR_MSIS (TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM2_ETR is connected to MSIS */ #define TIM_TIM2_ETR_TIM3_ETR TIM1_AF1_ETRSEL_3 /*!< TIM2_ETR is connected to TIM3 ETR */ #define TIM_TIM2_ETR_TIM4_ETR (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_0) /*!< TIM2_ETR is connected to TIM4 ETR */ #define TIM_TIM2_ETR_TIM5_ETR (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_1) /*!< TIM2_ETR is connected to TIM5 ETR */ #define TIM_TIM2_ETR_LSE (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM2_ETR is connected to LSE */ #define TIM_TIM3_ETR_GPIO 0x00000000UL /*!< TIM3_ETR is not connected to I/O */ #define TIM_TIM3_ETR_COMP1 TIM1_AF1_ETRSEL_0 /*!< TIM3_ETR is connected to COMP1 output */ #define TIM_TIM3_ETR_COMP2 TIM1_AF1_ETRSEL_1 /*!< TIM3_ETR is connected to COMP2 output */ #define TIM_TIM3_ETR_MSIK (TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM3_ETR is connected to MSIK */ #define TIM_TIM3_ETR_HSI TIM1_AF1_ETRSEL_2 /*!< TIM3_ETR is connected to HSI */ #define TIM_TIM3_ETR_MSIS (TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM3_ETR is connected to MSIS */ #define TIM_TIM3_ETR_TIM2_ETR TIM1_AF1_ETRSEL_3 /*!< TIM3_ETR is connected to TIM2 ETR */ #define TIM_TIM3_ETR_TIM4_ETR (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_0) /*!< TIM3_ETR is connected to TIM4 ETR */ #define TIM_TIM3_ETR_ADC1_AWD1 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_1| TIM1_AF1_ETRSEL_0) /*!< TIM3_ETR is connected to ADC1 AWD1 */ #define TIM_TIM3_ETR_ADC1_AWD2 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_2) /*!< TIM3_ETR is connected to ADC1 AWD2 */ #define TIM_TIM3_ETR_ADC1_AWD3 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM3_ETR is connected to ADC1 AWD3 */ #define TIM_TIM4_ETR_GPIO 0x00000000UL /*!< TIM4_ETR is not connected to I/O */ #define TIM_TIM4_ETR_COMP1 TIM1_AF1_ETRSEL_0 /*!< TIM4_ETR is connected to COMP1 output */ #define TIM_TIM4_ETR_COMP2 TIM1_AF1_ETRSEL_1 /*!< TIM4_ETR is connected to COMP2 output */ #define TIM_TIM4_ETR_MSIK (TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM4_ETR is connected to MSIK */ #define TIM_TIM4_ETR_HSI TIM1_AF1_ETRSEL_2 /*!< TIM4_ETR is connected to HSI */ #define TIM_TIM4_ETR_MSIS (TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM4_ETR is connected to MSIS */ #define TIM_TIM4_ETR_TIM3_ETR TIM1_AF1_ETRSEL_3 /*!< TIM4_ETR is connected to TIM3 ETR */ #define TIM_TIM4_ETR_TIM5_ETR (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_0) /*!< TIM4_ETR is connected to TIM5 ETR */ #define TIM_TIM5_ETR_GPIO 0x00000000UL /*!< TIM5_ETR is not connected to I/O */ #define TIM_TIM5_ETR_COMP1 TIM1_AF1_ETRSEL_0 /*!< TIM5_ETR is connected to COMP1 output */ #define TIM_TIM5_ETR_COMP2 TIM1_AF1_ETRSEL_1 /*!< TIM5_ETR is connected to COMP2 output */ #define TIM_TIM5_ETR_MSIK (TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM5_ETR is connected to MSIK */ #define TIM_TIM5_ETR_HSI TIM1_AF1_ETRSEL_2 /*!< TIM5_ETR is connected to HSI */ #define TIM_TIM5_ETR_MSIS (TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM5_ETR is connected to MSIS */ #define TIM_TIM5_ETR_TIM2_ETR TIM1_AF1_ETRSEL_3 /*!< TIM5_ETR is connected to TIM2 ETR */ #define TIM_TIM5_ETR_TIM3_ETR (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_0) /*!< TIM5_ETR is connected to TIM3 ETR */ #define TIM_TIM8_ETR_GPIO 0x00000000UL /*!< TIM8_ETR is not connected to I/O */ #define TIM_TIM8_ETR_COMP1 TIM1_AF1_ETRSEL_0 /*!< TIM8_ETR is connected to COMP1 output */ #define TIM_TIM8_ETR_COMP2 TIM1_AF1_ETRSEL_1 /*!< TIM8_ETR is connected to COMP2 output */ #define TIM_TIM8_ETR_MSIK (TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM8_ETR is connected to MSIK */ #define TIM_TIM8_ETR_HSI TIM1_AF1_ETRSEL_2 /*!< TIM8_ETR is connected to HSI */ #define TIM_TIM8_ETR_MSIS (TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM8_ETR is connected to MSIS */ #define TIM_TIM8_ETR_ADC1_AWD1 TIM1_AF1_ETRSEL_3 /*!< TIM8_ETR is connected to ADC1 AWD1 */ #define TIM_TIM8_ETR_ADC1_AWD2 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_0) /*!< TIM8_ETR is connected to ADC1 AWD2 */ #define TIM_TIM8_ETR_ADC1_AWD3 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_1) /*!< TIM8_ETR is connected to ADC1 AWD3 */ #define TIM_TIM8_ETR_ADC4_AWD1 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_1 | TIM1_AF1_ETRSEL_0) /*!< TIM8_ETR is connected to ADC4 AWD1 */ #define TIM_TIM8_ETR_ADC4_AWD2 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_2) /*!< TIM8_ETR is connected to ADC4 AWD2 */ #define TIM_TIM8_ETR_ADC4_AWD3 (TIM1_AF1_ETRSEL_3 | TIM1_AF1_ETRSEL_2 | TIM1_AF1_ETRSEL_0) /*!< TIM8_ETR is connected to ADC4 AWD3 */ /** * @} */ /** @defgroup TIMEx_Break_Input TIM Extended Break input * @{ */ #define TIM_BREAKINPUT_BRK 0x00000001U /*!< Timer break input */ #define TIM_BREAKINPUT_BRK2 0x00000002U /*!< Timer break2 input */ /** * @} */ /** @defgroup TIMEx_Break_Input_Source TIM Extended Break input source * @{ */ #define TIM_BREAKINPUTSOURCE_BKIN 0x00000001U /*!< An external source (GPIO) is connected to the BKIN pin */ #define TIM_BREAKINPUTSOURCE_COMP1 0x00000002U /*!< The COMP1 output is connected to the break input */ #define TIM_BREAKINPUTSOURCE_COMP2 0x00000004U /*!< The COMP2 output is connected to the break input */ #define TIM_BREAKINPUTSOURCE_MDF1 0x00000008U /*!< The analog watchdog output of the MDF1 peripheral is connected to the break input */ /** * @} */ /** @defgroup TIMEx_Break_Input_Source_Enable TIM Extended Break input source enabling * @{ */ #define TIM_BREAKINPUTSOURCE_DISABLE 0x00000000U /*!< Break input source is disabled */ #define TIM_BREAKINPUTSOURCE_ENABLE 0x00000001U /*!< Break input source is enabled */ /** * @} */ /** @defgroup TIMEx_Break_Input_Source_Polarity TIM Extended Break input polarity * @{ */ #define TIM_BREAKINPUTSOURCE_POLARITY_LOW 0x00000001U /*!< Break input source is active low */ #define TIM_BREAKINPUTSOURCE_POLARITY_HIGH 0x00000000U /*!< Break input source is active_high */ /** * @} */ /** @defgroup TIMEx_Timer_Input_Selection TIM Extended Timer input selection * @{ */ #define TIM_TIM1_TI1_GPIO 0x00000000UL /*!< TIM1_TI1 is connected to GPIO */ #define TIM_TIM1_TI1_COMP1 TIM_TISEL_TI1SEL_0 /*!< TIM1_TI1 is connected to COMP1 OUT */ #define TIM_TIM1_TI1_COMP2 TIM_TISEL_TI1SEL_1 /*!< TIM1_TI1 is connected to COMP2 OUT */ #define TIM_TIM2_TI1_GPIO 0x00000000UL /*!< TIM2_TI1 is connected to GPIO */ #define TIM_TIM2_TI1_COMP1 TIM_TISEL_TI1SEL_0 /*!< TIM2_TI1 is connected to COMP1 OUT */ #define TIM_TIM2_TI1_COMP2 TIM_TISEL_TI1SEL_1 /*!< TIM2_TI1 is connected to COMP2 OUT */ #define TIM_TIM2_TI2_GPIO 0x00000000UL /*!< TIM2_TI2 is connected to GPIO */ #define TIM_TIM2_TI2_COMP1 TIM_TISEL_TI2SEL_0 /*!< TIM2_TI2 is connected to COMP1 OUT */ #define TIM_TIM2_TI2_COMP2 TIM_TISEL_TI2SEL_1 /*!< TIM2_TI2 is connected to COMP2 OUT */ #define TIM_TIM2_TI4_GPIO 0x00000000UL /*!< TIM2_TI4 is connected to GPIO */ #define TIM_TIM2_TI4_COMP1 TIM_TISEL_TI4SEL_0 /*!< TIM2_TI4 is connected to COMP1 OUT */ #define TIM_TIM2_TI4_COMP2 TIM_TISEL_TI4SEL_1 /*!< TIM2_TI4 is connected to COMP2 OUT */ #define TIM_TIM3_TI1_GPIO 0x00000000UL /*!< TIM3_TI1 is connected to GPIO */ #define TIM_TIM3_TI1_COMP1 TIM_TISEL_TI1SEL_0 /*!< TIM3_TI1 is connected to COMP1 OUT */ #define TIM_TIM3_TI1_COMP2 TIM_TISEL_TI1SEL_1 /*!< TIM3_TI1 is connected to COMP2 OUT */ #define TIM_TIM3_TI2_GPIO 0x00000000UL /*!< TIM3_TI2 is connected to GPIO */ #define TIM_TIM3_TI2_COMP1 TIM_TISEL_TI2SEL_0 /*!< TIM3_TI2 is connected to COMP1 OUT */ #define TIM_TIM3_TI2_COMP2 TIM_TISEL_TI2SEL_1 /*!< TIM3_TI2 is connected to COMP2 OUT */ #define TIM_TIM4_TI1_GPIO 0x00000000UL /*!< TIM4_TI1 is connected to GPIO */ #define TIM_TIM4_TI1_COMP1 TIM_TISEL_TI1SEL_0 /*!< TIM4_TI1 is connected to COMP1 OUT */ #define TIM_TIM4_TI1_COMP2 TIM_TISEL_TI1SEL_1 /*!< TIM4_TI1 is connected to COMP2 OUT */ #define TIM_TIM4_TI2_GPIO 0x00000000UL /*!< TIM4_TI2 is connected to GPIO */ #define TIM_TIM4_TI2_COMP1 TIM_TISEL_TI2SEL_0 /*!< TIM4_TI2 is connected to COMP1 OUT */ #define TIM_TIM4_TI2_COMP2 TIM_TISEL_TI2SEL_1 /*!< TIM4_TI2 is connected to COMP2 OUT */ #define TIM_TIM5_TI1_GPIO 0x00000000UL /*!< TIM5_TI1 is connected to GPIO */ #define TIM_TIM5_TI1_LSI TIM_TISEL_TI1SEL_0 /*!< TIM5_TI1 is connected to LSI */ #define TIM_TIM5_TI1_LSE TIM_TISEL_TI1SEL_1 /*!< TIM5_TI1 is connected to LSE */ #define TIM_TIM5_TI1_RTC_WKUP (TIM_TISEL_TI1SEL_1 | TIM_TISEL_TI1SEL_0) /*!< TIM5_TI1 is connected to RTC Wakeup */ #define TIM_TIM5_TI1_COMP1 TIM_TISEL_TI1SEL_2 /*!< TIM5_COMP1 is connected to COMP1 OUT */ #define TIM_TIM5_TI1_COMP2 (TIM_TISEL_TI1SEL_2 | TIM_TISEL_TI1SEL_0) /*!< TIM5_COMP2 is connected to COMP2 OUT */ #define TIM_TIM5_TI2_GPIO 0x00000000UL /*!< TIM5_TI2 is connected to GPIO */ #define TIM_TIM5_TI2_COMP1 TIM_TISEL_TI2SEL_0 /*!< TIM5_TI2 is connected to COMP1 OUT */ #define TIM_TIM5_TI2_COMP2 TIM_TISEL_TI2SEL_1 /*!< TIM5_TI2 is connected to COMP2 OUT */ #define TIM_TIM8_TI1_GPIO 0x00000000UL /*!< TIM8_TI1 is connected to GPIO */ #define TIM_TIM8_TI1_COMP1 TIM_TISEL_TI1SEL_0 /*!< TIM8_TI1 is connected to COMP1 OUT */ #define TIM_TIM8_TI1_COMP2 TIM_TISEL_TI1SEL_1 /*!< TIM8_TI1 is connected to COMP2 OUT */ #define TIM_TIM15_TI1_GPIO 0x00000000UL /*!< TIM15_TI1 is connected to GPIO */ #define TIM_TIM15_TI1_LSE TIM_TISEL_TI1SEL_0 /*!< TIM15_TI1 is connected to LSE */ #define TIM_TIM15_TI1_COMP1 TIM_TISEL_TI1SEL_1 /*!< TIM15_TI1 is connected to COMP1 OUT */ #define TIM_TIM15_TI1_COMP2 (TIM_TISEL_TI1SEL_1 | TIM_TISEL_TI1SEL_0) /*!< TIM15_TI1 is connected to COMP2 OUT */ #define TIM_TIM15_TI2_GPIO 0x00000000UL /*!< TIM15_TI2 is connected to GPIO */ #define TIM_TIM15_TI2_COMP2 TIM_TISEL_TI2SEL_0 /*!< TIM15_TI2 is connected to COMP2 OUT */ #define TIM_TIM16_TI1_GPIO 0x00000000UL /*!< TIM16_TI1 is connected to GPIO */ #define TIM_TIM16_TI1_MCO TIM_TISEL_TI1SEL_1 /*!< TIM16_TI1 is connected to MCO */ #define TIM_TIM16_TI1_HSE_DIV32 (TIM_TISEL_TI1SEL_1 | TIM_TISEL_TI1SEL_0) /*!< TIM16_TI1 is connected to HSE/32 */ #define TIM_TIM16_TI1_RTC_WKUP TIM_TISEL_TI1SEL_2 /*!< TIM16_TI1 is connected to RTC Wakeup */ #define TIM_TIM16_TI1_LSE (TIM_TISEL_TI1SEL_2 | TIM_TISEL_TI1SEL_0) /*!< TIM16_TI1 is connected to LSE */ #define TIM_TIM16_TI1_LSI (TIM_TISEL_TI1SEL_2 | TIM_TISEL_TI1SEL_1) /*!< TIM16_TI1 is connected to LSI */ #define TIM_TIM16_TI1_MSIS_1024 (TIM_TISEL_TI1SEL_2 | TIM_TISEL_TI1SEL_1 | TIM_TISEL_TI1SEL_0) /*!< TIM16_TI1 is connected to MSIS/1024 */ #define TIM_TIM16_TI1_MSIS_4 TIM_TISEL_TI1SEL_3 /*!< TIM16_TI1 is connected to MSIS/4 */ #define TIM_TIM16_TI1_HSI_256 (TIM_TISEL_TI1SEL_3 | TIM_TISEL_TI1SEL_0) /*!< TIM16_TI1 is connected to HSI/256 */ #define TIM_TIM17_TI1_GPIO 0x00000000UL /*!< TIM17_TI1 is connected to GPIO */ #define TIM_TIM17_TI1_MCO TIM_TISEL_TI1SEL_1 /*!< TIM17_TI1 is connected to MCO */ #define TIM_TIM17_TI1_HSE_DIV32 (TIM_TISEL_TI1SEL_1 | TIM_TISEL_TI1SEL_0) /*!< TIM17_TI1 is connected to HSE/32 */ #define TIM_TIM17_TI1_RTC_WKUP TIM_TISEL_TI1SEL_2 /*!< TIM17_TI1 is connected to RTC Wakeup */ #define TIM_TIM17_TI1_LSE (TIM_TISEL_TI1SEL_2 | TIM_TISEL_TI1SEL_0) /*!< TIM17_TI1 is connected to LSE */ #define TIM_TIM17_TI1_LSI (TIM_TISEL_TI1SEL_2 | TIM_TISEL_TI1SEL_1) /*!< TIM17_TI1 is connected to LSI */ #define TIM_TIM17_TI1_MSIS_1024 (TIM_TISEL_TI1SEL_2 | TIM_TISEL_TI1SEL_1 | TIM_TISEL_TI1SEL_0) /*!< TIM17_TI1 is connected to MSIS/1024 */ #define TIM_TIM17_TI1_MSIS_4 TIM_TISEL_TI1SEL_3 /*!< TIM17_TI1 is connected to MSIS/4 */ #define TIM_TIM17_TI1_HSI_256 (TIM_TISEL_TI1SEL_3 | TIM_TISEL_TI1SEL_0) /*!< TIM17_TI1 is connected to HSI/256 */ /** * @} */ /** @defgroup TIMEx_SMS_Preload_Enable TIM Extended Bitfield SMS preload enabling * @{ */ #define TIM_SMS_PRELOAD_SOURCE_UPDATE 0x00000000U /*!< Prelaod of SMS bitfield is disabled */ #define TIM_SMS_PRELOAD_SOURCE_INDEX TIM_SMCR_SMSPS /*!< Preload of SMS bitfield is enabled */ /** * @} */ /** @defgroup TIMEx_Encoder_Index_Blanking TIM Extended Encoder index blanking * @{ */ #define TIM_ENCODERINDEX_BLANKING_DISABLE 0x00000000U /*!< Encoder index blanking is disabled */ #define TIM_ENCODERINDEX_BLANKING_TI3 TIM_ECR_IBLK_0 /*!< Encoder index blanking is enabled on TI3 */ #define TIM_ENCODERINDEX_BLANKING_TI4 TIM_ECR_IBLK_1 /*!< Encoder index blanking is enabled on TI4 */ /** * @} */ /** @defgroup TIMEx_Encoder_Index_Position TIM Extended Encoder index position * @{ */ #define TIM_ENCODERINDEX_POSITION_00 0x00000000U /*!< Encoder index position is AB=00 */ #define TIM_ENCODERINDEX_POSITION_01 TIM_ECR_IPOS_0 /*!< Encoder index position is AB=01 */ #define TIM_ENCODERINDEX_POSITION_10 TIM_ECR_IPOS_1 /*!< Encoder index position is AB=10 */ #define TIM_ENCODERINDEX_POSITION_11 (TIM_ECR_IPOS_1 | TIM_ECR_IPOS_0) /*!< Encoder index position is AB=11 */ #define TIM_ENCODERINDEX_POSITION_0 0x00000000U /*!< In directional clock mode or clock plus direction mode, index resets the counter when clock is 0 */ #define TIM_ENCODERINDEX_POSITION_1 TIM_ECR_IPOS_0 /*!< In directional clock mode or clock plus direction mode, index resets the counter when clock is 1 */ /** * @} */ /** @defgroup TIMEx_Encoder_Index_Direction TIM Extended Encoder index direction * @{ */ #define TIM_ENCODERINDEX_DIRECTION_UP_DOWN 0x00000000U /*!< Index resets the counter whatever the direction */ #define TIM_ENCODERINDEX_DIRECTION_UP TIM_ECR_IDIR_0 /*!< Index resets the counter when up-counting only */ #define TIM_ENCODERINDEX_DIRECTION_DOWN TIM_ECR_IDIR_1 /*!< Index resets the counter when down-counting only */ /** * @} */ /** @defgroup TIMEx_Encoder_Index_Polarity TIM Extended Encoder index polarity * @{ */ #define TIM_ENCODERINDEX_POLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ #define TIM_ENCODERINDEX_POLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ /** * @} */ /** @defgroup TIMEx_Encoder_Index_Prescaler TIM Extended Encodder index prescaler * @{ */ #define TIM_ENCODERINDEX_PRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ #define TIM_ENCODERINDEX_PRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ #define TIM_ENCODERINDEX_PRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ #define TIM_ENCODERINDEX_PRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ /** * @} */ /** * @} */ /* End of exported constants -------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Macros TIM Extended Exported Macros * @{ */ /** * @brief HELPER macro calculating the prescaler value to achieve the required counter clock frequency. * @note ex: @ref __HAL_TIM_CALC_PSC(80000000, 1000000); * @param __TIMCLK__ timer input clock frequency (in Hz) * @param __CNTCLK__ counter clock frequency (in Hz) * @retval Prescaler value (between Min_Data=0 and Max_Data=65535) */ #define __HAL_TIM_CALC_PSC(__TIMCLK__, __CNTCLK__) \ ((__TIMCLK__) >= (__CNTCLK__)) ? (uint32_t)((__TIMCLK__)/(__CNTCLK__) - 1U) : 0U /** * @brief HELPER macro calculating the auto-reload value to achieve the required output signal frequency. * @note ex: @ref __HAL_TIM_CALC_PERIOD(1000000, 0, 10000); * @param __TIMCLK__ timer input clock frequency (in Hz) * @param __PSC__ prescaler * @param __FREQ__ output signal frequency (in Hz) * @retval Auto-reload value (between Min_Data=0 and Max_Data=65535) */ #define __HAL_TIM_CALC_PERIOD(__TIMCLK__, __PSC__, __FREQ__) \ (((__TIMCLK__)/((__PSC__) + 1U)) >= (__FREQ__)) ? ((__TIMCLK__)/((__FREQ__) * ((__PSC__) + 1U)) - 1U) : 0U /** * @brief HELPER macro calculating the auto-reload value, with dithering feature enabled, to achieve the required * output signal frequency. * @note ex: @ref __HAL_TIM_CALC_PERIOD_DITHER(1000000, 0, 10000); * @note This macro should be used only if dithering is already enabled * @param __TIMCLK__ timer input clock frequency (in Hz) * @param __PSC__ prescaler * @param __FREQ__ output signal frequency (in Hz) * @retval Auto-reload value (between Min_Data=0 and Max_Data=65519) */ #define __HAL_TIM_CALC_PERIOD_DITHER(__TIMCLK__, __PSC__, __FREQ__) \ (((__TIMCLK__)/((__PSC__) + 1U)) >= (__FREQ__)) ? \ (uint32_t)(((uint64_t)(__TIMCLK__)*16/((__FREQ__) * ((__PSC__) + 1U)) - 16U)) : 0U /** * @brief HELPER macro calculating the compare value required to achieve the required timer output compare * active/inactive delay. * @note ex: @ref __HAL_TIM_CALC_PULSE(1000000, 0, 10); * @param __TIMCLK__ timer input clock frequency (in Hz) * @param __PSC__ prescaler * @param __DELAY__ timer output compare active/inactive delay (in us) * @retval Compare value (between Min_Data=0 and Max_Data=65535) */ #define __HAL_TIM_CALC_PULSE(__TIMCLK__, __PSC__, __DELAY__) \ ((uint32_t)(((uint64_t)(__TIMCLK__) * (uint64_t)(__DELAY__)) \ / ((uint64_t)1000000U * (uint64_t)((__PSC__) + 1U)))) /** * @brief HELPER macro calculating the compare value, with dithering feature enabled, to achieve the required timer * output compare active/inactive delay. * @note ex: @ref __HAL_TIM_CALC_PULSE_DITHER(1000000, 0, 10); * @note This macro should be used only if dithering is already enabled * @param __TIMCLK__ timer input clock frequency (in Hz) * @param __PSC__ prescaler * @param __DELAY__ timer output compare active/inactive delay (in us) * @retval Compare value (between Min_Data=0 and Max_Data=65519) */ #define __HAL_TIM_CALC_PULSE_DITHER(__TIMCLK__, __PSC__, __DELAY__) \ ((uint32_t)(((uint64_t)(__TIMCLK__) * (uint64_t)(__DELAY__) * 16U) \ / ((uint64_t)1000000U * (uint64_t)((__PSC__) + 1U)))) /** * @brief HELPER macro calculating the auto-reload value to achieve the required pulse duration * (when the timer operates in one pulse mode). * @note ex: @ref __HAL_TIM_CALC_PERIOD_BY_DELAY(1000000, 0, 10, 20); * @param __TIMCLK__ timer input clock frequency (in Hz) * @param __PSC__ prescaler * @param __DELAY__ timer output compare active/inactive delay (in us) * @param __PULSE__ pulse duration (in us) * @retval Auto-reload value (between Min_Data=0 and Max_Data=65535) */ #define __HAL_TIM_CALC_PERIOD_BY_DELAY(__TIMCLK__, __PSC__, __DELAY__, __PULSE__) \ ((uint32_t)(__HAL_TIM_CALC_PULSE((__TIMCLK__), (__PSC__), (__PULSE__)) \ + __HAL_TIM_CALC_PULSE((__TIMCLK__), (__PSC__), (__DELAY__)))) /** * @brief HELPER macro calculating the auto-reload value, with dithering feature enabled, to achieve the required * pulse duration (when the timer operates in one pulse mode). * @note ex: @ref __HAL_TIM_CALC_PERIOD_DITHER_BY_DELAY(1000000, 0, 10, 20); * @note This macro should be used only if dithering is already enabled * @param __TIMCLK__ timer input clock frequency (in Hz) * @param __PSC__ prescaler * @param __DELAY__ timer output compare active/inactive delay (in us) * @param __PULSE__ pulse duration (in us) * @retval Auto-reload value (between Min_Data=0 and Max_Data=65519) */ #define __HAL_TIM_CALC_PERIOD_DITHER_BY_DELAY(__TIMCLK__, __PSC__, __DELAY__, __PULSE__) \ ((uint32_t)(__HAL_TIM_CALC_PULSE_DITHER((__TIMCLK__), (__PSC__), (__PULSE__)) \ + __HAL_TIM_CALC_PULSE_DITHER((__TIMCLK__), (__PSC__), (__DELAY__)))) /** * @} */ /* End of exported macro -----------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /** @defgroup TIMEx_Private_Macros TIM Extended Private Macros * @{ */ #define IS_TIM_REMAP(__REMAP__) ((((__REMAP__) & 0xFFFC3FFFU) == 0x00000000U)) #define IS_TIM_BREAKINPUT(__BREAKINPUT__) (((__BREAKINPUT__) == TIM_BREAKINPUT_BRK) || \ ((__BREAKINPUT__) == TIM_BREAKINPUT_BRK2)) #define IS_TIM_BREAKINPUTSOURCE(__SOURCE__) (((__SOURCE__) == TIM_BREAKINPUTSOURCE_BKIN) || \ ((__SOURCE__) == TIM_BREAKINPUTSOURCE_COMP1) || \ ((__SOURCE__) == TIM_BREAKINPUTSOURCE_COMP2) || \ ((__SOURCE__) == TIM_BREAKINPUTSOURCE_MDF1)) #define IS_TIM_BREAKINPUTSOURCE_STATE(__STATE__) (((__STATE__) == TIM_BREAKINPUTSOURCE_DISABLE) || \ ((__STATE__) == TIM_BREAKINPUTSOURCE_ENABLE)) #define IS_TIM_BREAKINPUTSOURCE_POLARITY(__POLARITY__) (((__POLARITY__) == TIM_BREAKINPUTSOURCE_POLARITY_LOW) || \ ((__POLARITY__) == TIM_BREAKINPUTSOURCE_POLARITY_HIGH)) #define IS_TIM_TISEL(__TISEL__) ((((__TISEL__) & 0xF0F0F0F0U) == 0x00000000U)) #define IS_TIM_TISEL_TIX_INSTANCE(INSTANCE, CHANNEL) \ (IS_TIM_CCX_INSTANCE(INSTANCE, CHANNEL) && ((CHANNEL) < TIM_CHANNEL_5)) #define IS_TIM_CLOCKSOURCE_INSTANCE(INSTANCE, __CLOCK__) \ ((((INSTANCE) == TIM1) && \ (((__CLOCK__) == TIM_CLOCKSOURCE_INTERNAL) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR3) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1ED) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR4) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR5) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR6) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR7) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR8))) \ || \ (((INSTANCE) == TIM2) && \ (((__CLOCK__) == TIM_CLOCKSOURCE_INTERNAL) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR0) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR3) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1ED) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR4) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR5) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR6) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR7) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR8) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR11))) \ || \ (((INSTANCE) == TIM3) && \ (((__CLOCK__) == TIM_CLOCKSOURCE_INTERNAL) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR0) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR3) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1ED) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR4) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR5) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR6) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR7) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR8))) \ || \ (((INSTANCE) == TIM4) && \ (((__CLOCK__) == TIM_CLOCKSOURCE_INTERNAL) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR0) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR4) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1ED) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR5) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR6) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR7) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR8))) \ || \ (((INSTANCE) == TIM5) && \ (((__CLOCK__) == TIM_CLOCKSOURCE_INTERNAL) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR0) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR3) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1ED) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR5) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR6) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR7) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR8))) \ || \ (((INSTANCE) == TIM8) && \ (((__CLOCK__) == TIM_CLOCKSOURCE_INTERNAL) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR0) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR3) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1ED) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ETRMODE1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR4) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR6) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR7) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR8))) \ || \ (((INSTANCE) == TIM15) && \ (((__CLOCK__) == TIM_CLOCKSOURCE_INTERNAL) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR0) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR3) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1ED) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI1) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_TI2) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR4) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR5) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR7) || \ ((__CLOCK__) == TIM_CLOCKSOURCE_ITR8)))) #define IS_TIM_TRIGGER_INSTANCE(INSTANCE, __SELECTION__) \ ((((INSTANCE) == TIM1) && \ (((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_TI1F_ED) || \ ((__SELECTION__) == TIM_TS_TI1FP1) || \ ((__SELECTION__) == TIM_TS_TI2FP2) || \ ((__SELECTION__) == TIM_TS_ETRF) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8))) \ || \ (((INSTANCE) == TIM2) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_TI1F_ED) || \ ((__SELECTION__) == TIM_TS_TI1FP1) || \ ((__SELECTION__) == TIM_TS_TI2FP2) || \ ((__SELECTION__) == TIM_TS_ETRF) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8))) \ || \ (((INSTANCE) == TIM3) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_TI1F_ED) || \ ((__SELECTION__) == TIM_TS_TI1FP1) || \ ((__SELECTION__) == TIM_TS_TI2FP2) || \ ((__SELECTION__) == TIM_TS_ETRF) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8))) \ || \ (((INSTANCE) == TIM4) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_TI1F_ED) || \ ((__SELECTION__) == TIM_TS_TI1FP1) || \ ((__SELECTION__) == TIM_TS_TI2FP2) || \ ((__SELECTION__) == TIM_TS_ETRF) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8))) \ || \ (((INSTANCE) == TIM5) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_TI1F_ED) || \ ((__SELECTION__) == TIM_TS_TI1FP1) || \ ((__SELECTION__) == TIM_TS_TI2FP2) || \ ((__SELECTION__) == TIM_TS_ETRF) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8))) \ || \ (((INSTANCE) == TIM8) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_TI1F_ED) || \ ((__SELECTION__) == TIM_TS_TI1FP1) || \ ((__SELECTION__) == TIM_TS_TI2FP2) || \ ((__SELECTION__) == TIM_TS_ETRF) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8))) \ || \ (((INSTANCE) == TIM15) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_TI1F_ED) || \ ((__SELECTION__) == TIM_TS_TI1FP1) || \ ((__SELECTION__) == TIM_TS_TI2FP2) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8)))) #define IS_TIM_INTERNAL_TRIGGEREVENT_INSTANCE(INSTANCE, __SELECTION__) \ ((((INSTANCE) == TIM1) && \ (((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8) || \ ((__SELECTION__) == TIM_TS_NONE))) \ || \ (((INSTANCE) == TIM2) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8) || \ ((__SELECTION__) == TIM_TS_ITR11)|| \ ((__SELECTION__) == TIM_TS_NONE))) \ || \ (((INSTANCE) == TIM3) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8) || \ ((__SELECTION__) == TIM_TS_NONE))) \ || \ (((INSTANCE) == TIM4) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8) || \ ((__SELECTION__) == TIM_TS_NONE))) \ || \ (((INSTANCE) == TIM5) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8) || \ ((__SELECTION__) == TIM_TS_NONE))) \ || \ (((INSTANCE) == TIM8) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR6) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8) || \ ((__SELECTION__) == TIM_TS_NONE))) \ || \ (((INSTANCE) == TIM15) && \ (((__SELECTION__) == TIM_TS_ITR0) || \ ((__SELECTION__) == TIM_TS_ITR1) || \ ((__SELECTION__) == TIM_TS_ITR2) || \ ((__SELECTION__) == TIM_TS_ITR3) || \ ((__SELECTION__) == TIM_TS_ITR4) || \ ((__SELECTION__) == TIM_TS_ITR5) || \ ((__SELECTION__) == TIM_TS_ITR7) || \ ((__SELECTION__) == TIM_TS_ITR8) || \ ((__SELECTION__) == TIM_TS_NONE)))) #define IS_TIM_OC_CHANNEL_MODE(__MODE__, __CHANNEL__) \ (IS_TIM_OC_MODE(__MODE__) \ && ((((__MODE__) == TIM_OCMODE_DIRECTION_OUTPUT) || ((__MODE__) == TIM_OCMODE_PULSE_ON_COMPARE)) \ ? (((__CHANNEL__) == TIM_CHANNEL_3) || ((__CHANNEL__) == TIM_CHANNEL_4)) : (1==1)) ) #define IS_TIM_PULSEONCOMPARE_CHANNEL(__CHANNEL__) \ (((__CHANNEL__) == TIM_CHANNEL_3) || \ ((__CHANNEL__) == TIM_CHANNEL_4)) #define IS_TIM_PULSEONCOMPARE_INSTANCE(INSTANCE) IS_TIM_CC3_INSTANCE(INSTANCE) #define IS_TIM_PULSEONCOMPARE_WIDTH(__WIDTH__) ((__WIDTH__) <= 0xFFU) #define IS_TIM_PULSEONCOMPARE_WIDTHPRESCALER(__PRESCALER__) ((__PRESCALER__) <= 0x7U) #define IS_TIM_SLAVE_PRELOAD_SOURCE(__SOURCE__) (((__SOURCE__) == TIM_SMS_PRELOAD_SOURCE_UPDATE) \ || ((__SOURCE__) == TIM_SMS_PRELOAD_SOURCE_INDEX)) #define IS_TIM_ENCODERINDEX_POLARITY(__POLARITY__) (((__POLARITY__) == TIM_ENCODERINDEX_POLARITY_INVERTED) || \ ((__POLARITY__) == TIM_ENCODERINDEX_POLARITY_NONINVERTED)) #define IS_TIM_ENCODERINDEX_PRESCALER(__PRESCALER__) (((__PRESCALER__) == TIM_ENCODERINDEX_PRESCALER_DIV1) || \ ((__PRESCALER__) == TIM_ENCODERINDEX_PRESCALER_DIV2) || \ ((__PRESCALER__) == TIM_ENCODERINDEX_PRESCALER_DIV4) || \ ((__PRESCALER__) == TIM_ENCODERINDEX_PRESCALER_DIV8)) #define IS_TIM_ENCODERINDEX_FILTER(__FILTER__) ((__FILTER__) <= 0xFUL) #define IS_TIM_ENCODERINDEX_POSITION(__POSITION__) (((__POSITION__) == TIM_ENCODERINDEX_POSITION_00) || \ ((__POSITION__) == TIM_ENCODERINDEX_POSITION_01) || \ ((__POSITION__) == TIM_ENCODERINDEX_POSITION_10) || \ ((__POSITION__) == TIM_ENCODERINDEX_POSITION_11) || \ ((__POSITION__) == TIM_ENCODERINDEX_POSITION_0) || \ ((__POSITION__) == TIM_ENCODERINDEX_POSITION_1)) #define IS_TIM_ENCODERINDEX_DIRECTION(__DIRECTION__) (((__DIRECTION__) == TIM_ENCODERINDEX_DIRECTION_UP_DOWN) || \ ((__DIRECTION__) == TIM_ENCODERINDEX_DIRECTION_UP) || \ ((__DIRECTION__) == TIM_ENCODERINDEX_DIRECTION_DOWN)) #define IS_TIM_ENCODERINDEX_BLANKING(__BLANKING__) (((__BLANKING__) == TIM_ENCODERINDEX_BLANKING_DISABLE) || \ ((__BLANKING__) == TIM_ENCODERINDEX_BLANKING_TI3) || \ ((__BLANKING__) == TIM_ENCODERINDEX_BLANKING_TI4)) /** * @} */ /* End of private macro ------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup TIMEx_Exported_Functions TIM Extended Exported Functions * @{ */ /** @addtogroup TIMEx_Exported_Functions_Group1 Extended Timer Hall Sensor functions * @brief Timer Hall Sensor functions * @{ */ /* Timer Hall Sensor functions **********************************************/ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef *sConfig); HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim); void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim); void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim); /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group2 Extended Timer Complementary Output Compare functions * @brief Timer Complementary Output Compare functions * @{ */ /* Timer Complementary Output Compare functions *****************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group3 Extended Timer Complementary PWM functions * @brief Timer Complementary PWM functions * @{ */ /* Timer Complementary PWM functions ****************************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); /* Non-Blocking mode: DMA */ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group4 Extended Timer Complementary One Pulse functions * @brief Timer Complementary One Pulse functions * @{ */ /* Timer Complementary One Pulse functions **********************************/ /* Blocking mode: Polling */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group5 Extended Peripheral Control functions * @brief Peripheral Control functions * @{ */ /* Extended Control functions ************************************************/ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_ConfigCommutEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef *sMasterConfig); HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig); HAL_StatusTypeDef HAL_TIMEx_ConfigBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput, TIMEx_BreakInputConfigTypeDef *sBreakInputConfig); HAL_StatusTypeDef HAL_TIMEx_GroupChannel5(TIM_HandleTypeDef *htim, uint32_t Channels); HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap); HAL_StatusTypeDef HAL_TIMEx_TISelection(TIM_HandleTypeDef *htim, uint32_t TISelection, uint32_t Channel); HAL_StatusTypeDef HAL_TIMEx_EnableHSE32(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DisableHSE32(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DisarmBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput); HAL_StatusTypeDef HAL_TIMEx_ReArmBreakInput(TIM_HandleTypeDef *htim, uint32_t BreakInput); HAL_StatusTypeDef HAL_TIMEx_DitheringEnable(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DitheringDisable(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_OC_ConfigPulseOnCompare(TIM_HandleTypeDef *htim, uint32_t PulseWidthPrescaler, uint32_t PulseWidth); HAL_StatusTypeDef HAL_TIMEx_ConfigSlaveModePreload(TIM_HandleTypeDef *htim, uint32_t Source); HAL_StatusTypeDef HAL_TIMEx_EnableSlaveModePreload(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DisableSlaveModePreload(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_EnableDeadTimePreload(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DisableDeadTimePreload(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_ConfigDeadTime(TIM_HandleTypeDef *htim, uint32_t Deadtime); HAL_StatusTypeDef HAL_TIMEx_ConfigAsymmetricalDeadTime(TIM_HandleTypeDef *htim, uint32_t FallingDeadtime); HAL_StatusTypeDef HAL_TIMEx_EnableAsymmetricalDeadTime(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DisableAsymmetricalDeadTime(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_ConfigEncoderIndex(TIM_HandleTypeDef *htim, TIMEx_EncoderIndexConfigTypeDef *sEncoderIndexConfig); HAL_StatusTypeDef HAL_TIMEx_EnableEncoderIndex(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DisableEncoderIndex(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_EnableEncoderFirstIndex(TIM_HandleTypeDef *htim); HAL_StatusTypeDef HAL_TIMEx_DisableEncoderFirstIndex(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group6 Extended Callbacks functions * @brief Extended Callbacks functions * @{ */ /* Extended Callback **********************************************************/ void HAL_TIMEx_CommutCallback(TIM_HandleTypeDef *htim); void HAL_TIMEx_CommutHalfCpltCallback(TIM_HandleTypeDef *htim); void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim); void HAL_TIMEx_Break2Callback(TIM_HandleTypeDef *htim); void HAL_TIMEx_EncoderIndexCallback(TIM_HandleTypeDef *htim); void HAL_TIMEx_DirectionChangeCallback(TIM_HandleTypeDef *htim); void HAL_TIMEx_IndexErrorCallback(TIM_HandleTypeDef *htim); void HAL_TIMEx_TransitionErrorCallback(TIM_HandleTypeDef *htim); /** * @} */ /** @addtogroup TIMEx_Exported_Functions_Group7 Extended Peripheral State functions * @brief Extended Peripheral State functions * @{ */ /* Extended Peripheral State functions ***************************************/ HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim); HAL_TIM_ChannelStateTypeDef HAL_TIMEx_GetChannelNState(TIM_HandleTypeDef *htim, uint32_t ChannelN); /** * @} */ /** * @} */ /* End of exported functions -------------------------------------------------*/ /* Private functions----------------------------------------------------------*/ /** @addtogroup TIMEx_Private_Functions TIMEx Private Functions * @{ */ void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma); void TIMEx_DMACommutationHalfCplt(DMA_HandleTypeDef *hdma); /** * @} */ /* End of private functions --------------------------------------------------*/ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32U5xx_HAL_TIM_EX_H */
34,059
763
<filename>projects/batfish-common-protocol/src/main/java/org/batfish/specifier/parboiled/UdpAppAstNode.java package org.batfish.specifier.parboiled; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Objects; import javax.annotation.ParametersAreNonnullByDefault; import org.batfish.datamodel.SubRange; /** AST node for tcp application definition */ @ParametersAreNonnullByDefault final class UdpAppAstNode extends PortAppAstNode { public UdpAppAstNode() { this(ImmutableList.of()); } public UdpAppAstNode(List<SubRange> ports) { super(ports); } @Override public <T> T accept(AstNodeVisitor<T> visitor) { return visitor.visitUdpAppAstNode(this); } @Override public <T> T accept(AppAstNodeVisitor<T> visitor) { return visitor.visitUdpAppAstNode(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof UdpAppAstNode)) { return false; } UdpAppAstNode that = (UdpAppAstNode) o; return Objects.equals(_ports, that._ports); } @Override public int hashCode() { return Objects.hashCode(_ports); } }
426
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Broyes","circ":"5ème circonscription","dpt":"Marne","inscrits":288,"abs":169,"votants":119,"blancs":3,"nuls":1,"exp":115,"res":[{"nuance":"UDI","nom":"M. <NAME>","voix":84},{"nuance":"FN","nom":"<NAME>","voix":31}]}
110
799
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 RED_HTML_STYLE = "color:#FF1744;text-align:center;font-size:800%;>" GREEN_HTML_STYLE = "color:#00CD33;text-align:center;font-size:800%;>" def main(): incident = demisto.incidents() query = incident[0].get('CustomFields', {}).get('numberofentriesiderrors', 0) if not query: html = f"<h1 style={GREEN_HTML_STYLE}0</h1>" else: html = f"<h1 style={RED_HTML_STYLE}{str(query)}</h1>" demisto.results({ 'ContentsFormat': formats['html'], 'Type': entryTypes['note'], 'Contents': html }) if __name__ in ["__main__", "builtin", "builtins"]: main()
302
308
<reponame>yusufcakal/Modular-Architecture-Hexagonal-Demo-Project<filename>ticket-api/infra/src/test/java/com/hexagonaldemo/ticketapi/AbstractIT.java package com.hexagonaldemo.ticketapi; import com.hexagonaldemo.ticketapi.common.event.consumer.ReservationEventKafkaStreamTestConsumer; import org.junit.jupiter.api.BeforeEach; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; public abstract class AbstractIT { @Autowired protected TestRestTemplate testRestTemplate; @Autowired protected ReservationEventKafkaStreamTestConsumer reservationEventKafkaStreamTestConsumer; @LocalServerPort protected Integer port; @BeforeEach void setUp() { reservationEventKafkaStreamTestConsumer.reset(); } }
285
956
#include <Rcpp.h> #include "nodes.h" using namespace Rcpp; void icicleLayout(Node* node, double x, double y) { Rectangle r = {x, y, node->weight(), node->height()}; node->bounds = r; std::vector<Node*> children = node->getChildren(); if (children.size() != 0) { y += node->height(); for (unsigned int i = 0; i < children.size(); i++) { icicleLayout(children[i], x, y); x += children[i]->weight(); } } } //[[Rcpp::export]] NumericMatrix partitionTree(IntegerVector parent, IntegerVector order, NumericVector weight, NumericVector height) { NumericMatrix rect(parent.size(), 4); unsigned int i; std::vector<Node*> nodes = createHierarchy(as< std::vector<int> >(parent), as< std::vector<int> >(order), as< std::vector<double> >(weight), as< std::vector<double> >(height)); for (i = 0; i < nodes.size(); ++i) { nodes[i]->sortChildren(); } Node* startNode = nodes[0]->getRoot(); icicleLayout(startNode, 0, 0); for (i = 0; i < nodes.size(); ++i) { rect(i, 0) = nodes[i]->bounds.x; rect(i, 1) = nodes[i]->bounds.y; rect(i, 2) = nodes[i]->bounds.width; rect(i, 3) = nodes[i]->bounds.height; delete nodes[i]; } return rect; }
473
2,201
#!/usr/bin/env python3 """ Copyright (c) 2020-2022 Intel Corporation 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 logging as log import sys from argparse import ArgumentParser, SUPPRESS from pathlib import Path from time import perf_counter import numpy as np sys.path.append(str(Path(__file__).resolve().parents[2] / 'common/python')) from html_reader import get_paragraphs from openvino.model_zoo.model_api.models import BertQuestionAnswering from openvino.model_zoo.model_api.models.tokens_bert import text_to_tokens, load_vocab_file, ContextWindow from openvino.model_zoo.model_api.pipelines import get_user_config, AsyncPipeline from openvino.model_zoo.model_api.adapters import create_core, OpenvinoAdapter, OVMSAdapter log.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.DEBUG, stream=sys.stdout) def build_argparser(): parser = ArgumentParser(add_help=False) args = parser.add_argument_group('Options') args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.') args.add_argument("-v", "--vocab", help="Required. Path to the vocabulary file with tokens", required=True, type=str) args.add_argument('-m', '--model', required=True, help='Required. Path to an .xml file with a trained model ' 'or address of model inference service if using OVMS adapter.') args.add_argument("-i", "--input", help="Required. URL to a page with context", action='append', required=True, type=str) args.add_argument('--adapter', help='Optional. Specify the model adapter. Default is openvino.', default='openvino', type=str, choices=('openvino', 'ovms')) args.add_argument("--questions", type=str, nargs='+', metavar='QUESTION', help="Optional. Prepared questions") args.add_argument("--input_names", help="Optional. Inputs names for the network. " "Default values are \"input_ids,attention_mask,token_type_ids\" ", required=False, type=str, default="input_ids,attention_mask,token_type_ids") args.add_argument('--layout', type=str, default=None, help='Optional. Model inputs layouts. ' 'Ex. NCHW or input0:NCHW,input1:NC in case of more than one input.') args.add_argument("--output_names", help="Optional. Outputs names for the network. " "Default values are \"output_s,output_e\" ", required=False, type=str, default="output_s,output_e") args.add_argument("--model_squad_ver", help="Optional. SQUAD version used for model fine tuning", default="1.2", required=False, type=str) args.add_argument("-q", "--max_question_token_num", help="Optional. Maximum number of tokens in question", default=8, required=False, type=int) args.add_argument("-a", "--max_answer_token_num", help="Optional. Maximum number of tokens in answer", default=15, required=False, type=int) args.add_argument("-d", "--device", help="Optional. Target device to perform inference on." "Default value is CPU", default="CPU", type=str) args.add_argument('-r', '--reshape', action='store_true', help="Optional. Auto reshape sequence length to the " "input context + max question len (to improve the speed)") args.add_argument('-c', '--colors', action='store_true', help="Optional. Nice coloring of the questions/answers. " "Might not work on some terminals (like Windows* cmd console)") args.add_argument('-nireq', '--num_infer_requests', help='Optional. Number of infer requests.', default=0, type=int) args.add_argument('-nstreams', '--num_streams', help='Optional. Number of streams to use for inference on the CPU or/and GPU in throughput ' 'mode (for HETERO and MULTI device cases use format ' '<device1>:<nstreams1>,<device2>:<nstreams2> or just <nstreams>).', default='', type=str) args.add_argument('-nthreads', '--num_threads', default=None, type=int, help='Optional. Number of threads to use for inference on CPU (including HETERO cases).') return parser def update_answers_list(answers, output): same = [i for i, ans in enumerate(answers) if ans[1:3] == output[1:3]] if not same: answers.append(output) else: assert len(same) == 1 prev_score = answers[same[0]][0] answers[same[0]] = (max(output[0], prev_score), *output[1:]) class Visualizer: def __init__(self, context, use_colors): self.context = context self.use_colors = use_colors def mark(self, text): return "\033[91m" + text + "\033[0m" if self.use_colors else "*" + text + "*" # return entire sentence as start-end positions for a given answer (within the sentence) def find_sentence_range(self, s, e): # find start of sentence for c_s in range(s, max(-1, s - 200), -1): if self.context[c_s] in "\n.": c_s += 1 break # find end of sentence for c_e in range(max(0, e - 1), min(len(self.context), e + 200), +1): if self.context[c_e] in "\n.": break return c_s, c_e def show_answers(self, answers): log.info("\t\tShow top 3 answers") answers = sorted(answers, key=lambda x: -x[0])[:3] for score, s, e in answers: c_s, c_e = self.find_sentence_range(s, e) marked_answer = self.mark(self.context[s:e]) context_str = self.context[c_s:s] + marked_answer + self.context[e:c_e] log.info("Answer: {}\n\t Score: {:0.2f}\n\t Context: {}".format(marked_answer, score, context_str)) class ContextSource: def __init__(self, q_tokens_id, c_tokens, model_max_length): self.q_tokens_id = q_tokens_id # calculate number of tokens for context in each inference request. # reserve 3 positions for special tokens: [CLS] q_tokens [SEP] c_tokens [SEP] c_window_len = model_max_length - (len(self.q_tokens_id) + 3) self.window = ContextWindow(c_window_len, *c_tokens) def get_data(self): c_data = self.window.get_context_data() self.window.move() return (c_data, self.q_tokens_id) def is_over(self): return self.window.is_over() def main(): args = build_argparser().parse_args() paragraphs = get_paragraphs(args.input) preprocessing_start_time = perf_counter() vocab = load_vocab_file(args.vocab) log.debug("Loaded vocab file from {}, get {} tokens".format(args.vocab, len(vocab))) # get context as a string (as we might need it's length for the sequence reshape) context = '\n'.join(paragraphs) visualizer = Visualizer(context, args.colors) # encode context into token ids list c_tokens = text_to_tokens(context.lower(), vocab) total_latency = (perf_counter() - preprocessing_start_time) * 1e3 if args.adapter == 'openvino': plugin_config = get_user_config(args.device, args.num_streams, args.num_threads) model_adapter = OpenvinoAdapter(create_core(), args.model, device=args.device, plugin_config=plugin_config, max_num_requests=args.num_infer_requests, model_parameters = {'input_layouts': args.layout}) elif args.adapter == 'ovms': model_adapter = OVMSAdapter(args.model) config = { 'vocab': vocab, 'input_names': args.input_names, 'output_names': args.output_names, 'max_answer_token_num': args.max_answer_token_num, 'squad_ver': args.model_squad_ver } model = BertQuestionAnswering(model_adapter, config) if args.reshape: # find the closest multiple of 64, if it is smaller than current network's sequence length, do reshape new_length = min(model.max_length, int(np.ceil((len(c_tokens[0]) + args.max_question_token_num) / 64) * 64)) if new_length < model.max_length: try: model.reshape(new_length) except RuntimeError: log.error("Failed to reshape the network, please retry the demo without '-r' option") sys.exit(-1) else: log.debug("\tSkipping network reshaping," " as (context length + max question length) exceeds the current (input) network sequence length") model.log_layers_info() pipeline = AsyncPipeline(model) if args.questions: def questions(): for question in args.questions: log.info("\n\tQuestion: {}".format(question)) yield question else: def questions(): while True: yield input('\n\tType a question (empty string to exit): ') for question in questions(): if not question.strip(): break answers = [] next_window_id = 0 next_window_id_to_show = 0 start_time = perf_counter() q_tokens_id, _ = text_to_tokens(question.lower(), vocab) source = ContextSource(q_tokens_id, c_tokens, model.max_length) while True: if pipeline.callback_exceptions: raise pipeline.callback_exceptions[0] results = pipeline.get_result(next_window_id_to_show) if results: next_window_id_to_show += 1 update_answers_list(answers, results[0]) continue if pipeline.is_ready(): if source.is_over(): break pipeline.submit_data(source.get_data(), next_window_id) next_window_id += 1 else: pipeline.await_any() pipeline.await_all() if pipeline.callback_exceptions: raise pipeline.callback_exceptions[0] for window_id in range(next_window_id_to_show, next_window_id): results = pipeline.get_result(window_id) update_answers_list(answers, results[0]) visualizer.show_answers(answers) total_latency += (perf_counter() - start_time) * 1e3 log.info("Metrics report:") log.info("\tLatency: {:.1f} ms".format(total_latency)) if __name__ == '__main__': sys.exit(main() or 0)
4,885
1,604
package org.bouncycastle.math.ec.custom.sec; import java.math.BigInteger; import org.bouncycastle.math.raw.Interleave; import org.bouncycastle.math.raw.Nat; import org.bouncycastle.math.raw.Nat576; public class SecT571Field { private static final long M59 = -1L >>> 5; private static final long[] ROOT_Z = new long[]{ 0x2BE1195F08CAFB99L, 0x95F08CAF84657C23L, 0xCAF84657C232BE11L, 0x657C232BE1195F08L, 0xF84657C2308CAF84L, 0x7C232BE1195F08CAL, 0xBE1195F08CAF8465L, 0x5F08CAF84657C232L, 0x784657C232BE119L }; public static void add(long[] x, long[] y, long[] z) { for (int i = 0; i < 9; ++i) { z[i] = x[i] ^ y[i]; } } private static void add(long[] x, int xOff, long[] y, int yOff, long[] z, int zOff) { for (int i = 0; i < 9; ++i) { z[zOff + i] = x[xOff + i] ^ y[yOff + i]; } } public static void addBothTo(long[] x, long[] y, long[] z) { for (int i = 0; i < 9; ++i) { z[i] ^= x[i] ^ y[i]; } } private static void addBothTo(long[] x, int xOff, long[] y, int yOff, long[] z, int zOff) { for (int i = 0; i < 9; ++i) { z[zOff + i] ^= x[xOff + i] ^ y[yOff + i]; } } public static void addExt(long[] xx, long[] yy, long[] zz) { for (int i = 0; i < 18; ++i) { zz[i] = xx[i] ^ yy[i]; } } public static void addOne(long[] x, long[] z) { z[0] = x[0] ^ 1L; for (int i = 1; i < 9; ++i) { z[i] = x[i]; } } private static void addTo(long[] x, long[] z) { for (int i = 0; i < 9; ++i) { z[i] ^= x[i]; } } public static long[] fromBigInteger(BigInteger x) { return Nat.fromBigInteger64(571, x); } public static void halfTrace(long[] x, long[] z) { long[] tt = Nat576.createExt64(); Nat576.copy64(x, z); for (int i = 1; i < 571; i += 2) { implSquare(z, tt); reduce(tt, z); implSquare(z, tt); reduce(tt, z); addTo(x, z); } } public static void invert(long[] x, long[] z) { if (Nat576.isZero64(x)) { throw new IllegalStateException(); } // Itoh-Tsujii inversion with bases { 2, 3, 5 } long[] t0 = Nat576.create64(); long[] t1 = Nat576.create64(); long[] t2 = Nat576.create64(); square(x, t2); // 5 | 570 square(t2, t0); square(t0, t1); multiply(t0, t1, t0); squareN(t0, 2, t1); multiply(t0, t1, t0); multiply(t0, t2, t0); // 3 | 114 squareN(t0, 5, t1); multiply(t0, t1, t0); squareN(t1, 5, t1); multiply(t0, t1, t0); // 2 | 38 squareN(t0, 15, t1); multiply(t0, t1, t2); // ! {2,3,5} | 19 squareN(t2, 30, t0); squareN(t0, 30, t1); multiply(t0, t1, t0); // 3 | 9 squareN(t0, 60, t1); multiply(t0, t1, t0); squareN(t1, 60, t1); multiply(t0, t1, t0); // 3 | 3 squareN(t0, 180, t1); multiply(t0, t1, t0); squareN(t1, 180, t1); multiply(t0, t1, t0); multiply(t0, t2, z); } public static void multiply(long[] x, long[] y, long[] z) { long[] tt = Nat576.createExt64(); implMultiply(x, y, tt); reduce(tt, z); } public static void multiplyAddToExt(long[] x, long[] y, long[] zz) { long[] tt = Nat576.createExt64(); implMultiply(x, y, tt); addExt(zz, tt, zz); } public static void multiplyPrecomp(long[] x, long[] precomp, long[] z) { long[] tt = Nat576.createExt64(); implMultiplyPrecomp(x, precomp, tt); reduce(tt, z); } public static void multiplyPrecompAddToExt(long[] x, long[] precomp, long[] zz) { long[] tt = Nat576.createExt64(); implMultiplyPrecomp(x, precomp, tt); addExt(zz, tt, zz); } public static long[] precompMultiplicand(long[] x) { /* * Precompute table of all 4-bit products of x (first section) */ int len = 9 << 4; long[] t = new long[len << 1]; System.arraycopy(x, 0, t, 9, 9); // reduce5(T0, 9); int tOff = 0; for (int i = 7; i > 0; --i) { tOff += 18; Nat.shiftUpBit64(9, t, tOff >>> 1, 0L, t, tOff); reduce5(t, tOff); add(t, 9, t, tOff, t, tOff + 9); } /* * Second section with all 4-bit products of x shifted 4 bits */ Nat.shiftUpBits64(len, t, 0, 4, 0L, t, len); return t; } public static void reduce(long[] xx, long[] z) { long xx09 = xx[9]; long u = xx[17], v = xx09; xx09 = v ^ (u >>> 59) ^ (u >>> 57) ^ (u >>> 54) ^ (u >>> 49); v = xx[8] ^ (u << 5) ^ (u << 7) ^ (u << 10) ^ (u << 15); for (int i = 16; i >= 10; --i) { u = xx[i]; z[i - 8] = v ^ (u >>> 59) ^ (u >>> 57) ^ (u >>> 54) ^ (u >>> 49); v = xx[i - 9] ^ (u << 5) ^ (u << 7) ^ (u << 10) ^ (u << 15); } u = xx09; z[1] = v ^ (u >>> 59) ^ (u >>> 57) ^ (u >>> 54) ^ (u >>> 49); v = xx[0] ^ (u << 5) ^ (u << 7) ^ (u << 10) ^ (u << 15); long x08 = z[8]; long t = x08 >>> 59; z[0] = v ^ t ^ (t << 2) ^ (t << 5) ^ (t << 10); z[8] = x08 & M59; } public static void reduce5(long[] z, int zOff) { long z8 = z[zOff + 8], t = z8 >>> 59; z[zOff ] ^= t ^ (t << 2) ^ (t << 5) ^ (t << 10); z[zOff + 8] = z8 & M59; } public static void sqrt(long[] x, long[] z) { long[] evn = Nat576.create64(), odd = Nat576.create64(); int pos = 0; for (int i = 0; i < 4; ++i) { long u0 = Interleave.unshuffle(x[pos++]); long u1 = Interleave.unshuffle(x[pos++]); evn[i] = (u0 & 0x00000000FFFFFFFFL) | (u1 << 32); odd[i] = (u0 >>> 32) | (u1 & 0xFFFFFFFF00000000L); } { long u0 = Interleave.unshuffle(x[pos]); evn[4] = (u0 & 0x00000000FFFFFFFFL); odd[4] = (u0 >>> 32); } multiply(odd, ROOT_Z, z); add(z, evn, z); } public static void square(long[] x, long[] z) { long[] tt = Nat576.createExt64(); implSquare(x, tt); reduce(tt, z); } public static void squareAddToExt(long[] x, long[] zz) { long[] tt = Nat576.createExt64(); implSquare(x, tt); addExt(zz, tt, zz); } public static void squareN(long[] x, int n, long[] z) { // assert n > 0; long[] tt = Nat576.createExt64(); implSquare(x, tt); reduce(tt, z); while (--n > 0) { implSquare(z, tt); reduce(tt, z); } } public static int trace(long[] x) { // Non-zero-trace bits: 0, 561, 569 return (int)(x[0] ^ (x[8] >>> 49) ^ (x[8] >>> 57)) & 1; } protected static void implMultiply(long[] x, long[] y, long[] zz) { // long[] precomp = precompMultiplicand(y); // // implMultiplyPrecomp(x, precomp, zz); long[] u = new long[16]; for (int i = 0; i < 9; ++i) { implMulwAcc(u, x[i], y[i], zz, i << 1); } long v0 = zz[0], v1 = zz[1]; v0 ^= zz[ 2]; zz[1] = v0 ^ v1; v1 ^= zz[ 3]; v0 ^= zz[ 4]; zz[2] = v0 ^ v1; v1 ^= zz[ 5]; v0 ^= zz[ 6]; zz[3] = v0 ^ v1; v1 ^= zz[ 7]; v0 ^= zz[ 8]; zz[4] = v0 ^ v1; v1 ^= zz[ 9]; v0 ^= zz[10]; zz[5] = v0 ^ v1; v1 ^= zz[11]; v0 ^= zz[12]; zz[6] = v0 ^ v1; v1 ^= zz[13]; v0 ^= zz[14]; zz[7] = v0 ^ v1; v1 ^= zz[15]; v0 ^= zz[16]; zz[8] = v0 ^ v1; v1 ^= zz[17]; long w = v0 ^ v1; zz[ 9] = zz[0] ^ w; zz[10] = zz[1] ^ w; zz[11] = zz[2] ^ w; zz[12] = zz[3] ^ w; zz[13] = zz[4] ^ w; zz[14] = zz[5] ^ w; zz[15] = zz[6] ^ w; zz[16] = zz[7] ^ w; zz[17] = zz[8] ^ w; implMulwAcc(u, x[0] ^ x[1], y[0] ^ y[1], zz, 1); implMulwAcc(u, x[0] ^ x[2], y[0] ^ y[2], zz, 2); implMulwAcc(u, x[0] ^ x[3], y[0] ^ y[3], zz, 3); implMulwAcc(u, x[1] ^ x[2], y[1] ^ y[2], zz, 3); implMulwAcc(u, x[0] ^ x[4], y[0] ^ y[4], zz, 4); implMulwAcc(u, x[1] ^ x[3], y[1] ^ y[3], zz, 4); implMulwAcc(u, x[0] ^ x[5], y[0] ^ y[5], zz, 5); implMulwAcc(u, x[1] ^ x[4], y[1] ^ y[4], zz, 5); implMulwAcc(u, x[2] ^ x[3], y[2] ^ y[3], zz, 5); implMulwAcc(u, x[0] ^ x[6], y[0] ^ y[6], zz, 6); implMulwAcc(u, x[1] ^ x[5], y[1] ^ y[5], zz, 6); implMulwAcc(u, x[2] ^ x[4], y[2] ^ y[4], zz, 6); implMulwAcc(u, x[0] ^ x[7], y[0] ^ y[7], zz, 7); implMulwAcc(u, x[1] ^ x[6], y[1] ^ y[6], zz, 7); implMulwAcc(u, x[2] ^ x[5], y[2] ^ y[5], zz, 7); implMulwAcc(u, x[3] ^ x[4], y[3] ^ y[4], zz, 7); implMulwAcc(u, x[0] ^ x[8], y[0] ^ y[8], zz, 8); implMulwAcc(u, x[1] ^ x[7], y[1] ^ y[7], zz, 8); implMulwAcc(u, x[2] ^ x[6], y[2] ^ y[6], zz, 8); implMulwAcc(u, x[3] ^ x[5], y[3] ^ y[5], zz, 8); implMulwAcc(u, x[1] ^ x[8], y[1] ^ y[8], zz, 9); implMulwAcc(u, x[2] ^ x[7], y[2] ^ y[7], zz, 9); implMulwAcc(u, x[3] ^ x[6], y[3] ^ y[6], zz, 9); implMulwAcc(u, x[4] ^ x[5], y[4] ^ y[5], zz, 9); implMulwAcc(u, x[2] ^ x[8], y[2] ^ y[8], zz, 10); implMulwAcc(u, x[3] ^ x[7], y[3] ^ y[7], zz, 10); implMulwAcc(u, x[4] ^ x[6], y[4] ^ y[6], zz, 10); implMulwAcc(u, x[3] ^ x[8], y[3] ^ y[8], zz, 11); implMulwAcc(u, x[4] ^ x[7], y[4] ^ y[7], zz, 11); implMulwAcc(u, x[5] ^ x[6], y[5] ^ y[6], zz, 11); implMulwAcc(u, x[4] ^ x[8], y[4] ^ y[8], zz, 12); implMulwAcc(u, x[5] ^ x[7], y[5] ^ y[7], zz, 12); implMulwAcc(u, x[5] ^ x[8], y[5] ^ y[8], zz, 13); implMulwAcc(u, x[6] ^ x[7], y[6] ^ y[7], zz, 13); implMulwAcc(u, x[6] ^ x[8], y[6] ^ y[8], zz, 14); implMulwAcc(u, x[7] ^ x[8], y[7] ^ y[8], zz, 15); } protected static void implMultiplyPrecomp(long[] x, long[] precomp, long[] zz) { int MASK = 0xF; /* * Lopez-Dahab algorithm */ for (int k = 56; k >= 0; k -= 8) { for (int j = 1; j < 9; j += 2) { int aVal = (int)(x[j] >>> k); int u = aVal & MASK; int v = (aVal >>> 4) & MASK; addBothTo(precomp, 9 * u, precomp, 9 * (v + 16), zz, j - 1); } Nat.shiftUpBits64(16, zz, 0, 8, 0L); } for (int k = 56; k >= 0; k -= 8) { for (int j = 0; j < 9; j += 2) { int aVal = (int)(x[j] >>> k); int u = aVal & MASK; int v = (aVal >>> 4) & MASK; addBothTo(precomp, 9 * u, precomp, 9 * (v + 16), zz, j); } if (k > 0) { Nat.shiftUpBits64(18, zz, 0, 8, 0L); } } } protected static void implMulwAcc(long[] u, long x, long y, long[] z, int zOff) { // u[0] = 0; u[1] = y; for (int i = 2; i < 16; i += 2) { u[i ] = u[i >>> 1] << 1; u[i + 1] = u[i ] ^ y; } int j = (int)x; long g, h = 0, l = u[j & 15] ^ u[(j >>> 4) & 15] << 4; int k = 56; do { j = (int)(x >>> k); g = u[j & 15] ^ u[(j >>> 4) & 15] << 4; l ^= (g << k); h ^= (g >>> -k); } while ((k -= 8) > 0); for (int p = 0; p < 7; ++p) { x = (x & 0xFEFEFEFEFEFEFEFEL) >>> 1; h ^= x & ((y << p) >> 63); } // assert h >>> 63 == 0; z[zOff ] ^= l; z[zOff + 1] ^= h; } protected static void implSquare(long[] x, long[] zz) { Interleave.expand64To128(x, 0, 9, zz, 0); } }
7,518
7,353
<reponame>LK26/outline-client /** * @file BPredicate.h * @author <NAME> <<EMAIL>> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * Object that parses and evaluates a logical expression. * Allows the user to define custom functions than can be * used in the expression. * * Syntax and semantics for logical expressions: * * - true * Logical true constant. Evaluates to 1. * * - false * Logical false constant. Evaluates to 0. * * - NOT expression * Logical negation. If the expression evaluates to error, the * negation evaluates to error. * * - expression OR expression * Logical disjunction. The second expression is only evaluated * if the first expression evaluates to false. If a sub-expression * evaluates to error, the disjunction evaluates to error. * * - expression AND expression * Logical conjunction. The second expression is only evaluated * if the first expression evaluates to true. If a sub-expression * evaluates to error, the conjunction evaluates to error. * * - function(arg, ..., arg) * Evaluation of a user-provided function (function is the name of the * function, [a-zA-Z0-9_]+). * If the function with the given name does not exist, it evaluates to * error. * Arguments are evaluated from left to right. Each argument can either * be a logical expression or a string (characters enclosed in double * quotes, without any double quote). * If an argument is encountered, but all needed arguments have already * been evaluated, the function evaluates to error. * If an argument is of wrong type, it is not evaluated and the function * evaluates to error. * If an argument evaluates to error, the function evaluates to error. * If after all arguments have been evaluated, the function needs more * arguments, it evaluates to error. * Then the handler function is called. If it returns anything other * than 1 and 0, the function evaluates to error. Otherwise it evaluates * to what the handler function returned. */ #ifndef BADVPN_PREDICATE_BPREDICATE_H #define BADVPN_PREDICATE_BPREDICATE_H #include <misc/debug.h> #include <structure/BAVL.h> #include <base/DebugObject.h> #define PREDICATE_TYPE_BOOL 1 #define PREDICATE_TYPE_STRING 2 #define PREDICATE_MAX_NAME 16 #define PREDICATE_MAX_ARGS 16 /** * Handler function called when evaluating a custom function in the predicate. * * @param user value passed to {@link BPredicateFunction_Init} * @param args arguments to the function. Points to an array of pointers (as many as the * function has arguments), where each pointer points to either to an int or * a zero-terminated string (depending on the type of the argument). * @return 1 for true, 0 for false, -1 for error */ typedef int (*BPredicate_callback) (void *user, void **args); /** * Object that parses and evaluates a logical expression. * Allows the user to define custom functions than can be * used in the expression. */ typedef struct { DebugObject d_obj; void *root; BAVL functions_tree; #ifndef NDEBUG int in_function; #endif } BPredicate; /** * Object that represents a custom function in {@link BPredicate}. */ typedef struct { DebugObject d_obj; BPredicate *p; char name[PREDICATE_MAX_NAME + 1]; int args[PREDICATE_MAX_ARGS]; int num_args; BPredicate_callback callback; void *user; BAVLNode tree_node; } BPredicateFunction; /** * Initializes the object. * * @param p the object * @param str logical expression * @return 1 on success, 0 on failure */ int BPredicate_Init (BPredicate *p, char *str) WARN_UNUSED; /** * Frees the object. * Must have no custom functions. * Must not be called from function handlers. * * @param p the object */ void BPredicate_Free (BPredicate *p); /** * Evaluates the logical expression. * Must not be called from function handlers. * * @param p the object * @return 1 for true, 0 for false, -1 for error */ int BPredicate_Eval (BPredicate *p); /** * Registers a custom function for {@link BPredicate}. * Must not be called from function handlers. * * @param o the object * @param p predicate to register the function for * @param args array of argument types. Each type is either PREDICATE_TYPE_BOOL or PREDICATE_TYPE_STRING. * @param num_args number of arguments for the function. Must be >=0 and <=PREDICATE_MAX_ARGS. * @param callback handler to call to evaluate the function * @param user value to pass to handler */ void BPredicateFunction_Init (BPredicateFunction *o, BPredicate *p, char *name, int *args, int num_args, BPredicate_callback callback, void *user); /** * Removes a custom function for {@link BPredicate}. * Must not be called from function handlers. * * @param o the object */ void BPredicateFunction_Free (BPredicateFunction *o); #endif
1,961
12,278
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 by EMC Corporation, 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. /// /// Copyright holder is EMC Corporation /// /// @author <NAME> /// @author <NAME> //////////////////////////////////////////////////////////////////////////////// #include "tests_shared.hpp" #include "utils/ebo.hpp" TEST(compact_pair_tests, check_size) { struct empty { }; struct non_empty { int i; }; static_assert( sizeof(irs::compact_pair<empty, non_empty>) == sizeof(non_empty), "Invalid size" ); static_assert( sizeof(irs::compact_pair<non_empty, empty>) == sizeof(non_empty), "Invalid size" ); static_assert( sizeof(irs::compact_pair<non_empty, non_empty>) == 2*sizeof(non_empty), "Invalid size" ); } TEST(ebo_tests, check_size) { struct empty { }; struct non_empty { int i; }; struct empty_inherited : irs::compact<0, empty> { int i; }; static_assert( sizeof(empty_inherited) == sizeof(int), "Invalid size" ); struct non_empty_inherited : irs::compact<0, non_empty> { int i; }; static_assert( sizeof(non_empty_inherited) == 2*sizeof(int), "Invalid size" ); struct empty_ref_inherited : irs::compact_ref<0, empty> { int i; }; static_assert( sizeof(empty_ref_inherited) == sizeof(int), "Invalid size" ); struct non_empty_ref_inherited : irs::compact_ref<0, non_empty> { int i; }; static_assert( sizeof(non_empty_ref_inherited) == 2*sizeof(non_empty*), // because of non_empty* alignment "Invalid size" ); }
696
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.java.source.classpath; import java.util.Iterator; import java.util.List; import java.io.File; import java.net.URL; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.classpath.GlobalPathRegistry; import org.netbeans.api.java.queries.SourceForBinaryQuery; import org.netbeans.api.java.source.ClasspathInfo; import org.netbeans.junit.NbTestCase; import org.netbeans.modules.java.source.ClassIndexTestCase; import org.netbeans.modules.java.source.usages.ClasspathInfoAccessor; import org.netbeans.modules.java.source.usages.IndexUtil; import org.netbeans.spi.java.classpath.support.ClassPathSupport; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.filesystems.URLMapper; /** * * @author <NAME> */ public class CacheSourceForBinaryQueryImplTest extends ClassIndexTestCase { FileObject[] srcRoots; ClasspathInfo cpInfo; CacheSourceForBinaryQueryImpl sfbq; public CacheSourceForBinaryQueryImplTest(String testName) { super(testName); } protected @Override void setUp() throws Exception { this.clearWorkDir(); File fwd = this.getWorkDir(); FileObject wd = FileUtil.toFileObject(fwd); assertNotNull(wd); File cacheFolder = new File (fwd,"cache"); //NOI18N cacheFolder.mkdirs(); IndexUtil.setCacheFolder (cacheFolder); this.srcRoots = new FileObject [2]; this.srcRoots[0] = wd.createFolder("src1"); //NOI18N this.srcRoots[1] = wd.createFolder("src2"); //NOI18N ClassPath bootPath = ClassPathSupport.createClassPath(new URL[0]); ClassPath compilePath = ClassPathSupport.createClassPath(new URL[0]); ClassPath srcPath = ClassPathSupport.createClassPath(srcRoots); GlobalPathRegistry gpr = GlobalPathRegistry.getDefault(); gpr.register(ClassPath.SOURCE, new ClassPath[]{srcPath}); gpr.register(ClassPath.BOOT, new ClassPath[] {bootPath}); gpr.register(ClassPath.COMPILE, new ClassPath[] {compilePath}); beginTx(); this.cpInfo = ClasspathInfoAccessor.getINSTANCE().create(bootPath,ClassPath.EMPTY,compilePath,ClassPath.EMPTY,ClassPath.EMPTY,srcPath,ClassPath.EMPTY,null,true,false,false,false,false,null); this.sfbq = new CacheSourceForBinaryQueryImpl (); } protected @Override void tearDown() throws Exception { this.cpInfo = null; } public void testFindSourceRoots() throws Exception { ClassPath outCp = ClasspathInfoAccessor.getINSTANCE().getCachedClassPath(this.cpInfo,ClasspathInfo.PathKind.OUTPUT); assertNotNull(outCp); assertEquals(srcRoots.length,outCp.entries().size()); Iterator<ClassPath.Entry> it = ((List<ClassPath.Entry>)outCp.entries()).iterator(); for (int i=0; it.hasNext(); i++) { ClassPath.Entry entry = it.next(); URL url = entry.getURL(); SourceForBinaryQuery.Result result = this.sfbq.findSourceRoots(url); FileObject[] sourceRoots = result.getRoots(); assertNotNull(sourceRoots); assertEquals(1,sourceRoots.length); assertEquals(srcRoots[i],sourceRoots[0]); } } public void testFindSourceRootsWithAptRoot() throws Exception { //Force Apt Source cache creation final FileObject[] aptSrcRoots = new FileObject[srcRoots.length]; for (int i=0; i<srcRoots.length; i++) { aptSrcRoots[i]=URLMapper.findFileObject(AptCacheForSourceQuery.getAptFolder(srcRoots[i].getURL())); } ClassPath outCp = ClasspathInfoAccessor.getINSTANCE().getCachedClassPath(this.cpInfo,ClasspathInfo.PathKind.OUTPUT); assertNotNull(outCp); assertEquals(srcRoots.length,outCp.entries().size()); Iterator<ClassPath.Entry> it = ((List<ClassPath.Entry>)outCp.entries()).iterator(); for (int i=0; it.hasNext(); i++) { ClassPath.Entry entry = it.next(); URL url = entry.getURL(); SourceForBinaryQuery.Result result = this.sfbq.findSourceRoots(url); FileObject[] sourceRoots = result.getRoots(); assertNotNull(sourceRoots); assertEquals(2,sourceRoots.length); assertEquals(srcRoots[i],sourceRoots[0]); assertEquals(aptSrcRoots[i], sourceRoots[1]); } } }
1,986
3,200
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "backend/optimizer/ascend/ir_fission/dynamic_rnn_grad_fission_v2.h" #include <vector> #include <memory> #include "backend/session/kernel_graph.h" #include "backend/session/anf_runtime_algorithm.h" #include "utils/trace_base.h" #include "utils/tensor_construct_utils.h" namespace mindspore { namespace opt { namespace { constexpr size_t kDynamicRNNGradInputNum = 16; constexpr size_t kSplitVOutputNum = 2; constexpr size_t kBasicCellOutputNum = 2; constexpr size_t kBasicLstmCStateGradOutput0DimNum = 3; constexpr int64_t kAttrNValue = 2; constexpr int64_t kAttrDynInputSizesValue = 2; constexpr int64_t kAttrAxis2Value = 2; constexpr int64_t kAttrNumSplitValue = 2; constexpr int64_t kAttrSplitDimValue = 2; constexpr size_t kDimMultiNum = 4; void CreateTLoopNode(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode, std::vector<std::vector<AnfNodePtr>> *result_nodes) { MS_EXCEPTION_IF_NULL(func_graph); MS_EXCEPTION_IF_NULL(dynamic_rnn_grad_cnode); MS_EXCEPTION_IF_NULL(result_nodes); std::vector<AnfNodePtr> basic_lstm_cell_c_state_grad_nodes; std::vector<AnfNodePtr> matmul_nodes; std::vector<AnfNodePtr> split_nodes; // Get the size of t auto origin_input9_shape = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex11), 0); size_t t_size = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex9), 0)[0]; auto input_i_shape = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex12), 0); for (size_t i = 0; i < t_size; ++i) { // Create basic_lstm_cell_c_state_grad std::vector<AnfNodePtr> basic_lstm_cell_c_state_grad_inputs = { NewValueNode(std::make_shared<Primitive>(kBasicLSTMCellCStateGradV2OpName))}; auto basic_lstm_cell_c_state_grad = func_graph->NewCNode(basic_lstm_cell_c_state_grad_inputs); std::vector<size_t> output0_dims{ origin_input9_shape[kDim0], kDimMultiNum * (((origin_input9_shape[kDim1] + kCubeSize - 1) / kCubeSize) * kCubeSize)}; std::vector<size_t> output1_dims{input_i_shape[kDim1], input_i_shape[kDim2]}; AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat16, kNumberTypeFloat32}, {output0_dims, output1_dims}, basic_lstm_cell_c_state_grad.get()); AnfAlgo::SetNodeAttr("forget_bias", MakeValue(1.0f), basic_lstm_cell_c_state_grad); AnfAlgo::SetNodeAttr("activation", MakeValue("Tanh"), basic_lstm_cell_c_state_grad); // Create matmul auto origin_input1_shape = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex2), 0); std::vector<AnfNodePtr> matmul_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimMatMul->name()))}; auto matmul = func_graph->NewCNode(matmul_inputs); AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat32}, {{IntToSize(1), output0_dims[0], origin_input1_shape[0]}}, matmul.get()); AnfAlgo::SetNodeAttr("transpose_x1", MakeValue(false), matmul); AnfAlgo::SetNodeAttr("transpose_x2", MakeValue(true), matmul); // Create split std::vector<AnfNodePtr> splitv_input = {NewValueNode(std::make_shared<Primitive>(prim::kPrimSplitV->name()))}; auto split_v = func_graph->NewCNode(splitv_input); auto origin_output2_shape = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode, kIndex2); auto origin_output3_shape = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode, kIndex3); std::vector<size_t> split_v_output0_shape{IntToSize(1), origin_output2_shape[kDim1], origin_output2_shape[kDim2]}; std::vector<size_t> split_v_output1_shape{IntToSize(1), origin_output3_shape[kDim0], origin_output3_shape[kDim1]}; AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat32, kNumberTypeFloat32}, {split_v_output0_shape, split_v_output1_shape}, split_v.get()); AnfAlgo::SetNodeAttr(kAttrSizeSplits, MakeValue(std::vector<int64_t>{ SizeToLong((origin_output2_shape[kDim2] + kCubeSize - 1) / kCubeSize * kCubeSize), SizeToLong((origin_output3_shape[kDim1] + kCubeSize - 1) / kCubeSize * kCubeSize)}), split_v); AnfAlgo::SetNodeAttr(kAttrSplitDim, MakeValue(static_cast<int64_t>(kAttrSplitDimValue)), split_v); AnfAlgo::SetNodeAttr(kAttrNumSplit, MakeValue(static_cast<int64_t>(kAttrNumSplitValue)), split_v); basic_lstm_cell_c_state_grad_nodes.emplace_back(basic_lstm_cell_c_state_grad); matmul_nodes.emplace_back(matmul); split_nodes.emplace_back(split_v); } result_nodes->emplace_back(basic_lstm_cell_c_state_grad_nodes); result_nodes->emplace_back(matmul_nodes); result_nodes->emplace_back(split_nodes); } AnfNodePtr CreateLSTMSPlitV(const FuncGraphPtr &func_graph, const AnfNodePtr &input, const std::vector<std::vector<size_t>> &split_shapes, const std::vector<TypeId> &split_types, const std::vector<int64_t> &size_split, size_t num_split_x) { std::vector<AnfNodePtr> lstm_split_input = {NewValueNode(std::make_shared<Primitive>(prim::kPrimSplitV->name())), input}; auto lstm_split = func_graph->NewCNode(lstm_split_input); AnfAlgo::SetOutputInferTypeAndShape(split_types, split_shapes, lstm_split.get()); AnfAlgo::SetNodeAttr(kAttrSizeSplits, MakeValue(size_split), lstm_split); AnfAlgo::SetNodeAttr(kAttrSplitDim, MakeValue(static_cast<int64_t>(0)), lstm_split); AnfAlgo::SetNodeAttr(kAttrNumSplit, MakeValue(SizeToLong(num_split_x)), lstm_split); return lstm_split; } AnfNodePtr AddLSTMInputGradNode(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode, std::vector<AnfNodePtr> *outputs) { std::vector<std::vector<AnfNodePtr>> result_nodes; CreateTLoopNode(func_graph, dynamic_rnn_grad_cnode, &result_nodes); auto origin_input5_shape = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex6), 0); std::vector<size_t> split_c_dims{IntToSize(1), origin_input5_shape[0], origin_input5_shape[1]}; auto origin_input7 = dynamic_rnn_grad_cnode->input(kIndex8); size_t num_split_x = AnfAlgo::GetOutputInferShape(origin_input7, 0)[0]; std::vector<std::vector<size_t>> split_shapes; std::vector<TypeId> split_types; std::vector<int64_t> size_split; for (size_t i = 0; i < num_split_x; ++i) { split_shapes.emplace_back(split_c_dims); split_types.emplace_back(kNumberTypeFloat32); size_split.emplace_back(1); } // Create lstm_split_c auto lstm_split_c = CreateLSTMSPlitV(func_graph, origin_input7, split_shapes, split_types, size_split, num_split_x); std::vector<AnfNodePtr> lstm_split_c_outputs; CreateMultipleOutputsOfAnfNode(func_graph, lstm_split_c, num_split_x, &lstm_split_c_outputs); // Create lstm_split_dy auto lstm_split_dy = CreateLSTMSPlitV(func_graph, dynamic_rnn_grad_cnode->input(kIndex9), split_shapes, split_types, size_split, num_split_x); std::vector<AnfNodePtr> lstm_split_dy_outputs; CreateMultipleOutputsOfAnfNode(func_graph, lstm_split_dy, num_split_x, &lstm_split_dy_outputs); // Create lstm_split_i auto lstm_split_i = CreateLSTMSPlitV(func_graph, dynamic_rnn_grad_cnode->input(kIndex12), split_shapes, split_types, size_split, num_split_x); std::vector<AnfNodePtr> lstm_split_i_outputs; CreateMultipleOutputsOfAnfNode(func_graph, lstm_split_i, num_split_x, &lstm_split_i_outputs); // Create lstm_split_j auto lstm_split_j = CreateLSTMSPlitV(func_graph, dynamic_rnn_grad_cnode->input(kIndex13), split_shapes, split_types, size_split, num_split_x); std::vector<AnfNodePtr> lstm_split_j_outputs; CreateMultipleOutputsOfAnfNode(func_graph, lstm_split_j, num_split_x, &lstm_split_j_outputs); // Create lstm_split_f auto lstm_split_f = CreateLSTMSPlitV(func_graph, dynamic_rnn_grad_cnode->input(kIndex14), split_shapes, split_types, size_split, num_split_x); std::vector<AnfNodePtr> lstm_split_f_outputs; CreateMultipleOutputsOfAnfNode(func_graph, lstm_split_f, num_split_x, &lstm_split_f_outputs); // Create lstm_split_o auto lstm_split_o = CreateLSTMSPlitV(func_graph, dynamic_rnn_grad_cnode->input(kIndex15), split_shapes, split_types, size_split, num_split_x); std::vector<AnfNodePtr> lstm_split_o_outputs; CreateMultipleOutputsOfAnfNode(func_graph, lstm_split_o, num_split_x, &lstm_split_o_outputs); // Create lstm_split_tanh auto lstm_split_tanh = CreateLSTMSPlitV(func_graph, dynamic_rnn_grad_cnode->input(kIndex16), split_shapes, split_types, size_split, num_split_x); std::vector<AnfNodePtr> lstm_split_tanh_outputs; CreateMultipleOutputsOfAnfNode(func_graph, lstm_split_tanh, num_split_x, &lstm_split_tanh_outputs); // Add edges std::vector<AnfNodePtr> pre_basic_lstm_cell_c_state_grad_outputs; std::vector<AnfNodePtr> pre_split_outputs; auto basic_lstm_cell_c_state_grad_nodes = result_nodes[kIndex0]; auto matmul_nodes = result_nodes[kIndex1]; auto split_nodes = result_nodes[kIndex2]; std::vector<AnfNodePtr> lstm_x_concat_input(num_split_x + 1); lstm_x_concat_input[0] = NewValueNode(std::make_shared<Primitive>(prim::kPrimConcat->name())); std::vector<AnfNodePtr> lstm_gage_concat_input(num_split_x + 1); lstm_gage_concat_input[0] = NewValueNode(std::make_shared<Primitive>(prim::kPrimConcat->name())); for (size_t i = 0; i < num_split_x; ++i) { size_t idx = num_split_x - i - 1; // Create basic_lstm_cell_c_state_grad std::vector<AnfNodePtr> basic_lstm_cell_c_state_grad_inputs = { NewValueNode(std::make_shared<Primitive>(kBasicLSTMCellCStateGradV2OpName))}; if (i == num_split_x - 1) { std::vector<AnfNodePtr> reshape_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReshape->name())), dynamic_rnn_grad_cnode->input(6)}; auto reshape = func_graph->NewCNode(reshape_inputs); auto reshape_out_shape = {IntToSize(1), AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex6), 0)[0], AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex6), 0)[1]}; AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat32}, {reshape_out_shape}, reshape.get()); (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(reshape); } else { (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(lstm_split_c_outputs[idx - 1]); } (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(lstm_split_dy_outputs[idx]); if (i == 0) { (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(dynamic_rnn_grad_cnode->input(kIndex10)); (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(dynamic_rnn_grad_cnode->input(kIndex11)); } else { (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(pre_split_outputs[1]); (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(pre_basic_lstm_cell_c_state_grad_outputs[1]); } (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(lstm_split_i_outputs[idx]); (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(lstm_split_j_outputs[idx]); (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(lstm_split_f_outputs[idx]); (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(lstm_split_o_outputs[idx]); (void)basic_lstm_cell_c_state_grad_inputs.emplace_back(lstm_split_tanh_outputs[idx]); auto basic_lstm_cell_c_state_grad = func_graph->NewCNode(basic_lstm_cell_c_state_grad_inputs); MS_EXCEPTION_IF_NULL(basic_lstm_cell_c_state_grad); basic_lstm_cell_c_state_grad->set_abstract(basic_lstm_cell_c_state_grad_nodes[i]->abstract()); AnfAlgo::CopyNodeAttrs(basic_lstm_cell_c_state_grad_nodes[i], basic_lstm_cell_c_state_grad); // Create outputs for current basic_lstm_cell_c_state_grad node std::vector<AnfNodePtr> basic_lstm_cell_c_state_grad_outputs; CreateMultipleOutputsOfAnfNode(func_graph, basic_lstm_cell_c_state_grad, kBasicCellOutputNum, &basic_lstm_cell_c_state_grad_outputs); pre_basic_lstm_cell_c_state_grad_outputs = basic_lstm_cell_c_state_grad_outputs; // Create MatMul std::vector<AnfNodePtr> matmul_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimMatMul->name()))}; (void)matmul_inputs.emplace_back(basic_lstm_cell_c_state_grad_outputs[0]); (void)matmul_inputs.emplace_back(dynamic_rnn_grad_cnode->input(kIndex2)); auto matmul = func_graph->NewCNode(matmul_inputs); MS_EXCEPTION_IF_NULL(matmul); matmul->set_abstract(matmul_nodes[i]->abstract()); AnfAlgo::CopyNodeAttrs(matmul_nodes[i], matmul); // Create splitv std::vector<AnfNodePtr> splitv_input = {NewValueNode(std::make_shared<Primitive>(prim::kPrimSplitV->name())), matmul}; auto split_v = func_graph->NewCNode(splitv_input); MS_EXCEPTION_IF_NULL(split_v); split_v->set_abstract(split_nodes[i]->abstract()); AnfAlgo::CopyNodeAttrs(split_nodes[i], split_v); // Create outputs for current split node std::vector<AnfNodePtr> split_outputs; CreateMultipleOutputsOfAnfNode(func_graph, split_v, kSplitVOutputNum, &split_outputs); pre_split_outputs = split_outputs; lstm_x_concat_input[idx + 1] = split_outputs[0]; auto basic_lstm_cell_c_state_grad_outputs_0_shape = AnfAlgo::GetOutputInferShape(basic_lstm_cell_c_state_grad_outputs[0], 0); std::vector<size_t> temp_shape; if (basic_lstm_cell_c_state_grad_outputs_0_shape.size() == kBasicLstmCStateGradOutput0DimNum) { temp_shape = basic_lstm_cell_c_state_grad_outputs_0_shape; } else { temp_shape = {1, basic_lstm_cell_c_state_grad_outputs_0_shape[0], basic_lstm_cell_c_state_grad_outputs_0_shape[1]}; } std::vector<AnfNodePtr> reshape_input = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReshape->name())), basic_lstm_cell_c_state_grad_outputs[0]}; auto reshape = func_graph->NewCNode(reshape_input); AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(basic_lstm_cell_c_state_grad_outputs[0], 0)}, {temp_shape}, reshape.get()); lstm_gage_concat_input[idx + 1] = reshape; } // Create lstm_x_concat auto lstm_x_concat = func_graph->NewCNode(lstm_x_concat_input); AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat32}, {AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode, 2)}, lstm_x_concat.get()); AnfAlgo::SetNodeAttr(kAttrN, MakeValue(SizeToLong(num_split_x)), lstm_x_concat); AnfAlgo::SetNodeAttr(kAttrDynInputSizes, MakeValue(std::vector<int64_t>{SizeToLong(num_split_x)}), lstm_x_concat); AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(static_cast<int64_t>(0)), lstm_x_concat); // Create lstm_gage_concat auto lstm_gage_concat = func_graph->NewCNode(lstm_gage_concat_input); auto origin_input7_shape = AnfAlgo::GetOutputInferShape(origin_input7, 0); AnfAlgo::SetOutputInferTypeAndShape( {kNumberTypeFloat16}, {{origin_input7_shape[kDim0], origin_input7_shape[kDim1], kDimMultiNum * origin_input7_shape[kDim2]}}, lstm_gage_concat.get()); AnfAlgo::SetNodeAttr(kAttrN, MakeValue(SizeToLong(num_split_x)), lstm_gage_concat); AnfAlgo::SetNodeAttr(kAttrDynInputSizes, MakeValue(std::vector<int64_t>{SizeToLong(num_split_x)}), lstm_gage_concat); AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(SizeToLong(0)), lstm_gage_concat); outputs->emplace_back(lstm_x_concat); outputs->emplace_back(pre_split_outputs[1]); outputs->emplace_back(pre_basic_lstm_cell_c_state_grad_outputs[1]); return lstm_gage_concat; } AnfNodePtr CreateSplitV(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode) { MS_EXCEPTION_IF_NULL(func_graph); MS_EXCEPTION_IF_NULL(dynamic_rnn_grad_cnode); // Create node auto origin_input6 = dynamic_rnn_grad_cnode->input(kIndex7); std::vector<AnfNodePtr> splitv_input = {NewValueNode(std::make_shared<Primitive>(prim::kPrimSplitV->name())), origin_input6}; auto split_v = func_graph->NewCNode(splitv_input); // Set infer data type and shape auto dtypes = {AnfAlgo::GetOutputInferDataType(origin_input6, 0), AnfAlgo::GetOutputInferDataType(origin_input6, 0)}; auto origin_input6_shape = AnfAlgo::GetOutputInferShape(origin_input6, 0); std::vector<size_t> shape1 = {origin_input6_shape[kDim0] - 1, origin_input6_shape[kDim1], origin_input6_shape[kDim2]}; std::vector<size_t> shape2 = {1, origin_input6_shape[kDim1], origin_input6_shape[kDim2]}; std::vector<std::vector<size_t>> shapes = {shape1, shape2}; AnfAlgo::SetOutputInferTypeAndShape(dtypes, shapes, split_v.get()); // Set attr AnfAlgo::SetNodeAttr(kAttrSplitDim, MakeValue(SizeToLong(0)), split_v); AnfAlgo::SetNodeAttr(kAttrNumSplit, MakeValue(SizeToLong(kAttrNumSplitValue)), split_v); AnfAlgo::SetNodeAttr(kAttrSizeSplits, MakeValue(std::vector<int64_t>{SizeToLong(origin_input6_shape[0] - 1), 1}), split_v); AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), split_v); return split_v; } AnfNodePtr CreateHConcat(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode, const AnfNodePtr &splitv) { MS_EXCEPTION_IF_NULL(func_graph); MS_EXCEPTION_IF_NULL(dynamic_rnn_grad_cnode); MS_EXCEPTION_IF_NULL(splitv); // Create node std::vector<AnfNodePtr> splitv_outputs; CreateMultipleOutputsOfAnfNode(func_graph, splitv, kSplitVOutputNum, &splitv_outputs); if (splitv_outputs.size() != kSplitVOutputNum) { MS_LOG(EXCEPTION) << "Create outputs of node " << splitv->DebugString() << " failed" << " trace: " << trace::DumpSourceLines(dynamic_rnn_grad_cnode); } auto origin_input4 = dynamic_rnn_grad_cnode->input(kIndex5); auto origin_input4_shape = AnfAlgo::GetOutputInferShape(origin_input4, 0); // Create reshape to change shape std::vector<size_t> shape_tmp; if (origin_input4_shape.size() == kShape4dDims) { shape_tmp = origin_input4_shape; } else { shape_tmp = {1, origin_input4_shape[0], origin_input4_shape[1]}; } std::vector<AnfNodePtr> reshape_input = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReshape->name())), origin_input4}; auto reshape = func_graph->NewCNode(reshape_input); AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(origin_input4, 0)}, {shape_tmp}, reshape.get()); std::vector<AnfNodePtr> concat_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimConcat->name())), reshape, splitv_outputs[0]}; auto concat = func_graph->NewCNode(concat_inputs); // Set infer data type and shape auto splitv_output0_shape = AnfAlgo::GetOutputInferShape(splitv, 0); std::vector<size_t> shape = {splitv_output0_shape[0] + 1, origin_input4_shape[0], origin_input4_shape[1]}; AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(origin_input4, 0)}, {shape}, concat.get()); // Set attr AnfAlgo::SetNodeAttr(kAttrN, MakeValue(SizeToLong(kAttrNValue)), concat); AnfAlgo::SetNodeAttr(kAttrDynInputSizes, MakeValue(std::vector<int64_t>{kAttrDynInputSizesValue}), concat); AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(SizeToLong(0)), concat); AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), concat); return concat; } AnfNodePtr CreateConcat(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode, const AnfNodePtr &h_concat) { MS_EXCEPTION_IF_NULL(func_graph); MS_EXCEPTION_IF_NULL(dynamic_rnn_grad_cnode); // Create node auto origin_input0 = dynamic_rnn_grad_cnode->input(1); std::vector<AnfNodePtr> concat_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimConcat->name())), origin_input0, h_concat}; auto concat = func_graph->NewCNode(concat_inputs); // Set infer data type and shape auto origin_output0_shape = AnfAlgo::GetOutputInferShape(origin_input0, 0); auto h_concat_output_shape = AnfAlgo::GetOutputInferShape(h_concat, 0); std::vector<size_t> shape = {origin_output0_shape[kDim0], origin_output0_shape[kDim1], origin_output0_shape[kDim2] + h_concat_output_shape[kDim2]}; AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(origin_input0, 0)}, {shape}, concat.get()); // Set attr AnfAlgo::SetNodeAttr(kAttrN, MakeValue(SizeToLong(kAttrNValue)), concat); AnfAlgo::SetNodeAttr(kAttrDynInputSizes, MakeValue(std::vector<int64_t>{kAttrDynInputSizesValue}), concat); AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(SizeToLong(kAttrAxis2Value)), concat); AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), concat); return concat; } AnfNodePtr CreateConcatNodeT1(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode) { MS_EXCEPTION_IF_NULL(func_graph); MS_EXCEPTION_IF_NULL(dynamic_rnn_grad_cnode); // Create node auto origin_input0 = dynamic_rnn_grad_cnode->input(kIndex1); auto origin_input4 = dynamic_rnn_grad_cnode->input(kIndex5); auto origin_input4_shape = AnfAlgo::GetOutputInferShape(origin_input4, 0); // Create reshape to change shape std::vector<size_t> shape_tmp; if (origin_input4_shape.size() == kShape3dDims) { shape_tmp = origin_input4_shape; } else { shape_tmp = {1, origin_input4_shape[0], origin_input4_shape[1]}; } std::vector<AnfNodePtr> reshape_input = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReshape->name())), origin_input4}; auto reshape = func_graph->NewCNode(reshape_input); AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(origin_input4, 0)}, {shape_tmp}, reshape.get()); std::vector<AnfNodePtr> concat_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimConcat->name())), origin_input0, reshape}; auto concat = func_graph->NewCNode(concat_inputs); // Set infer data type and shape auto origin_input0_shape = AnfAlgo::GetOutputInferShape(origin_input0, 0); std::vector<size_t> shape = {origin_input0_shape[kDim0], origin_input0_shape[kDim1], origin_input0_shape[kDim2] + shape_tmp[kDim2]}; AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(origin_input0, 0)}, {shape}, concat.get()); // Set attr AnfAlgo::SetNodeAttr(kAttrN, MakeValue(SizeToLong(kAttrNValue)), concat); AnfAlgo::SetNodeAttr(kAttrDynInputSizes, MakeValue(std::vector<int64_t>{kAttrDynInputSizesValue}), concat); AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(SizeToLong(kAttrAxis2Value)), concat); AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), concat); return concat; } AnfNodePtr CreateBatchMatMul(const FuncGraphPtr &func_graph, const AnfNodePtr &lstm_input_grad, const AnfNodePtr &concat) { MS_EXCEPTION_IF_NULL(func_graph); // Create node std::vector<AnfNodePtr> matmul_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimBatchMatMul->name())), concat, lstm_input_grad}; auto batch_matmul = func_graph->NewCNode(matmul_inputs); // Set infer data type and shape auto concat_shape = AnfAlgo::GetOutputInferShape(concat, 0); auto lstm_input_grad_shape = AnfAlgo::GetOutputInferShape(lstm_input_grad, 0); std::vector<size_t> shape = {concat_shape[kDim0], concat_shape[kDim2], lstm_input_grad_shape[kDim2]}; AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat32}, {shape}, batch_matmul.get()); // Set attr AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), batch_matmul); AnfAlgo::SetNodeAttr("transpose_x1", MakeValue(true), batch_matmul); AnfAlgo::SetNodeAttr("transpose_x2", MakeValue(false), batch_matmul); return batch_matmul; } AnfNodePtr CreateBatchMatMul2(const FuncGraphPtr &func_graph, const AnfNodePtr &lstm_input_grad, const AnfNodePtr &node) { MS_EXCEPTION_IF_NULL(func_graph); // Create node std::vector<AnfNodePtr> matmul_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimBatchMatMul->name())), node, lstm_input_grad}; auto batch_matmul = func_graph->NewCNode(matmul_inputs); // Set infer data type and shape auto out_shape = {AnfAlgo::GetOutputInferShape(lstm_input_grad, 0)[kIndex0], IntToSize(1), AnfAlgo::GetOutputInferShape(lstm_input_grad, 0)[kIndex2]}; AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat16}, {out_shape}, batch_matmul.get()); // Set attr AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), batch_matmul); AnfAlgo::SetNodeAttr("transpose_x1", MakeValue(false), batch_matmul); AnfAlgo::SetNodeAttr("transpose_x2", MakeValue(false), batch_matmul); return batch_matmul; } AnfNodePtr CreateDwReduceSum(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode, const AnfNodePtr &batch_matmul) { MS_EXCEPTION_IF_NULL(func_graph); // Create node std::vector<AnfNodePtr> reduce_sum_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReduceSum->name())), batch_matmul}; auto reduce_sum = func_graph->NewCNode(reduce_sum_inputs); // Set infer data type and shape AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(dynamic_rnn_grad_cnode, 0)}, {AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode, 0)}, reduce_sum.get()); // Set attr AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(std::vector<int64_t>{0}), reduce_sum); AnfAlgo::SetNodeAttr(kAttrKeepDims, MakeValue(false), reduce_sum); AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), reduce_sum); return reduce_sum; } AnfNodePtr CreateDwReshape(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode, const AnfNodePtr &batch_matmul) { MS_EXCEPTION_IF_NULL(func_graph); // Create node std::vector<AnfNodePtr> reshape_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReshape->name())), batch_matmul}; auto reshape = func_graph->NewCNode(reshape_inputs); // Set infer data type and shape AnfAlgo::SetOutputInferTypeAndShape({AnfAlgo::GetOutputInferDataType(dynamic_rnn_grad_cnode, 0)}, {AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode, 0)}, reshape.get()); AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), reshape); return reshape; } AnfNodePtr CreateValueNode(const FuncGraphPtr &func_graph, const CNodePtr &dynamic_rnn_grad_cnode) { auto origin_input7 = dynamic_rnn_grad_cnode->input(kIndex8); auto origin_input7_shape = AnfAlgo::GetOutputInferShape(origin_input7, 0); auto t_size = origin_input7_shape[0]; auto n_size = origin_input7_shape[1]; std::vector<size_t> shape = {t_size, IntToSize(1), n_size}; std::vector<int64_t> output_shape = {SizeToLong(t_size), SizeToLong(1), SizeToLong(n_size)}; std::vector<int64_t> output_tensor = {SizeToLong(t_size) * SizeToLong(n_size)}; auto tensor = TensorConstructUtils::CreateOnesTensor(kFloat32, output_tensor); auto x_abstract = std::make_shared<abstract::AbstractTensor>(kFloat32, output_shape); auto kernel_graph = func_graph->cast<KernelGraphPtr>(); auto value_node = kernel_graph->NewValueNode(x_abstract, tensor); kernel_graph->AddValueNodeToGraph(value_node); AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat32}, {shape}, value_node.get()); return value_node; } AnfNodePtr CreateDbReduceSum(const FuncGraphPtr &func_graph, const CNodePtr &, const AnfNodePtr &lstm_input_grad, const AnfNodePtr &value_node) { MS_EXCEPTION_IF_NULL(func_graph); // Create node auto batch_matmul = CreateBatchMatMul2(func_graph, lstm_input_grad, value_node); std::vector<AnfNodePtr> reduce_sum_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimReduceSum->name())), batch_matmul}; auto reduce_sum = func_graph->NewCNode(reduce_sum_inputs); // Set infer data type and shape auto out_shape = {AnfAlgo::GetOutputInferShape(lstm_input_grad, 0)[kDim2]}; AnfAlgo::SetOutputInferTypeAndShape({kNumberTypeFloat16}, {out_shape}, reduce_sum.get()); // Set attr AnfAlgo::SetNodeAttr(kAttrAxis, MakeValue(std::vector<int64_t>{0}), reduce_sum); AnfAlgo::SetNodeAttr(kAttrKeepDims, MakeValue(false), reduce_sum); AnfAlgo::SetNodeAttr("is_backend_insert", MakeValue(true), reduce_sum); return reduce_sum; } } // namespace const BaseRef DynamicRnnGradFissionV2::DefinePattern() const { VarPtr Xs = std::make_shared<SeqVar>(); return VectorRef({prim::kPrimDynamicRNNGrad, Xs}); } const AnfNodePtr DynamicRnnGradFissionV2::Process(const FuncGraphPtr &func_graph, const AnfNodePtr &node, const EquivPtr &) const { MS_EXCEPTION_IF_NULL(func_graph); MS_EXCEPTION_IF_NULL(node); auto dynamic_rnn_grad_cnode = node->cast<CNodePtr>(); MS_EXCEPTION_IF_NULL(dynamic_rnn_grad_cnode); if (dynamic_rnn_grad_cnode->inputs().size() < kDynamicRNNGradInputNum + 1) { MS_LOG(INFO) << "The node " << dynamic_rnn_grad_cnode->DebugString() << " has less than " << (kDynamicRNNGradInputNum + 1) << " inputs"; return nullptr; } if (AnfAlgo::IsDynamicShape(node)) { MS_LOG(INFO) << "DynamicRnnGrad is dynamic shape, can not do fission."; return nullptr; } std::vector<AnfNodePtr> new_outputs; auto lstm_input_grad = AddLSTMInputGradNode(func_graph, dynamic_rnn_grad_cnode, &new_outputs); size_t t_size = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex7), 0)[0]; size_t hidden_size = AnfAlgo::GetOutputInferShape(dynamic_rnn_grad_cnode->input(kIndex7), 0)[kDim2]; if (hidden_size % kCubeSize != 0) { MS_LOG(EXCEPTION) << "`hidden_size` in this node should be multiple of 16, but got " << hidden_size << ". " << dynamic_rnn_grad_cnode->DebugString(); } AnfNodePtr concat = nullptr; if (t_size != 1) { auto splitv = CreateSplitV(func_graph, dynamic_rnn_grad_cnode); auto h_concat = CreateHConcat(func_graph, dynamic_rnn_grad_cnode, splitv); concat = CreateConcat(func_graph, dynamic_rnn_grad_cnode, h_concat); } else { concat = CreateConcatNodeT1(func_graph, dynamic_rnn_grad_cnode); } auto batch_matmul = CreateBatchMatMul(func_graph, lstm_input_grad, concat); std::vector<AnfNodePtr> make_tuple_inputs = {NewValueNode(prim::kPrimMakeTuple)}; if (t_size != 1) { auto dw_reduce_sum = CreateDwReduceSum(func_graph, dynamic_rnn_grad_cnode, batch_matmul); make_tuple_inputs.emplace_back(dw_reduce_sum); } else { auto dw_reshape = CreateDwReshape(func_graph, dynamic_rnn_grad_cnode, batch_matmul); make_tuple_inputs.emplace_back(dw_reshape); } auto value_node = CreateValueNode(func_graph, dynamic_rnn_grad_cnode); // create reduce_sum_2 auto db_reduce_sum = CreateDbReduceSum(func_graph, dynamic_rnn_grad_cnode, lstm_input_grad, value_node); make_tuple_inputs.emplace_back(db_reduce_sum); make_tuple_inputs.insert(make_tuple_inputs.end(), new_outputs.begin(), new_outputs.end()); auto make_tuple = func_graph->NewCNode(make_tuple_inputs); return make_tuple; } } // namespace opt } // namespace mindspore
14,309
1,144
<reponame>dram/metasfresh<filename>backend/de.metas.marketing/base/src/main/java/de/metas/marketing/base/interceptor/MKTG_ContactPerson.java package de.metas.marketing.base.interceptor; import org.adempiere.ad.dao.IQueryBL; import org.adempiere.ad.dao.IQueryUpdater; import org.adempiere.ad.modelvalidator.annotations.Interceptor; import org.adempiere.ad.modelvalidator.annotations.ModelChange; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.model.IQuery; import org.compiere.model.ModelValidator; import org.springframework.stereotype.Component; import de.metas.i18n.Language; import de.metas.marketing.base.UserService; import de.metas.marketing.base.model.ContactPerson; import de.metas.marketing.base.model.ContactPersonRepository; import de.metas.marketing.base.model.I_MKTG_Campaign_ContactPerson; import de.metas.marketing.base.model.I_MKTG_ContactPerson; import de.metas.util.Services; import lombok.NonNull; /* * #%L * de.metas.marketing * %% * Copyright (C) 2018 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @Component @Interceptor(I_MKTG_ContactPerson.class) public class MKTG_ContactPerson { private final UserService userService; private final ContactPersonRepository contactPersonRepo; private MKTG_ContactPerson(@NonNull final UserService userService, @NonNull final ContactPersonRepository contactPersonRepo) { this.userService = userService; this.contactPersonRepo = contactPersonRepo; } /** * When MKTG_ContactPerson.AD_User_ID changes, then update MKTG_Campaign_ContactPerson.AD_User_ID accordingly */ @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_MKTG_ContactPerson.COLUMNNAME_AD_User_ID) public void updateCampaignContactPersonAdUserId(@NonNull final I_MKTG_ContactPerson contactPerson) { final IQueryBL queryBL = Services.get(IQueryBL.class); // note AD_User_ID=0 needs special treatment final Integer newAdUserID = contactPerson.getAD_User_ID() <= 0 ? null : contactPerson.getAD_User_ID(); final IQueryUpdater<I_MKTG_Campaign_ContactPerson> updater = queryBL .createCompositeQueryUpdater(I_MKTG_Campaign_ContactPerson.class) .addSetColumnValue(I_MKTG_Campaign_ContactPerson.COLUMNNAME_AD_User_ID, newAdUserID); createContactPersonQuery(contactPerson) .update(updater); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteCampaignContactPersonAdUserId(@NonNull final I_MKTG_ContactPerson contactPerson) { createContactPersonQuery(contactPerson) .delete(); } private IQuery<I_MKTG_Campaign_ContactPerson> createContactPersonQuery(@NonNull final I_MKTG_ContactPerson contactPerson) { final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_MKTG_Campaign_ContactPerson.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_MKTG_Campaign_ContactPerson.COLUMN_MKTG_ContactPerson_ID, contactPerson.getMKTG_ContactPerson_ID()) .create(); } @ModelChange( // timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, // ifColumnsChanged = { I_MKTG_ContactPerson.COLUMNNAME_EMail, I_MKTG_ContactPerson.COLUMNNAME_AD_Language }) public void updateUserFromContactPerson(final I_MKTG_ContactPerson contactPersonRecord) { final I_MKTG_ContactPerson oldContactPerson = InterfaceWrapperHelper.createOld(contactPersonRecord, I_MKTG_ContactPerson.class); final String oldContactPersonMail = oldContactPerson.getEMail(); final Language oldContactPersonLanguage = Language.asLanguage(oldContactPerson.getAD_Language()); final ContactPerson contactPerson = contactPersonRepo.asContactPerson(contactPersonRecord); userService.updateUserFromContactPersonIfFeasible( contactPerson, oldContactPersonMail, oldContactPersonLanguage); } }
1,433
3,507
package com.xiaojinzi.component.cache; import android.app.ActivityManager; import android.content.Context; import android.support.annotation.NonNull; import com.xiaojinzi.component.support.Utils; /** * 构建 {@link Cache} 时,使用 {@link CacheType} 中声明的类型,来区分不同的模块 * 从而为不同的模块构建不同的缓存策略 */ public interface CacheType { int CLASS_CACHE_TYPE_ID = 0; /** * 缓存 {@link Class} 的容器 */ CacheType CLASS_CACHE = new CacheType() { private static final int MAX_SIZE = 25; @Override public int getCacheTypeId() { return CLASS_CACHE_TYPE_ID; } @Override public int calculateCacheSize(Context context) { Utils.checkNullPointer(context, "context"); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); int targetMemoryCacheSize; if (Utils.isLowMemoryDevice(activityManager)) { targetMemoryCacheSize = activityManager.getMemoryClass() / 6; } else { targetMemoryCacheSize = activityManager.getMemoryClass() / 4; } if (targetMemoryCacheSize > MAX_SIZE) { return MAX_SIZE; } return targetMemoryCacheSize; } }; /** * 返回框架内需要缓存的模块对应的 {@code id} */ int getCacheTypeId(); /** * 计算对应模块需要的缓存大小 */ int calculateCacheSize(@NonNull Context context); }
777
1,451
<reponame>emanruoy/template.js { "name": "template_js", "description": "A javascript template engine, simple, easy & extras, support webpack and fis", "version": "0.8.0", "author": { "name": "yanhaijing", "email": "<EMAIL>", "url": "http://yanhaijing.com" }, "repository": { "type": "git", "url": "git://github.com/yanhaijing/template.js.git" }, "bugs": { "url": "https://github.com/yanhaijing/template.js/issues" }, "licenses": [ { "type": "MIT", "url": "https://github.com/yanhaijing/template.js/blob/master/MIT-LICENSE.txt" } ], "engines": { "node": ">= 0.8.0" }, "scripts": { "test": "mocha test" }, "devDependencies": { "expect.js": "~0.3.1", "mocha": "^3.5.3" }, "keywords": [ "template", "template.js", "js" ], "main": "template.js" }
397
397
<reponame>r4b3rt/wLogger from abc import abstractmethod,ABCMeta import datetime,time class Adapter(): __metaclass__ = ABCMeta save_engine = [] split_save = ['day', 'week', 'month' ,'year'] def __init__(self): pass def _getTableName(self,table_key_name): table_suffix = '' save_engine_conf = self.conf[self.conf['outputer']['save_engine']] try: self.table = save_engine_conf[table_key_name] except KeyError as e: raise Exception('配置错误: %s not exists' % e.args) if 'split_save' in save_engine_conf: if save_engine_conf['split_save'] not in self.split_save: raise Exception('outputer 配置项 split_save 只支持 %s 选项' % ','.join(self.split_save)) if save_engine_conf['split_save'] == 'day': table_suffix = time.strftime( '%Y_%m_%d' , time.localtime()) elif save_engine_conf['split_save'] == 'week': now = datetime.datetime.now() this_week_start = now - datetime.timedelta(days=now.weekday()) this_week_end = now + datetime.timedelta(days=6 - now.weekday()) table_suffix = datetime.datetime.strftime(this_week_start,'%Y_%m_%d') + datetime.datetime.strftime(this_week_end,'_%d') elif save_engine_conf['split_save'] == 'month': table_suffix = time.strftime( '%Y_%m' , time.localtime()) elif save_engine_conf['split_save'] == 'year': table_suffix = time.strftime( '%Y' , time.localtime()) if len(table_suffix) : self.table = self.table +'_' + table_suffix @abstractmethod def initStorage(self): pass @abstractmethod def analysisTraffic(self):pass @abstractmethod def pushDataToStorage(self ): pass @abstractmethod def _handle_queue_data_before_into_storage(self):pass @abstractmethod def _handle_queue_data_after_into_storage(self):pass
922
1,109
<filename>src/main/java/org/cboard/pojo/DashboardUser.java<gh_stars>1000+ package org.cboard.pojo; /** * Created by yfyuan on 2016/12/2. */ public class DashboardUser { private String userId; private String loginName; private String userName; private String userPassword; private String userStatus; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = <PASSWORD>; } public String getUserStatus() { return userStatus; } public void setUserStatus(String userStatus) { this.userStatus = userStatus; } }
436
392
package io.logz.apollo.common; import okhttp3.Response; import org.rapidoid.http.MediaType; import org.rapidoid.http.Req; import java.nio.ByteBuffer; /** * Created by roiravhon on 3/21/17. */ public class ControllerCommon { public static void assignJsonResponseToReq(Req req, int code, Object json) { req.response().code(code); req.response().contentType(MediaType.APPLICATION_JSON); req.response().json(json); } public static void assignJsonBytesToReq(Req req, int code, byte[] bytes) { req.response().code(code); req.response().contentType(MediaType.APPLICATION_JSON); req.response().body(bytes); } }
261
443
import h5py import os # Note : Weights obtained from https://github.com/flyyufelix/DenseNet-Keras f = h5py.File('densenet161_weights_tf.h5') conv_weights = [] bn_weights = [] dense_classifier_weights = None for name in f.attrs['layer_names']: if 'data' in str(name): continue if 'zeropadding' in str(name): continue if 'relu' in str(name): continue if 'prob' in str(name): continue if 'pool' in str(name): continue if 'concat' in str(name): continue if 'fc' in str(name): v = f[name] v = [v[attr][:] for attr in v.attrs['weight_names']] dense_classifier_weights = v break if 'bn' in str(name): v = f[name] v_w = [v[attr][:] for attr in v.attrs['weight_names']] bn_weights.append(v_w) continue if 'scale' in str(name): v = f[name] v_w = [v[attr][:] for attr in v.attrs['weight_names']] bn_weights[-1][0] = v_w[0] bn_weights[-1][1] = v_w[1] continue v = f[name] v_w = v[v.attrs['weight_names'][0]][:] conv_weights.append(v_w) count_layers = 1 # for dense matrix count_layers += len(conv_weights) count_layers += len(bn_weights) print('Copying %d weights. (%d layers)' % (count_layers, count_layers // 2)) import densenet model = densenet.DenseNetImageNet161((224, 224, 3), weights=None) conv_layer_ids = [] bn_layer_ids = [] for i, layer in enumerate(model.layers): if layer.__class__.__name__ == 'Input': continue if layer.__class__.__name__ == 'Activation': continue if layer.__class__.__name__ == 'MaxPooling2D': continue if layer.__class__.__name__ == 'AveragePooling2D': continue if layer.__class__.__name__ == 'Concatenate': continue if layer.__class__.__name__ == 'GlobalAveragePooling2D': continue if layer.__class__.__name__ == 'Conv2D': conv_layer_ids.append(i) continue if layer.__class__.__name__ == 'BatchNormalization': bn_layer_ids.append(i) continue count = 0 for i, weights in enumerate(conv_weights): conv_idx = conv_layer_ids[i] model.layers[conv_idx].set_weights([weights]) count += 1 for i, weights in enumerate(bn_weights): bn_idx = bn_layer_ids[i] model.layers[bn_idx].set_weights(weights) count += 1 model.layers[-1].set_weights(dense_classifier_weights) count += 1 print("Sanity check : %d weights loaded" % count) model.save_weights('DenseNet-BC-161-48.h5', overwrite=True) print("Finished saving weights") import shutil shutil.copy('DenseNet-BC-161-48.h5', 'DenseNet-BC-161-48-no-top.h5') f = h5py.File('DenseNet-BC-161-48-no-top.h5') layers = f.attrs['layer_names'] f.attrs['layer_names'] = layers[:-2] for layer in layers[-2:]: del f[layer] f.close() print("Finished saving no-top weights")
1,305
399
package org.chromium.net.impl; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import io.envoyproxy.envoymobile.engine.EnvoyHTTPStream; /** * CancelProofEnvoyStream is a consistency layer above the {@link EnvoyHTTPStream} preventing * unwarranted Stream operations after a "cancel" operation. There are no "synchronized" - this is * Compare And Swap based logic. This class is Thread Safe. * * <p>This contraption ensures that once a "cancel" operation is invoked, there will be no further * operations allowed with the EnvoyHTTPStream - subsequent operations will be ignored silently. * However, in the event that that one or more EnvoyHTTPStream operations are currently being * executed, the "cancel" operation gets postponed: the last concurrent operation will invoke * "cancel" at the end. * * <p>Instances of this class start with a state of "Busy Starting". This ensure that if a cancel * is invoked while the stream is being created, that cancel will be executed only once the stream * is completely initialized. Doing otherwise leads to unpredictable outcomes. */ final class CancelProofEnvoyStream { private static final int CANCEL_BIT = 0x8000; /** * Mainly maintains a counter of how many Stream operations are currently in-flight. However when * bit 15 (0x8000) is set, it indicates that the cancel operation has been requested. If the * counter is greater than 0, then that "cancel" operation is postponed until the last in-flight * operation finishes, i.e. then the counter is back to 0. Then that last operation also invokes * "cancel". On the other hand, if the counter is already 0 when invoking "cancel", then it means * that there are no in-flight operations: the "cancel" operation is immediately executed. Once * the state is "canceled", any new stream operation is silently ignored. */ private final AtomicInteger mConcurrentInvocationCount = new AtomicInteger(); private volatile EnvoyHTTPStream mStream; // Cancel can come from any Thread. /** * The "mConcurrentInvocationCount" does not start with "zero" - this is on purpose. At this * stage, the Stream is considered to be in its initialization/starting phase. That phase ends * when mStream is set: {@link #setStream}. This way, if "cancel" gets called before the * {@link #setStream} method, then the intent is recorded, and the effect will be delivered * when {@link #setStream} will be invoked. */ CancelProofEnvoyStream() { mConcurrentInvocationCount.set(1); } /** Sets the stream. Can only be invoked once. */ void setStream(EnvoyHTTPStream stream) { // "if (returnTrueIfCanceledOrIncreaseConcurrentlyRunningStreamOperations()) { ..." // is not called here - see the Constructor's comment. assert mStream == null; mStream = stream; if (decreaseConcurrentlyRunningStreamOperationsAndReturnTrueIfAwaitingCancel()) { mStream.cancel(); // Cancel was called meanwhile, so now this is honored. } } /** Initiates the sending of the request headers if the state permits. */ void sendHeaders(Map<String, List<String>> envoyRequestHeaders, boolean endStream) { if (returnTrueIfCanceledOrIncreaseConcurrentlyRunningStreamOperations()) { return; // Already Cancelled - to late to send something. } mStream.sendHeaders(envoyRequestHeaders, endStream); if (decreaseConcurrentlyRunningStreamOperationsAndReturnTrueIfAwaitingCancel()) { mStream.cancel(); // Cancel was called previously, so now this is honored. } } /** Initiates the sending of one chunk of the request body if the state permits. */ void sendData(ByteBuffer buffer, boolean finalChunk) { if (returnTrueIfCanceledOrIncreaseConcurrentlyRunningStreamOperations()) { return; // Already Cancelled - to late to send something. } // The Envoy Mobile library only cares about the capacity - must use the correct ByteBuffer if (buffer.position() == 0) { mStream.sendData(buffer, buffer.remaining(), finalChunk); } else { // TODO(https://github.com/envoyproxy/envoy-mobile/issues/2247): avoid ByteBuffer copies ByteBuffer resizedBuffer = ByteBuffer.allocateDirect(buffer.remaining()); buffer.mark(); resizedBuffer.put(buffer); buffer.reset(); mStream.sendData(resizedBuffer, finalChunk); } if (decreaseConcurrentlyRunningStreamOperationsAndReturnTrueIfAwaitingCancel()) { mStream.cancel(); // Cancel was called previously, so now this is honored. } } /** Initiates the reading of one chunk of the the request body if the state permits. */ void readData(int size) { if (returnTrueIfCanceledOrIncreaseConcurrentlyRunningStreamOperations()) { return; // Already Cancelled - to late to read something. } mStream.readData(size); if (decreaseConcurrentlyRunningStreamOperationsAndReturnTrueIfAwaitingCancel()) { mStream.cancel(); // Cancel was called previously, so now this is honored. } } /** * Cancels the Stream if the state permits. Will be delayed when an operation is concurrently * running. Idempotent and Thread Safe. */ void cancel() { // With "Compare And Swap", the contract is the mutation succeeds only if the original value // matches the expected one - this is atomic at the assembly language level: most CPUs have // dedicated mnemonics for this operation - extremely efficient. And this might look like an // infinite loop. There is always one Thread that will succeed - the others may/will loop, and // so forth. "Compare And Swap" maybe bad under heavy contention - in that case it is probably // better to go with "synchronized" blocks. In our case, there is none or very little // contention. What matters is correctness and efficiency. while (true) { int count = mConcurrentInvocationCount.get(); if ((count & CANCEL_BIT) != 0) { return; // Cancel already invoked. } if (mConcurrentInvocationCount.compareAndSet(count, count | CANCEL_BIT)) { if (count == 0) { mStream.cancel(); // Was not busy with other EM operations - cancel right now. } return; } } } private boolean returnTrueIfCanceledOrIncreaseConcurrentlyRunningStreamOperations() { while (true) { int count = mConcurrentInvocationCount.get(); if ((count & CANCEL_BIT) != 0) { return true; // Already canceled } if (mConcurrentInvocationCount.compareAndSet(count, count + 1)) { return false; } } } private boolean decreaseConcurrentlyRunningStreamOperationsAndReturnTrueIfAwaitingCancel() { // Only true if the count is back to zero and the cancel bit is set. return mConcurrentInvocationCount.decrementAndGet() == CANCEL_BIT; } }
2,059
890
// Copyright (C) <2019> Intel Corporation // // SPDX-License-Identifier: Apache-2.0 #ifndef BUILDING_NODE_EXTENSION #define BUILDING_NODE_EXTENSION #endif #include "MediaDefinitions.h" #include "SipCallConnection.h" #include "SipGateway.h" using namespace v8; Persistent<Function> SipCallConnection::constructor; SipCallConnection::SipCallConnection() {} SipCallConnection::~SipCallConnection() {} void SipCallConnection::Init(Local<Object> exports) { // Prepare constructor template Isolate* isolate = Isolate::GetCurrent(); Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(Nan::New("SipCallConnection").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "close", close); NODE_SET_PROTOTYPE_METHOD(tpl, "setAudioReceiver", setAudioReceiver); NODE_SET_PROTOTYPE_METHOD(tpl, "setVideoReceiver", setVideoReceiver); constructor.Reset(isolate, Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(exports, Nan::New("SipCallConnection").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } void SipCallConnection::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); SipCallConnection* obj = new SipCallConnection(); SipGateway* gateway = node::ObjectWrap::Unwrap<SipGateway>( Nan::To<v8::Object>(args[0]).ToLocalChecked()); Nan::Utf8String str0(Nan::To<v8::String>(args[0]).ToLocalChecked()); std::string calleeURI = std::string(*str0); obj->me = new sip_gateway::SipCallConnection(gateway->me, calleeURI); obj->msink = obj->me; obj->msource = obj->me; obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } void SipCallConnection::close(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); SipCallConnection* obj = Nan::ObjectWrap::Unwrap<SipCallConnection>(args.Holder()); sip_gateway::SipCallConnection* me = obj->me; delete me; me = NULL; } void SipCallConnection::setAudioReceiver(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); SipCallConnection* obj = Nan::ObjectWrap::Unwrap<SipCallConnection>(args.Holder()); sip_gateway::SipCallConnection* me = obj->me; MediaSink* param = Nan::ObjectWrap::Unwrap<MediaSink>( Nan::To<v8::Object>(args[0]).ToLocalChecked()); erizo::MediaSink* mr = param->msink; me->setAudioSink(mr); } void SipCallConnection::setVideoReceiver(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); SipCallConnection* obj = Nan::ObjectWrap::Unwrap<SipCallConnection>(args.Holder()); sip_gateway::SipCallConnection* me = obj->me; MediaSink* param = Nan::ObjectWrap::Unwrap<MediaSink>( Nan::To<v8::Object>(args[0]).ToLocalChecked()); erizo::MediaSink* mr = param->msink; me->setVideoSink(mr); }
1,049
522
package algs.example.gui.problems.tictactoe.variations.slide; /** * The slide state must store the current phase. * * @author <NAME> * @version 1.0, 6/15/08 * @since 1.0 */ public class SlideState { /** Knows the current phase. */ private int phase; /** * Knows the current turnNumber. * <p> * Incremented after each turn */ private int turnNumber; public SlideState() { turnNumber = 1; phase = SlideLogic.PLACE_PHASE; } public void setPhase (int p) { this.phase = p; } public int getPhase() { return phase; } public void advanceTurn () { turnNumber++; if (turnNumber == 9) { phase = SlideLogic.SLIDE_PHASE; } } public void reverseTurn() { turnNumber--; if (turnNumber < 9) { phase = SlideLogic.PLACE_PHASE; } } }
418
1,442
<gh_stars>1000+ #include "editor_controller.h" #include "menu_controller.h" #include "script_parameter_controller.h" #include "app.h" #include <escher/metric.h> #include <ion.h> using namespace Shared; using namespace Escher; namespace Code { EditorController::EditorController(MenuController * menuController, App * pythonDelegate) : ViewController(nullptr), m_editorView(this, pythonDelegate), m_script(Ion::Storage::Record()), m_scriptIndex(-1), m_menuController(menuController) { m_editorView.setTextAreaDelegates(this, this); } void EditorController::setScript(Script script, int scriptIndex) { m_script = script; m_scriptIndex = scriptIndex; /* We edit the script directly in the storage buffer. We thus put all the * storage available space at the end of the current edited script and we set * its size. * * |****|****|m_script|****|**********|¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨| * available space * is transformed to: * * |****|****|m_script|¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨|****|**********| * available space * * */ Ion::Storage::sharedStorage()->putAvailableSpaceAtEndOfRecord(m_script); m_editorView.setText(const_cast<char *>(m_script.content()), m_script.contentSize()); } void EditorController::willExitApp() { cleanStorageEmptySpace(); } // TODO: this should be done in textAreaDidFinishEditing maybe?? bool EditorController::handleEvent(Ion::Events::Event event) { if (event == Ion::Events::OK || event == Ion::Events::Back || event == Ion::Events::Home || event == Ion::Events::USBEnumeration) { /* Exit the edition on USB enumeration, because the storage needs to be in a * "clean" state (with all records packed at the beginning of the storage) */ cleanStorageEmptySpace(); stackController()->pop(); return event != Ion::Events::Home && event != Ion::Events::USBEnumeration; } return false; } void EditorController::didBecomeFirstResponder() { Container::activeApp()->setFirstResponder(&m_editorView); } void EditorController::viewWillAppear() { ViewController::viewWillAppear(); m_editorView.loadSyntaxHighlighter(); m_editorView.setCursorLocation(m_editorView.text() + strlen(m_editorView.text())); } void EditorController::viewDidDisappear() { m_editorView.resetSelection(); m_menuController->scriptContentEditionDidFinish(); } bool EditorController::textAreaDidReceiveEvent(TextArea * textArea, Ion::Events::Event event) { if (App::app()->textInputDidReceiveEvent(textArea, event)) { return true; } if (event == Ion::Events::EXE) { textArea->handleEventWithText("\n", true, false); return true; } if (event == Ion::Events::Backspace && textArea->selectionIsEmpty()) { /* If the cursor is on the left of the text of a line, backspace one * indentation space at a time. */ const char * text = textArea->text(); const char * cursorLocation = textArea->cursorLocation(); const char * firstNonSpace = UTF8Helper::NotCodePointSearch(text, ' ', true, cursorLocation); assert(firstNonSpace >= text); bool cursorIsPrecededOnTheLineBySpacesOnly = false; size_t numberOfSpaces = cursorLocation - firstNonSpace; if (UTF8Helper::CodePointIs(firstNonSpace, '\n')) { cursorIsPrecededOnTheLineBySpacesOnly = true; numberOfSpaces -= UTF8Decoder::CharSizeOfCodePoint('\n'); } else if (firstNonSpace == text) { cursorIsPrecededOnTheLineBySpacesOnly = true; } numberOfSpaces = numberOfSpaces / UTF8Decoder::CharSizeOfCodePoint(' '); if (cursorIsPrecededOnTheLineBySpacesOnly && numberOfSpaces >= TextArea::k_indentationSpaces) { for (int i = 0; i < TextArea::k_indentationSpaces; i++) { textArea->removePreviousGlyph(); } return true; } } else if (event == Ion::Events::Space) { /* If the cursor is on the left of the text of a line, a space triggers an * indentation. */ const char * text = textArea->text(); const char * firstNonSpace = UTF8Helper::NotCodePointSearch(text, ' ', true, textArea->cursorLocation()); assert(firstNonSpace >= text); if (UTF8Helper::CodePointIs(firstNonSpace, '\n')) { assert(UTF8Decoder::CharSizeOfCodePoint(' ') == 1); char indentationBuffer[TextArea::k_indentationSpaces+1]; for (int i = 0; i < TextArea::k_indentationSpaces; i++) { indentationBuffer[i] = ' '; } indentationBuffer[TextArea::k_indentationSpaces] = 0; textArea->handleEventWithText(indentationBuffer); return true; } } return false; } VariableBoxController * EditorController::variableBoxForInputEventHandler(InputEventHandler * textInput) { VariableBoxController * varBox = App::app()->variableBoxController(); // Subtitle display status must be set before as it alter loaded node order varBox->setDisplaySubtitles(true); varBox->setTitle(I18n::Message::Autocomplete); /* If the editor should be autocompleting an identifier, the variable box has * already been loaded. We check shouldAutocomplete and not isAutocompleting, * because the autocompletion result might be empty. */ const char * beginningOfAutocompletion = nullptr; const char * cursor = nullptr; PythonTextArea::AutocompletionType autocompType = m_editorView.autocompletionType(&beginningOfAutocompletion, &cursor); if (autocompType == PythonTextArea::AutocompletionType::NoIdentifier) { varBox->loadFunctionsAndVariables(m_scriptIndex, nullptr, 0); } else if (autocompType == PythonTextArea::AutocompletionType::MiddleOfIdentifier) { varBox->empty(); } else { assert(autocompType == PythonTextArea::AutocompletionType::EndOfIdentifier); assert(beginningOfAutocompletion != nullptr && cursor != nullptr); assert(cursor > beginningOfAutocompletion); varBox->loadFunctionsAndVariables(m_scriptIndex, beginningOfAutocompletion, cursor - beginningOfAutocompletion); } return varBox; } StackViewController * EditorController::stackController() { return static_cast<StackViewController *>(parentResponder()); } void EditorController::cleanStorageEmptySpace() { if (m_script.isNull() || !Ion::Storage::sharedStorage()->hasRecord(m_script)) { return; } Ion::Storage::sharedStorage()->getAvailableSpaceFromEndOfRecord(m_script, m_script.usedSize()); } }
2,165
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.csl.api; import java.util.Collections; import java.util.List; import java.util.Set; import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.annotations.common.NonNull; /** * The CompletionResult object returns a list of proposals along with some * information about the result. You should subclass this class * yourself (or use the default implementation, * {@link org.netbeans.modules.gsf.spi.DefaultCompletionResult} * and return an instance of it from the {@link CodeCompletionHandler#complete} method. * object is provided by the language implementation * * @author <NAME> */ public abstract class CodeCompletionResult { /** * Special code completion result which means that there are no proposals */ public static final CodeCompletionResult NONE = new CodeCompletionResult() { @Override public List<CompletionProposal> getItems() { return Collections.emptyList(); } @Override public boolean isTruncated() { return false; } @Override public boolean isFilterable() { return false; } }; /** * Return the list of completion proposals that should be presented to * the user. * * @return A list of items to show the user */ @NonNull public abstract List<CompletionProposal> getItems(); /** * This method is called when the user has chosen to insert a code completion item. * The method is called BEFORE the actual item is inserted into the document. * * @param item The proposal that is about to be inserted into the document. */ public void beforeInsert(@NonNull CompletionProposal item) { } /** * <p>Insert the given item into the document. (The document and other context * was passed in as part of the {@link CodeCompletionContext} passed to the completion * handler.) * </p> * <p><b>NOTE</b>: Most implementation should just return false from this * method. False means that you have not handled the insertion, and the framework * will do it for you. Return true if you want to have custom handling here. * In that case, the infrastructure will not do anything else. * </p> * * @param item The item to be inserted into the document. * @return true if you want to handle the insertion yourself, or false to get the * infrastructure to do it on your behalf. */ public boolean insert(@NonNull CompletionProposal item) { return false; } /** * This method is called when the user has chosen to insert a code completion item. * The method is called AFTER the actual item is inserted into the document. * * @param item The proposal that has been inserted into the document. */ public void afterInsert(@NonNull CompletionProposal item) { } /** * Return true if you have truncated the items that are returned. For example, * it is probably pointless to return a list of 5,000 methods to the user. * This just means a slow response time, so implementations may choose to abort * when the set is probably too large to be used without further filtering. * In this case, you should return "true" from this method, which will cause * the infrastructure to (a) insert an item at the bottom of the list stating * that the list has been truncated, and (b) it will NOT do its normal optimization * or simply filtering the first result set as the user types additional characters; * it will repeat the full search whenever the list has been truncated. * @return true if and only if the {@link #getItems()} method returned a truncated * result. */ public abstract boolean isTruncated(); /** * Return true iff the code completion result can be "filtered" (narrowed down) * by the infrastructure without repeating the search. In other words, * if the prefix was "f", and your search returned {"foo", "fuu"}, then * if your result is filterable (by default true), and the user types "u" * then the infrastructure will not repeat the search it will just filter * your original result down from {"foo", "fuu"} to just {"fuu"}. * * @return true iff the result can be filtered (by default, true). */ public abstract boolean isFilterable(); }
1,604
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datafactory.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.datafactory.fluent.models.MongoDbLinkedServiceTypeProperties; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import java.util.List; import java.util.Map; /** Linked service for MongoDb data source. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeName("MongoDb") @Fluent public final class MongoDbLinkedService extends LinkedService { @JsonIgnore private final ClientLogger logger = new ClientLogger(MongoDbLinkedService.class); /* * MongoDB linked service properties. */ @JsonProperty(value = "typeProperties", required = true) private MongoDbLinkedServiceTypeProperties innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); /** * Get the innerTypeProperties property: MongoDB linked service properties. * * @return the innerTypeProperties value. */ private MongoDbLinkedServiceTypeProperties innerTypeProperties() { return this.innerTypeProperties; } /** {@inheritDoc} */ @Override public MongoDbLinkedService withConnectVia(IntegrationRuntimeReference connectVia) { super.withConnectVia(connectVia); return this; } /** {@inheritDoc} */ @Override public MongoDbLinkedService withDescription(String description) { super.withDescription(description); return this; } /** {@inheritDoc} */ @Override public MongoDbLinkedService withParameters(Map<String, ParameterSpecification> parameters) { super.withParameters(parameters); return this; } /** {@inheritDoc} */ @Override public MongoDbLinkedService withAnnotations(List<Object> annotations) { super.withAnnotations(annotations); return this; } /** * Get the server property: The IP address or server name of the MongoDB server. Type: string (or Expression with * resultType string). * * @return the server value. */ public Object server() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().server(); } /** * Set the server property: The IP address or server name of the MongoDB server. Type: string (or Expression with * resultType string). * * @param server the server value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withServer(Object server) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withServer(server); return this; } /** * Get the authenticationType property: The authentication type to be used to connect to the MongoDB database. * * @return the authenticationType value. */ public MongoDbAuthenticationType authenticationType() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().authenticationType(); } /** * Set the authenticationType property: The authentication type to be used to connect to the MongoDB database. * * @param authenticationType the authenticationType value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withAuthenticationType(MongoDbAuthenticationType authenticationType) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withAuthenticationType(authenticationType); return this; } /** * Get the databaseName property: The name of the MongoDB database that you want to access. Type: string (or * Expression with resultType string). * * @return the databaseName value. */ public Object databaseName() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().databaseName(); } /** * Set the databaseName property: The name of the MongoDB database that you want to access. Type: string (or * Expression with resultType string). * * @param databaseName the databaseName value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withDatabaseName(Object databaseName) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withDatabaseName(databaseName); return this; } /** * Get the username property: Username for authentication. Type: string (or Expression with resultType string). * * @return the username value. */ public Object username() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().username(); } /** * Set the username property: Username for authentication. Type: string (or Expression with resultType string). * * @param username the username value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withUsername(Object username) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withUsername(username); return this; } /** * Get the password property: Password for authentication. * * @return the password value. */ public SecretBase password() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().password(); } /** * Set the password property: Password for authentication. * * @param password the password value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withPassword(SecretBase password) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withPassword(password); return this; } /** * Get the authSource property: Database to verify the username and password. Type: string (or Expression with * resultType string). * * @return the authSource value. */ public Object authSource() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().authSource(); } /** * Set the authSource property: Database to verify the username and password. Type: string (or Expression with * resultType string). * * @param authSource the authSource value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withAuthSource(Object authSource) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withAuthSource(authSource); return this; } /** * Get the port property: The TCP port number that the MongoDB server uses to listen for client connections. The * default value is 27017. Type: integer (or Expression with resultType integer), minimum: 0. * * @return the port value. */ public Object port() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().port(); } /** * Set the port property: The TCP port number that the MongoDB server uses to listen for client connections. The * default value is 27017. Type: integer (or Expression with resultType integer), minimum: 0. * * @param port the port value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withPort(Object port) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withPort(port); return this; } /** * Get the enableSsl property: Specifies whether the connections to the server are encrypted using SSL. The default * value is false. Type: boolean (or Expression with resultType boolean). * * @return the enableSsl value. */ public Object enableSsl() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().enableSsl(); } /** * Set the enableSsl property: Specifies whether the connections to the server are encrypted using SSL. The default * value is false. Type: boolean (or Expression with resultType boolean). * * @param enableSsl the enableSsl value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withEnableSsl(Object enableSsl) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withEnableSsl(enableSsl); return this; } /** * Get the allowSelfSignedServerCert property: Specifies whether to allow self-signed certificates from the server. * The default value is false. Type: boolean (or Expression with resultType boolean). * * @return the allowSelfSignedServerCert value. */ public Object allowSelfSignedServerCert() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().allowSelfSignedServerCert(); } /** * Set the allowSelfSignedServerCert property: Specifies whether to allow self-signed certificates from the server. * The default value is false. Type: boolean (or Expression with resultType boolean). * * @param allowSelfSignedServerCert the allowSelfSignedServerCert value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withAllowSelfSignedServerCert(Object allowSelfSignedServerCert) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withAllowSelfSignedServerCert(allowSelfSignedServerCert); return this; } /** * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted * using the integration runtime credential manager. Type: string (or Expression with resultType string). * * @return the encryptedCredential value. */ public Object encryptedCredential() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().encryptedCredential(); } /** * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted * using the integration runtime credential manager. Type: string (or Expression with resultType string). * * @param encryptedCredential the encryptedCredential value to set. * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withEncryptedCredential(Object encryptedCredential) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new MongoDbLinkedServiceTypeProperties(); } this.innerTypeProperties().withEncryptedCredential(encryptedCredential); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (innerTypeProperties() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property innerTypeProperties in model MongoDbLinkedService")); } else { innerTypeProperties().validate(); } } }
4,273
4,224
<filename>src/drivers/uavcan/uavcan_drivers/kinetis/driver/include/uavcan_kinetis/build_config.hpp /* * Copyright (C) 2015, 2018 <NAME> <<EMAIL>> * Kinetis Port Author <NAME> <<EMAIL>> */ #pragma once /** * OS detection */ #ifndef UAVCAN_KINETIS_NUTTX # error "Only NuttX is supported" #endif /** * Number of interfaces must be enabled explicitly */ #if !defined(UAVCAN_KINETIS_NUM_IFACES) || (UAVCAN_KINETIS_NUM_IFACES != 1 && UAVCAN_KINETIS_NUM_IFACES != 2) # error "UAVCAN_KINETIS_NUM_IFACES must be set to either 1 or 2" #endif /** * Any PIT timer channel (PIT0-PIT3) * e.g. -DUAVCAN_KINETIS_TIMER_NUMBER=2 */ #ifndef UAVCAN_KINETIS_TIMER_NUMBER // In this case the clock driver should be implemented by the application # define UAVCAN_KINETIS_TIMER_NUMBER 0 #endif
323
451
from config.redfish1_0_config import config from config.auth import * from config.settings import * from logger import Log from json import loads, dumps import pexpect import pxssh import subprocess LOG = Log(__name__) class Auth(object): """ Class to abstract python authentication functionality """ @staticmethod def get_auth_token(): """ call /SessionService/Sessions to get auth_token """ resource_path = '/redfish/v1/SessionService/Sessions' method = 'POST' body_params = { 'UserName': 'admin', 'Password': '<PASSWORD>' } config.api_client.host = config.host_authed config.api_client.call_api(resource_path, method, body=body_params) return config.api_client.last_response.getheader('X-Auth-Token') @staticmethod def enable(): """ update config to enable auth """ if config.auth_enabled: LOG.info('auth already enabled.') config.api_client.default_headers['X-Auth-Token'] = Auth.get_auth_token() config.api_client.host = config.host_authed + config.api_root config.auth_enabled = True LOG.info('Enable auth successfully.') @staticmethod def disable(): """ update config to disable auth """ if not config.auth_enabled: LOG.info('auth already disabled.') del config.api_client.default_headers['X-Auth-Token'] config.api_client.host = config.host + config.api_root config.auth_enabled = False LOG.info('Disable auth successfully.')
617
6,465
<filename>dropwizard-jdbi3/src/test/java/io/dropwizard/jdbi3/JdbiHealthCheckTest.java package io.dropwizard.jdbi3; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.sql.Connection; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import com.codahale.metrics.health.HealthCheck; import io.dropwizard.util.Duration; class JdbiHealthCheckTest { private static final String VALIDATION_QUERY = "select 1"; private Jdbi jdbi; private Handle handle; private Connection connection; private ExecutorService executorService; @BeforeEach void setup() { jdbi = mock(Jdbi.class); handle = mock(Handle.class); connection = mock(Connection.class); when(jdbi.open()).thenReturn(handle); when(handle.getConnection()).thenReturn(connection); executorService = Executors.newSingleThreadExecutor(); } @AfterEach void teardown() { executorService.shutdown(); } @Test void testNoTimeoutReturnsHealthy() throws Exception { when(handle.execute(VALIDATION_QUERY)).thenReturn(0); HealthCheck.Result result = healthCheck(VALIDATION_QUERY).check(); assertThat(result.isHealthy()).isTrue(); } @Test void tesHealthyAfterWhenMissingValidationQuery() throws Exception { when(connection.isValid(anyInt())).thenReturn(true); HealthCheck.Result result = healthCheck().check(); assertThat(result.isHealthy()).isTrue(); verify(connection).isValid(anyInt()); } @Test void testItTimesOutProperly() throws Exception { when(handle.execute(VALIDATION_QUERY)).thenAnswer((Answer<Integer>) invocation -> { TimeUnit.SECONDS.sleep(10); return null; }); HealthCheck.Result result = healthCheck(VALIDATION_QUERY).check(); assertThat(result.isHealthy()).isFalse(); } @Test void testUnhealthyWhenMissingValidationQuery() throws Exception { HealthCheck.Result result = healthCheck().check(); assertThat(result.isHealthy()).isFalse(); verify(connection).isValid(anyInt()); } private JdbiHealthCheck healthCheck() { return healthCheck(null); } private JdbiHealthCheck healthCheck(@Nullable String validationQuery) { return new JdbiHealthCheck(executorService, Duration.milliseconds(100), jdbi, Optional.ofNullable(validationQuery)); } }
1,155
307
// // FCExtensionPipe.h // Part of FCUtilities by <NAME>. See included LICENSE file for BSD license. // // A basic way for members of a shared iOS App Group container to pass messages to each other. // // Any given pipe identifier should be one-way within a process, and each pipe should only have one writer, e.g.: // // - the master app can write to a pipe named e.g. "fromApp" but should not read from it, while extensions can read it // - an extension could write to a pipe named e.g. "fromWatchKit" that the master app reads from but doesn't write // #import <Foundation/Foundation.h> @interface FCExtensionPipe : NSObject // Receive messages by retaining one of these. remotePipeIdentifier must be filename-safe. - (instancetype)initWithAppGroupIdentifier:(NSString *)appGroupID remotePipeIdentifier:(NSString *)remotePipeID target:(__weak id)target action:(SEL)actionTakingNSDictionary; // Send messages statically. pipeIdentifier must be filename-safe. + (BOOL)sendMessageToAppGroupIdentifier:(NSString *)appGroupIdentifier pipeIdentifier:(NSString *)pipeIdentifier userInfo:(NSDictionary *)userInfo; @property (nonatomic, weak) id target; @property (nonatomic) SEL action; @property (nonatomic, readonly) NSDictionary *lastMessage; // For optional conveniences only. Retention not guaranteed. @end
371
3,428
<reponame>ghalimi/stdlib {"id":"00136","group":"easy-ham-1","checksum":{"type":"MD5","value":"c507301e643ec123aa6e487ce2e2e3e2"},"text":"From <EMAIL> Tue Oct 8 10:55:22 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby spamassassin.taint.org (Postfix) with ESMTP id 4B66916F16\n\tfor <zzzz@localhost>; Tue, 8 Oct 2002 10:55:17 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Tue, 08 Oct 2002 10:55:17 +0100 (IST)\nReceived: from egwn.net (auth02.nl.egwn.net [192.168.3.11]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g987avK05522 for\n <<EMAIL>>; Tue, 8 Oct 2002 08:36:57 +0100\nReceived: from auth02.nl.egwn.net (localhost [127.0.0.1]) by egwn.net\n (8.11.6/8.11.6/EGWN) with ESMTP id g987U2f06824; Tue, 8 Oct 2002 09:30:02\n +0200\nReceived: from snickers.hotpop.com (snickers.hotpop.com [204.57.55.49]) by\n egwn.net (8.11.6/8.11.6/EGWN) with ESMTP id g987TMf04275 for\n <<EMAIL>>; Tue, 8 Oct 2002 09:29:22 +0200\nReceived: from punkass.com (kubrick.hotpop.com [204.57.55.16]) by\n snickers.hotpop.com (Postfix) with SMTP id B5FC0707E2 for\n <<EMAIL>>; Tue, 8 Oct 2002 07:29:10 +0000 (UTC)\nReceived: from punkass.com (unknown [80.178.1.203]) by smtp-2.hotpop.com\n (Postfix) with ESMTP id 4BADD1B8497 for <<EMAIL>>;\n Tue, 8 Oct 2002 07:28:31 +0000 (UTC)\nMessage-Id: <<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.1) Gecko/20020830\nX-Accept-Language: en-us, en, he\nMIME-Version: 1.0\nTo: [email protected]\nSubject: xine src packge still gives errors\nReferences: <1033908698.1724.11.camel@l<EMAIL>pelle>\nContent-Type: text/plain; charset=us-ascii; format=flowed\nContent-Transfer-Encoding: 7bit\nX-Hotpop: ----------------------------------------------- Sent By\n HotPOP.com FREE Email Get your FREE POP email at www.HotPOP.com\n -----------------------------------------------\nX-Mailscanner: Found to be clean, Found to be clean\nSender: <EMAIL>.net\nErrors-To: [email protected]\nX-Beenthere: [email protected]\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nReply-To: <EMAIL>\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Freshrpms RPM discussion list <rpm-zzzlist.freshrpms.net>\nList-Unsubscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://lists.freshrpms.net/pipermail/rpm-zzzlist/>\nX-Original-Date: Tue, 08 Oct 2002 09:30:10 +0200\nDate: Tue, 08 Oct 2002 09:30:10 +0200\n\nHi\n\nI try to rebuild xine from src package and I get these errors:\n\n.\n.\n.\n.\n.\nFinding Provides: /usr/lib/rpm/find-provides\nFinding Requires: /usr/lib/rpm/find-requires\nPreReq: rpmlib(PayloadFilesHavePrefix) <= 4.0-1 \nrpmlib(CompressedFileNames) <= 3.0.4-1\nRequires(rpmlib): rpmlib(PayloadFilesHavePrefix) <= 4.0-1 \nrpmlib(CompressedFileNames) <= 3.0.4-1\nRequires: xine-libs = 0.9.13 /bin/sh\nObsoletes: xine-devel\n\n\nRPM build errors:\n user dude does not exist - using root\n user dude does not exist - using root\n user dude does not exist - using root\n user dude does not exist - using root\n user dude does not exist - using root\n File not found: /var/tmp/xine-root/usr/bin/aaxine\n\n\nthx,\nRoi\n\n\n\n\n_______________________________________________\nRPM-List mailing list <<EMAIL>>\nhttp://lists.freshrpms.net/mailman/listinfo/rpm-list\n\n\n"}
1,571
852
import FWCore.ParameterSet.Config as cms ##____________________________________________________________________________|| muonTCMETValueMapProducer = cms.EDProducer( "MuonTCMETValueMapProducer", muonInputTag = cms.InputTag("muons"), beamSpotInputTag = cms.InputTag("offlineBeamSpot"), vertexInputTag = cms.InputTag("offlinePrimaryVertices"), rf_type = cms.int32(1), trackAlgos = cms.vstring("undefAlgorithm", "ctf", "rs", "cosmics", "initialStep", "lowPtTripletStep", "pixelPairStep", "detachedTripletStep"), d0_max = cms.double(0.3), pt_min = cms.double(1.), pt_max = cms.double(100.), eta_max = cms.double(2.65), chi2_max = cms.double(5), nhits_min = cms.double(6), ptErr_max = cms.double(0.2), track_quality = cms.vint32(2), track_algos = cms.vstring(), chi2_max_tight = cms.double(5.), nhits_min_tight = cms.double(9), ptErr_max_tight = cms.double(0.2), usePvtxd0 = cms.bool(False), d0cuta = cms.double(0.015), d0cutb = cms.double(0.5), d0_muon = cms.double(0.2), muon_dptrel = cms.double(1), pt_muon = cms.double(10), eta_muon = cms.double(2.5), chi2_muon = cms.double(10), nhits_muon = cms.double(11), global_muon = cms.bool(True), tracker_muon = cms.bool(True), deltaR_muon = cms.double(0.05), useCaloMuons = cms.bool(False), muonMinValidStaHits = cms.int32(1), nLayers = cms.int32(0), nLayersTight = cms.int32(0), vertexNdof = cms.int32(4), vertexZ = cms.double(15.), vertexRho = cms.double(2.), vertexMaxDZ = cms.double(0.2), maxpt_eta25 = cms.double(0.), maxpt_eta20 = cms.double(100.), ) ##____________________________________________________________________________||
1,058
995
<reponame>yusufcakmakk/zemberek-nlp<filename>apps/src/main/java/zemberek/apps/corpus/PreprocessTurkishCorpus.java package zemberek.apps.corpus; import com.beust.jcommander.Parameter; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import zemberek.apps.ConsoleApp; import zemberek.core.concurrency.BlockingExecutor; import zemberek.core.concurrency.ConcurrencyUtil; import zemberek.core.logging.Log; import zemberek.core.text.BlockTextLoader; import zemberek.core.text.TextChunk; import zemberek.core.text.TextIO; import zemberek.core.text.TextUtil; import zemberek.core.turkish.Turkish; import zemberek.morphology.TurkishMorphology; import zemberek.morphology.analysis.SentenceAnalysis; import zemberek.morphology.analysis.SentenceWordAnalysis; import zemberek.morphology.analysis.SingleAnalysis; import zemberek.tokenization.TurkishSentenceExtractor; import zemberek.tokenization.TurkishTokenizer; public class PreprocessTurkishCorpus extends ConsoleApp { @Parameter(names = {"--input", "-i"}, required = true, description = "Input corpus file or directory. " + "If this is a directory, all files in it will be processed. Files must be in UTF-8 Format.") private Path input; @Parameter(names = {"--output", "-o"}, required = true, description = "Output corpus file. One sentence per line and tokenized.") private Path output; @Parameter(names = {"--extension", "-e"}, description = "If used, only file(s) that ends with `[extension]` will be processed.") private String extension; @Parameter(names = {"--toLowercase", "-lc"}, description = "If used, applies Turkish lower casing to resulting sentences.") private boolean toLowercase = false; @Parameter(names = {"--recurse", "-r"}, description = "If used and input is a directory, sub directories in input is also processed.") private boolean recurse = false; @Parameter(names = {"--dirList", "-dl"}, description = "If provided, only input directory names listed in this file will be processed.") private Path dirList; @Parameter(names = {"--operation", "-op"}, description = "Applies operation to words. If LEMMA is selected, words are replaced with " + "longest lemmas. By default sentence segmentation and tokenization is applied.") private Operation operation = Operation.NONE; @Parameter(names = {"--threadCount", "-tc"}, description = "Thread Count.") int threadCount = ConcurrencyUtil.getHalfCpuCount(); @Override public String description() { return "Applies Turkish Sentence boundary detection and tokenization to a corpus file or a " + "directory of corpus files. " + "Lines start with `<` character are ignored. It applies white space normalization and " + " removes soft hyphens. Sentences that contain `combining diacritic` symbols are " + "ignored."; } enum Operation { NONE, LEMMA } private TurkishMorphology morphology; @Override public void run() throws IOException, InterruptedException { List<Path> paths = new ArrayList<>(); if (input.toFile().isFile()) { paths.add(input); } else { Set<String> dirNamesToProcess = new HashSet<>(); if (dirList != null) { List<String> dirNames = TextIO.loadLines(dirList); Log.info("Directory names to process:"); for (String dirName : dirNames) { Log.info(dirName); } dirNamesToProcess.addAll(dirNames); } List<Path> directories = Files.walk(input, recurse ? Integer.MAX_VALUE : 1) .filter(s -> s.toFile().isDirectory() && !s.equals(input)) .collect(Collectors.toList()); for (Path directory : directories) { if (dirList != null && !dirNamesToProcess.contains(directory.toFile().getName())) { continue; } paths.addAll(Files.walk(directory, 1) .filter(s -> s.toFile().isFile() && (extension == null || s.endsWith(extension))) .collect(Collectors.toList())); } } Log.info("There are %d files to process.", paths.size()); long totalLines = 0; for (Path path : paths) { totalLines += TextIO.lineCount(path); } final long total = totalLines; if (paths.size() == 0) { Log.info("No corpus files found for input : %s", input); System.exit(0); } AtomicLong sentenceCount = new AtomicLong(0); if (operation == Operation.LEMMA) { morphology = TurkishMorphology.createWithDefaults(); } try (PrintWriter pw = new PrintWriter(output.toFile(), "UTF-8")) { BlockTextLoader loader = BlockTextLoader.fromPaths(paths, 10_000); BlockingExecutor executor = new BlockingExecutor(threadCount); AtomicInteger count = new AtomicInteger(0); for (TextChunk chunk : loader) { executor.submit(() -> { List<String> processed = chunk.getData().stream() .filter(s -> !s.startsWith("<")) // ignore meta tag lines. .map(TextUtil::normalizeSpacesAndSoftHyphens) .collect(Collectors.toList()); List<String> sentences = TurkishSentenceExtractor.DEFAULT.fromParagraphs(processed); sentences = sentences.stream() .filter(s -> !TextUtil.containsCombiningDiacritics(s)) .map(s -> { if (operation == Operation.LEMMA) { return replaceWordsWithLemma(s); } else { return String.join(" ", TurkishTokenizer.DEFAULT.tokenizeToStrings(s)); } }) .map(s -> toLowercase ? s.toLowerCase(Turkish.LOCALE) : s) .collect(Collectors.toList()); synchronized (this) { sentences.forEach(pw::println); sentenceCount.addAndGet(sentences.size()); int c = count.addAndGet(chunk.size()); System.out.println(String.format("(%d of %d lines) processed.", c, total)); } }); } executor.shutdown(); executor.awaitTermination(1, TimeUnit.DAYS); } Log.info("%d sentences are written in %s", sentenceCount.get(), output); } private String replaceWordsWithLemma(String sentence) { SentenceAnalysis analysis = morphology.analyzeAndDisambiguate(sentence); List<String> res = new ArrayList<>(); for (SentenceWordAnalysis e : analysis) { SingleAnalysis best = e.getBestAnalysis(); if (best.isUnknown()) { res.add(e.getWordAnalysis().getInput()); continue; } List<String> lemmas = best.getLemmas(); res.add(lemmas.get(0)); } return String.join(" ", res); } public static void main(String[] args) { new PreprocessTurkishCorpus().execute(args); } }
2,678
1,091
<reponame>tohotforice/onos-sdwsn /* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.net.resource; import com.google.common.annotations.Beta; /** * Factory class for discrete-type resource related instances. */ @Beta public final class DiscreteFactory { private final DiscreteResourceId id; private final DiscreteResource resource; /** * Create an instance with the specified resource ID. * * @param id resource ID that is associated with the resource related instances * which will be created from this instance */ DiscreteFactory(DiscreteResourceId id) { this.id = id; this.resource = new DiscreteResource(id); } /** * Returns the resource ID for discrete-type. * * @return discrete-type resource ID */ public DiscreteResourceId id() { return id; } /** * Returns the resource for discrete-type. * * @return discrete-type resource */ public DiscreteResource resource() { return resource; } }
523
1,127
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <debug.h> #include "shared_test_classes/subgraph/reshape_squeeze_reshape_relu.hpp" namespace SubgraphTestsDefinitions { std::string ReshapeSqueezeReshapeRelu::getTestCaseName(const testing::TestParamInfo<ReshapeSqueezeReshapeReluTuple> &obj) { ShapeAxesTuple squeezeShape; InferenceEngine::Precision netPrecision; std::string targetName; ngraph::helpers::SqueezeOpType opType; std::tie(squeezeShape, netPrecision, targetName, opType) = obj.param; std::ostringstream results; results << "OpType=" << opType; results << "IS=" << CommonTestUtils::vec2str(squeezeShape.first) << "_"; results << "indices=" << CommonTestUtils::vec2str(squeezeShape.second) << "_"; results << "netPRC=" << netPrecision.name() << "_"; results << "targetDevice=" << targetName << "_"; return results.str(); } void ReshapeSqueezeReshapeRelu::SetUp() { ShapeAxesTuple squeezeShape; InferenceEngine::Precision netPrecision; ngraph::helpers::SqueezeOpType opType; std::tie(squeezeShape, netPrecision, targetDevice, opType) = this->GetParam(); const std::size_t input_dim = InferenceEngine::details::product(squeezeShape.first); auto ngPrc = FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision); std::vector<size_t> shape_input{1, input_dim}; auto input = ngraph::builder::makeParams(ngPrc, {shape_input}); auto reshape1_pattern = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{squeezeShape.first.size()}, squeezeShape.first); auto reshape1 = std::make_shared<ngraph::op::v1::Reshape>(input[0], reshape1_pattern, false); auto squeeze = ngraph::builder::makeSqueezeUnsqueeze(reshape1, ngraph::element::i64, squeezeShape.second, opType); auto reshape2_pattern = std::make_shared<ngraph::op::Constant>(ngraph::element::i64, ngraph::Shape{2}, std::vector<size_t>{1, input_dim}); auto reshape2 = std::make_shared<ngraph::op::v1::Reshape>(squeeze, reshape2_pattern, false); auto func = std::make_shared<ngraph::opset1::Relu>(reshape2); std::string squeezeType; function = std::make_shared<ngraph::Function>(func, input, "reshape_squeeze_reshape_relu"); } } // namespace SubgraphTestsDefinitions
1,257
9,701
<gh_stars>1000+ # How many labels are at max put into the output # ranking, everything else will be cut off LABEL_RANKING_LENGTH = 10
42
3,102
// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s // Examples from CWG1056. namespace Example1 { template<class T> struct A; template<class T> using B = A<T>; template<class T> struct A { struct C {}; B<T>::C bc; // ok, B<T> is the current instantiation. }; template<class T> struct A<A<T>> { struct C {}; B<B<T>>::C bc; // ok, B<B<T>> is the current instantiation. }; template<class T> struct A<A<A<T>>> { struct C {}; B<B<T>>::C bc; // expected-error {{missing 'typename'}} }; } namespace Example2 { template<class T> struct A { void g(); }; template<class T> using B = A<T>; template<class T> void B<T>::g() {} // ok. }
289
367
{ "name": "grpc", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "install": " (cd books && npm install) & (cd orders && npm install) & (cd 'reverse_proxy' && npm install)", "clean": " (cd books && npm run clean) & (cd orders && npm run clean) & (cd 'reverse_proxy' && npm run clean)", "dev": " (cd books && npm start) & (cd orders && npm start) & (cd 'reverse_proxy' && npm start)" }, "author": "", "license": "ISC" }
193
645
// Copyright 2013-2016 Stanford University // // 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 "src/symstate/bitvector.h" #include "src/symstate/typecheck_visitor.h" namespace stoke { TEST(SymBitvectorTest, CanPrintConstantsAtWidth) { auto a = SymBitVector::constant(3, 5); std::stringstream ss; ss << a; EXPECT_EQ("0x5\xE2\x82\x83", ss.str()); } TEST(SymBitvectorTest, CanPrintConstantsOverWidth) { auto a = SymBitVector::constant(4, 5); std::stringstream ss; ss << a; EXPECT_EQ("0x5\xE2\x82\x84", ss.str()); } TEST(SymBitvectorTest, CanPrintExpressions) { auto x = SymBitVector::var(3, "x"); auto y = SymBitVector::var(3, "y"); auto z = ((x+y) & (( x << 3) ^ !y))[2][1]; std::stringstream ss; ss << z; EXPECT_EQ("(x + y & (x << 0x3\xE2\x82\x83 \xE2\x8A\x95 !y))[2:1]", ss.str()); } TEST(SymBitVectorTest, TypecheckWorks) { auto x = SymBitVector::var(32, "x"); auto y = SymBitVector::var(32, "y"); auto z = ((x+y) & (( x << 3) ^ !y))[10][5]; SymTypecheckVisitor tc; EXPECT_EQ(6, tc(z)); } TEST(SymBitVectorTest, TypecheckDetectsBad) { auto x = SymBitVector::var(32, "x"); auto y = SymBitVector::var(32, "y"); auto z = ((x || y) == y); SymTypecheckVisitor tc; EXPECT_EQ(0, tc(z)); } TEST(SymBitVectorTest, ConstantsTypecheck) { SymTypecheckVisitor tc; auto x = SymBitVector::constant(0, 8); EXPECT_EQ(0, tc(x)); auto y = SymBitVector::constant(3, 7); EXPECT_EQ(3, tc(y)); } TEST(SymBitVectorTest, ExtractTypechecks) { auto x = SymBitVector::constant(32, 8); SymTypecheckVisitor tc; EXPECT_EQ(0, tc(x[33][0])); EXPECT_EQ(0, tc(x[0][7])); EXPECT_EQ(8, tc(x[7][0])); } TEST(SymBitVectorTest, UninterpretedFunctionTypechecks) { auto x = SymBitVector::var(32, "x"); auto y = SymBitVector::var(32, "y"); auto f = SymFunction("f", 32, {32, 32}); auto eq = f(x,y) == f(x,y); auto constraints = std::vector<SymBool>(); constraints.push_back(eq); SymTypecheckVisitor tc; EXPECT_EQ(32, tc(f(x,y))); EXPECT_EQ(1, tc(eq)); } TEST(SymBitVectorTest, UninterpretedFunctionWrongArg) { auto x = SymBitVector::var(32, "x"); auto y = SymBitVector::var(40, "y"); auto f = SymFunction("f", 32, {32, 32}); auto eq = f(x,y) == f(x,y); auto constraints = std::vector<SymBool>(); constraints.push_back(eq); SymTypecheckVisitor tc; EXPECT_EQ(0, tc(f(x,y))); EXPECT_EQ(0, tc(eq)); } TEST(SymBitVectorTest, UninterpretedFunctionWrongArgNum) { auto x = SymBitVector::var(32, "x"); auto y = SymBitVector::var(32, "y"); auto f = SymFunction("f", 32, {32, 32}); SymTypecheckVisitor tc; EXPECT_EQ(0, tc(f(x,y, x))); } TEST(SymBitVectorTest, UninterpretedFunctionTypesDisagree) { auto x = SymBitVector::var(32, "x"); auto y = SymBitVector::var(32, "y"); auto f = SymFunction("f", 32, {32, 32}); auto g = SymFunction("f", 32, {32, 32, 32}); SymTypecheckVisitor tc; EXPECT_EQ(0, tc(f(x,y) == g(x,x,y))); } } //namespace stoke
1,395
732
// // AVIMConversation+Custon.h // DSLolita // // Created by <NAME> on 15/6/5. // Copyright (c) 2015年 samDing. All rights reserved. // #import "DSIMConfig.h" #define CONV_TYPE @"type" #define CONV_ATTR_TYPE_KEY @"attr.type" #define CONV_MEMBERS_KEY @"m" typedef enum : NSUInteger { DSConvTypeSingle = 0, DSConvTypeGroup, } DSConvType; @interface AVIMConversation(Custom) -(DSConvType)type; -(NSString*)otherId; -(NSString*)displayName; +(NSString*)nameOfUserIds:(NSArray*)userIds; -(NSString*)title; -(UIImage*)icon; @end
235
453
// Copyright (c) the JPEG XL 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 LIB_JXL_BASE_THREAD_POOL_INTERNAL_H_ #define LIB_JXL_BASE_THREAD_POOL_INTERNAL_H_ #include <stddef.h> #include <cmath> #include "jxl/parallel_runner.h" #include "lib/jxl/base/data_parallel.h" #include "lib/threads/thread_parallel_runner_internal.h" namespace jxl { // Helper class to pass an internal ThreadPool-like object using threads. This // is only suitable for tests or tools that access the internal API of JPEG XL. // In other cases the caller will provide a JxlParallelRunner() for handling // this. This class uses jpegxl::ThreadParallelRunner (from jpegxl_threads // library). For interface details check jpegxl::ThreadParallelRunner. class ThreadPoolInternal : public ThreadPool { public: // Starts the given number of worker threads and blocks until they are ready. // "num_worker_threads" defaults to one per hyperthread. If zero, all tasks // run on the main thread. explicit ThreadPoolInternal( int num_worker_threads = std::thread::hardware_concurrency()) : ThreadPool(&jpegxl::ThreadParallelRunner::Runner, static_cast<void*>(&runner_)), runner_(num_worker_threads) {} ThreadPoolInternal(const ThreadPoolInternal&) = delete; ThreadPoolInternal& operator&(const ThreadPoolInternal&) = delete; size_t NumThreads() const { return runner_.NumThreads(); } size_t NumWorkerThreads() const { return runner_.NumWorkerThreads(); } template <class Func> void RunOnEachThread(const Func& func) { runner_.RunOnEachThread(func); } private: jpegxl::ThreadParallelRunner runner_; }; } // namespace jxl #endif // LIB_JXL_BASE_THREAD_POOL_INTERNAL_H_
607
777
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_METRICS_PROFILER_TRACKING_SYNCHRONIZER_DELEGATE_H_ #define COMPONENTS_METRICS_PROFILER_TRACKING_SYNCHRONIZER_DELEGATE_H_ namespace metrics { class TrackingSynchronizer; // An abstraction of TrackingSynchronizer-related operations that depend on the // platform. class TrackingSynchronizerDelegate { public: virtual ~TrackingSynchronizerDelegate() {} // Should perform the platform-specific action that is needed to start // gathering profiler data for all relevant child processes. virtual void GetProfilerDataForChildProcesses( int sequence_number, int current_profiling_phase) = 0; // Called when |profiling_phase| has completed. virtual void OnProfilingPhaseCompleted(int profiling_phase) = 0; }; } // namespace metrics #endif // COMPONENTS_METRICS_PROFILER_TRACKING_SYNCHRONIZER_DELEGATE_H_
319
460
<reponame>cluesblues/google-oauth-java-client<gh_stars>100-1000 /* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.auth.oauth2; import com.google.api.client.http.BasicAuthentication; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.http.UrlEncodedContent; import com.google.api.client.testing.http.HttpTesting; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import java.util.Map; /** * Tests {@link Credential} and {@link BearerToken}. * * @author <NAME> */ public class CredentialTest extends AuthenticationTestBase { public void testConstructor_header() throws Exception { Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(ACCESS_TOKEN); HttpRequest request = subtestConstructor(credential); assertEquals("Bearer abc", request.getHeaders().getAuthorization()); } public void testConstructor_queryParam() throws Exception { Credential credential = new Credential(BearerToken.queryParameterAccessMethod()).setAccessToken(ACCESS_TOKEN); HttpRequest request = subtestConstructor(credential); assertEquals(ACCESS_TOKEN, request.getUrl().get("access_token")); } public void testConstructor_body() throws Exception { Credential credential = new Credential(BearerToken.formEncodedBodyAccessMethod()).setAccessToken(ACCESS_TOKEN); HttpRequest request = subtestConstructor(credential); assertEquals( ACCESS_TOKEN, ((Map<?, ?>) ((UrlEncodedContent) request.getContent()).getData()).get("access_token")); } private HttpRequest subtestConstructor(Credential credential) throws Exception { MockHttpTransport transport = new MockHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL); request.execute(); return request; } public void testConstructor_expiredHeader() throws Exception { HttpRequest request = subtestConstructor_expired( BearerToken.authorizationHeaderAccessMethod(), new CheckAuth() { public boolean checkAuth(MockLowLevelHttpRequest req) { return req.getFirstHeaderValue("Authorization").equals("Bearer def"); } }); assertEquals("Bearer def", request.getHeaders().getAuthorization()); } public void testConstructor_expiredQueryParam() throws Exception { HttpRequest request = subtestConstructor_expired( BearerToken.queryParameterAccessMethod(), new CheckAuth() { public boolean checkAuth(MockLowLevelHttpRequest req) { return req.getUrl().contains("access_token=def"); } }); assertEquals(NEW_ACCESS_TOKEN, request.getUrl().get("access_token")); } public void testConstructor_expiredBody() throws Exception { HttpRequest request = subtestConstructor_expired( BearerToken.formEncodedBodyAccessMethod(), new CheckAuth() { public boolean checkAuth(MockLowLevelHttpRequest req) { return NEW_ACCESS_TOKEN.equals( ((Map<?, ?>) ((UrlEncodedContent) req.getStreamingContent()).getData()) .get("access_token")); } }); assertEquals( NEW_ACCESS_TOKEN, ((Map<?, ?>) ((UrlEncodedContent) request.getContent()).getData()).get("access_token")); } interface CheckAuth { boolean checkAuth(MockLowLevelHttpRequest req); } private HttpRequest subtestConstructor_expired( Credential.AccessMethod method, final CheckAuth checkAuth) throws Exception { final Credential credential = new Credential.Builder(method) .setTransport(new AccessTokenTransport()) .setJsonFactory(JSON_FACTORY) .setTokenServerUrl(TOKEN_SERVER_URL) .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)) .build() .setAccessToken(ACCESS_TOKEN) .setRefreshToken(REFRESH_TOKEN); class MyTransport extends MockHttpTransport { boolean resetAccessToken; @Override public LowLevelHttpRequest buildRequest(String method, String url) { return new MockLowLevelHttpRequest(url) { @Override public LowLevelHttpResponse execute() { MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); if (!checkAuth.checkAuth(this)) { response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); if (resetAccessToken) { credential.setAccessToken(NEW_ACCESS_TOKEN); } } return response; } }; } } MyTransport transport = new MyTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL); request.execute(); credential.setAccessToken(ACCESS_TOKEN); transport.resetAccessToken = true; request.execute(); return request; } public void testRefreshToken_noRefreshToken() throws Exception { Credential access = new Credential(BearerToken.queryParameterAccessMethod()).setAccessToken(ACCESS_TOKEN); assertFalse(access.refreshToken()); } public void testRefreshToken_noRefreshToken2() throws Exception { AccessTokenTransport transport = new AccessTokenTransport(); Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()) .setTransport(transport) .setJsonFactory(JSON_FACTORY) .setTokenServerUrl(TOKEN_SERVER_URL) .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)) .build() .setAccessToken(ACCESS_TOKEN); assertFalse(access.refreshToken()); assertEquals(ACCESS_TOKEN, access.getAccessToken()); assertNull(access.getRefreshToken()); assertNull(access.getExpirationTimeMilliseconds()); } public void testRefreshToken_refreshToken() throws Exception { AccessTokenTransport transport = new AccessTokenTransport(); Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()) .setTransport(transport) .setJsonFactory(JSON_FACTORY) .setTokenServerUrl(TOKEN_SERVER_URL) .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)) .build() .setRefreshToken(REFRESH_TOKEN) .setAccessToken(ACCESS_TOKEN); assertTrue(access.refreshToken()); assertEquals(NEW_ACCESS_TOKEN, access.getAccessToken()); assertEquals(NEW_REFRESH_TOKEN, access.getRefreshToken()); assertNotNull(access.getExpirationTimeMilliseconds()); } public void testRefreshToken_request_401() throws Exception { AccessTokenTransport transport = new AccessTokenTransport(); transport.statusCode = 401; // 3 requests = 1 invalid token, 1 refresh token, and 1 retry subtestRefreshToken_request(transport, 3); } public void testRefreshToken_request_www_authenticate() throws Exception { AccessTokenTransport transport = new AccessTokenTransport(); transport.statusCode = 444; transport.wwwAuthenticate = "Bearer realm=\"https://www.google.com/accounts/AuthSubRequest\" error=invalid_token"; // WWW-Authenticate contains invalid_token error, so we expect 3 requests = 1 invalid token, 1 // refresh token, and 1 retry subtestRefreshToken_request(transport, 3); transport = new AccessTokenTransport(); transport.statusCode = 401; transport.wwwAuthenticate = "Bearer error=invalid_token"; // WWW-Authenticate contains invalid_token error, so we expect 3 requests = 1 invalid token, 1 // refresh token, and 1 retry subtestRefreshToken_request(transport, 3); transport = new AccessTokenTransport(); transport.statusCode = 401; transport.wwwAuthenticate = "doesn't contain b-e-a-r-e-r"; // WWW-Authenticate doesn't contain "Bearer" but the status code is 401, so we expect 3 requests // = 1 invalid token, 1 refresh token, and 1 retry subtestRefreshToken_request(transport, 3); transport = new AccessTokenTransport(); transport.statusCode = 401; transport.wwwAuthenticate = "Bearer blah blah blah"; // WWW-Authenticate contains "Bearer" but no invalid_token error, and although the error code is // 401, we expect only 1 failed request subtestRefreshToken_request(transport, 1); transport = new AccessTokenTransport(); transport.statusCode = 444; transport.wwwAuthenticate = "Bearer blah blah blah"; // WWW-Authenticate contains "Bearer" but no invalid_token error, we expect only 1 failed // request subtestRefreshToken_request(transport, 1); transport = new AccessTokenTransport(); transport.statusCode = 444; transport.wwwAuthenticate = "doesn't contain b-e-a-r-e-r"; // WWW-Authenticate doesn't contain "Bearer" and no 401, we expect only 1 failed request subtestRefreshToken_request(transport, 1); } private void subtestRefreshToken_request(AccessTokenTransport transport, int expectedCalls) throws Exception { Credential credential = new Credential.Builder(BearerToken.queryParameterAccessMethod()) .setTransport(transport) .setJsonFactory(JSON_FACTORY) .setTokenServerUrl(TOKEN_SERVER_URL) .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)) .build() .setRefreshToken(REFRESH_TOKEN) .setAccessToken(ACCESS_TOKEN); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL); request.setThrowExceptionOnExecuteError(false); request.execute(); assertEquals(expectedCalls, transport.calls); } public void testRefreshToken_withoutRequiredParameters() { Credential access = new Credential(BearerToken.queryParameterAccessMethod()); try { access.setRefreshToken(REFRESH_TOKEN); fail("Expected an " + IllegalArgumentException.class); } catch (IllegalArgumentException e) { // Expected } } public void testRefreshToken_refreshTokenErrorWith400() throws Exception { AccessTokenTransport transport = new AccessTokenTransport(); transport.statusCode = 400; Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()) .setTransport(transport) .setJsonFactory(JSON_FACTORY) .setTokenServerUrl(TOKEN_SERVER_URL) .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)) .build() .setExpiresInSeconds(3600L) .setAccessToken(ACCESS_TOKEN) .setRefreshToken(REFRESH_TOKEN); try { access.refreshToken(); fail("Expected " + TokenResponseException.class); } catch (TokenResponseException e) { // Expected } assertNull(access.getAccessToken()); assertEquals("refreshToken", access.getRefreshToken()); assertNull(access.getExpirationTimeMilliseconds()); } public void testRefreshToken_refreshTokenErrorWith500() throws Exception { AccessTokenTransport transport = new AccessTokenTransport(); transport.statusCode = 500; Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()) .setTransport(transport) .setJsonFactory(JSON_FACTORY) .setTokenServerUrl(TOKEN_SERVER_URL) .setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)) .build() .setExpiresInSeconds(3600L) .setAccessToken(ACCESS_TOKEN) .setRefreshToken(REFRESH_TOKEN); assertFalse(access.refreshToken()); assertNotNull(access.getAccessToken()); assertEquals("refreshToken", access.getRefreshToken()); assertNotNull(access.getExpirationTimeMilliseconds()); } public void testInvalidTokenErrorMatcher() { String withQuote = "error = \"invalid_token\""; String withoutQuote = "error = invalid_token"; assertTrue(BearerToken.INVALID_TOKEN_ERROR.matcher(withQuote).find()); assertTrue(BearerToken.INVALID_TOKEN_ERROR.matcher(withoutQuote).find()); } }
4,918
2,112
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <atomic> #include <cassert> #include <memory> #include <utility> #include <glog/logging.h> #include <folly/experimental/channels/detail/AtomicQueue.h> #include <folly/lang/Assume.h> namespace apache { namespace thrift { namespace detail { namespace twowaybridge_detail { template <typename T> using Queue = folly::channels::detail::Queue<T>; template <typename T> class QueueWithTailPtr : public Queue<T> { public: QueueWithTailPtr() = default; template <typename F> QueueWithTailPtr(Queue<T>&& queue, F&& visitor) : Queue<T>(std::move(queue)) { for (auto* node = Queue<T>::head_; node; node = node->next) { visitor(node->value); tail_ = node; } } void append(QueueWithTailPtr&& other) { if (!other.head_) { return; } if (!Queue<T>::head_) { Queue<T>::head_ = std::exchange(other.head_, nullptr); } else { tail_->next = std::exchange(other.head_, nullptr); } tail_ = other.tail_; } private: // holds invalid pointer if head_ is null typename Queue<T>::Node* tail_; }; template <typename Consumer, typename Message> using AtomicQueue = folly::channels::detail::AtomicQueue<Consumer, Message>; // queue with no consumers template <typename Message, typename Value> class AtomicQueueOrPtr { public: using MessageQueue = Queue<Message>; AtomicQueueOrPtr() {} ~AtomicQueueOrPtr() { auto storage = storage_.load(std::memory_order_relaxed); auto type = static_cast<Type>(storage & kTypeMask); auto ptr = storage & kPointerMask; switch (type) { case Type::EMPTY: case Type::CLOSED: return; case Type::TAIL: MessageQueue::fromReversed( reinterpret_cast<typename MessageQueue::Node*>(ptr)); return; default: folly::assume_unreachable(); }; } AtomicQueueOrPtr(const AtomicQueueOrPtr&) = delete; AtomicQueueOrPtr& operator=(const AtomicQueueOrPtr&) = delete; // returns closed payload and does not move from message on failure Value* pushOrGetClosedPayload(Message&& message) { auto storage = storage_.load(std::memory_order_acquire); if (static_cast<Type>(storage & kTypeMask) == Type::CLOSED) { return closedPayload_; } std::unique_ptr<typename MessageQueue::Node> node( new typename MessageQueue::Node(std::move(message))); assert(!(reinterpret_cast<intptr_t>(node.get()) & kTypeMask)); while (true) { auto type = static_cast<Type>(storage & kTypeMask); auto ptr = storage & kPointerMask; switch (type) { case Type::EMPTY: case Type::TAIL: node->next = reinterpret_cast<typename MessageQueue::Node*>(ptr); if (storage_.compare_exchange_weak( storage, reinterpret_cast<intptr_t>(node.get()) | static_cast<intptr_t>(Type::TAIL), std::memory_order_release, std::memory_order_acquire)) { node.release(); return nullptr; } break; case Type::CLOSED: message = std::move(node->value); return closedPayload_; default: folly::assume_unreachable(); } } } MessageQueue closeOrGetMessages(Value* payload) { assert(payload); // nullptr is used as a sentinel // this is only read if the compare_exchange succeeds closedPayload_ = payload; while (true) { auto storage = storage_.exchange( static_cast<intptr_t>(Type::EMPTY), std::memory_order_acquire); auto type = static_cast<Type>(storage & kTypeMask); auto ptr = storage & kPointerMask; switch (type) { case Type::TAIL: return MessageQueue::fromReversed( reinterpret_cast<typename MessageQueue::Node*>(ptr)); case Type::EMPTY: if (storage_.compare_exchange_weak( storage, static_cast<intptr_t>(Type::CLOSED), std::memory_order_release, std::memory_order_relaxed)) { return MessageQueue(); } break; case Type::CLOSED: default: folly::assume_unreachable(); } } } bool isClosed() const { return static_cast<Type>(storage_ & kTypeMask) == Type::CLOSED; } private: enum class Type : intptr_t { EMPTY = 0, TAIL = 1, CLOSED = 2 }; static constexpr intptr_t kTypeMask = 3; static constexpr intptr_t kPointerMask = ~kTypeMask; // These can be combined if the platform requires Value to be 8-byte aligned. // Most platforms don't require that for functions. // A workaround is to make that function a member of an aligned struct // and pass in the address of the struct, but that is not necessarily a win // because of the runtime indirection cost. std::atomic<intptr_t> storage_{0}; Value* closedPayload_{nullptr}; }; } // namespace twowaybridge_detail template < typename ClientConsumer, typename ClientMessage, typename ServerConsumer, typename ServerMessage, typename Derived> class TwoWayBridge { using ClientAtomicQueue = twowaybridge_detail::AtomicQueue<ClientConsumer, ClientMessage>; using ServerAtomicQueue = twowaybridge_detail::AtomicQueue<ServerConsumer, ServerMessage>; public: using ClientQueue = twowaybridge_detail::Queue<ClientMessage>; using ServerQueue = twowaybridge_detail::Queue<ServerMessage>; using ClientQueueWithTailPtr = twowaybridge_detail::QueueWithTailPtr<ClientMessage>; struct Deleter { void operator()(Derived* ptr) { ptr->decref(); } }; using Ptr = std::unique_ptr<Derived, Deleter>; Ptr copy() { auto refCount = refCount_.fetch_add(1, std::memory_order_relaxed); DCHECK(refCount > 0); return Ptr(derived()); } protected: TwoWayBridge() = default; // These should only be called from the client thread void clientPush(ServerMessage&& value) { serverQueue_.push(std::move(value)); } bool clientWait(ClientConsumer* consumer) { return clientQueue_.wait(consumer); } ClientConsumer* cancelClientWait() { return clientQueue_.cancelCallback(); } ClientQueue clientGetMessages() { return clientQueue_.getMessages(); } void clientClose() { clientQueue_.close(); } bool isClientClosed() { return clientQueue_.isClosed(); } // These should only be called from the server thread void serverPush(ClientMessage&& value) { clientQueue_.push(std::move(value)); } bool serverWait(ServerConsumer* consumer) { return serverQueue_.wait(consumer); } ServerConsumer* cancelServerWait() { return serverQueue_.cancelCallback(); } ServerQueue serverGetMessages() { return serverQueue_.getMessages(); } void serverClose() { serverQueue_.close(); } bool isServerClosed() { return serverQueue_.isClosed(); } private: void decref() { if (refCount_.fetch_sub(1, std::memory_order_acq_rel) == 1) { delete derived(); } } Derived* derived() { return static_cast<Derived*>(this); } ClientAtomicQueue clientQueue_; ServerAtomicQueue serverQueue_; std::atomic<int8_t> refCount_{1}; }; } // namespace detail } // namespace thrift } // namespace apache
2,913
1,159
<reponame>dyuri/vizzu-lib<gh_stars>1000+ #ifndef TESTSTYLE_H #define TESTSTYLE_H #include <optional> struct Foo { std::optional<double> foo; std::optional<double> bar; void visit(auto &visitor) { visitor (foo, "foo") (bar, "bar"); } }; struct Baz { std::optional<double> baz; std::optional<double> fobar; void visit(auto &visitor) { visitor (baz, "baz") (fobar, "fobar"); } }; struct Fobar { Foo foo; Baz baz; void visit(auto &visitor) { visitor (foo, "foo") (baz, "baz"); } }; #endif
261
392
<gh_stars>100-1000 /* * Copyright 2010-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.android.facebookclient; import java.util.List; import org.springframework.social.facebook.api.Facebook; import org.springframework.social.facebook.api.Post; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; /** * @author <NAME> */ public class FacebookHomeFeedActivity extends AbstractAsyncListActivity { protected static final String TAG = FacebookHomeFeedActivity.class.getSimpleName(); private Facebook facebook; // *************************************** // Activity methods // *************************************** @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.facebook = getApplicationContext().getConnectionRepository().findPrimaryConnection(Facebook.class) .getApi(); } @Override public void onStart() { super.onStart(); new FetchWallFeedTask().execute(); } // *************************************** // Private methods // *************************************** private void showResult(List<Post> entries) { FacebookFeedListAdapter adapter = new FacebookFeedListAdapter(this, entries); setListAdapter(adapter); } // *************************************** // Private classes // *************************************** private class FetchWallFeedTask extends AsyncTask<Void, Void, List<Post>> { @Override protected void onPreExecute() { showProgressDialog("Fetching home feed..."); } @Override protected List<Post> doInBackground(Void... params) { try { return facebook.feedOperations().getHomeFeed(); } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage(), e); } return null; } @Override protected void onPostExecute(List<Post> entries) { dismissProgressDialog(); showResult(entries); } } }
701
480
/* * Copyright [2013-2021], Alibaba Group Holding 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.polardbx.optimizer.core.function.calc.scalar.math; import com.alibaba.polardbx.optimizer.context.ExecutionContext; import com.alibaba.polardbx.optimizer.core.datatype.DataType; import com.alibaba.polardbx.optimizer.core.datatype.DataTypeUtil; import com.alibaba.polardbx.optimizer.core.datatype.DataTypes; import com.alibaba.polardbx.optimizer.core.function.calc.AbstractScalarFunction; import com.alibaba.polardbx.optimizer.utils.FunctionUtils; import java.util.List; /** * Converts numbers between different number bases. Returns a string * representation of the number N, converted from base from_base to base * to_base. Returns NULL if any argument is NULL. The argument N is interpreted * as an integer, but may be specified as an integer or a string. The minimum * base is 2 and the maximum base is 36. If to_base is a negative number, N is * regarded as a signed number. Otherwise, N is treated as unsigned. CONV() * works with 64-bit precision. * * <pre> * mysql> SELECT CONV('a',16,2); * -> '1010' * mysql> SELECT CONV('6E',18,8); * -> '172' * mysql> SELECT CONV(-17,10,-18); * -> '-H' * mysql> SELECT CONV(10+'10'+'10'+0xa,10,10); * -> '40' * </pre> * * @author jianghang 2014-4-14 下午9:52:58 * @since 5.0.7 */ public class Conv extends AbstractScalarFunction { public Conv(List<DataType> operandTypes, DataType resultType) { super(operandTypes, resultType); } // The maximum possible number with the given (radix - 2). private static final char[] MAX_NUMBER = "123456789abcdefghijklmnopqrstuvwxyz".toCharArray(); @Override public Object compute(Object[] args, ExecutionContext ec) { for (Object arg : args) { if (FunctionUtils.isNull(arg)) { return null; } } String n = DataTypeUtil.convert(operandTypes.get(0), DataTypes.StringType, args[0]); Integer f = DataTypes.IntegerType.convertFrom(args[1]); Integer t = DataTypes.IntegerType.convertFrom(args[2]); int unsignedF = Math.abs(f); int unsignedT = Math.abs(t); // check the boundaries of from_base and to_base. if (unsignedF > Character.MAX_RADIX || unsignedF < Character.MIN_RADIX || unsignedT > Character.MAX_RADIX || unsignedT < Character.MIN_RADIX) { return null; } // Truncate the invalid char n = n.toLowerCase(); int truncatedIndex = -1; final char maxChar = MAX_NUMBER[unsignedF - 2]; for (int i = 0; i < n.length(); i++) { char ch = n.charAt(i); if (ch == '-' && i == 0) { continue; } if (ch > maxChar || ch < '0' || (ch > '9' && ch < 'a')) { truncatedIndex = i; break; } } if (truncatedIndex >= 0) { n = n.substring(0, truncatedIndex); if ("-".equals(n) || "".equals(n)) { return null; } } Object result; Long d = Long.parseLong(n, unsignedF); if (t < 0) { result = Long.toString(d, unsignedT).toUpperCase(); } else { result = Long.toUnsignedString(d, unsignedT).toUpperCase(); } return result; } @Override public String[] getFunctionNames() { return new String[] {"CONV"}; } }
1,657
652
<filename>PC/pythonnt_rc_d.h<gh_stars>100-1000 /* This file created by make_versioninfo.exe */ #define FIELD3 104884 #define MS_DLL_ID "3.3" #ifndef _DEBUG #define PYTHON_DLL_NAME "python33.dll" #else #define PYTHON_DLL_NAME "python33_d.dll" #endif
109
12,718
<reponame>aruniiird/zig<filename>lib/libc/musl/src/math/__invtrigl.h #include <features.h> /* shared by acosl, asinl and atan2l */ #define pio2_hi __pio2_hi #define pio2_lo __pio2_lo hidden extern const long double pio2_hi, pio2_lo; hidden long double __invtrigl_R(long double z);
122
464
package dev.fiki.forgehax.api.classloader; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import static dev.fiki.forgehax.api.FileHelper.asFilePath; /** * Created on 2/16/2018 by fr1kin */ public class CustomClassLoaders { public static ClassLoader newFsClassLoader(ClassLoader parent, FileSystem fs) throws RuntimeException { try { return new FsClassLoader(parent, fs); } catch (MalformedURLException e) { throw new RuntimeException(e); } } private static class FsClassLoader extends URLClassLoader { private final Path root; private FsClassLoader(ClassLoader parent, Path path) throws MalformedURLException { super(new URL[]{path.toUri().toURL()}, parent); this.root = path; } public FsClassLoader(ClassLoader parent, FileSystem fileSystem) throws MalformedURLException { this(parent, fileSystem.getRootDirectories().iterator().next()); } public Path getRoot() { return root; } public FileSystem getFileSystem() { return root.getFileSystem(); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { Path location = getRoot().resolve(asFilePath(name, "/").concat(".class")); if (Files.exists(location)) { byte[] classData = Files.readAllBytes(location); return defineClass(name, classData, 0, classData.length); } } catch (IOException e) { e.printStackTrace(); } return null; } } }
658
348
{"nom":"Saint-Saud-Lacoussière","circ":"3ème circonscription","dpt":"Dordogne","inscrits":678,"abs":247,"votants":431,"blancs":11,"nuls":1,"exp":419,"res":[{"nuance":"MDM","nom":"<NAME>","voix":131},{"nuance":"LR","nom":"Mme <NAME>","voix":103},{"nuance":"SOC","nom":"Mme <NAME>","voix":86},{"nuance":"FN","nom":"M. <NAME>","voix":34},{"nuance":"FI","nom":"M. <NAME>","voix":33},{"nuance":"COM","nom":"<NAME>","voix":21},{"nuance":"DLF","nom":"M. <NAME>","voix":8},{"nuance":"EXG","nom":"M. <NAME>","voix":3},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]}
227
1,663
{ "name": "nunuStudio", "description": "Javascript powered framework for 3D and VR applications that run directly on the browser without the need for additional plugins", "version": "0.9", "url": "https://www.nunustudio.org" }
72
354
#ifndef _SGLRCONTEXTWRAPPER_HPP #define _SGLRCONTEXTWRAPPER_HPP /*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES Utilities * ------------------------------------------------ * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Context wrapper that exposes sglr API as GL-compatible API. *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "tcuVector.hpp" namespace sglr { class Shader; class Context; class ContextWrapper { public: ContextWrapper (void); ~ContextWrapper (void); void setContext (Context* context); Context* getCurrentContext (void) const; int getWidth (void) const; int getHeight (void) const; // GL-compatible API. void glActiveTexture (deUint32 texture); void glAttachShader (deUint32 program, deUint32 shader); void glBindAttribLocation (deUint32 program, deUint32 index, const char* name); void glBindBuffer (deUint32 target, deUint32 buffer); void glBindFramebuffer (deUint32 target, deUint32 framebuffer); void glBindRenderbuffer (deUint32 target, deUint32 renderbuffer); void glBindTexture (deUint32 target, deUint32 texture); void glBlendColor (float red, float green, float blue, float alpha); void glBlendEquation (deUint32 mode); void glBlendEquationSeparate (deUint32 modeRGB, deUint32 modeAlpha); void glBlendFunc (deUint32 sfactor, deUint32 dfactor); void glBlendFuncSeparate (deUint32 srcRGB, deUint32 dstRGB, deUint32 srcAlpha, deUint32 dstAlpha); void glBufferData (deUint32 target, deIntptr size, const void* data, deUint32 usage); void glBufferSubData (deUint32 target, deIntptr offset, deIntptr size, const void* data); deUint32 glCheckFramebufferStatus (deUint32 target); void glClear (deUint32 mask); void glClearColor (float red, float green, float blue, float alpha); void glClearDepthf (float depth); void glClearStencil (int s); void glColorMask (deBool red, deBool green, deBool blue, deBool alpha); void glCompileShader (deUint32 shader); void glCompressedTexImage2D (deUint32 target, int level, deUint32 internalformat, int width, int height, int border, int imageSize, const void* data); void glCompressedTexSubImage2D (deUint32 target, int level, int xoffset, int yoffset, int width, int height, deUint32 format, int imageSize, const void* data); void glCopyTexImage1D (deUint32 target, int level, deUint32 internalformat, int x, int y, int width, int border); void glCopyTexImage2D (deUint32 target, int level, deUint32 internalformat, int x, int y, int width, int height, int border); void glCopyTexSubImage1D (deUint32 target, int level, int xoffset, int x, int y, int width); void glCopyTexSubImage2D (deUint32 target, int level, int xoffset, int yoffset, int x, int y, int width, int height); deUint32 glCreateProgram (); deUint32 glCreateShader (deUint32 type); void glCullFace (deUint32 mode); void glDeleteBuffers (int n, const deUint32* buffers); void glDeleteFramebuffers (int n, const deUint32* framebuffers); void glDeleteProgram (deUint32 program); void glDeleteRenderbuffers (int n, const deUint32* renderbuffers); void glDeleteShader (deUint32 shader); void glDeleteTextures (int n, const deUint32* textures); void glDepthFunc (deUint32 func); void glDepthMask (deBool flag); void glDepthRangef (float n, float f); void glDetachShader (deUint32 program, deUint32 shader); void glDisable (deUint32 cap); void glDisableVertexAttribArray (deUint32 index); void glDrawArrays (deUint32 mode, int first, int count); void glDrawElements (deUint32 mode, int count, deUint32 type, const void* indices); void glEnable (deUint32 cap); void glEnableVertexAttribArray (deUint32 index); void glFinish (); void glFlush (); void glFramebufferRenderbuffer (deUint32 target, deUint32 attachment, deUint32 renderbuffertarget, deUint32 renderbuffer); void glFramebufferTexture2D (deUint32 target, deUint32 attachment, deUint32 textarget, deUint32 texture, int level); void glFrontFace (deUint32 mode); void glGenBuffers (int n, deUint32* buffers); void glGenerateMipmap (deUint32 target); void glGenFramebuffers (int n, deUint32* framebuffers); void glGenRenderbuffers (int n, deUint32* renderbuffers); void glGenTextures (int n, deUint32* textures); void glGetActiveAttrib (deUint32 program, deUint32 index, int bufsize, int* length, int* size, deUint32* type, char* name); void glGetActiveUniform (deUint32 program, deUint32 index, int bufsize, int* length, int* size, deUint32* type, char* name); void glGetAttachedShaders (deUint32 program, int maxcount, int* count, deUint32* shaders); int glGetAttribLocation (deUint32 program, const char* name); void glGetBooleanv (deUint32 pname, deBool* params); void glGetBufferParameteriv (deUint32 target, deUint32 pname, int* params); deUint32 glGetError (); void glGetFloatv (deUint32 pname, float* params); void glGetFramebufferAttachmentParameteriv (deUint32 target, deUint32 attachment, deUint32 pname, int* params); void glGetIntegerv (deUint32 pname, int* params); void glGetProgramiv (deUint32 program, deUint32 pname, int* params); void glGetProgramInfoLog (deUint32 program, int bufsize, int* length, char* infolog); void glGetRenderbufferParameteriv (deUint32 target, deUint32 pname, int* params); void glGetShaderiv (deUint32 shader, deUint32 pname, int* params); void glGetShaderInfoLog (deUint32 shader, int bufsize, int* length, char* infolog); void glGetShaderPrecisionFormat (deUint32 shadertype, deUint32 precisiontype, int* range, int* precision); void glGetShaderSource (deUint32 shader, int bufsize, int* length, char* source); const deUint8* glGetString (deUint32 name); void glGetTexParameterfv (deUint32 target, deUint32 pname, float* params); void glGetTexParameteriv (deUint32 target, deUint32 pname, int* params); void glGetUniformfv (deUint32 program, int location, float* params); void glGetUniformiv (deUint32 program, int location, int* params); int glGetUniformLocation (deUint32 program, const char* name); void glGetVertexAttribfv (deUint32 index, deUint32 pname, float* params); void glGetVertexAttribiv (deUint32 index, deUint32 pname, int* params); void glGetVertexAttribPointerv (deUint32 index, deUint32 pname, void** pointer); void glHint (deUint32 target, deUint32 mode); deBool glIsBuffer (deUint32 buffer); deBool glIsEnabled (deUint32 cap); deBool glIsFramebuffer (deUint32 framebuffer); deBool glIsProgram (deUint32 program); deBool glIsRenderbuffer (deUint32 renderbuffer); deBool glIsShader (deUint32 shader); deBool glIsTexture (deUint32 texture); void glLineWidth (float width); void glLinkProgram (deUint32 program); void glPixelStorei (deUint32 pname, int param); void glPolygonOffset (float factor, float units); void glReadPixels (int x, int y, int width, int height, deUint32 format, deUint32 type, void* pixels); void glReleaseShaderCompiler (); void glRenderbufferStorage (deUint32 target, deUint32 internalformat, int width, int height); void glSampleCoverage (float value, deBool invert); void glScissor (int x, int y, int width, int height); void glShaderBinary (int n, const deUint32* shaders, deUint32 binaryformat, const void* binary, int length); void glShaderSource (deUint32 shader, int count, const char* const* string, const int* length); void glStencilFunc (deUint32 func, int ref, deUint32 mask); void glStencilFuncSeparate (deUint32 face, deUint32 func, int ref, deUint32 mask); void glStencilMask (deUint32 mask); void glStencilMaskSeparate (deUint32 face, deUint32 mask); void glStencilOp (deUint32 fail, deUint32 zfail, deUint32 zpass); void glStencilOpSeparate (deUint32 face, deUint32 fail, deUint32 zfail, deUint32 zpass); void glTexImage1D (deUint32 target, int level, int internalformat, int width, int border, deUint32 format, deUint32 type, const void* pixels); void glTexImage2D (deUint32 target, int level, int internalformat, int width, int height, int border, deUint32 format, deUint32 type, const void* pixels); void glTexParameterf (deUint32 target, deUint32 pname, float param); void glTexParameterfv (deUint32 target, deUint32 pname, const float* params); void glTexParameteri (deUint32 target, deUint32 pname, int param); void glTexParameteriv (deUint32 target, deUint32 pname, const int* params); void glTexSubImage1D (deUint32 target, int level, int xoffset, int width, deUint32 format, deUint32 type, const void* pixels); void glTexSubImage2D (deUint32 target, int level, int xoffset, int yoffset, int width, int height, deUint32 format, deUint32 type, const void* pixels); void glUniform1f (int location, float x); void glUniform1fv (int location, int count, const float* v); void glUniform1i (int location, int x); void glUniform1iv (int location, int count, const int* v); void glUniform2f (int location, float x, float y); void glUniform2fv (int location, int count, const float* v); void glUniform2i (int location, int x, int y); void glUniform2iv (int location, int count, const int* v); void glUniform3f (int location, float x, float y, float z); void glUniform3fv (int location, int count, const float* v); void glUniform3i (int location, int x, int y, int z); void glUniform3iv (int location, int count, const int* v); void glUniform4f (int location, float x, float y, float z, float w); void glUniform4fv (int location, int count, const float* v); void glUniform4i (int location, int x, int y, int z, int w); void glUniform4iv (int location, int count, const int* v); void glUniformMatrix2fv (int location, int count, deBool transpose, const float* value); void glUniformMatrix3fv (int location, int count, deBool transpose, const float* value); void glUniformMatrix4fv (int location, int count, deBool transpose, const float* value); void glUseProgram (deUint32 program); void glValidateProgram (deUint32 program); void glVertexAttrib1f (deUint32 indx, float x); void glVertexAttrib1fv (deUint32 indx, const float* values); void glVertexAttrib2f (deUint32 indx, float x, float y); void glVertexAttrib2fv (deUint32 indx, const float* values); void glVertexAttrib3f (deUint32 indx, float x, float y, float z); void glVertexAttrib3fv (deUint32 indx, const float* values); void glVertexAttrib4f (deUint32 indx, float x, float y, float z, float w); void glVertexAttrib4fv (deUint32 indx, const float* values); void glVertexAttribPointer (deUint32 indx, int size, deUint32 type, deBool normalized, int stride, const void* ptr); void glViewport (int x, int y, int width, int height); void glReadBuffer (deUint32 mode); void glDrawRangeElements (deUint32 mode, deUint32 start, deUint32 end, int count, deUint32 type, const void* indices); void glTexImage3D (deUint32 target, int level, int internalformat, int width, int height, int depth, int border, deUint32 format, deUint32 type, const void* pixels); void glTexSubImage3D (deUint32 target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, deUint32 format, deUint32 type, const void* pixels); void glCopyTexSubImage3D (deUint32 target, int level, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height); void glCompressedTexImage3D (deUint32 target, int level, deUint32 internalformat, int width, int height, int depth, int border, int imageSize, const void* data); void glCompressedTexSubImage3D (deUint32 target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, deUint32 format, int imageSize, const void* data); void glGenQueries (int n, deUint32* ids); void glDeleteQueries (int n, const deUint32* ids); deBool glIsQuery (deUint32 id); void glBeginQuery (deUint32 target, deUint32 id); void glEndQuery (deUint32 target); void glGetQueryiv (deUint32 target, deUint32 pname, int* params); void glGetQueryObjectuiv (deUint32 id, deUint32 pname, deUint32* params); deBool glUnmapBuffer (deUint32 target); void glGetBufferPointerv (deUint32 target, deUint32 pname, void** params); void glDrawBuffers (int n, const deUint32* bufs); void glUniformMatrix2x3fv (int location, int count, deBool transpose, const float* value); void glUniformMatrix3x2fv (int location, int count, deBool transpose, const float* value); void glUniformMatrix2x4fv (int location, int count, deBool transpose, const float* value); void glUniformMatrix4x2fv (int location, int count, deBool transpose, const float* value); void glUniformMatrix3x4fv (int location, int count, deBool transpose, const float* value); void glUniformMatrix4x3fv (int location, int count, deBool transpose, const float* value); void glBlitFramebuffer (int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, deUint32 mask, deUint32 filter); void glRenderbufferStorageMultisample (deUint32 target, int samples, deUint32 internalformat, int width, int height); void glFramebufferTextureLayer (deUint32 target, deUint32 attachment, deUint32 texture, int level, int layer); void* glMapBufferRange (deUint32 target, deIntptr offset, deIntptr length, deUint32 access); void glFlushMappedBufferRange (deUint32 target, deIntptr offset, deIntptr length); void glBindVertexArray (deUint32 array); void glDeleteVertexArrays (int n, const deUint32* arrays); void glGenVertexArrays (int n, deUint32* arrays); deBool glIsVertexArray (deUint32 array); void glGetIntegeri_v (deUint32 target, deUint32 index, int* data); void glBeginTransformFeedback (deUint32 primitiveMode); void glEndTransformFeedback (); void glBindBufferRange (deUint32 target, deUint32 index, deUint32 buffer, deIntptr offset, deIntptr size); void glBindBufferBase (deUint32 target, deUint32 index, deUint32 buffer); void glTransformFeedbackVaryings (deUint32 program, int count, const char* const* varyings, deUint32 bufferMode); void glGetTransformFeedbackVarying (deUint32 program, deUint32 index, int bufSize, int* length, int* size, deUint32* type, char* name); void glVertexAttribIPointer (deUint32 index, int size, deUint32 type, int stride, const void* pointer); void glGetVertexAttribIiv (deUint32 index, deUint32 pname, int* params); void glGetVertexAttribIuiv (deUint32 index, deUint32 pname, deUint32* params); void glVertexAttribI4i (deUint32 index, int x, int y, int z, int w); void glVertexAttribI4ui (deUint32 index, deUint32 x, deUint32 y, deUint32 z, deUint32 w); void glVertexAttribI4iv (deUint32 index, const int* v); void glVertexAttribI4uiv (deUint32 index, const deUint32* v); void glGetUniformuiv (deUint32 program, int location, deUint32* params); int glGetFragDataLocation (deUint32 program, const char* name); void glUniform1ui (int location, deUint32 v0); void glUniform2ui (int location, deUint32 v0, deUint32 v1); void glUniform3ui (int location, deUint32 v0, deUint32 v1, deUint32 v2); void glUniform4ui (int location, deUint32 v0, deUint32 v1, deUint32 v2, deUint32 v3); void glUniform1uiv (int location, int count, const deUint32* value); void glUniform2uiv (int location, int count, const deUint32* value); void glUniform3uiv (int location, int count, const deUint32* value); void glUniform4uiv (int location, int count, const deUint32* value); void glClearBufferiv (deUint32 buffer, int drawbuffer, const int* value); void glClearBufferuiv (deUint32 buffer, int drawbuffer, const deUint32* value); void glClearBufferfv (deUint32 buffer, int drawbuffer, const float* value); void glClearBufferfi (deUint32 buffer, int drawbuffer, float depth, int stencil); const deUint8* glGetStringi (deUint32 name, deUint32 index); void glCopyBufferSubData (deUint32 readTarget, deUint32 writeTarget, deIntptr readOffset, deIntptr writeOffset, deIntptr size); void glGetUniformIndices (deUint32 program, int uniformCount, const char* const* uniformNames, deUint32* uniformIndices); void glGetActiveUniformsiv (deUint32 program, int uniformCount, const deUint32* uniformIndices, deUint32 pname, int* params); deUint32 glGetUniformBlockIndex (deUint32 program, const char* uniformBlockName); void glGetActiveUniformBlockiv (deUint32 program, deUint32 uniformBlockIndex, deUint32 pname, int* params); void glGetActiveUniformBlockName (deUint32 program, deUint32 uniformBlockIndex, int bufSize, int* length, char* uniformBlockName); void glUniformBlockBinding (deUint32 program, deUint32 uniformBlockIndex, deUint32 uniformBlockBinding); void glDrawArraysInstanced (deUint32 mode, int first, int count, int primcount); void glDrawElementsInstanced (deUint32 mode, int count, deUint32 type, const void* indices, int primcount); void* glFenceSync (deUint32 condition, deUint32 flags); deBool glIsSync (void* sync); void glDeleteSync (void* sync); deUint32 glClientWaitSync (void* sync, deUint32 flags, deUint64 timeout); void glWaitSync (void* sync, deUint32 flags, deUint64 timeout); void glGetInteger64v (deUint32 pname, deInt64* params); void glGetSynciv (void* sync, deUint32 pname, int bufSize, int* length, int* values); void glGetInteger64i_v (deUint32 target, deUint32 index, deInt64* data); void glGetBufferParameteri64v (deUint32 target, deUint32 pname, deInt64* params); void glGenSamplers (int count, deUint32* samplers); void glDeleteSamplers (int count, const deUint32* samplers); deBool glIsSampler (deUint32 sampler); void glBindSampler (deUint32 unit, deUint32 sampler); void glSamplerParameteri (deUint32 sampler, deUint32 pname, int param); void glSamplerParameteriv (deUint32 sampler, deUint32 pname, const int* param); void glSamplerParameterf (deUint32 sampler, deUint32 pname, float param); void glSamplerParameterfv (deUint32 sampler, deUint32 pname, const float* param); void glGetSamplerParameteriv (deUint32 sampler, deUint32 pname, int* params); void glGetSamplerParameterfv (deUint32 sampler, deUint32 pname, float* params); void glVertexAttribDivisor (deUint32 index, deUint32 divisor); void glBindTransformFeedback (deUint32 target, deUint32 id); void glDeleteTransformFeedbacks (int n, const deUint32* ids); void glGenTransformFeedbacks (int n, deUint32* ids); deBool glIsTransformFeedback (deUint32 id); void glPauseTransformFeedback (); void glResumeTransformFeedback (); void glGetProgramBinary (deUint32 program, int bufSize, int* length, deUint32* binaryFormat, void* binary); void glProgramBinary (deUint32 program, deUint32 binaryFormat, const void* binary, int length); void glProgramParameteri (deUint32 program, deUint32 pname, int value); void glInvalidateFramebuffer (deUint32 target, int numAttachments, const deUint32* attachments); void glInvalidateSubFramebuffer (deUint32 target, int numAttachments, const deUint32* attachments, int x, int y, int width, int height); void glTexStorage2D (deUint32 target, int levels, deUint32 internalformat, int width, int height); void glTexStorage3D (deUint32 target, int levels, deUint32 internalformat, int width, int height, int depth); void glGetInternalformativ (deUint32 target, deUint32 internalformat, deUint32 pname, int bufSize, int* params); private: Context* m_curCtx; }; } // sglr #endif // _SGLRCONTEXTWRAPPER_HPP
9,058
2,039
package org.nd4j.linalg.api.indexing; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.nd4j.linalg.BaseNd4jTest; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.factory.Nd4jBackend; import org.nd4j.linalg.indexing.INDArrayIndex; import org.nd4j.linalg.indexing.NDArrayIndex; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author <NAME> */ @RunWith(Parameterized.class) public class IndexingTests extends BaseNd4jTest { public IndexingTests(Nd4jBackend backend) { super(backend); } @Test public void testINDArrayIndexingEqualToRank() { INDArray x = Nd4j.linspace(1,6,6).reshape('c',3,2); INDArray indexes = Nd4j.create(new double[][]{ {0,1,2}, {0,1,0} }); INDArray assertion = Nd4j.create(new double[]{1,4,5}); INDArray getTest = x.get(indexes); assertEquals(assertion,getTest); } @Test public void testINDArrayIndexingLessThanRankSimple() { INDArray x = Nd4j.linspace(1,6,6).reshape('c',3,2); INDArray indexes = Nd4j.create(new double[][]{ {0}, }); INDArray assertion = Nd4j.create(new double[]{1,2}); INDArray getTest = x.get(indexes); assertEquals(assertion, getTest); } @Test public void testINDArrayIndexingLessThanRankFourDimension() { INDArray x = Nd4j.linspace(1,16,16).reshape('c',2,2,2,2); INDArray indexes = Nd4j.create(new double[][]{ {0},{1} }); INDArray assertion = Nd4j.create(new double[]{5,6,7,8}).reshape('c',1,2,2); INDArray getTest = x.get(indexes); assertEquals(assertion,getTest); } @Test public void testPutSimple() { INDArray x = Nd4j.linspace(1,16,16).reshape('c',2,2,2,2); INDArray indexes = Nd4j.create(new double[][]{ {0},{1} }); x.put(indexes,Nd4j.create(new double[] {5,5})); INDArray vals = Nd4j.valueArrayOf(new int[] {2,2,2,2},5); assertEquals(vals,x); } @Test public void testPutUnMatchDims() { List<List<Integer>> indices = new ArrayList<>(); indices.add(Arrays.asList(0)); indices.add(Arrays.asList(0,1)); INDArray linspace = Nd4j.linspace(1,16,16).reshape('c',2,2,2,2); linspace.put(indices,Nd4j.scalar(99)); INDArray assertion = Nd4j.valueArrayOf(new int[] {2,2},99.0); for(int i = 0; i < 2; i++) assertEquals(assertion,linspace.slice(0).slice(i)); } @Test public void testScalarPut() { List<List<Integer>> indices = new ArrayList<>(); indices.add(Arrays.asList(0)); indices.add(Arrays.asList(1)); indices.add(Arrays.asList(0)); indices.add(Arrays.asList(0)); INDArray linspace = Nd4j.linspace(1,16,16).reshape('c',2,2,2,2); linspace.put(indices,Nd4j.scalar(99.0)); assertEquals(99.0,linspace.getDouble(0,1,0,0),1e-1); } @Test public void testIndexGetDuplicate() { List<List<Integer>> indices = new ArrayList<>(); indices.add(Arrays.asList(0,0)); INDArray linspace = Nd4j.linspace(1,16,16).reshape('c',2,2,2,2); INDArray get = linspace.get(indices); INDArray assertion = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8}).reshape('c',2,2,2,2); assertEquals(assertion,get); } @Test public void testGetScalar() { INDArray arr = Nd4j.linspace(1, 5, 5); INDArray d = arr.get(NDArrayIndex.point(1)); assertTrue(d.isScalar()); assertEquals(2.0, d.getDouble(0), 1e-1); } @Test public void testNewAxis() { INDArray arr = Nd4j.rand(new int[] {4, 2, 3}); INDArray view = arr.get(NDArrayIndex.newAxis(), NDArrayIndex.all(), NDArrayIndex.point(1)); System.out.println(view); } @Test public void testVectorIndexing() { INDArray x = Nd4j.linspace(0, 10, 11); int[] index = new int[] {5, 8, 9}; INDArray columnsTest = x.getColumns(index); assertEquals(Nd4j.create(new double[] {5, 8, 9}), columnsTest); int[] index2 = new int[] {2, 2, 4}; //retrieve the same columns twice INDArray columnsTest2 = x.getColumns(index2); assertEquals(Nd4j.create(new double[] {2, 2, 4}), columnsTest2); } @Test public void testGetRowsColumnsMatrix() { INDArray arr = Nd4j.linspace(1, 24, 24).reshape(4, 6); INDArray firstAndSecondColumnsAssertion = Nd4j.create(new double[][] {{1, 5}, {2, 6}, {3, 7}, {4, 8}}); System.out.println(arr); INDArray firstAndSecondColumns = arr.getColumns(0, 1); assertEquals(firstAndSecondColumnsAssertion, firstAndSecondColumns); INDArray firstAndSecondRows = Nd4j.create(new double[][] {{1.00, 5.00, 9.00, 13.00, 17.00, 21.00}, {1.00, 5.00, 9.00, 13.00, 17.00, 21.00}, {2.00, 6.00, 10.00, 14.00, 18.00, 22.00}}); INDArray rows = arr.getRows(new int[] {0, 0, 1}); assertEquals(firstAndSecondRows, rows); } @Test public void testSlicing() { INDArray arange = Nd4j.arange(1, 17).reshape(4, 4); INDArray slice1Assert = Nd4j.create(new double[] {2, 6, 10, 14}); INDArray slice1Test = arange.slice(1); assertEquals(slice1Assert, slice1Test); } @Test public void testArangeMul() { INDArray arange = Nd4j.arange(1, 17).reshape('f', 4, 4); INDArrayIndex index = NDArrayIndex.interval(0, 2); INDArray get = arange.get(index, index); INDArray zeroPointTwoFive = Nd4j.ones(2, 2).mul(0.25); INDArray mul = get.mul(zeroPointTwoFive); INDArray assertion = Nd4j.create(new double[][] {{0.25, 1.25}, {0.5, 1.5}}, 'f'); assertEquals(assertion, mul); } @Test public void testGetIndicesVector() { INDArray line = Nd4j.linspace(1, 4, 4); INDArray test = Nd4j.create(new float[] {2, 3}); INDArray result = line.get(NDArrayIndex.point(0), NDArrayIndex.interval(1, 3)); assertEquals(test, result); } @Override public char ordering() { return 'f'; } }
3,100
412
class A { public void dummy() { // check some setup assert this instanceof A; } public B b; } class B { public A a; } public class Main { public static void main(String[] args) { B B = new B(); } }
94
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/workers/worker_module_tree_client.h" #include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/core/events/error_event.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/script/module_script.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h" namespace blink { WorkerModuleTreeClient::WorkerModuleTreeClient(Modulator* modulator) : modulator_(modulator) {} // A partial implementation of the "Processing model" algorithm in the HTML // WebWorker spec: // https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model void WorkerModuleTreeClient::NotifyModuleTreeLoadFinished( ModuleScript* module_script) { auto* execution_context = ExecutionContext::From(modulator_->GetScriptState()); if (!module_script) { // Step 13: "If the algorithm asynchronously completes with null, queue // a task to fire an event named error at worker, and return." // This ErrorEvent object is just used for passing error information to a // worker object on the parent context thread and not dispatched directly. execution_context->ExceptionThrown( ErrorEvent::Create("Failed to load a module script.", SourceLocation::Capture(), nullptr /* world */)); return; } // Step 13: "Otherwise, continue the rest of these steps after the algorithm's // asynchronous completion, with script being the asynchronous completion // value." ScriptValue error = modulator_->ExecuteModule( module_script, Modulator::CaptureEvalErrorFlag::kReport); ToWorkerGlobalScope(execution_context) ->ReportingProxy() .DidEvaluateModuleScript(error.IsEmpty()); } void WorkerModuleTreeClient::Trace(blink::Visitor* visitor) { visitor->Trace(modulator_); ModuleTreeClient::Trace(visitor); } } // namespace blink
701
477
"""Functions to read text or tsv files containing GO IDs and sections of GO IDs.""" from __future__ import print_function import os import sys import re import pkgutil import importlib from goatools.gosubdag.go_tasks import chk_goids from goatools.grouper.hdrgos import HdrgosSections from goatools.grouper.grprobj import Grouper from goatools.grouper.tasks import SummarySec2dHdrGos __copyright__ = "Copyright (C) 2016-2018, <NAME>, All rights reserved." __author__ = "<NAME>" def read_sections(sections_file, exclude_ungrouped=False, prt=sys.stdout): """Get sections and GO grouping hdrgos from file, if sections exist.""" if sections_file is None: return None assert isinstance(sections_file, str), "BAD SECTIONS FILENAME({S})".format( S=sections_file) if os.path.exists(sections_file): return ReadGoids().read_sections(sections_file, False, exclude_ungrouped) # Is 'sections_file' a module string? if '/' not in sections_file and r'\\' not in sections_file and \ pkgutil.find_loader(sections_file) is not None: mod = importlib.import_module(sections_file) var = getattr(mod, 'SECTIONS', None) if var is not None: dat = SummarySec2dHdrGos().summarize_sec2hdrgos(var) print(Grouper.fmtsum.format( GO_DESC='hdr', SECs=len(dat['S']), GOs=len(dat['G']), UNGRP="N/A", undesc="unused", ACTION="IMPORTED: ", FILE=sections_file)) return var raise RuntimeError("NO 'SECTIONS' VARIABLE FOUND IN MODULE({M})".format(M=sections_file)) if prt: prt.write("CANNOT READ: {SEC}\n".format(SEC=sections_file)) def read_goids(fin_txt, get_goids_only=False, exclude_ungrouped=False, prt=sys.stdout): """Get user list of GO IDs either from a list or from GO IDs on the command-line""" return ReadGoids().read_txt(fin_txt, get_goids_only, exclude_ungrouped, prt) class ReadGoids(object): """Get user list of GO IDs either from a list or from GO IDs on the command-line""" srch_section = re.compile(r'^#?\s*SECTION:\s*(\S.*\S)\s*$', flags=re.IGNORECASE) # For reading SECTIONS from a Python file as text (without importing) # ("cell death", [ # 6 GO-headers # ("viral/bacteria", [ # 4 GO-headers srch_py_section = re.compile(r'^\s*(\(|\[)\s*(\'|")(.*)\s*(\'|")\s*,\s*\[') # "GO:0002376", # BP 564 L01 D01 M immune system process # "GO:0002682", # BP 1,183 L02 D02 AB regulation of immune system process srch_py_goids = re.compile(r'^\s*(\'|")(GO:\d{7})(\'|")\s*,?') def __init__(self): self.goids_fin = [] self.sections_seen = [] self.section2goids = {} def read_txt(self, fin_txt, get_goids_only, exclude_ungrouped, prt=sys.stdout): """Get user list of GO IDs either from a list or from GO IDs on the command-line""" goids_fin = self._read_txt(fin_txt, get_goids_only, exclude_ungrouped) sections = self._read_finish(goids_fin, prt) # Print summary of GO IDs read if prt is not None: self._prt_read_msg(prt, fin_txt, exclude_ungrouped) return sections def read_py(self, fin_txt, get_goids_only, exclude_ungrouped, prt=sys.stdout): """Read GO IDs or sections data from a Python file.""" goids_fin = self._read_py(fin_txt, get_goids_only, exclude_ungrouped) sections = self._read_finish(goids_fin, prt) # Print summary of GO IDs read if prt is not None: self._prt_read_msg(prt, fin_txt, exclude_ungrouped) return sections def read_sections(self, sections_file, get_goids_only, exclude_ungrouped): """Read sections variable from a text file of from a Python file.""" ext = os.path.splitext(sections_file)[1] file_contents = None if ext == '.py': file_contents = self.read_py(sections_file, get_goids_only, exclude_ungrouped) else: file_contents = self.read_txt(sections_file, get_goids_only, exclude_ungrouped) if file_contents: return file_contents.get('sections', None) def _read_finish(self, goids_fin, prt): """Get one of: {'goids':...} or {'sections':...} from reading a file.""" # Report unused sections, if any if len(self.section2goids) != len(self.sections_seen): self._rpt_unused_sections(prt) # If there are no sections, then goids_fin holds all GO IDs in file if not self.sections_seen: self.goids_fin = goids_fin if goids_fin: return self.internal_get_goids_or_sections() # {'goids':...} or {'sections':...} else: sys.stdout.write( "\n**WARNING: GO IDs MUST BE THE FIRST 10 CHARACTERS OF EACH LINE\n\n") def _read_txt(self, fin_txt, get_goids_only, exclude_ungrouped): """Read GO file. Store results in: section2goids sections_seen. Return goids_fin.""" goids_sec = [] with open(fin_txt) as istrm: # Lines starting with a GO ID will have that GO ID read and stored. # * Lines that do not start with a GO ID will be ignored. # * Text after the 10 characters in a GO ID will be ignored. section_name = None for line in istrm: if line[:3] == "GO:": goids_sec.append(line[:10]) elif not get_goids_only and ":" in line: mtch = self.srch_section.match(line) if mtch: secstr = mtch.group(1) if section_name is not None and goids_sec: self.section2goids[section_name] = goids_sec if not exclude_ungrouped or secstr != HdrgosSections.secdflt: section_name = secstr self.sections_seen.append(section_name) else: section_name = None goids_sec = [] if section_name is not None and goids_sec: self.section2goids[section_name] = goids_sec return goids_sec def _read_py(self, fin_py, get_goids_only, exclude_ungrouped): """Read Python sections file. Store: section2goids sections_seen. Return goids_fin.""" goids_sec = [] with open(fin_py) as istrm: section_name = None for line in istrm: mgo = self.srch_py_goids.search(line) # Matches GO IDs in sections if mgo: goids_sec.append(mgo.group(2)) elif not get_goids_only and "[" in line: msec = self.srch_py_section.search(line) # Matches sections if msec: secstr = msec.group(3) if section_name is not None and goids_sec: self.section2goids[section_name] = goids_sec if not exclude_ungrouped or secstr != HdrgosSections.secdflt: section_name = secstr self.sections_seen.append(section_name) else: section_name = None goids_sec = [] if section_name is not None and goids_sec: self.section2goids[section_name] = goids_sec return goids_sec def _rpt_unused_sections(self, prt): """Report unused sections.""" sections_unused = set(self.sections_seen).difference(self.section2goids.keys()) for sec in sections_unused: prt.write(" UNUSED SECTION: {SEC}\n".format(SEC=sec)) def internal_get_goids_or_sections(self): """Return GO IDs, Sections/GOs, or None.""" if self.goids_fin: chk_goids(self.goids_fin, "read_goids") return {'goids' : self.goids_fin} else: # Convert dict into 2D list retaining original section order sections_2d = [] for section_name in self.sections_seen: if section_name in self.section2goids: goids = self.section2goids.get(section_name) chk_goids(goids, "GO IDs IN SECTION({S})".format(S=section_name)) sections_2d.append((section_name, goids)) return {'sections' : sections_2d} def _prt_read_msg(self, prt, fin_txt, exclude_ungrouped): """Print which file was read and the number of GO IDs found.""" if self.sections_seen or exclude_ungrouped: # dat = Grouper.get_summary_data(self.section2goids.items(), HdrgosSections.secdflt) dat = SummarySec2dHdrGos().summarize_sec2hdrgos(self.section2goids.items()) sys.stdout.write(Grouper.fmtsum.format( GO_DESC='hdr', SECs=len(dat['S']), GOs=len(dat['G']), UNGRP="N/A", undesc="unused", ACTION="READ: ", FILE=fin_txt)) elif self.goids_fin: prt.write(" {G} GO IDs READ: {FIN}\n".format(G=len(self.goids_fin), FIN=fin_txt)) # Copyright (C) 2016-2018, <NAME>, All rights reserved.
4,376
309
<gh_stars>100-1000 #ifndef RD_CPP_ANYSERIALIZER_H #define RD_CPP_ANYSERIALIZER_H #include "serialization/SerializationCtx.h" #include "serialization/RdAny.h" #include "thirdparty.hpp" namespace rd { // region predeclared class Buffer; // endregion class InternedAnySerializer { public: static optional<InternedAny> read(SerializationCtx& ctx, Buffer& buffer) { return ctx.get_serializers().readAny(ctx, buffer); } template <typename T> static void write(SerializationCtx& ctx, Buffer& buffer, T const& value) { ctx.get_serializers().writePolymorphicNullable(ctx, buffer, value); } }; } // namespace rd #endif // RD_CPP_ANYSERIALIZER_H
257
366
// Copyright (c) 2014-2021 The Gridcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or https://opensource.org/licenses/mit-license.php. #ifndef GRIDCOIN_SUPPORT_FILEHASH_H #define GRIDCOIN_SUPPORT_FILEHASH_H #include "serialize.h" #include "streams.h" #include "hash.h" namespace GRC { class CAutoHasherFile : public CAutoFile, public CHashWriter { public: explicit CAutoHasherFile(FILE* filenew, int nTypeIn, int nVersionIn) : CAutoFile(filenew, nTypeIn, nVersionIn), CHashWriter(nTypeIn, nVersionIn) {}; void read(Span<std::byte> dst) { CAutoFile::read(dst); CHashWriter::write(dst); } void write(Span<const std::byte> src) { CAutoFile::write(src); CHashWriter::write(src); } int GetType() const { return CAutoFile::GetType(); } int GetVersion() const { return CAutoFile::GetVersion(); } template <typename T> CAutoHasherFile& operator<<(const T& obj) { ::Serialize(*this, obj); return *this; } template <typename T> CAutoHasherFile& operator>>(T& obj) { ::Unserialize(*this, obj); return *this; } }; } // namespace GRC #endif // GRIDCOIN_SUPPORT_FILEHASH_H
535
2,753
<filename>src/shogun/machine/gp/LaplaceInference.h /* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 <NAME> * Written (W) 2013 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. * */ #ifndef CLAPLACEINFERENCE_H_ #define CLAPLACEINFERENCE_H_ #include <shogun/lib/config.h> #include <shogun/machine/gp/Inference.h> namespace shogun { /** @brief The Laplace approximation inference method base class * * This inference method approximates the posterior likelihood function by using * Laplace's method. Here, we compute a Gaussian approximation to the posterior * via a Taylor expansion around the maximum of the posterior likelihood * function. * */ class LaplaceInference: public Inference { public: /** default constructor */ LaplaceInference(); /** constructor * * @param kernel covariance function * @param features features to use in inference * @param mean mean function * @param labels labels of the features * @param model Likelihood model to use */ LaplaceInference(std::shared_ptr<Kernel> kernel, std::shared_ptr<Features> features, std::shared_ptr<MeanFunction> mean, std::shared_ptr<Labels> labels, std::shared_ptr<LikelihoodModel> model); ~LaplaceInference() override; /** return what type of inference we are * * @return inference type Laplace */ EInferenceType get_inference_type() const override { return INF_LAPLACE; } /** returns the name of the inference method * * @return name Laplace */ const char* get_name() const override { return "LaplaceInference"; } /** get alpha vector * * @return vector to compute posterior mean of Gaussian Process: * * \f[ * \mu = K\alpha+meanf * \f] * * where \f$\mu\f$ is the mean, * \f$K\f$ is the prior covariance matrix, * and \f$meanf\f$ is the mean prior fomr MeanFunction * */ SGVector<float64_t> get_alpha() override; /** get Cholesky decomposition matrix * * @return Cholesky decomposition of matrix: * * for binary and regression case * \f[ * L = Cholesky(W^{\frac{1}{2}}*K*W^{\frac{1}{2}}+I) * \f] * where \f$K\f$ is the prior covariance matrix, \f$sW\f$ is the vector * returned by get_diagonal_vector(), and \f$I\f$ is the identity matrix. * * for multiclass case * \f[ * M = Cholesky(\sum_\text{c}{E_\text{c}) * \f] * * where \f$E_\text{c}\f$ is the matrix defined in the algorithm 3.3 of the GPML textbook for class c * Note the E matrix is used to store these \f$E_\text{c}\f$ matrices, where E=[E_1, E_2, ..., E_C], * where C is the number of classes and C should be greater than 1. * */ SGMatrix<float64_t> get_cholesky() override; /** returns covariance matrix \f$\Sigma=(K^{-1}+W)^{-1}\f$ of the Gaussian * distribution \f$\mathcal{N}(\mu,\Sigma)\f$, which is an approximation to * the posterior: * * \f[ * p(f|y) \approx q(f|y) = \mathcal{N}(f|\mu,\Sigma) * \f] * * @return covariance matrix */ SGMatrix<float64_t> get_posterior_covariance() override; /** update all matrices except gradients*/ void update() override; private: /** init */ void init(); protected: /** update gradients */ void compute_gradient() override; /** update covariance matrix of the approximation to the posterior */ virtual void update_approx_cov()=0; /** derivative of log likelihood with respect to function location */ SGVector<float64_t> m_dlp; /** noise matrix */ SGVector<float64_t> m_W; /** mean vector of the approximation to the posterior */ SGVector<float64_t> m_mu; /** covariance matrix of the approximation to the posterior */ SGMatrix<float64_t> m_Sigma; }; } #endif /* CLAPLACEINFERENCE_H_ */
1,734
378
<filename>dnsdb_common/dal/models/view_acl_subnets.py # -*- coding: utf-8 -*- from . import AuditTimeMixin, JsonMixin from .. import db class ViewAclSubnet(db.Model, AuditTimeMixin, JsonMixin): __tablename__ = 'tb_view_acl_subnets' id = db.Column(db.Integer, primary_key=True) subnet = db.Column(db.String(32), nullable=False, unique=True) start_ip = db.Column(db.Float, nullable=False) end_ip = db.Column(db.Float, nullable=False) origin_acl = db.Column(db.String(32), nullable=False) now_acl = db.Column(db.String(32), nullable=False) update_user = db.Column(db.String(64), nullable=False) is_ipv6 = db.Column(db.Boolean, nullable=False, default=False) def __str__(self): return 'ViewAclSubnet[subnet=%s, now_acl=%s, start=%s, end=%s]' % ( self.subnet, self.now_acl, self.start, self.end )
411
493
package com.novoda.downloadmanager.demo.migration; import android.content.ContentResolver; import android.database.CharArrayBuffer; import android.database.ContentObserver; import android.database.Cursor; import android.database.DataSetObserver; import android.net.Uri; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; class StubCursor implements Cursor { private final List<String> columnNames; private final Map<String, List<String>> rowsByColumn; private int position = -1; private boolean isClosed; private StubCursor(List<String> columnNames, Map<String, List<String>> rowsByColumn) { this.columnNames = columnNames; this.rowsByColumn = rowsByColumn; } @Override public int getCount() { String firstColumn = columnNames.get(0); return rowsByColumn.get(firstColumn).size(); } @Override public int getPosition() { return position; } @Override public boolean move(int i) { int moveTo = position + i; if (moveTo > getCount()) { return false; } position = moveTo; return true; } @Override public boolean moveToPosition(int i) { position = i; return true; } @Override public boolean moveToFirst() { position = 0; return true; } @Override public boolean moveToLast() { String firstColumn = columnNames.get(0); position = rowsByColumn.get(firstColumn).size() - 1; return true; } @Override public boolean moveToNext() { position++; return !isAfterLast(); } @Override public boolean moveToPrevious() { position--; return !isBeforeFirst(); } @Override public boolean isFirst() { return position == 0; } @Override public boolean isLast() { String firstColumn = columnNames.get(0); return position == rowsByColumn.get(firstColumn).size() - 1; } @Override public boolean isBeforeFirst() { return position < 0; } @Override public boolean isAfterLast() { String firstColumn = columnNames.get(0); return position >= rowsByColumn.get(firstColumn).size(); } @Override public int getColumnIndex(String s) { for (int i = 0; i < columnNames.size(); i++) { if (columnNames.get(i).equals(s)) { return i; } } return -1; } @Override public int getColumnIndexOrThrow(String s) throws IllegalArgumentException { int columnIndex = getColumnIndex(s); if (columnIndex == -1) { throw new IllegalArgumentException("Could not find index of column with: " + s); } return columnIndex; } @Override public String getColumnName(int i) { return columnNames.get(i); } @Override public String[] getColumnNames() { return columnNames.toArray(new String[columnNames.size()]); } @Override public int getColumnCount() { return columnNames.size(); } @Override public byte[] getBlob(int i) { return new byte[0]; } @Override public String getString(int i) { String columnName = columnNames.get(i); List<String> rowsInColumn = rowsByColumn.get(columnName); return rowsInColumn.get(position); } @Override public void copyStringToBuffer(int i, CharArrayBuffer charArrayBuffer) { } @Override public short getShort(int i) { return 0; } @Override public int getInt(int i) { return 0; } @Override public long getLong(int i) { String longAsString = getString(i); return Long.parseLong(longAsString); } @Override public float getFloat(int i) { String floatAsString = getString(i); return Float.parseFloat(floatAsString); } @Override public double getDouble(int i) { String doubleAsString = getString(i); return Double.parseDouble(doubleAsString); } @Override public int getType(int i) { return FIELD_TYPE_STRING; } @Override public boolean isNull(int i) { return false; } @Override public void deactivate() { } @Override public boolean requery() { return false; } @Override public void close() { position = -1; isClosed = true; } @Override public boolean isClosed() { return isClosed; } @Override public void registerContentObserver(ContentObserver contentObserver) { } @Override public void unregisterContentObserver(ContentObserver contentObserver) { } @Override public void registerDataSetObserver(DataSetObserver dataSetObserver) { } @Override public void unregisterDataSetObserver(DataSetObserver dataSetObserver) { } @Override public void setNotificationUri(ContentResolver contentResolver, Uri uri) { } @Override public Uri getNotificationUri() { return null; } @Override public boolean getWantsAllOnMoveCalls() { return false; } @Override public void setExtras(Bundle bundle) { } @Override public Bundle getExtras() { return null; } @Override public Bundle respond(Bundle bundle) { return null; } static class Builder { private List<String> columns = new ArrayList<>(); private Map<String, List<String>> rowsByColumn = new HashMap<>(); Builder with(String columnName, String value, String... values) { if (columns.contains(columnName)) { Log.w(getClass().getSimpleName(), "Cursor already contains column: " + columnName); return this; } columns.add(columnName); List<String> copyRowValues = new ArrayList<>(); copyRowValues.add(value); copyRowValues.addAll(Arrays.asList(values)); rowsByColumn.put(columnName, copyRowValues); return this; } StubCursor build() { return new StubCursor(columns, rowsByColumn); } } }
2,614
401
<gh_stars>100-1000 { "tools": { "GeoNamesOnTool": { "keyin": "GeoNames On", "description": "Turns on display of GeoName Markers" }, "GeoNamesOffTool": { "keyin": "GeoNames Off", "description": "Turns off display of GeoName Markers" }, "GeoNamesUpdateTool": { "keyin": "GeoNames Update", "description": "Update display of GeoName Markers for current view" } }, "messages": { "LoadingLocations": "Loading locations from wwww.geonames.org...", "LoadingComplete": "Location loading complete." }, "misc": { "Population": "Population" } }
245
1,841
<reponame>boudabass/noobs #ifndef JSON_H #define JSON_H /* Json helper class * * Outsources the hard work to QJson * * Initial author: <NAME> * Maintained by Raspberry Pi * * See LICENSE.txt for license details * */ #include <QVariant> class Json { public: static QVariant parse(const QByteArray &json); static QByteArray serialize(const QVariant &json); static QVariant loadFromFile(const QString &filename); static void saveToFile(const QString &filename, const QVariant &json); }; #endif // JSON_H
186
764
<filename>eos-token/[email protected] { "symbol": "ZION", "account_name": "ziongameseos", "overview": { "en": "Blockchain entertainment platform based on EOS" }, "website": "https://zion.games" }
101
308
<filename>scripts/plot_fid.py<gh_stars>100-1000 import pickle import os from tl2.proj.argparser import argparser_utils from tl2.proj.matplot import plt_utils def main(data_pkl, data_key, title, outdir): os.makedirs(outdir, exist_ok=True) with open(data_pkl, 'rb') as f: loaded_data = pickle.load(f) data_dict = loaded_data['FID_r64'] data = data_dict[data_key] fig, ax = plt_utils.get_fig_ax() ax.plot(data[:, 0], data[:, 1]) plt_utils.ax_set_ylim(ax, [0, 100]) plt_utils.ax_set_xlabel(ax, xlabel='Iters') plt_utils.ax_set_ylabel(ax, ylabel='FID') plt_utils.ax_set_title(ax, title=title, fontsize=20) plt_utils.savefig(saved_file=f"{outdir}/{data_key}.png", fig=fig, debug=True) pass if __name__ == '__main__': """ python scripts/plot_fid.py --data_key ffhq_r64 """ parser = argparser_utils.get_parser() argparser_utils.add_argument_str(parser, 'data_pkl', default="datasets/data/ffhq_fid.pkl") argparser_utils.add_argument_str(parser, 'data_key', default="<KEY>") argparser_utils.add_argument_str(parser, 'title', default=r"FFHQ $64\times64$") argparser_utils.add_argument_str(parser, 'outdir', default="results/plot_fid") args, _ = parser.parse_known_args() argparser_utils.print_args(args) main(**vars(args))
564
556
/* * 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.plc4x.java.transport.serial; import io.netty.channel.ChannelOption; public class SerialChannelOptions { /** * Option to configure the baud rate. */ public static final ChannelOption<Integer> BAUD_RATE = ChannelOption.valueOf(Integer.class, "BAUD_RATE"); /** * Option to configure the number of data bits. */ public static final ChannelOption<Integer> DATA_BITS = ChannelOption.valueOf(Integer.class, "DATA_BITS"); /** * Option to configure the number of stop bits. */ public static final ChannelOption<Integer> STOP_BITS = ChannelOption.valueOf(Integer.class, "STOP_BITS"); /** * Option to configure the number of parity bits. */ public static final ChannelOption<Integer> PARITY_BITS = ChannelOption.valueOf(Integer.class, "PARITY_BITS"); }
510
17,242
<reponame>virdio/mediapipe // Copyright 2019 The MediaPipe Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.mediapipe.components; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Build; import android.util.Log; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; /** Manages camera permission request and handling. */ public class PermissionHelper { private static final String TAG = "PermissionHelper"; private static final String AUDIO_PERMISSION = Manifest.permission.RECORD_AUDIO; private static final String CAMERA_PERMISSION = Manifest.permission.CAMERA; private static final String READ_EXTERNAL_STORAGE_PERMISSION = Manifest.permission.READ_EXTERNAL_STORAGE; private static final int REQUEST_CODE = 0; public static boolean permissionsGranted(Activity context, String[] permissions) { for (String permission : permissions) { int permissionStatus = ContextCompat.checkSelfPermission(context, permission); if (permissionStatus != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public static void checkAndRequestPermissions(Activity context, String[] permissions) { if (!permissionsGranted(context, permissions)) { ActivityCompat.requestPermissions(context, permissions, REQUEST_CODE); } } /** Called by context to check if camera permissions have been granted. */ public static boolean cameraPermissionsGranted(Activity context) { return permissionsGranted(context, new String[] {CAMERA_PERMISSION}); } /** * Called by context to check if camera permissions have been granted and if not, request them. */ public static void checkAndRequestCameraPermissions(Activity context) { Log.d(TAG, "checkAndRequestCameraPermissions"); checkAndRequestPermissions(context, new String[] {CAMERA_PERMISSION}); } /** Called by context to check if audio permissions have been granted. */ public static boolean audioPermissionsGranted(Activity context) { return permissionsGranted(context, new String[] {AUDIO_PERMISSION}); } /** Called by context to check if audio permissions have been granted and if not, request them. */ public static void checkAndRequestAudioPermissions(Activity context) { Log.d(TAG, "checkAndRequestAudioPermissions"); checkAndRequestPermissions(context, new String[] {AUDIO_PERMISSION}); } /** Called by context to check if read external storage permissions have been granted. */ public static boolean readExternalStoragePermissionsGranted(Activity context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return true; } return permissionsGranted(context, new String[] {READ_EXTERNAL_STORAGE_PERMISSION}); } /** * Called by context to check if read external storage permissions have been granted and if not, * request them. */ public static void checkAndRequestReadExternalStoragePermissions(Activity context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { Log.d(TAG, "checkAndRequestReadExternalStoragePermissions"); checkAndRequestPermissions(context, new String[] {READ_EXTERNAL_STORAGE_PERMISSION}); } } /** Called by context when permissions request has been completed. */ public static void onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults) { Log.d(TAG, "onRequestPermissionsResult"); if (permissions.length > 0 && grantResults.length != permissions.length) { Log.d(TAG, "Permission denied."); return; } for (int i = 0; i < grantResults.length; ++i) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, permissions[i] + " permission granted."); } } // Note: We don't need any special callbacks when permissions are ready because activities // using this helper class can have code in onResume() which is called after the // permissions dialog box closes. The code can be branched depending on if permissions are // available via permissionsGranted(Activity). return; } }
1,387
335
{ "word": "Nimble", "definitions": [ "Quick and light in movement or action; agile.", "(of the mind) able to think and understand quickly." ], "parts-of-speech": "Adjective" }
83
1,144
/* * * btusb_lite.h * * * * Copyright (C) 2011-2013 Broadcom Corporation. * * * * This software is licensed under the terms of the GNU General Public License, * version 2, as published by the Free Software Foundation (the "GPL"), and may * be copied, distributed, and modified under those terms. * * 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 GPL for more details. * * * A copy of the GPL is available at http://www.broadcom.com/licenses/GPLv2.php * or by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA * * */ #ifndef BTUSB_LITE_H #define BTUSB_LITE_H struct btusb; struct btpcm; #include "bt_target.h" #include "hcidefs.h" #include "bd.h" #include "uipc_msg.h" #include "btusb_lite_av.h" #include "btusb_lite_avdt.h" #include "btusb_lite_l2c.h" #include "btusb_lite_hci.h" /* * Definitions */ /* IPC Length Header Size (16 bits) */ #define BTUSB_LITE_IPC_HDR_LEN_SIZE (sizeof(UINT16)) /* IPC Event Header Size (16 bits) */ #define BTUSB_LITE_IPC_HDR_EVT_SIZE (sizeof(UINT16)) /* IPC Header contains a Length and an Event code */ #define BTUSB_LITE_IPC_HDR_SIZE (BTUSB_LITE_IPC_HDR_LEN_SIZE + BTUSB_LITE_IPC_HDR_EVT_SIZE) struct btusb_lite_mgt_cb { bool opened; }; struct btusb_lite_stat { unsigned long event_bytes; unsigned long event_completed; }; struct btusb_lite_from_app { BT_HDR *p_rx_msg; UINT8 rx_header[BTUSB_LITE_IPC_HDR_SIZE]; UINT8 rx_header_len; UINT16 rx_len; /* Decoded Rx Payload length */ }; struct btusb_lite_to_app { BUFFER_Q ipc_queue; /* IPC message queue */ BT_HDR *p_ipc_msg; BT_HDR *p_hdr_msg; BT_HDR *p_hci_msg; }; /* Lite Stack mode */ #define BTU_FULL_STACK_ACTIVE 0 #define BTU_LITE_STACK_ACTIVE 1 #define BTU_TRANSPORT_HOLD 2 #define BTU_FULL_TRANSPORT_ACTIVE 3 #define BTU_LITE_TRANSPORT_ACTIVE 4 #define BTU_IPC_CMD_SET_TRANSPORT_STATE 0 /* Set transport state (param=transprt state) */ #define BTU_IPC_CMD_DISABLE_TRANSPORT 1 /* Set transport hardware (param=1 to disable) */ struct btusb_lite_btu_cb { UINT8 transport_state; UINT8 transport_disabled; }; enum btusb_lite_pcm_state { PCM_CLOSED = 0, PCM_OPENED, PCM_CONFIGURED, PCM_STARTED }; struct btusb_lite_pcm_ccb { enum btusb_lite_pcm_state state; int frequency; }; struct btusb_lite_encoder_ccb { int channel; int opened; int encoded_frame_size; int pcm_frame_size; int header_size; int type; /* SBC, SEC, etc. */ tBTA_AV_AUDIO_CODEC_INFO encoder; }; typedef void (tAV_LITE_STREAM_FUNC) (struct btusb*, BT_HDR*, UINT8, UINT8, UINT8, UINT32); struct btusb_lite_av_cb { UINT8 audio_open_cnt; UINT16 stack_mtu; /* received value from bt stack */ UINT16 curr_mtu; /* modified value in btusb to meet PCM buffer size */ UINT8 multi_av; struct btusb_lite_pcm_ccb pcm; struct btusb_lite_encoder_ccb encoder; struct btusb_lite_av_scb scb[BTA_AV_NUM_STRS]; BT_HDR *p_buf_working; UINT8 option; UINT8 m_pt; int header_len; int payload_len; UINT32 timestamp; tBTA_AV_LITE_STREAMING_TYPE streaming_type; tAV_LITE_STREAM_FUNC *p_stream_func; UINT16 seq_number; /* for BTUSB_LITE_CLB */ }; /* Main Lite Control Block */ struct btusb_lite_cb { /* static entries */ struct proc_dir_entry *p_lite_pde; struct btpcm *p_btpcm; /* dynamic entries */ struct { bool opened; struct btusb_lite_stat stat; struct btusb_lite_from_app from_app; struct btusb_lite_to_app to_app; struct btusb_lite_mgt_cb mgt; /* Management */ struct btusb_lite_btu_cb btu; /* BTU */ struct btusb_lite_l2c_cb l2c; /* L2C */ struct btusb_lite_av_cb av; /* AV */ struct btusb_lite_avdt_cb avdt; } s; }; /******************************************************************************* ** ** Function btusb_lite_create ** ** Description Create BTUSB Lite interface ** ** Returns status (< 0 if error) ** *******************************************************************************/ int btusb_lite_create(struct btusb *p_dev, struct usb_interface *p_interface); /******************************************************************************* ** ** Function btusb_lite_delete ** ** Description Delete BTUSB Lite interface ** ** Returns none ** *******************************************************************************/ void btusb_lite_delete(struct btusb *p_dev, struct usb_interface *p_interface); /******************************************************************************* ** ** Function btusb_lite_stop_all ** ** Description Stop all sound streams ** ** Returns void ** *******************************************************************************/ void btusb_lite_stop_all(struct btusb *p_dev); /******************************************************************************* ** ** Function btusb_lite_is_hci_over_ipc ** ** Description Check if HCI is over IPC (Lite Interface). ** ** Returns int (1 if HCI is over IPC otherwise 0) ** *******************************************************************************/ int btusb_lite_is_hci_over_ipc(struct btusb *p_dev); #endif /* BTUSB_LITE_H*/
2,182
1,694
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <MMCommon/MMObject.h> @class NSArray; @interface ABTestListWrap : MMObject { NSArray *_aryABTestItems; NSArray *_aryABTestExpKeyItems; } @property(retain, nonatomic) NSArray *aryABTestExpKeyItems; // @synthesize aryABTestExpKeyItems=_aryABTestExpKeyItems; @property(retain, nonatomic) NSArray *aryABTestItems; // @synthesize aryABTestItems=_aryABTestItems; - (void).cxx_destruct; @end
224
8,232
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // test <climits> #define TEST_NAME "<climits>" #include "tdefs.h" #include <climits> void test_cpp() { // test C++ header static const char char_val[] = {CHAR_MAX, CHAR_MIN}; static const signed char schar_val[] = {SCHAR_MAX, SCHAR_MIN}; static const short shrt_val[] = {SHRT_MAX, SHRT_MIN}; static const int int_val[] = {INT_MAX, INT_MIN}; static const long long_val[] = {LONG_MAX, LONG_MIN}; static const unsigned char uchar_val[] = {UCHAR_MAX}; static const unsigned short ushrt_val[] = {USHRT_MAX}; static const unsigned int uint_val[] = {UINT_MAX}; static const unsigned long ulong_val[] = {ULONG_MAX}; CHECK_INT(char_val[0], CHAR_MAX); CHECK_INT(char_val[1], CHAR_MIN); CHECK_INT(schar_val[0], SCHAR_MAX); CHECK_INT(schar_val[1], SCHAR_MIN); CHECK_INT(shrt_val[0], SHRT_MAX); CHECK_INT(shrt_val[1], SHRT_MIN); CHECK_INT(int_val[0], INT_MAX); CHECK_INT(int_val[1], INT_MIN); CHECK(long_val[0] == LONG_MAX); CHECK(long_val[1] == LONG_MIN); CHECK(uchar_val[0] == UCHAR_MAX); CHECK(ushrt_val[0] == USHRT_MAX); CHECK(uint_val[0] == UINT_MAX); CHECK(ulong_val[0] == ULONG_MAX); static const long long long_long_val[] = {LLONG_MAX, LLONG_MIN}; // C99 only static const unsigned long long ulong_long_val[] = {ULLONG_MAX}; CHECK(long_long_val[0] == LLONG_MAX); CHECK(long_long_val[1] == LLONG_MIN); CHECK(ulong_long_val[0] == ULLONG_MAX); } void test_main() { // test basic workings of climits definitions test_cpp(); }
798
713
<reponame>ScriptBox99/spiceai import json from pathlib import Path from typing import Tuple import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import optimizers from tensorflow.keras import layers import tensorflow_probability as tfp from algorithms.agent_interface import SpiceAIAgent from algorithms.dql.memory import ReplayBuffer tf.keras.backend.set_floatx("float64") class SACD(keras.Model): ACTIVATION = "leaky_relu" LEARNING_RATE = 1e-3 REWARD_DISCOUNT = 0.95 TARGET_ENTROPY_SCALE = 0.2 TARGET_MOMEMTUM = 0.05 UPDATE_STEPS = 10 @staticmethod def create_network(output_dim: int, final_activation: str = None) -> keras.Model: return keras.Sequential( [ layers.Dense(128, activation=SACD.ACTIVATION), layers.Dense(128, activation=SACD.ACTIVATION), layers.Dense(64, activation=SACD.ACTIVATION), layers.Dense(32, activation=SACD.ACTIVATION), layers.Dense(output_dim, activation=final_activation), ] ) class Actor(keras.Model): def __init__(self, action_dim: int): super().__init__() self.seq = SACD.create_network(action_dim, "softmax") def call(self, input_tensor: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: action_probs = self.seq(input_tensor) distribution = tfp.distributions.Categorical(action_probs) return distribution.sample(), action_probs def __init__(self, state_shape: tuple, action_size, log_dir: Path = None): super().__init__() self.state_shape = state_shape self.action_size = action_size self.actor = self.Actor(action_size) self._critic_1 = SACD.create_network(action_size) self._critic_2 = SACD.create_network(action_size) self._target_critic_1 = SACD.create_network(action_size) self._target_critic_2 = SACD.create_network(action_size) self.target_entropy = -np.log((1.0 / action_size)) * self.TARGET_ENTROPY_SCALE self.log_alpha = tf.Variable( [1.0], trainable=True, name="log_alpha", dtype=tf.float64 ) self.alpha = tf.Variable([1.0], trainable=False, name="alpha", dtype=tf.float64) self.alpha.assign(tf.exp(self.log_alpha)) init_input = tf.expand_dims(tf.zeros(state_shape), 0) self.actor(init_input) self._critic_1(init_input) self._critic_2(init_input) self._target_critic_1(init_input) self._target_critic_2(init_input) for critic_var, target_var in zip( self._critic_1.trainable_variables, self._target_critic_1.trainable_variables, ): target_var.assign(critic_var) for critic_var, target_var in zip( self._critic_2.trainable_variables, self._target_critic_2.trainable_variables, ): target_var.assign(critic_var) self._actor_optimizer = optimizers.Adam(learning_rate=self.LEARNING_RATE) self._critic_1_optimizer = optimizers.Adam(learning_rate=self.LEARNING_RATE) self._critic_2_optimizer = optimizers.Adam(learning_rate=self.LEARNING_RATE) self._alpha_optimizer = optimizers.Adam(learning_rate=self.LEARNING_RATE) self.writer = ( tf.summary.create_file_writer(str(log_dir / "sacd")) if log_dir else None ) self.global_step = 0 def call(self, input_tensor: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: return self.actor(input_tensor) @tf.function def _copy_target_models(self): for critic_var, target_var in zip( self._critic_1.trainable_variables, self._target_critic_1.trainable_variables, ): target_var.assign( self.TARGET_MOMEMTUM * critic_var + (1.0 - self.TARGET_MOMEMTUM) * target_var ) for critic_var, target_var in zip( self._critic_2.trainable_variables, self._target_critic_2.trainable_variables, ): target_var.assign( self.TARGET_MOMEMTUM * critic_var + (1.0 - self.TARGET_MOMEMTUM) * target_var ) def train(self, data): for _ in range(self.UPDATE_STEPS): state_batch, action_batch, reward_batch, next_state_batch = data action_batch = tf.cast(tf.expand_dims(action_batch, 1), tf.float64) reward_batch = tf.cast(tf.expand_dims(reward_batch, 1), tf.float64) # with tf.name_scope("actor_loss"): with tf.GradientTape() as actor_tape: _action, action_probs = self.actor(state_batch) action_logprobs = tf.math.log(action_probs) q1_value = self._critic_1(state_batch) q2_value = self._critic_2(state_batch) q_log_target = tf.minimum(q1_value, q2_value) actor_loss = tf.reduce_mean( tf.reduce_sum( action_probs * (self.alpha * action_logprobs - q_log_target), 1 ) ) self._actor_optimizer.apply_gradients( zip( actor_tape.gradient(actor_loss, self.actor.trainable_variables), self.actor.trainable_variables, ) ) # with tf.name_scope("critic_loss"): _next_action, next_action_probs = self.actor(next_state_batch) next_action_logprobs = tf.math.log(next_action_probs) q1_next_target = self._critic_1(next_state_batch) q2_next_target = self._critic_2(next_state_batch) min_q = next_action_probs * ( tf.minimum(q1_next_target, q2_next_target) - self.alpha * next_action_logprobs ) q_target = reward_batch + self.REWARD_DISCOUNT * min_q critic_losses = [] critic_tapes = [] for q_net in [self._critic_1, self._critic_2]: with tf.GradientTape() as critic_tape: q_value = tf.gather( q_net(state_batch), tf.cast(action_batch, tf.int64), axis=1 ) critic_losses.append( 0.5 * tf.reduce_mean((q_value - q_target) ** 2) ) critic_tapes.append(critic_tape) self._critic_1_optimizer.apply_gradients( zip( critic_tapes[0].gradient( critic_losses[0], self._critic_1.trainable_variables ), self._critic_1.trainable_variables, ) ) self._critic_2_optimizer.apply_gradients( zip( critic_tapes[1].gradient( critic_losses[1], self._critic_2.trainable_variables ), self._critic_2.trainable_variables, ) ) # with tf.name_scope("alpha_loss"): neg_entropy = tf.reduce_sum(action_logprobs * action_probs, axis=1) with tf.GradientTape() as alpha_tape: alpha_loss = tf.reduce_mean( -1 * self.log_alpha * (neg_entropy + self.target_entropy) ) self._alpha_optimizer.apply_gradients( zip(alpha_tape.gradient(alpha_loss, [self.log_alpha]), [self.log_alpha]) ) self.alpha.assign(tf.exp(self.log_alpha)) self._copy_target_models() if self.writer: with self.writer.as_default(step=self.global_step): for tag, value in [ ("metrics/actor_loss", actor_loss), *[ (f"metrics/critic_{critic_index}_loss", critic_loss) for critic_index, critic_loss in enumerate(critic_losses) ], ("metrics/alpha_loss", alpha_loss), ("metrics/entropy", tf.reduce_mean(-neg_entropy)), ]: tf.summary.scalar(tag, value) self.writer.flush() self.global_step += 1 class SoftActorCriticDiscreteAgent(SpiceAIAgent): BATCH_SIZE = 128 def __init__(self, state_shape: tuple, action_size, loggers, log_dir: Path): super().__init__(state_shape, action_size, loggers, log_dir) tf.compat.v1.enable_eager_execution() self.model = SACD( state_shape, action_size, log_dir=log_dir if loggers and "tensorboard" in loggers else None, ) self.buffer = ReplayBuffer(self.BATCH_SIZE) def add_experience(self, state, action, reward, next_state): self.buffer.store(state, action, reward, next_state) def act(self, state): if tf.executing_eagerly(): action, action_probs = self.model.actor(np.expand_dims(state, 0)) return action[0].numpy(), action_probs[0].numpy() action, action_probs = self.model.actor.predict(np.expand_dims(state, 0)) return action[0], action_probs[0] def save(self, path: Path): model_name = "model.pb" model_path = path / model_name with open(path / "meta.json", "w", encoding="utf-8") as meta_file: meta_file.write(json.dumps({"algorithm": "sacd", "model_name": model_name})) self.model.actor.save(model_path) def load(self, path: Path) -> bool: if (path / "meta.json").exists(): with open(path / "meta.json", "r", encoding="utf-8") as meta_file: meta_info = json.loads(meta_file.read()) self.model.actor = keras.models.load_model( str(path / meta_info["model_name"]), compile=False ) return True return False def learn(self): if self.buffer.size() < self.BATCH_SIZE: return self.model.train(self.buffer.sample())
5,185
1,066
<filename>terminal/src/main/java/org/jline/terminal/impl/AbstractPty.java /* * Copyright (c) 2002-2019, the original author or authors. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. * * https://opensource.org/licenses/BSD-3-Clause */ package org.jline.terminal.impl; import org.jline.terminal.Attributes; import org.jline.terminal.spi.Pty; import org.jline.utils.NonBlockingInputStream; import java.io.IOError; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import static org.jline.terminal.TerminalBuilder.PROP_NON_BLOCKING_READS; public abstract class AbstractPty implements Pty { private Attributes current; @Override public void setAttr(Attributes attr) throws IOException { current = new Attributes(attr); doSetAttr(attr); } @Override public InputStream getSlaveInput() throws IOException { InputStream si = doGetSlaveInput(); if (Boolean.parseBoolean(System.getProperty(PROP_NON_BLOCKING_READS, "true"))) { return new PtyInputStream(si); } else { return si; } } protected abstract void doSetAttr(Attributes attr) throws IOException; protected abstract InputStream doGetSlaveInput() throws IOException; protected void checkInterrupted() throws InterruptedIOException { if (Thread.interrupted()) { throw new InterruptedIOException(); } } class PtyInputStream extends NonBlockingInputStream { final InputStream in; int c = 0; PtyInputStream(InputStream in) { this.in = in; } @Override public int read(long timeout, boolean isPeek) throws IOException { checkInterrupted(); if (c != 0) { int r = c; if (!isPeek) { c = 0; } return r; } else { setNonBlocking(); long start = System.currentTimeMillis(); while (true) { int r = in.read(); if (r >= 0) { if (isPeek) { c = r; } return r; } checkInterrupted(); long cur = System.currentTimeMillis(); if (timeout > 0 && cur - start > timeout) { return NonBlockingInputStream.READ_EXPIRED; } } } } @Override public int readBuffered(byte[] b) throws IOException { return in.read(b); } private void setNonBlocking() { if (current == null || current.getControlChar(Attributes.ControlChar.VMIN) != 0 || current.getControlChar(Attributes.ControlChar.VTIME) != 1) { try { Attributes attr = getAttr(); attr.setControlChar(Attributes.ControlChar.VMIN, 0); attr.setControlChar(Attributes.ControlChar.VTIME, 1); setAttr(attr); } catch (IOException e) { throw new IOError(e); } } } } }
1,676
854
__________________________________________________________________________________________________ sample 2 ms submission class Solution { public int uniqueLetterString(String S) { int[] lastPosition = new int[26]; int[] contribution = new int[26]; int result = 0; // at each iteration, we count the contribution of all the characters to all the substrings ending till that point for(int i = 0; i < S.length(); i++) { int current = S.charAt(i) - 'A'; // update contribution to current character. // total # of substrings ending at i are i + 1. If it was a unique character, it would contribute to all of the substrings and its contribution is i + 1 // if it is repeating, then it was contributed previously, so we will subtract its previous contribution // these are the contributions for strings which start after this character's last occurence and end at i int totalNumOfSubstrings = i + 1; contribution[current] = totalNumOfSubstrings - lastPosition[current]; // the contribution of all other charcters will remain the same // count the current answer by adding all the contributions, only 26 letters in alphabet int curr = 0; for(int j = 0; j < 26; j++) { curr += contribution[j]; } // add current value to final answer result += curr; // update last position of the current character lastPosition[current] = i + 1; } return result; } } __________________________________________________________________________________________________ sample 35660 kb submission class Solution { public int uniqueLetterString(String S) { Map<Character, List<Integer>> index = new HashMap(); for (int i = 0; i < S.length(); ++i) { char c = S.charAt(i); index.computeIfAbsent(c, x-> new ArrayList<Integer>()).add(i); } long ans = 0; for (List<Integer> A: index.values()) { for (int i = 0; i < A.size(); ++i) { long prev = i > 0 ? A.get(i-1) : -1; long next = i < A.size() - 1 ? A.get(i+1) : S.length(); ans += (A.get(i) - prev) * (next - A.get(i)); } } return (int) ans % 1_000_000_007; } } __________________________________________________________________________________________________
1,025
794
<reponame>pjfanning/mina /* * 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.mina.util; import static org.junit.Assert.*; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.util.LinkedList; import java.util.List; import org.junit.Test; /** * A {@link ByteBufferOutputStream} test. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class ByteBufferOutputStreamTest { @Test public void testEmpty() throws IOException { ByteBufferOutputStream bbos = new ByteBufferOutputStream(); bbos.close(); assertEquals(0, bbos.getByteBuffer().remaining()); } @Test public void testSingleWrite() throws IOException { ByteBufferOutputStream bbos = new ByteBufferOutputStream(); bbos.write(86); bbos.close(); assertEquals(1, bbos.getByteBuffer().remaining()); assertEquals(86, bbos.getByteBuffer().get()); } @Test public void testWrite() throws IOException { byte[] src = "HELLO MINA!".getBytes(); ByteBufferOutputStream bbos = new ByteBufferOutputStream(1024); bbos.write(src); bbos.close(); assertEquals(src.length, bbos.getByteBuffer().remaining()); assertEquals(ByteBuffer.wrap(src), bbos.getByteBuffer()); } @Test public void testElasticity() throws IOException { final int allocatedSize = 1024; List<ByteBufferOutputStream> list = new LinkedList<ByteBufferOutputStream>(); ByteBufferOutputStream elastic = new ByteBufferOutputStream(allocatedSize); elastic.setElastic(true); ByteBufferOutputStream nonElastic = new ByteBufferOutputStream(allocatedSize); nonElastic.setElastic(false); list.add(elastic); list.add(nonElastic); byte[] src = new byte[321]; for (int i = 0; i < src.length; i++) src[i] = (byte) (0xff & (i / 7)); for (ByteBufferOutputStream bbos : list) { for (int j = 0; j < allocatedSize * 10; j += src.length) { try { bbos.write(src); if (!bbos.isElastic() && j > allocatedSize) fail("Overflooded buffer without any exception!"); } catch (BufferOverflowException boe) { if (bbos.isElastic()) fail("Elastic buffer overflooded! " + boe); } } bbos.close(); } } }
1,292
365
package org.superboot.controller.sys; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.superboot.base.AuthRoles; import org.superboot.base.BaseConstants; import org.superboot.base.BaseException; import org.superboot.base.BaseResponse; import org.superboot.service.ErrorLogService; import org.superboot.service.LogService; /** * <b> 后台管理首页面 </b> * <p> * 功能描述: 用于后台管理打开首页面的时候显示的内容,多数为图表信息 * </p> * */ @RequestMapping("/sys") @RestController @Api(tags = "用户中心首页管理公共接口", description = "后台首页管理,提供一些图表类的接口") @AuthRoles(roles = {BaseConstants.SYS_ADMIN_NAME, BaseConstants.DEV_USER_NAME, BaseConstants.OPER_USER_NAME}) public class SysIndexController { @Autowired private ErrorLogService errorLogService; @Autowired private LogService logService; @ApiOperation(value = "获取今天错误日志分组信息", notes = "获取今天错误日志分组信息,系统管理员默认可以访问") @RequestMapping(value = "/todayErrorCount", method = RequestMethod.GET) public BaseResponse getTodayErrorCount() throws BaseException { return errorLogService.getErrorLogGroupByAppName(); } @ApiOperation(value = "获取过去7天各模块请求信息", notes = "获取过去7天各模块请求信息,系统管理员默认可以访问") @RequestMapping(value = "/requestCountByWeek", method = RequestMethod.GET) public BaseResponse getRequestCountByWeek() throws BaseException { return logService.getRequestCountByWeek(); } }
828
1,682
package com.linkedin.r2.message.rest; import com.linkedin.data.ByteString; import java.util.Collections; /** * Factory methods for {@link RestResponse}. */ public final class RestResponseFactory { private static final RestResponse NO_RESPONSE = new RestResponseImpl( ByteString.empty(), Collections.<String, String>emptyMap(), Collections.<String>emptyList(), 0); /** * Returns an empty response. * * This is intended only for use in tests, hence the status code of 0. * * @return an instance of an empty response */ public static RestResponse noResponse() { return NO_RESPONSE; } private RestResponseFactory() { } }
207
466
<filename>lib_common/src/test/java/com/gykj/zhumulangma/common/ExampleUnitTest.java package com.gykj.zhumulangma.common; import com.gykj.zhumulangma.common.net.exception.ExceptionRetry; import org.junit.Test; import java.util.Calendar; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import static org.junit.Assert.assertEquals; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } static String mString; private static Observable t() { return Observable.create(new ObservableOnSubscribe<Object>() { @Override public void subscribe(ObservableEmitter<Object> emitter) throws Exception { mString = "aa"; mString = "11"; } }).doOnDispose(new Action() { @Override public void run() throws Exception { System.out.println(mString); } }); } String s; @Test public void test1(){ Observable<String> stringObservable = Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(ObservableEmitter<String> emitter) throws Exception { try { emitter.onNext(System.currentTimeMillis() + ""); emitter.onComplete(); } catch (Exception e) { emitter.onError(e); } } }) .doOnNext(new Consumer<String>() { @Override public void accept(String aVoid) throws Exception { System.out.println(aVoid); } }) .doOnComplete(new Action() { @Override public void run() throws Exception { System.out.println(11); } }).retryWhen(new ExceptionRetry()); stringObservable.subscribe(); } @Test public void test2(){ Calendar calendar = Calendar.getInstance(); System.out.println(calendar.get(7)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.DAY_OF_MONTH,-1); System.out.println(calendar1.get(7)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.DAY_OF_MONTH,1); System.out.println(calendar2.get(7)); } }
1,265
1,882
import unittest import tempfile import numpy as np import pandas as pd from supervised.preprocessing.exclude_missing_target import ExcludeRowsMissingTarget class ExcludeRowsMissingTargetTest(unittest.TestCase): def test_transform(self): d_test = { "col1": [1, 1, np.nan, 3], "col2": ["a", "a", np.nan, "a"], "col3": [1, 1, 1, 3], "col4": ["a", "a", "b", "c"], "y": [np.nan, 1, np.nan, 2], } df_test = pd.DataFrame(data=d_test) X = df_test.loc[:, ["col1", "col2", "col3", "col4"]] y = df_test.loc[:, "y"] self.assertEqual(X.shape[0], 4) self.assertEqual(y.shape[0], 4) X, y, _ = ExcludeRowsMissingTarget.transform(X, y) self.assertEqual(X.shape[0], 2) self.assertEqual(y.shape[0], 2) self.assertEqual(y[0], 1) self.assertEqual(y[1], 2) def test_transform_with_sample_weight(self): d_test = { "col1": [1, 1, np.nan, 3], "col2": ["a", "a", np.nan, "a"], "col3": [1, 1, 1, 3], "col4": ["a", "a", "b", "c"], "sample_weight": [1, 2, 3, 4], "y": [np.nan, 1, np.nan, 2], } df_test = pd.DataFrame(data=d_test) X = df_test.loc[:, ["col1", "col2", "col3", "col4"]] y = df_test.loc[:, "y"] sample_weight = df_test.loc[:, "sample_weight"] self.assertEqual(X.shape[0], 4) self.assertEqual(y.shape[0], 4) X, y, sw = ExcludeRowsMissingTarget.transform(X, y, sample_weight) self.assertEqual(X.shape[0], 2) self.assertEqual(y.shape[0], 2) self.assertEqual(sw.shape[0], 2) self.assertEqual(y[0], 1) self.assertEqual(y[1], 2) self.assertEqual(sw[0], 2) self.assertEqual(sw[1], 4)
988
417
/* * 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 com.alibaba.metrics; /** * A metric which calculates the distribution of a value. * 直方分布指标,例如,可以用于统计某个接口的响应时间,可以展示50%, 70%, 90%的请求响应时间落在哪个区间内 * * @see <a href="http://www.johndcook.com/standard_deviation.html">Accurately computing running * variance</a> */ public interface Histogram extends Metric, Sampling, Counting { /** * Adds a recorded value. * 将某个整型值添加到 * * @param value the length of the value */ void update(int value); /** * Adds a recorded value. * * @param value the length of the value */ void update(long value); }
524