max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
493
<filename>oss_src/perf/memory_info.hpp /** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ /** * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef GRAPHLAB_MEMORY_INFO_HPP #define GRAPHLAB_MEMORY_INFO_HPP #include <string> #include <cstdint> #include <iostream> #ifdef HAS_TCMALLOC #include <google/malloc_extension.h> #endif #include <logger/assertions.hpp> namespace graphlab { /** * \internal \brief Memory info namespace contains functions used to * compute memory usage. * * The memory info functions require TCMalloc to actually compute * memory usage values. If TCMalloc is not present then calls to * memory info will generate warnings and return the default value. */ namespace memory_info { /** * \internal * * \brief Returns whether memory info reporting is * available on this system (if memory_info was built with TCMalloc) * * @return if memory info is available on this system. */ inline bool available() { #ifdef HAS_TCMALLOC return true; #else return false; #endif } /** * \internal * * \brief Estimates the total current size of the memory heap in * bytes. If memory info is not available then 0 is returned. * * @return size of heap in bytes */ inline size_t heap_bytes() { size_t heap_size(0); #ifdef HAS_TCMALLOC MallocExtension::instance()-> GetNumericProperty("generic.heap_size", &heap_size); #else logstream(LOG_WARNING) << "memory_info::heap_bytes() requires tcmalloc" << std::endl; #endif return heap_size; } /** * \internal * * \brief Determines the total number of allocated bytes. If * memory info is not available then 0 is returned. * * @return the total bytes allocated */ inline size_t allocated_bytes() { size_t allocated_size(0); #ifdef HAS_TCMALLOC MallocExtension::instance()-> GetNumericProperty("generic.current_allocated_bytes", &allocated_size); #else logstream_once(LOG_WARNING) << "memory_info::allocated_bytes() requires tcmalloc" << std::endl; #endif return allocated_size; } /** * \internal * * \brief Print a memory usage summary prefixed by the string * argument. * * @param [in] label the string to print before the memory usage summary. */ inline void print_usage(const std::string& label = "") { #ifdef HAS_TCMALLOC const double BYTES_TO_MB = double(1) / double(1024 * 1024); std::cerr << "Memory Info: " << label << std::endl << "\t Heap: " << (heap_bytes() * BYTES_TO_MB) << " MB" << std::endl << "\t Allocated: " << (allocated_bytes() * BYTES_TO_MB) << " MB" << std::endl; #else logstream_once(LOG_WARNING) << "Unable to print memory info for: " << label << ". " << "No memory extensions api available." << std::endl; #endif } /** * \internal * * \brief Log a memory usage summary prefixed by the string * argument. * * @param [in] label the string to print before the memory usage summary. */ inline void log_usage(const std::string& label = "") { #ifdef HAS_TCMALLOC const double BYTES_TO_MB = double(1) / double(1024 * 1024); logstream(LOG_INFO) << "Memory Info: " << label << "\n\t Heap: " << (heap_bytes() * BYTES_TO_MB) << " MB" << "\n\t Allocated: " << (allocated_bytes() * BYTES_TO_MB) << " MB" << std::endl; #else logstream_once(LOG_WARNING) << "Unable to print memory info for: " << label << ". " << "No memory extensions api available." << std::endl; #endif } } // end of namespace memory info }; #endif
1,808
1,056
package org.netbeans.test.java.hints; import java.io.IOException; public class AddThrowsClause4 { public AddThrowsClause4() { } public void test() { throw exc(); System.out.println(""); } public IOException exc() { return new IOException(); } }
138
2,338
<reponame>mkinsner/llvm int a [[gnu::used]]; // RUN: %clang_cc1 -code-completion-at=%s:1:9 %s | FileCheck --check-prefix=STD %s // STD: COMPLETION: Pattern : __carries_dependency__ // STD-NOT: COMPLETION: Pattern : __convergent__ // STD: COMPLETION: Pattern : __gnu__::__used__ // STD-NOT: COMPLETION: Pattern : __gnu__::used // STD-NOT: COMPLETION: Pattern : __used__ // STD: COMPLETION: Pattern : _Clang::__convergent__ // STD: COMPLETION: Pattern : carries_dependency // STD-NOT: COMPLETION: Pattern : clang::called_once // STD: COMPLETION: Pattern : clang::convergent // STD-NOT: COMPLETION: Pattern : convergent // STD-NOT: COMPLETION: Pattern : gnu::__used__ // STD: COMPLETION: Pattern : gnu::abi_tag(<#Tags...#>) // STD: COMPLETION: Pattern : gnu::alias(<#Aliasee#>) // STD: COMPLETION: Pattern : gnu::used // STD-NOT: COMPLETION: Pattern : used // RUN: %clang_cc1 -code-completion-at=%s:1:9 -xobjective-c++ %s | FileCheck --check-prefix=STD-OBJC %s // STD-OBJC: COMPLETION: Pattern : clang::called_once // RUN: %clang_cc1 -code-completion-at=%s:1:14 %s | FileCheck --check-prefix=STD-NS %s // STD-NS-NOT: COMPLETION: Pattern : __used__ // STD-NS-NOT: COMPLETION: Pattern : carries_dependency // STD-NS-NOT: COMPLETION: Pattern : clang::convergent // STD-NS-NOT: COMPLETION: Pattern : convergent // STD-NS-NOT: COMPLETION: Pattern : gnu::used // STD-NS: COMPLETION: Pattern : used int b [[__gnu__::used]]; // RUN: %clang_cc1 -code-completion-at=%s:27:18 %s | FileCheck --check-prefix=STD-NSU %s // STD-NSU: COMPLETION: Pattern : __used__ // STD-NSU-NOT: COMPLETION: Pattern : used int c [[using gnu: used]]; // RUN: %clang_cc1 -code-completion-at=%s:32:15 %s | FileCheck --check-prefix=STD-USING %s // STD-USING: COMPLETION: __gnu__ // STD-USING: COMPLETION: _Clang // STD-USING-NOT: COMPLETION: Pattern : carries_dependency // STD-USING: COMPLETION: clang // STD-USING-NOT: COMPLETION: Pattern : clang:: // STD-USING-NOT: COMPLETION: Pattern : gnu:: // STD-USING: COMPLETION: gnu // RUN: %clang_cc1 -code-completion-at=%s:32:20 %s | FileCheck --check-prefix=STD-NS %s int d __attribute__((used)); // RUN: %clang_cc1 -code-completion-at=%s:43:22 %s | FileCheck --check-prefix=GNU %s // GNU: COMPLETION: Pattern : __carries_dependency__ // GNU: COMPLETION: Pattern : __convergent__ // GNU-NOT: COMPLETION: Pattern : __gnu__::__used__ // GNU: COMPLETION: Pattern : __used__ // GNU-NOT: COMPLETION: Pattern : _Clang::__convergent__ // GNU: COMPLETION: Pattern : carries_dependency // GNU-NOT: COMPLETION: Pattern : clang::convergent // GNU: COMPLETION: Pattern : convergent // GNU-NOT: COMPLETION: Pattern : gnu::used // GNU: COMPLETION: Pattern : used #pragma clang attribute push (__attribute__((internal_linkage)), apply_to=variable) int e; #pragma clang attribute pop // RUN: %clang_cc1 -code-completion-at=%s:56:46 %s | FileCheck --check-prefix=PRAGMA %s // PRAGMA: COMPLETION: Pattern : internal_linkage #ifdef MS_EXT int __declspec(thread) f; // RUN: %clang_cc1 -fms-extensions -DMS_EXT -code-completion-at=%s:63:16 %s | FileCheck --check-prefix=DS %s // DS-NOT: COMPLETION: Pattern : __convergent__ // DS-NOT: COMPLETION: Pattern : __used__ // DS-NOT: COMPLETION: Pattern : clang::convergent // DS-NOT: COMPLETION: Pattern : convergent // DS: COMPLETION: Pattern : thread // DS-NOT: COMPLETION: Pattern : used // DS: COMPLETION: Pattern : uuid [uuid("123e4567-e89b-12d3-a456-426614174000")] struct g; // RUN: %clang_cc1 -fms-extensions -DMS_EXT -code-completion-at=%s:73:2 %s | FileCheck --check-prefix=MS %s // MS-NOT: COMPLETION: Pattern : __uuid__ // MS-NOT: COMPLETION: Pattern : clang::convergent // MS-NOT: COMPLETION: Pattern : convergent // MS-NOT: COMPLETION: Pattern : thread // MS-NOT: COMPLETION: Pattern : used // MS: COMPLETION: Pattern : uuid #endif // MS_EXT void foo() { [[omp::sequence(directive(parallel), directive(critical))]] {} } // FIXME: support for omp attributes would be nice. // RUN: %clang_cc1 -fopenmp -code-completion-at=%s:84:5 %s | FileCheck --check-prefix=OMP-NS --allow-empty %s // OMP-NS-NOT: COMPLETION: omp // RUN: %clang_cc1 -fopenmp -code-completion-at=%s:84:10 %s | FileCheck --check-prefix=OMP-ATTR --allow-empty %s // OMP-ATTR-NOT: COMPLETION: Pattern : sequence // RUN: %clang_cc1 -fopenmp -code-completion-at=%s:84:19 %s | FileCheck --check-prefix=OMP-NESTED --allow-empty %s // OMP-NESTED-NOT: COMPLETION: Pattern : directive
1,713
4,535
// Copyright 2019, Intel Corporation #pragma once #include "tile/codegen/codegen.pb.h" #include "tile/codegen/compile_pass.h" namespace vertexai { namespace tile { namespace codegen { // Packages a block into a sub-block. // Creates passthrough refinements for the sub-block to access. class PackagePass final : public CompilePass { public: explicit PackagePass(const proto::PackagePass& options) : options_{options} {} void Apply(CompilerState* state) const final; private: proto::PackagePass options_; }; } // namespace codegen } // namespace tile } // namespace vertexai
178
4,262
/* * 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.camel.component.vertx.kafka.serde; import java.nio.ByteBuffer; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.support.DefaultExchange; import org.apache.camel.test.junit5.CamelTestSupport; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.ByteBufferSerializer; import org.apache.kafka.common.serialization.BytesSerializer; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.common.utils.Bytes; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class VertxKafkaTypeSerializerTest extends CamelTestSupport { @Test void testNormalTypes() { final Exchange exchange = new DefaultExchange(context); final Message message = exchange.getIn(); final Object convertedStringValue = VertxKafkaTypeSerializer.tryConvertToSerializedType(message, 12, StringSerializer.class.getName()); assertEquals("12", convertedStringValue); final Object convertedByteArr = VertxKafkaTypeSerializer.tryConvertToSerializedType(message, "test", ByteArraySerializer.class.getName()); assertTrue(convertedByteArr instanceof byte[]); final Object convertedByteBuffer = VertxKafkaTypeSerializer.tryConvertToSerializedType(message, "test", ByteBufferSerializer.class.getName()); assertTrue(convertedByteBuffer instanceof ByteBuffer); final Object convertedBytes = VertxKafkaTypeSerializer.tryConvertToSerializedType(message, "test", BytesSerializer.class.getName()); assertTrue(convertedBytes instanceof Bytes); final Object convertedFallback = VertxKafkaTypeSerializer.tryConvertToSerializedType(message, "test", "dummy"); assertEquals("test", convertedFallback); assertNull(VertxKafkaTypeSerializer.tryConvertToSerializedType(message, null, "dummy")); assertNull(VertxKafkaTypeSerializer.tryConvertToSerializedType(message, null, null)); assertEquals("test", VertxKafkaTypeSerializer.tryConvertToSerializedType(message, "test", null)); } }
1,037
4,054
<filename>eval/src/vespa/eval/instruction/generic_lambda.cpp // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_lambda.h" #include <vespa/eval/eval/llvm/compiled_function.h> #include <vespa/eval/eval/llvm/compile_cache.h> #include <assert.h> using namespace vespalib::eval::tensor_function; namespace vespalib::eval::instruction { using Instruction = InterpretedFunction::Instruction; using State = InterpretedFunction::State; namespace { //----------------------------------------------------------------------------- bool step_labels(double *labels, const ValueType &type) { for (size_t idx = type.dimensions().size(); idx-- > 0; ) { if ((labels[idx] += 1.0) < type.dimensions()[idx].size) { return true; } else { labels[idx] = 0.0; } } return false; } struct ParamProxy : public LazyParams { const SmallVector<double> &labels; const LazyParams &params; const std::vector<size_t> &bindings; ParamProxy(const SmallVector<double> &labels_in, const LazyParams &params_in, const std::vector<size_t> &bindings_in) : labels(labels_in), params(params_in), bindings(bindings_in) {} const Value &resolve(size_t idx, Stash &stash) const override { if (idx < labels.size()) { return stash.create<DoubleValue>(labels[idx]); } return params.resolve(bindings[idx - labels.size()], stash); } }; //----------------------------------------------------------------------------- struct CompiledParams { const ValueType &result_type; const std::vector<size_t> &bindings; size_t num_cells; CompileCache::Token::UP token; CompiledParams(const Lambda &lambda) : result_type(lambda.result_type()), bindings(lambda.bindings()), num_cells(result_type.dense_subspace_size()), token(CompileCache::compile(lambda.lambda(), PassParams::ARRAY)) { assert(lambda.lambda().num_params() == (result_type.dimensions().size() + bindings.size())); } }; template <typename CT> void my_compiled_lambda_op(InterpretedFunction::State &state, uint64_t param) { const CompiledParams &params = unwrap_param<CompiledParams>(param); SmallVector<double> args(params.result_type.dimensions().size() + params.bindings.size(), 0.0); double *bind_next = &args[params.result_type.dimensions().size()]; for (size_t binding: params.bindings) { *bind_next++ = state.params->resolve(binding, state.stash).as_double(); } auto fun = params.token->get().get_function(); ArrayRef<CT> dst_cells = state.stash.create_uninitialized_array<CT>(params.num_cells); CT *dst = &dst_cells[0]; do { *dst++ = fun(&args[0]); } while (step_labels(&args[0], params.result_type)); state.stack.push_back(state.stash.create<DenseValueView>(params.result_type, TypedCells(dst_cells))); } struct MyCompiledLambdaOp { template <typename CT> static auto invoke() { return my_compiled_lambda_op<CT>; } }; //----------------------------------------------------------------------------- struct InterpretedParams { const ValueType &result_type; const std::vector<size_t> &bindings; size_t num_cells; InterpretedFunction fun; InterpretedParams(const Lambda &lambda, const ValueBuilderFactory &factory) : result_type(lambda.result_type()), bindings(lambda.bindings()), num_cells(result_type.dense_subspace_size()), fun(factory, lambda.lambda().root(), lambda.types()) { assert(lambda.lambda().num_params() == (result_type.dimensions().size() + bindings.size())); } }; template <typename CT> void my_interpreted_lambda_op(InterpretedFunction::State &state, uint64_t param) { const InterpretedParams &params = unwrap_param<InterpretedParams>(param); SmallVector<double> labels(params.result_type.dimensions().size(), 0.0); ParamProxy param_proxy(labels, *state.params, params.bindings); InterpretedFunction::Context ctx(params.fun); ArrayRef<CT> dst_cells = state.stash.create_uninitialized_array<CT>(params.num_cells); CT *dst = &dst_cells[0]; do { *dst++ = params.fun.eval(ctx, param_proxy).as_double(); } while (step_labels(&labels[0], params.result_type)); state.stack.push_back(state.stash.create<DenseValueView>(params.result_type, TypedCells(dst_cells))); } struct MyInterpretedLambdaOp { template <typename CT> static auto invoke() { return my_interpreted_lambda_op<CT>; } }; //----------------------------------------------------------------------------- } // namespace <unnamed> Instruction GenericLambda::make_instruction(const tensor_function::Lambda &lambda_in, const ValueBuilderFactory &factory, Stash &stash) { const ValueType & result_type = lambda_in.result_type(); assert(result_type.count_mapped_dimensions() == 0); if (!CompiledFunction::detect_issues(lambda_in.lambda()) && lambda_in.types().all_types_are_double()) { // can do compiled version CompiledParams &params = stash.create<CompiledParams>(lambda_in); auto op = typify_invoke<1,TypifyCellType,MyCompiledLambdaOp>(result_type.cell_type()); return Instruction(op, wrap_param<CompiledParams>(params)); } else { InterpretedParams &params = stash.create<InterpretedParams>(lambda_in, factory); auto op = typify_invoke<1,TypifyCellType,MyInterpretedLambdaOp>(result_type.cell_type()); return Instruction(op, wrap_param<InterpretedParams>(params)); } } } // namespace
2,119
500
<reponame>thomasjpfan/dabl from sklearn.experimental import enable_halving_search_cv # noqa from sklearn.utils import deprecated from sklearn.model_selection import HalvingGridSearchCV as HalvingGridSearchCV from sklearn.model_selection import HalvingRandomSearchCV as \ HalvingRandomSearchCV __all__ = ['GridSuccessiveHalving', 'RandomSuccessiveHalving'] @deprecated("GridSuccessiveHalving was upstreamed to sklearn," " please import from sklearn.model_selection.") class GridSuccessiveHalving(HalvingGridSearchCV): pass @deprecated("RandomSuccessiveHalving was upstreamed to sklearn," " please import from sklearn.model_selection.") class RandomSuccessiveHalving(HalvingRandomSearchCV): pass
226
1,545
/** * 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.distributedlog; /** * The position of an entry, identified by log segment sequence number and entry id. */ class EntryPosition { private long lssn; private long entryId; EntryPosition(long lssn, long entryId) { this.lssn = lssn; this.entryId = entryId; } public synchronized long getLogSegmentSequenceNumber() { return lssn; } public synchronized long getEntryId() { return entryId; } public synchronized boolean advance(long lssn, long entryId) { if (lssn == this.lssn) { if (entryId <= this.entryId) { return false; } this.entryId = entryId; return true; } else if (lssn > this.lssn) { this.lssn = lssn; this.entryId = entryId; return true; } else { return false; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("(").append(lssn).append(", ").append(entryId).append(")"); return sb.toString(); } }
711
355
/* * Copyright 2011 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package net.tomp2p.connection; import java.util.Random; /** * Stores port information. * * @author <NAME> */ public class Ports { // The maximal port number, 2^16. public static final int MAX_PORT = 65535; //IANA recommends to use ports higher or equal 49152. public static final int MIN_DYN_PORT = 49152; // The default port of TomP2P. public static final int DEFAULT_PORT = 7700; private static final int RANGE = MAX_PORT - MIN_DYN_PORT; private static final Random RND = new Random(); // provide this information if you know your mapping beforehand // i.e., manual port-forwarding private final int tcpPort; private final int udpPort; private final boolean randomPorts; /** * Creates random ports for TCP and UDP. The random ports start from port 49152 */ public Ports() { this(-1, -1); } /** * Creates a Ports class that stores port information. * @param tcpPort The external TCP port, how other peers will see us. If the provided port is < 0, a random port will be used. * @param udpPort The external UDP port, how other peers will see us. If the provided port is < 0, a random port will be used. */ public Ports(final int tcpPort, final int udpPort) { this.randomPorts = tcpPort < 0 && udpPort < 0; this.tcpPort = tcpPort < 0 ? (RND.nextInt(RANGE) + MIN_DYN_PORT) : tcpPort; this.udpPort = udpPort < 0 ? (RND.nextInt(RANGE) + MIN_DYN_PORT) : udpPort; } /** * @return The external TCP port, how other peers see us. */ public int tcpPort() { return tcpPort; } /** * @return The external UDP port, how other peers see us. */ public int udpPort() { return udpPort; } /** * @return True, if the user specified both ports in advance. This tells us * that the user knows about the ports and did a manual * port-forwarding. */ public boolean isManualPort() { // set setExternalPortsManually to true if the user specified both ports // in advance. This tells us that the user knows about the ports and did // a manual port-forwarding. return !randomPorts; } }
974
319
/** * 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.feature.dense.gradient.dsift; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.StringTokenizer; import org.openimaj.feature.ByteFV; /** * Dense SIFT keypoint with a location and byte feature vector. Also includes * the energy of the feature prior to normalisation in case low-contrast * features need removing. * * @author <NAME> (<EMAIL>) * */ public class ByteDSIFTKeypoint extends AbstractDSIFTKeypoint<ByteFV, byte[]> { static final long serialVersionUID = 12345545L; /** * Construct with the default feature vector length for SIFT (128). */ public ByteDSIFTKeypoint() { this(DEFAULT_LENGTH); } /** * Construct with the given feature vector length. * * @param length * the length of the feature vector */ public ByteDSIFTKeypoint(final int length) { this.descriptor = new byte[length]; } /** * Construct with the given parameters. * * @param x * the x-ordinate of the keypoint * @param y * the y-ordinate of the keypoint * @param descriptor * the feature vector of the keypoint * @param energy * the energy of the keypoint */ public ByteDSIFTKeypoint(final float x, final float y, final byte[] descriptor, final float energy) { this.x = x; this.y = y; this.descriptor = descriptor; this.energy = energy; } /** * Construct with the given parameters. The float version of the descriptor * is converted to bytes by multiplying each bin by 512, clipping to 255 and * then subtracting 128. * * @param x * the x-ordinate of the keypoint * @param y * the y-ordinate of the keypoint * @param fdescriptor * the flaot version of feature vector of the keypoint * @param energy * the energy of the keypoint */ public ByteDSIFTKeypoint(final float x, final float y, final float[] fdescriptor, final float energy) { this.x = x; this.y = y; this.energy = energy; this.descriptor = new byte[fdescriptor.length]; for (int i = 0; i < descriptor.length; i++) { final int intval = (int) (512.0 * fdescriptor[i]); descriptor[i] = (byte) (Math.min(255, intval) - 128); } } @Override public ByteFV getFeatureVector() { return new ByteFV(descriptor); } @Override public String toString() { return ("ByteDSIFTKeypoint(" + this.x + ", " + this.y + ")"); } @Override public void writeBinary(DataOutput out) throws IOException { out.writeFloat(x); out.writeFloat(y); out.writeFloat(energy); out.write(this.descriptor); } @Override public void writeASCII(PrintWriter out) throws IOException { /* Output data for the keypoint. */ out.write(x + " " + y + " " + energy + "\n"); for (int i = 0; i < descriptor.length; i++) { if (i > 0 && i % 20 == 0) out.println(); out.print(" " + (descriptor[i] + 128)); } out.println(); } @Override public void readBinary(DataInput in) throws IOException { x = in.readFloat(); y = in.readFloat(); energy = in.readFloat(); in.readFully(descriptor); } @Override public void readASCII(Scanner in) throws IOException { x = in.nextFloat(); y = in.nextFloat(); energy = in.nextFloat(); int i = 0; while (i < descriptor.length) { final String line = in.nextLine(); final StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { descriptor[i] = (byte) (Integer.parseInt(st.nextToken()) - 128); i++; } } } }
1,782
1,801
<reponame>xzou999/Multitarget-tracker<filename>src/Tracker/graph/GTL/include/GTL/dijkstra.h /* This software is distributed under the GNU Lesser General Public License */ //========================================================================== // // dijkstra.h // //========================================================================== // $Id: dijkstra.h,v 1.8 2003/02/25 09:18:19 chris Exp $ #ifndef GTL_DIJKSTRA_H #define GTL_DIJKSTRA_H #include <GTL/GTL.h> #include <GTL/graph.h> #include <GTL/node_map.h> #include <GTL/edge_map.h> #include <GTL/algorithm.h> __GTL_BEGIN_NAMESPACE /** * @brief Dijkstra's Algorithm for computing single source shortest path. * * This class implements Dijkstra's algorithm for computing single source * shortest path in @f$\mathcal{O}((|V| + |E|) log |V|)@f$ worst case. * * @sa bellman_ford * * @author <NAME> <EMAIL> */ class GTL_EXTERN dijkstra final : public algorithm { public: /** * @brief Iterator type for traversing %nodes on one shortest path. */ typedef nodes_t::const_iterator shortest_path_node_iterator; /** * @brief Iterator type for traversing %edges on one shortest path. */ typedef edges_t::const_iterator shortest_path_edge_iterator; /** * @internal */ enum node_color {white, grey, black}; /** * @brief Default constructor. * * Enables only the calculation of shortest paths. * * @sa algorithm::algorithm */ dijkstra(); /** * @brief Destructor. * * @sa algorithm::~algorithm */ virtual ~dijkstra(); /** * @brief Sets source %node. * * The default source is the invalid %node (GTL::node::node()), * in this case an arbitrary %node is chosen and stored when * this algorithm is run. * * @param n source node */ void source(const node& n); /** * @brief Sets target %node. * * If a target is set with this method the %algorithm stops if a * shortest distance to @p n is found. Ohterwise shortest paths are * computed from source to any %node in the %graph. * * @param n target node */ void target(const node& n); /** * @brief Sets weights of the edges. * * This method @b must be called before check run. * * @param weight weights of the %edges */ void weights(const edge_map<double>& weight); /** * @brief Enables or disables the storing of predecessors. * * If enabled for every %node the predecessor on the shortest * path from will be stored. * * @param set @c true if predecessors should be stored * * @sa dijkstra::predecessor_node * @sa dijkstra::predecessor_edge */ void store_preds(bool set); /** * @brief Checks whether the preconditions for Dijkstra are satisfied. * * Necessary preconditions are: * - the weights of the edges are set * - the %graph @p G has at least one %node * - all %edge weights must be \f$\ge 0\f$ * - the source %node and (if set) target %node must be found in @p G * * @param G graph * * @retval algorithm::GTL_OK if %algorithm can be applied * @retval algorithm::GTL_ERROR otherwise * * @sa dijkstra::source * @sa dijkstra::weights * @sa algorithm::check */ virtual int check(GTL::graph& G); /** * @brief Runs shortest path %algorithm on @p G. * * This should return always algorithm::GTL_OK. The return value only * tracks errors that might occur. * Afterwards the result of the test can be accessed via access methods. * * @param G graph * * @retval algorithm::GTL_OK on success * @retval algorithm::GTL_ERROR otherwise * * @sa algorithm::run */ int run(GTL::graph& G); /** * @brief Returns source %node. * * @return source %node */ node source() const; /** * @brief Returns target %node if set, <code>node::node()</code> else. * * @return target %node */ node target() const; /** * @brief Returns whether the storing of predecessors is enabled. * * @return @c true iff the storing of predecessors is enabled * * @sa dijkstra::predecessor */ bool store_preds() const; /** * @brief Returns whether @p n is reachable from source %node. * * @param n node * * @return @c true iff @p n was reached from source */ bool reached(const node& n) const; /** * @brief Returns the distance from source %node to %node @p n. * * @param n node * * @return distance if @p n is dijkstra::reached, <code>-1.0</code> else */ double distance(const node& n) const; /** * @brief Predecessor %node of %node @p n on the shortest path from the * source %node. * * If @p n is a root or wasn't reached the return value is * the invalid %node node::node(). * * @param n node * * @return predecessor %node of @p n * * @sa dijkstra::store_preds * @sa dijkstra::predecessor_edge * * @note The method requires that predecessor calculation option was * enabled during last run. */ node predecessor_node(const node& n) const; /** * @brief Predecessor %edge of %node @p n on the shortest path from the * source %node. * * If @p n is a root or wasn't reached the return value is * the invalid %edge edge::edge(). * * @param n node * * @return predecessor %edge of @p n * * @sa dijkstra::store_preds * @sa dijkstra::predecessor_node * * @note The method requires that predecessor calculation option was * enabled during last run. */ edge predecessor_edge(const node& n) const; /** * @brief Returns an iterator to the beginning (to the source %node) of * a shortest %node path to %node @p dest. * * @param dest target %node * * @return beginning %node iterator of a shortest path * * @note The method requires that predecessor calculation option was * enabled during last run. If this method is called on the shortest * path to @p dest for the first time (before * dijkstra::shortest_path_nodes_end) it needs * @f$\mathcal{O}(\mbox{length of this path})@f$ time. */ shortest_path_node_iterator shortest_path_nodes_begin(const node& dest); /** * @brief Returns an iterator one after the end (one after * %node @p dest) of a shortest %node path to %node @p dest. * * @param dest target %node * * @return shortest path end %node iterator * * @note The method requires that predecessor calculation option was * enabled during last run. If this method is called on the shortest * path to @p dest for the first time (before * dijkstra::shortest_path_nodes_begin) it needs * @f$\mathcal{O}(\mbox{length of this path})@f$ time. */ shortest_path_node_iterator shortest_path_nodes_end(const node& dest); /** * @brief Returns an iterator to the beginning %edge of a shortest %edge * path to %node @p dest. * * @param dest target %node * * @return beginning %edge iterator of a shortest path * * @note The method requires that predecessor calculation option was * enabled during last run. If this method is called on the shortest * path to @p dest for the first time (before * dijkstra::shortest_path_edges_end) it needs * @f$\mathcal{O}(\mbox{length of this path})@f$ time. */ shortest_path_edge_iterator shortest_path_edges_begin(const node& dest); /** * @brief Returns an iterator one after the end of a shortest %edge path * to %node @p dest. * * @param dest target %node * * @return shortest path end %edge iterator * * @note The method requires that predecessor calculation option was * enabled during last run. If this method is called on the shortest * path to @p dest for the first time (before * dijkstra::shortest_path_edges_begin) it needs * @f$\mathcal{O}(\mbox{length of this path})@f$ time. */ shortest_path_edge_iterator shortest_path_edges_end(const node& dest); /** * @brief Resets Dijkstra's algorithm. * * It prepares the algorithm to be applied again, possibly to another * graph. * * @note The weights are not reset. You can apply this algorithms * * @sa algorithm::reset */ virtual void reset(); private: /** * @internal * Stores source. * * @sa dijkstra::source. */ node s; /** * @internal * Stores target. * * @sa dijkstra::source. */ node t; /** * @internal * Indicates whether weights were set. * * @sa dijkstra::weights. */ bool weights_set; /** * @internal * Indicates whether predecessors should be computed. * * @sa dijkstra::store_preds. */ bool preds_set; /** * @internal * Stores the weights of the %edges. * * @sa dijkstra::weights. */ edge_map<double> weight; /** * @internal * Stores father of each %node in shortest path tree (if enabled). * (default: edge() (if enabled)) * * @sa dijkstra::store_preds */ node_map<edge> pred; /** * @internal * Indicates the current %node status. * (default: black) */ node_map<int> mark; /** * @internal * Distance from source @a s. * (default: -1) * * @sa dijkstra::distance. */ node_map<double> dist; /** * @internal * Stores for every target %node a list of nodes on the shortest path * from source @a s to it. Filled on demand by methods creating * iterators. * (default: empty) * * @sa dijkstra::shortest_path_nodes_begin * @sa dijkstra::shortest_path_nodes_end */ node_map<nodes_t> shortest_path_node_list; /** * @internal * Stores for every target node a list of edges on the shortest path * from source @a s to it. Filled on demand by methods creating * iterators. * (default: empty) * * @sa dijkstra::shortest_path_edges_begin * @sa dijkstra::shortest_path_edges_end */ node_map<edges_t> shortest_path_edge_list; /** * @internal * Prepares the %algorithm to be applied once again. */ void reset_algorithm(); /** * @internal * Inits data structure. */ void init(GTL::graph& G); /** * @internal * Fills ordered list <code>shortest_path_node_list[t]</code> * with nodes of shortest path from @a s to @p t. */ void fill_node_list(const node& t); /** * @internal * Fills ordered list <code>shortest_path_edge_list[t]</code> * with edges of shortest path from @a s to @p t. */ void fill_edge_list(const node& t); }; __GTL_END_NAMESPACE #endif // GTL_DIJKSTRA_H //-------------------------------------------------------------------------- // end of file //--------------------------------------------------------------------------
4,943
704
<filename>scripts/aggregate_by_category.py """ Sums up popularity for all stocks by category and computes aggregate popularity history for each category """ from datetime import datetime import os from python_common.db import get_db def get_day_id(dt: datetime) -> str: return f"{dt.year}-{dt.month:02}-{dt.day:02}" def get_all_stock_fundamentals(): """ Returns a dict mapping instrument id to stock fundamentals """ db = get_db() fundamentals_by_instrument_id = dict() all_fundamentals = list(db["fundamentals"].find()) for f in all_fundamentals: fundamentals_by_instrument_id[f["instrument_id"]] = f return fundamentals_by_instrument_id def main(): fundamentals_by_instrument_id = get_all_stock_fundamentals() # sector -> instrument_id -> dayId -> popularity updates_by_sector = dict() # industry -> instrument_id -> dayId -> popularity updates_by_industry = dict() all_day_ids = set() db = get_db() for update in db["popularity"].find().sort("timestamp"): fundamentals = fundamentals_by_instrument_id.get(update["instrument_id"]) if fundamentals is None: continue day_id = get_day_id(update["timestamp"]) instrument_id = update["instrument_id"] sector = fundamentals["sector"] if sector is not None: if updates_by_sector.get(sector) is None: updates_by_sector[sector] = dict() if updates_by_sector[sector].get(instrument_id) is None: updates_by_sector[sector][instrument_id] = dict() if updates_by_sector[sector][instrument_id].get(day_id) is None: updates_by_sector[sector][instrument_id][day_id] = update["popularity"] industry = fundamentals["sector"] if industry is not None: if updates_by_industry.get(industry) is None: updates_by_industry[industry] = dict() if updates_by_industry[industry].get(instrument_id) is None: updates_by_industry[industry][instrument_id] = dict() if updates_by_industry[industry][instrument_id].get(day_id) is None: updates_by_industry[industry][instrument_id][day_id] = update["popularity"] if industry is not None and sector is not None: if day_id not in all_day_ids: print(day_id) all_day_ids.add(day_id) print("Finished scrolling all updates; starting to aggregate by popularity") # sector -> day_id -> popularity pop_by_sector = dict() # industry -> day_id -> popularity pop_by_industry = dict() # Sum it all up for day_id in sorted(all_day_ids): for (sector, updates_by_instrument_id) in updates_by_sector.items(): if pop_by_sector.get(sector) is None: pop_by_sector[sector] = dict() pop_by_sector[sector][day_id] = 0 for (instrument_id, pop_by_day_id) in updates_by_instrument_id.items(): pop = pop_by_day_id.get(day_id) if pop is None: continue pop_by_sector[sector][day_id] += pop for (industry, updates_by_instrument_id) in updates_by_industry.items(): if pop_by_industry.get(industry) is None: pop_by_industry[industry] = dict() pop_by_industry[industry][day_id] = 0 for (instrument_id, pop_by_day_id) in updates_by_instrument_id.items(): pop = pop_by_day_id.get(day_id) if pop is None: continue pop_by_industry[industry][day_id] += pop # Dump it all to CSV, one for each sector if not os.path.isdir("/tmp/out"): os.mkdir("/tmp/out") for (sector, vals) in pop_by_sector.items(): # Adapted from https://stackoverflow.com/a/295152/3833068 normalized_sector = "".join( x for x in sector.replace(" ", "-").replace("&", "and") if x.isalnum() or x == "-" ) with open(f"/tmp/out/sector_{normalized_sector}.csv", "w") as f: for (day_id, pop) in sorted(vals.items(), key=lambda x: x[0]): f.write(f"{day_id},{pop}\n") for (sector, vals) in pop_by_industry.items(): # Adapted from https://stackoverflow.com/a/295152/3833068 normalized_industry = "".join( x for x in sector.replace(" ", "-").replace("&", "and") if x.isalnum() or x == "-" ) with open(f"/tmp/out/industry_{normalized_industry}.csv", "w") as f: for (day_id, pop) in sorted(vals.items(), key=lambda x: x[0]): f.write(f"{day_id},{pop}\n") main()
2,100
5,119
#include "gmock/gmock.h" #include "gtest/gtest.h" #include <time.h> #include "child.h" #include "procmon.h" #include "childhelper.h" namespace bpftrace { namespace test { namespace procmon { using ::testing::HasSubstr; TEST(procmon, no_such_proc) { try { ProcMon(1 << 21); FAIL(); } catch (const std::runtime_error &e) { EXPECT_THAT(e.what(), HasSubstr("No such process")); } } TEST(procmon, child_terminates) { auto child = getChild("/bin/ls"); auto procmon = std::make_unique<ProcMon>(child->pid()); EXPECT_TRUE(procmon->is_alive()); child->run(); wait_for(child.get(), 1000); EXPECT_FALSE(child->is_alive()); EXPECT_FALSE(procmon->is_alive()); EXPECT_FALSE(procmon->is_alive()); } TEST(procmon, pid_string) { auto child = getChild("/bin/ls"); auto procmon = std::make_unique<ProcMon>(std::to_string(child->pid())); EXPECT_TRUE(procmon->is_alive()); } } // namespace procmon } // namespace test } // namespace bpftrace
402
14,668
<gh_stars>1000+ // 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. #ifndef IOS_CHROME_BROWSER_UI_AUTHENTICATION_SIGNIN_CONSISTENCY_PROMO_SIGNIN_CONSISTENCY_DEFAULT_ACCOUNT_CONSISTENCY_DEFAULT_ACCOUNT_COORDINATOR_H_ #define IOS_CHROME_BROWSER_UI_AUTHENTICATION_SIGNIN_CONSISTENCY_PROMO_SIGNIN_CONSISTENCY_DEFAULT_ACCOUNT_CONSISTENCY_DEFAULT_ACCOUNT_COORDINATOR_H_ #import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" @class ChromeIdentity; @class ConsistencyDefaultAccountCoordinator; @protocol ConsistencyLayoutDelegate; @protocol ConsistencyDefaultAccountCoordinatorDelegate <NSObject> // Called when the last identity has been removed (by another app). - (void)consistencyDefaultAccountCoordinatorAllIdentityRemoved: (ConsistencyDefaultAccountCoordinator*)coordinator; // Called when the user wants to skip the consistency promo. - (void)consistencyDefaultAccountCoordinatorSkip: (ConsistencyDefaultAccountCoordinator*)coordinator; // Called when the user wants to choose a different identity. - (void)consistencyDefaultAccountCoordinatorOpenIdentityChooser: (ConsistencyDefaultAccountCoordinator*)coordinator; // Called when the user wants to sign-in with the default identity. - (void)consistencyDefaultAccountCoordinatorSignin: (ConsistencyDefaultAccountCoordinator*)coordinator; @end // This coordinator presents an entry point to the Chrome sign-in flow with the // default account available on the device. @interface ConsistencyDefaultAccountCoordinator : ChromeCoordinator @property(nonatomic, strong, readonly) UIViewController* viewController; @property(nonatomic, weak) id<ConsistencyDefaultAccountCoordinatorDelegate> delegate; @property(nonatomic, weak) id<ConsistencyLayoutDelegate> layoutDelegate; // This property can be used only after the coordinator is started. @property(nonatomic, strong) ChromeIdentity* selectedIdentity; // Starts the spinner and disables buttons. - (void)startSigninSpinner; // Stops the spinner and enables buttons. - (void)stopSigninSpinner; @end #endif // IOS_CHROME_BROWSER_UI_AUTHENTICATION_SIGNIN_CONSISTENCY_PROMO_SIGNIN_CONSISTENCY_DEFAULT_ACCOUNT_CONSISTENCY_DEFAULT_ACCOUNT_COORDINATOR_H_
718
5,169
<reponame>Ray0218/Specs { "name": "HicoolFoundation", "version": "0.0.3", "summary": "HicoolFoundation.", "description": "HicoolFoundation is a private library", "homepage": "https://github.com/jindegege/HicoolFoundation", "license": "MIT", "authors": { "jindegege": "<EMAIL>" }, "platforms": { "ios": "5.0" }, "source": { "git": "https://github.com/jindegege/HicoolFoundation.git", "tag": "0.0.3" }, "source_files": "HicoolFoundation/*.{h,m,c}", "exclude_files": "Classes/Exclude", "frameworks": [ "CoreFoundation", "CoreGraphics" ], "libraries": [ "bz2.1.0", "z" ] }
293
1,998
/* * SPDX-License-Identifier: Apache-2.0 */ #include "LoopHelpers.hpp" #include "onnx2trt_utils.hpp" namespace onnx2trt { nvinfer1::ITensor* addLoopCounter(IImporterContext* ctx, nvinfer1::ILoop* loop, int32_t initial) { nvinfer1::ITensor* initialTensor = addConstantScalar(ctx, initial, ::ONNX_NAMESPACE::TensorProto::INT32, nvinfer1::Dims{1, 1})->getOutput(0); nvinfer1::ITensor* one = addConstantScalar(ctx, 1, ::ONNX_NAMESPACE::TensorProto::INT32, nvinfer1::Dims{1, 1})->getOutput(0); auto counter = loop->addRecurrence(*initialTensor); nvinfer1::ITensor* addOne = ctx->network()->addElementWise(*counter->getOutput(0), *one, nvinfer1::ElementWiseOperation::kSUM)->getOutput(0); counter->setInput(1, *addOne); return counter->getOutput(0); } } // namespace onnx2trt
336
2,338
<filename>openmp/runtime/test/tasking/kmp_taskwait_depend_all.c // RUN: %libomp-compile-and-run // The runtime currently does not get dependency information from GCC. // UNSUPPORTED: gcc // Tests OMP 5.x task dependence "omp_all_memory", // emulates compiler codegen versions for new dep kind // // Task tree created: // task0 - task1 (in: i1, i2) // \ // task2 (inoutset: i2), (in: i1) // / // task3 (omp_all_memory) via flag=0x80 // / // task4 - task5 (in: i1, i2) // / // task6 (omp_all_memory) via addr=-1 // / // task7 (omp_all_memory) via flag=0x80 // / // task8 (in: i3) // / // task9 - no dependences // / // taskwait (omp_all_memory) (should not wait for task9, see prints) // #include <stdio.h> #include <omp.h> #ifdef _WIN32 #include <windows.h> #define mysleep(n) Sleep(n) #else #include <unistd.h> #define mysleep(n) usleep((n)*1000) #endif // to check the # of concurrent tasks (must be 1 for MTX, <3 for other kinds) static int checker = 0; static int err = 0; static int taskwait_flag = 0; #ifndef DELAY // set delay interval in ms for dependent tasks #define DELAY 100 #endif // --------------------------------------------------------------------------- // internal data to emulate compiler codegen typedef struct DEP { size_t addr; size_t len; unsigned char flags; } dep; #define DEP_ALL_MEM 0x80 typedef struct task { void** shareds; void* entry; int part_id; void* destr_thunk; int priority; long long device_id; int f_priv; } task_t; #define TIED 1 typedef int(*entry_t)(int, task_t*); typedef struct ID { int reserved_1; int flags; int reserved_2; int reserved_3; char *psource; } id; // thunk routine for tasks with ALL dependency int thunk_m(int gtid, task_t* ptask) { int lcheck, th; #pragma omp atomic capture lcheck = ++checker; th = omp_get_thread_num(); printf("task m_%d, th %d, checker %d\n", ptask->f_priv, th, lcheck); if (lcheck != 1) { // no more than 1 task at a time err++; printf("Error m1, checker %d != 1\n", lcheck); } mysleep(DELAY); #pragma omp atomic read lcheck = checker; // must still be equal to 1 if (lcheck != 1) { err++; printf("Error m2, checker %d != 1\n", lcheck); } #pragma omp atomic --checker; return 0; } // thunk routine for tasks with inoutset dependency int thunk_s(int gtid, task_t* ptask) { int lcheck, th; #pragma omp atomic capture lcheck = ++checker; // 1 th = omp_get_thread_num(); printf("task 2_%d, th %d, checker %d\n", ptask->f_priv, th, lcheck); if (lcheck != 1) { // no more than 1 task at a time err++; printf("Error s1, checker %d != 1\n", lcheck); } mysleep(DELAY); #pragma omp atomic read lcheck = checker; // must still be equal to 1 if (lcheck != 1) { err++; printf("Error s2, checker %d != 1\n", lcheck); } #pragma omp atomic --checker; return 0; } #ifdef __cplusplus extern "C" { #endif int __kmpc_global_thread_num(id*); task_t *__kmpc_omp_task_alloc(id *loc, int gtid, int flags, size_t sz, size_t shar, entry_t rtn); int __kmpc_omp_task_with_deps(id *loc, int gtid, task_t *task, int ndeps, dep *dep_lst, int nd_noalias, dep *noalias_lst); void __kmpc_omp_wait_deps(id *loc, int gtid, int ndeps, dep *dep_lst, int ndeps_noalias, dep *noalias_dep_lst); static id loc = {0, 2, 0, 0, ";file;func;0;0;;"}; #ifdef __cplusplus } // extern "C" #endif // End of internal data // --------------------------------------------------------------------------- int main() { int i1,i2,i3; omp_set_num_threads(8); omp_set_dynamic(0); #pragma omp parallel { #pragma omp single nowait { dep sdep[2]; task_t *ptr; int gtid = __kmpc_global_thread_num(&loc); int t = omp_get_thread_num(); // Create longest task first to ensure it is stolen. // The test may hang if the task created last and // executed by a thread which executes taskwait. #pragma omp task { // task 9 - long running task int flag; int th = omp_get_thread_num(); printf("signalled independent task 9_%d, th %d started....\n", t, th); // Wait for taskwait depend() to finish // If the taskwait depend() improperly depends on this task // to finish, then the test will hang and a timeout should trigger while (1) { #pragma omp atomic read flag = taskwait_flag; if (flag == 1) break; } printf("signalled independent task 9_%d, th %d finished....\n", t, th); } #pragma omp task depend(in: i1, i2) { // task 0 int lcheck, th; #pragma omp atomic capture lcheck = ++checker; // 1 or 2 th = omp_get_thread_num(); printf("task 0_%d, th %d, checker %d\n", t, th, lcheck); if (lcheck > 2 || lcheck < 1) { err++; // no more than 2 tasks concurrently printf("Error1, checker %d, not 1 or 2\n", lcheck); } mysleep(DELAY); #pragma omp atomic read lcheck = checker; // 1 or 2 if (lcheck > 2 || lcheck < 1) { #pragma omp atomic err++; printf("Error2, checker %d, not 1 or 2\n", lcheck); } #pragma omp atomic --checker; } #pragma omp task depend(in: i1, i2) { // task 1 int lcheck, th; #pragma omp atomic capture lcheck = ++checker; // 1 or 2 th = omp_get_thread_num(); printf("task 1_%d, th %d, checker %d\n", t, th, lcheck); if (lcheck > 2 || lcheck < 1) { err++; // no more than 2 tasks concurrently printf("Error3, checker %d, not 1 or 2\n", lcheck); } mysleep(DELAY); #pragma omp atomic read lcheck = checker; // 1 or 2 if (lcheck > 2 || lcheck < 1) { err++; printf("Error4, checker %d, not 1 or 2\n", lcheck); } #pragma omp atomic --checker; } // compiler codegen start // task2 ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_s); sdep[0].addr = (size_t)&i1; sdep[0].len = 0; // not used sdep[0].flags = 1; // IN sdep[1].addr = (size_t)&i2; sdep[1].len = 0; // not used sdep[1].flags = 8; // INOUTSET ptr->f_priv = t + 10; // init single first-private variable __kmpc_omp_task_with_deps(&loc, gtid, ptr, 2, sdep, 0, 0); // task3 ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_m); sdep[0].addr = (size_t)&i1; // to be ignored sdep[0].len = 0; // not used sdep[0].flags = 1; // IN sdep[1].addr = 0; sdep[1].len = 0; // not used sdep[1].flags = DEP_ALL_MEM; // omp_all_memory ptr->f_priv = t + 20; // init single first-private variable __kmpc_omp_task_with_deps(&loc, gtid, ptr, 2, sdep, 0, 0); // compiler codegen end #pragma omp task depend(in: i1, i2) { // task 4 int lcheck, th; #pragma omp atomic capture lcheck = ++checker; // 1 or 2 th = omp_get_thread_num(); printf("task 4_%d, th %d, checker %d\n", t, th, lcheck); if (lcheck > 2 || lcheck < 1) { err++; // no more than 2 tasks concurrently printf("Error5, checker %d, not 1 or 2\n", lcheck); } mysleep(DELAY); #pragma omp atomic read lcheck = checker; // 1 or 2 if (lcheck > 2 || lcheck < 1) { err++; printf("Error6, checker %d, not 1 or 2\n", lcheck); } #pragma omp atomic --checker; } #pragma omp task depend(in: i1, i2) { // task 5 int lcheck, th; #pragma omp atomic capture lcheck = ++checker; // 1 or 2 th = omp_get_thread_num(); printf("task 5_%d, th %d, checker %d\n", t, th, lcheck); if (lcheck > 2 || lcheck < 1) { err++; // no more than 2 tasks concurrently printf("Error7, checker %d, not 1 or 2\n", lcheck); } mysleep(DELAY); #pragma omp atomic read lcheck = checker; // 1 or 2 if (lcheck > 2 || lcheck < 1) { err++; printf("Error8, checker %d, not 1 or 2\n", lcheck); } #pragma omp atomic --checker; } // compiler codegen start // task6 ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_m); sdep[0].addr = (size_t)(-1); // omp_all_memory sdep[0].len = 0; // not used sdep[0].flags = 2; // OUT ptr->f_priv = t + 30; // init single first-private variable __kmpc_omp_task_with_deps(&loc, gtid, ptr, 1, sdep, 0, 0); // task7 ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_m); sdep[0].addr = 0; sdep[0].len = 0; // not used sdep[0].flags = DEP_ALL_MEM; // omp_all_memory sdep[1].addr = (size_t)&i3; // to be ignored sdep[1].len = 0; // not used sdep[1].flags = 4; // MUTEXINOUTSET ptr->f_priv = t + 40; // init single first-private variable __kmpc_omp_task_with_deps(&loc, gtid, ptr, 2, sdep, 0, 0); // compiler codegen end #pragma omp task depend(in: i3) { // task 8 int lcheck, th; #pragma omp atomic capture lcheck = ++checker; // 1 th = omp_get_thread_num(); printf("task 8_%d, th %d, checker %d\n", t, th, lcheck); if (lcheck != 1) { err++; printf("Error9, checker %d, != 1\n", lcheck); } mysleep(DELAY); #pragma omp atomic read lcheck = checker; if (lcheck != 1) { err++; printf("Error10, checker %d, != 1\n", lcheck); } #pragma omp atomic --checker; } mysleep(1); // wait a bit to ensure at least first task is stolen // #pragma omp taskwait depend(omp_all_memory: out) printf("all 10 tasks generated;\n" "taskwait depend(omp_all_memory: out) started, th %d\n", t); __kmpc_omp_wait_deps(&loc, gtid, 1, sdep, 0, 0); #pragma omp atomic write taskwait_flag = 1; printf("taskwait depend(omp_all_memory: out) passed, th %d\n", t); fflush(0); } // single } // parallel if (err == 0 && checker == 0) { printf("passed\n"); return 0; } else { printf("failed, err = %d, checker = %d\n", err, checker); return 1; } }
5,115
5,169
<reponame>Ray0218/Specs { "name": "HCharts", "version": "0.1.0", "summary": "HCharts is a powerful & easy to use chart library for iOS", "homepage": "https://github.com/anthony0926/HChart", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/anthony0926/HChart.git", "tag": "0.1.0" }, "source_files": "HCharts/**/*.{swift}" }
219
14,668
<filename>media/capture/video/video_capture_buffer_pool_util.cc<gh_stars>1000+ // 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 "media/capture/video/video_capture_buffer_pool_util.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "media/capture/capture_switches.h" namespace media { int DeviceVideoCaptureMaxBufferPoolSize() { // The maximum number of video frame buffers in-flight at any one time. // If all buffers are still in use by consumers when new frames are produced // those frames get dropped. static int max_buffer_count = kVideoCaptureDefaultMaxBufferPoolSize; #if defined(OS_MAC) // On macOS, we allow a few more buffers as it's routinely observed that it // runs out of three when just displaying 60 FPS media in a video element. max_buffer_count = 10; #elif BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS with MIPI cameras running on HAL v3, there can be four // concurrent streams of camera pipeline depth ~6. We allow at most 36 buffers // here to take into account the delay caused by the consumer (e.g. display or // video encoder). if (switches::IsVideoCaptureUseGpuMemoryBufferEnabled()) { max_buffer_count = 36; } #elif defined(OS_WIN) // On Windows, for GMB backed zero-copy more buffers are needed because it's // routinely observed that it runs out of default buffer count when just // displaying 60 FPS media in a video element if (switches::IsVideoCaptureUseGpuMemoryBufferEnabled()) { max_buffer_count = 30; } #endif return max_buffer_count; } } // namespace media
503
744
<filename>ethers-solc/test-data/out/compiler-out-16.json<gh_stars>100-1000 {"contracts":{"contracts/Contract.sol":{"Contract":{"abi":[{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}],"evm":{"bytecode":{"linkReferences":{},"object":"6080604052348015600f57600080fd5b50600080fdfe","opcodes":"PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x0 DUP1 REVERT INVALID ","sourceMap":"25:64:0:-;;;47:40;8:9:-1;5:2;;;30:1;27;20:12;5:2;47:40:0;74:8;;"},"deployedBytecode":{"linkReferences":{},"object":"6080604052600080fdfea265627a7a72315820d636dde58d26efc4b725f6e3a9a0a79fadb306c0f4541cdd33caf1ea552cfb5464736f6c634300050f0032","opcodes":"PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x0 DUP1 REVERT INVALID LOG2 PUSH6 0x627A7A723158 KECCAK256 0xD6 CALLDATASIZE 0xDD 0xE5 DUP14 0x26 0xEF 0xC4 0xB7 0x25 0xF6 0xE3 0xA9 LOG0 0xA7 SWAP16 0xAD 0xB3 MOD 0xC0 DELEGATECALL SLOAD SHR 0xDD CALLER 0xCA CALL 0xEA SSTORE 0x2C 0xFB SLOAD PUSH5 0x736F6C6343 STOP SDIV 0xF STOP ORIGIN ","sourceMap":"25:64:0:-;;;;;"},"methodIdentifiers":{}}}}},"sources":{"contracts/Contract.sol":{"ast":{"absolutePath":"contracts/Contract.sol","exportedSymbols":{"Contract":[9]},"id":10,"nodeType":"SourceUnit","nodes":[{"id":1,"literals":["solidity","^","0.5",".0"],"nodeType":"PragmaDirective","src":"0:23:0"},{"baseContracts":[],"contractDependencies":[],"contractKind":"contract","documentation":null,"fullyImplemented":true,"id":9,"linearizedBaseContracts":[9],"name":"Contract","nodeType":"ContractDefinition","nodes":[{"body":{"id":7,"nodeType":"Block","src":"68:19:0","statements":[{"expression":{"argumentTypes":null,"arguments":[],"expression":{"argumentTypes":[],"id":4,"name":"revert","nodeType":"Identifier","overloadedDeclarations":[29,30],"referencedDeclaration":29,"src":"74:6:0","typeDescriptions":{"typeIdentifier":"t_function_revert_pure$__$returns$__$","typeString":"function () pure"}},"id":5,"isConstant":false,"isLValue":false,"isPure":false,"kind":"functionCall","lValueRequested":false,"names":[],"nodeType":"FunctionCall","src":"74:8:0","typeDescriptions":{"typeIdentifier":"t_tuple$__$","typeString":"tuple()"}},"id":6,"nodeType":"ExpressionStatement","src":"74:8:0"}]},"documentation":null,"id":8,"implemented":true,"kind":"constructor","modifiers":[],"name":"","nodeType":"FunctionDefinition","parameters":{"id":2,"nodeType":"ParameterList","parameters":[],"src":"58:2:0"},"returnParameters":{"id":3,"nodeType":"ParameterList","parameters":[],"src":"68:0:0"},"scope":9,"src":"47:40:0","stateMutability":"nonpayable","superFunction":null,"visibility":"public"}],"scope":10,"src":"25:64:0"}],"src":"0:90:0"},"id":0}}}
983
777
<gh_stars>100-1000 // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_CONTEXTUAL_SEARCH_CONTEXTUAL_SEARCH_PANEL_VIEW_H_ #define IOS_CHROME_BROWSER_UI_CONTEXTUAL_SEARCH_CONTEXTUAL_SEARCH_PANEL_VIEW_H_ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/contextual_search/panel_configuration.h" @protocol ContextualSearchPanelMotionObserver; @protocol ContextualSearchPanelTapHandler; // A view designed to sit "on top" of the frontmost tab in a range of positions, // with content can position controlled by a ContextualSearchPanelController. // Generally speaking each BrowserViewController will own both the panel view // and panel controller object. @interface ContextualSearchPanelView : UIView // Current state. @property(nonatomic, assign) ContextualSearch::PanelState state; // Panel configuration, for motion observers that want to do different // computations around panel state and position. @property(nonatomic, readonly) PanelConfiguration* configuration; // Create a panel view. It will need to have a delegate and controller assigned // to do anything useful. - (instancetype)initWithConfiguration:(PanelConfiguration*)configuration NS_DESIGNATED_INITIALIZER; - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; - (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; // Add panel content views. Views in |contentViews| will be arranged vertically // in the panel according to their intrinsic sizes, and will fill its width. // If a view in |contentViews| conforms to the panel motion observer protocol, // it will be automatically added as an observer. // If a view in |contentViews| conforms to the panel scroll synchronizer // protocol, its scrolling will be synchronized with panel dragging. - (void)addContentViews:(NSArray*)contentViews; // Add or remove observers. - (void)addMotionObserver:(id<ContextualSearchPanelMotionObserver>)observer; - (void)removeMotionObserver:(id<ContextualSearchPanelMotionObserver>)observer; // Inform the receiver it is about to promote to be tab-sized; it will inform // any obsevers. - (void)prepareForPromotion; // Have the receiver adjust its frame to match its superview's bounds, // vertically offset by |offset| points from the y-origin. - (void)promoteToMatchSuperviewWithVerticalOffset:(CGFloat)offset; @end #endif // IOS_CHROME_BROWSER_UI_CONTEXTUAL_SEARCH_CONTEXTUAL_SEARCH_PANEL_VIEW_H_
738
4,054
<gh_stars>1000+ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/util/programoptions_testutils.h> namespace vespalib { namespace { std::vector<std::string> splitString(const std::string& source) { std::vector<std::string> target; std::string::size_type start = 0; std::string::size_type stop = source.find(' '); while (stop != std::string::npos) { target.push_back(source.substr(start, stop - start)); start = stop + 1; stop = source.find(' ', start); } target.push_back(source.substr(start)); return target; } } // anonymous AppOptions::AppOptions(const std::string& optString) : _argc(0), _argv(0), _source() { _source = splitString(optString); _argc = _source.size(); _argv = new const char*[_source.size()]; for (int i=0; i<_argc; ++i) { if (_source[i].size() > 1 && _source[i][0] == _source[i][_source[i].size() - 1] && (_source[i][0] == '\'' || _source[i][0] == '"')) { if (_source[i].size() == 2) { _source[i] = ""; } else { _source[i] = _source[i].substr(1, _source.size() - 2); } } _argv[i] = _source[i].c_str(); } } AppOptions::~AppOptions() { delete[] _argv; } } // vespalib
679
28,056
package com.alibaba.json.bvt.bug; import com.alibaba.fastjson.JSON; import junit.framework.TestCase; public class Bug_for_jiangwei extends TestCase { public void test_0 () throws Exception { String text = "['42-0','超級聯隊\\x28中\\x29','辛當斯','1.418',10,'11/18/2012 02:15',1,0,1,0,'',0,0,0,0]"; JSON.parse(text); } }
162
317
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbMaskMuParserFilter_hxx #define otbMaskMuParserFilter_hxx #include "otbMaskMuParserFilter.h" #include <iostream> #include <string> #include "itkImageRegionIterator.h" #include "itkNumericTraits.h" namespace otb { // constructor template <class TInputImage, class TOutputImage, class TFunction> MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::MaskMuParserFilter() { m_UnderflowCount = 0; m_OverflowCount = 0; m_ThreadUnderflow.SetSize(1); m_ThreadOverflow.SetSize(1); m_Expression = ""; } // Destructor template <class TInputImage, class TOutputImage, class TFunction> MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::~MaskMuParserFilter() { } template <class TInputImage, class TOutputImage, class TFunction> void MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Expression: " << m_Expression << std::endl; } template <class TInputImage, class TOutputImage, class TFunction> void MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::SetExpression(const std::string expression) { if (m_Expression != expression) m_Expression = expression; this->Modified(); } template <class TInputImage, class TOutputImage, class TFunction> std::string MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::GetExpression() const { return m_Expression; } template <class TInputImage, class TOutputImage, class TFunction> std::vector<std::string> MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::GetVar() { std::vector<std::string> varList; FunctorPointer tempFunctor = FunctorType::New(); tempFunctor->SetExpression(m_Expression); FunctorType& functor = *tempFunctor; try { functor(this->GetInput()->GetPixel(this->GetInput()->GetBufferedRegion().GetIndex())); } catch (itk::ExceptionObject& err) { itkDebugMacro(<< err); } const std::map<std::string, double*>& varMap = functor.GetVar(); std::map<std::string, double*>::const_iterator it; for (it = varMap.begin(); it != varMap.end(); ++it) { varList.push_back(it->first); } return varList; } template <class TInputImage, class TOutputImage, class TFunction> Parser::FunctionMapType MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::GetFunList() { FunctorPointer tempFunctor = FunctorType::New(); tempFunctor->SetExpression(m_Expression); FunctorType& functor = *tempFunctor; try { functor(this->GetInput()->GetPixel(this->GetInput()->GetBufferedRegion().GetIndex())); } catch (itk::ExceptionObject& err) { itkDebugMacro(<< err); } return functor.GetFunList(); } template <class TInputImage, class TOutputImage, class TFunction> bool MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::CheckExpression() { FunctorPointer checkFunctor = FunctorType::New(); checkFunctor->SetExpression(m_Expression); FunctorType& functor = *checkFunctor; try { functor(this->GetInput()->GetPixel(this->GetInput()->GetBufferedRegion().GetIndex())); } catch (itk::ExceptionObject& err) { itkDebugMacro(<< err); return false; } return true; } /** * BeforeThreadedGenerateData */ template <class TInputImage, class TOutputImage, class TFunction> void MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::BeforeThreadedGenerateData() { typename std::vector<FunctorPointer>::iterator itFunctor; unsigned int nbThreads = this->GetNumberOfThreads(); unsigned int thread_index; std::ostringstream varName; // Allocate and initialize the thread temporaries m_ThreadUnderflow.SetSize(nbThreads); m_ThreadUnderflow.Fill(0); m_ThreadOverflow.SetSize(nbThreads); m_ThreadOverflow.Fill(0); m_VFunctor.resize(nbThreads); for (itFunctor = m_VFunctor.begin(); itFunctor < m_VFunctor.end(); itFunctor++) *itFunctor = FunctorType::New(); for (thread_index = 0; thread_index < nbThreads; thread_index++) { m_VFunctor.at(thread_index)->SetExpression(m_Expression); } } template <class TInputImage, class TOutputImage, class TFunction> void MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId) { InputImageConstPointer inputPtr = this->GetInput(); OutputImagePointer outputPtr = this->GetOutput(0); // Define the portion of the input to walk for this thread, using // the CallCopyOutputRegionToInputRegion method allows for the input // and output images to be different dimensions InputImageRegionType inputRegionForThread; this->CallCopyOutputRegionToInputRegion(inputRegionForThread, outputRegionForThread); // Define the iterators itk::ImageRegionConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); itk::ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); inputIt.GoToBegin(); outputIt.GoToBegin(); FunctorPointer functorP = m_VFunctor.at(threadId); FunctorType& functor = *functorP; while (!inputIt.IsAtEnd()) { outputIt.Set(functor(inputIt.Get())); ++inputIt; ++outputIt; progress.CompletedPixel(); // potential exception thrown here } } template <class TInputImage, class TOutputImage, class TFunction> void MaskMuParserFilter<TInputImage, TOutputImage, TFunction>::AfterThreadedGenerateData() { } } // end namespace otb #endif
2,260
1,738
<gh_stars>1000+ /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <AzCore/Module/Module.h> #include <Source/OceanSurfaceDataComponent.h> #include <LmbrCentral/Component/EditorWrappedComponentBase.h> namespace Water { class EditorOceanSurfaceDataComponent : public LmbrCentral::EditorWrappedComponentBase<OceanSurfaceDataComponent, OceanSurfaceDataConfig> { public: using BaseClassType = LmbrCentral::EditorWrappedComponentBase<OceanSurfaceDataComponent, OceanSurfaceDataConfig>; AZ_EDITOR_COMPONENT(EditorOceanSurfaceDataComponent, "{A8D2485F-F24F-4C3F-9A33-CA9783A9A359}", BaseClassType); static void Reflect(AZ::ReflectContext* context); static constexpr const char* const s_categoryName = "Surface Data"; static constexpr const char* const s_componentName = "Ocean Surface Tag Emitter"; static constexpr const char* const s_componentDescription = "Enables an ocean to emit surface tags"; static constexpr const char* const s_icon = "Editor/Icons/Components/SurfaceData.svg"; static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/SurfaceData.png"; static constexpr const char* const s_helpUrl = "https://docs.aws.amazon.com/console/lumberyard/surfacedata/ocean-surface-tag-emitter"; }; }
587
679
/************************************************************** * * 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. * *************************************************************/ #ifndef INCLUDED_MSIHELPER_HXX #define INCLUDED_MSIHELPER_HXX #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <msiquery.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <string> /** Get the value of the named property @param handle [in] a valid msi handle. @param name [in] the name of the property. @param value [out] receives this value of the property. @returns <TRUE/>if the property was found. */ bool GetMsiProp(MSIHANDLE handle, LPCTSTR name, /*out*/std::wstring& value); /** Set the value of a binary property which can only have the values "0" or "1" to "1". @param handle [in] a valid msi handle. @param name [in] the name of the property. */ void SetMsiProp(MSIHANDLE handle, LPCTSTR name); /** Set the value of a binary property which can only have the values "0" or "1" to "0". @param handle [in] a valid msi handle. @param name [in] the name of the property. */ void UnsetMsiProp(MSIHANDLE handle, LPCTSTR name); /** Returns whether a certain property is set meaning its value is "1". This method should be used for binary properties whose value can be "0" or "1". @returns <TRUE/>if the value of the specified property is "1" else if the property is not defined or its value is other than "1" <FALSE/> will be returned. */ bool IsSetMsiProp(MSIHANDLE handle, LPCTSTR name); /** Returns whether a certain property is set meaning its value is not empty. This method should be used for properties, that can have different values. @returns <TRUE/>if the value of the specified property is not empty. If it is empty <FALSE/> will be returned. */ bool IsMsiPropNotEmpty(MSIHANDLE handle, LPCTSTR name); /** Query if this is an installation for all user or not. @param handle [in] a valid msi handle. @returns <TRUE/>if this is an all user installation */ bool IsAllUserInstallation(MSIHANDLE handle); /** Returns the destination folder of the office installation as system path. The returned path contains a final '\'. @param handle [in] a valid msi handle. @returns the destination path of the office installation finalized with a '\'. */ std::wstring GetOfficeInstallationPath(MSIHANDLE handle); /** Returns the absolute path of the office executable that will be installed as system path. @param handle [in] a valid msi handle. @returns the absolute system path of the office executable (e.g. "C:\Program Files (x86)\OpenOffice 4\program\soffice.exe"). */ std::wstring GetOfficeExecutablePath(MSIHANDLE handle); /** Get the name of the office that will be installed @param handle [in] a valid msi handle. @returns the name of the office product that will be installed. */ std::wstring GetProductName(MSIHANDLE handle); /** Determine if the specified module is installed locally. @param handle [in] a valid msi handle. @param name [in] the name of the module. @returns <TRUE/>if the specified module is installed locally. */ bool IsModuleInstalled(MSIHANDLE handle, LPCTSTR name); /** Determine if the specified module is selected to be installed locally. @param handle [in] a valid msi handle. @param name [in] the name of the module. @returns <TRUE/>if the specified module is about to be installed locally. */ bool IsModuleSelectedForInstallation(MSIHANDLE handle, LPCTSTR name); /** Determine if the specified module which is locally installed is selected for deinstallation. @param handle [in] a valid msi handle. @param name [in] the name of the module. @returns <TRUE/>if the specified module is about to be deinstalled. */ bool IsModuleSelectedForDeinstallation(MSIHANDLE handle, LPCTSTR name); /** Determine whether this is a complete deinstallation or not. @param handle [in] a valid msi handle. @returns <TRUE/>if this is a complete deinstallation. */ bool IsCompleteDeinstallation(MSIHANDLE handle); #endif
1,672
380
// // HROperationQueue.h // HTTPRiot // // Created by <NAME> on 7/2/09. // Copyright 2009 LabratRevenge LLC.. All rights reserved. // #import <Foundation/Foundation.h> /** * Gives you access to the shared operation queue used to manage all connections. */ @interface HROperationQueue : NSOperationQueue { } /** * Shared operation queue. */ + (HROperationQueue *)sharedOperationQueue; @end
131
892
<filename>advisories/unreviewed/2022/05/GHSA-p9qj-4rjp-j3w9/GHSA-p9qj-4rjp-j3w9.json { "schema_version": "1.2.0", "id": "GHSA-p9qj-4rjp-j3w9", "modified": "2022-05-13T01:07:08Z", "published": "2022-05-13T01:07:08Z", "aliases": [ "CVE-2015-5349" ], "details": "The CSV export in Apache LDAP Studio and Apache Directory Studio before 2.0.0-M10 does not properly escape field values, which might allow attackers to execute arbitrary commands by leveraging a crafted LDAP entry that is interpreted as a formula when imported into a spreadsheet.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2015-5349" }, { "type": "WEB", "url": "https://directory.apache.org/studio/news.html" }, { "type": "WEB", "url": "https://lists.apache.org/thread.html/reb5443aaf781b364896ee9d7cf6e97fdc4f5a5174132c319252963b6@%3Ccommits.<EMAIL>%3E" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/537225/100/0/threaded" } ], "database_specific": { "cwe_ids": [ "CWE-77" ], "severity": "HIGH", "github_reviewed": false } }
633
2,151
<filename>third_party/blink/renderer/modules/shapedetection/detected_face.cc // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/shapedetection/detected_face.h" #include "third_party/blink/renderer/core/geometry/dom_rect.h" #include "third_party/blink/renderer/modules/shapedetection/landmark.h" namespace blink { DetectedFace* DetectedFace::Create() { return new DetectedFace(DOMRect::Create()); } DetectedFace* DetectedFace::Create(DOMRect* bounding_box) { return new DetectedFace(bounding_box); } DetectedFace* DetectedFace::Create(DOMRect* bounding_box, const HeapVector<Landmark>& landmarks) { return new DetectedFace(bounding_box, landmarks); } DOMRect* DetectedFace::boundingBox() const { return bounding_box_.Get(); } const HeapVector<Landmark>& DetectedFace::landmarks() const { return landmarks_; } DetectedFace::DetectedFace(DOMRect* bounding_box) : bounding_box_(bounding_box) {} DetectedFace::DetectedFace(DOMRect* bounding_box, const HeapVector<Landmark>& landmarks) : bounding_box_(bounding_box), landmarks_(landmarks) {} void DetectedFace::Trace(blink::Visitor* visitor) { visitor->Trace(bounding_box_); visitor->Trace(landmarks_); ScriptWrappable::Trace(visitor); } } // namespace blink
522
432
<filename>sys/dev/netif/ath/ath_hal/ar9002/ar9285.c /* * Copyright (c) 2008-2009 <NAME>, <NAME> * Copyright (c) 2008 Atheros Communications, Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * $FreeBSD$ */ #include "opt_ah.h" #include "ah.h" #include "ah_internal.h" #include "ah_eeprom_v14.h" #include "ar9002/ar9280.h" #include "ar9002/ar9285.h" #include "ar5416/ar5416reg.h" #include "ar5416/ar5416phy.h" /* * The ordering of nfarray is thus: * * nfarray[0]: Chain 0 ctl * nfarray[1]: Chain 1 ctl * nfarray[2]: Chain 2 ctl * nfarray[3]: Chain 0 ext * nfarray[4]: Chain 1 ext * nfarray[5]: Chain 2 ext */ static void ar9285GetNoiseFloor(struct ath_hal *ah, int16_t nfarray[]) { int16_t nf; nf = MS(OS_REG_READ(ah, AR_PHY_CCA), AR9280_PHY_MINCCA_PWR); if (nf & 0x100) nf = 0 - ((nf ^ 0x1ff) + 1); HALDEBUG(ah, HAL_DEBUG_NFCAL, "NF calibrated [ctl] [chain 0] is %d\n", nf); nfarray[0] = nf; nf = MS(OS_REG_READ(ah, AR_PHY_EXT_CCA), AR9280_PHY_EXT_MINCCA_PWR); if (nf & 0x100) nf = 0 - ((nf ^ 0x1ff) + 1); HALDEBUG(ah, HAL_DEBUG_NFCAL, "NF calibrated [ext] [chain 0] is %d\n", nf); nfarray[3] = nf; /* Chain 1 - invalid */ nfarray[1] = 0; nfarray[4] = 0; /* Chain 2 - invalid */ nfarray[2] = 0; nfarray[5] = 0; } HAL_BOOL ar9285RfAttach(struct ath_hal *ah, HAL_STATUS *status) { if (ar9280RfAttach(ah, status) == AH_FALSE) return AH_FALSE; AH_PRIVATE(ah)->ah_getNoiseFloor = ar9285GetNoiseFloor; return AH_TRUE; } static HAL_BOOL ar9285RfProbe(struct ath_hal *ah) { return (AR_SREV_KITE(ah)); } AH_RF(RF9285, ar9285RfProbe, ar9285RfAttach);
972
1,433
/* * Copyright (c) 2016, 2017, 2018, 2019 FabricMC * * 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 net.fabricmc.fabric.api.client.rendering.v1; import net.minecraft.client.model.Model; import net.minecraft.client.render.OverlayTexture; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.feature.FeatureRenderer; import net.minecraft.client.render.entity.model.BipedEntityModel; import net.minecraft.client.render.item.ItemRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.EquipmentSlot; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemConvertible; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.client.rendering.ArmorRendererRegistryImpl; /** * Armor renderers render worn armor items with custom code. * They may be used to render armor with special models or effects. * * <p>The renderers are registered with {@link net.fabricmc.fabric.api.client.rendering.v1.ArmorRenderer#register(ArmorRenderer, ItemConvertible...)}. */ @Environment(EnvType.CLIENT) @FunctionalInterface public interface ArmorRenderer { /** * Registers the armor renderer for the specified items. * @param renderer the renderer * @param items the items * @throws IllegalArgumentException if an item already has a registered armor renderer * @throws NullPointerException if either an item or the renderer is null */ static void register(ArmorRenderer renderer, ItemConvertible... items) { ArmorRendererRegistryImpl.register(renderer, items); } /** * Helper method for rendering a specific armor model, comes after setting visibility. * * <p>This primarily handles applying glint and the correct {@link RenderLayer} * @param matrices the matrix stack * @param vertexConsumers the vertex consumer provider * @param light packed lightmap coordinates * @param stack the item stack of the armor item * @param model the model to be rendered * @param texture the texture to be applied */ static void renderPart(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, ItemStack stack, Model model, Identifier texture) { VertexConsumer vertexConsumer = ItemRenderer.getArmorGlintConsumer(vertexConsumers, RenderLayer.getArmorCutoutNoCull(texture), false, stack.hasGlint()); model.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, 1, 1, 1, 1); } /** * Renders an armor part. * * @param matrices the matrix stack * @param vertexConsumers the vertex consumer provider * @param stack the item stack of the armor item * @param entity the entity wearing the armor item * @param slot the equipment slot in which the armor stack is worn * @param light packed lightmap coordinates * @param contextModel the model provided by {@link FeatureRenderer#getContextModel()} */ void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, ItemStack stack, LivingEntity entity, EquipmentSlot slot, int light, BipedEntityModel<LivingEntity> contextModel); }
1,098
734
<filename>app/src/main/java/com/cheikh/lazywaimai/base/BaseFragment.java package com.cheikh.lazywaimai.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.BindView; import butterknife.ButterKnife; import com.cheikh.lazywaimai.R; import com.cheikh.lazywaimai.util.ContentView; import com.cheikh.lazywaimai.widget.LoadingDialog; /** * author: cheikh.wang on 16/11/23 * email: <EMAIL> */ public abstract class BaseFragment<UC> extends CoreFragment<UC> { @Nullable @BindView(R.id.toolbar) Toolbar mToolbar; private LoadingDialog mLoading; @Override public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(getLayoutResId(), container, false); } @Override public final void onViewCreated(View view, @Nullable Bundle savedInstanceState) { ButterKnife.bind(this, view); initialToolbar(); handleArguments(getArguments()); initializeViews(savedInstanceState); } protected int getLayoutResId() { for (Class c = getClass(); c != Fragment.class; c = c.getSuperclass()) { ContentView annotation = (ContentView) c.getAnnotation(ContentView.class); if (annotation != null) { return annotation.value(); } } return 0; } protected void initialToolbar() { if (mToolbar != null) { mToolbar.setTitle(getTitle()); setSupportActionBar(mToolbar); if (isShowBack()) { getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } } protected void handleArguments(Bundle arguments) {} protected void initializeViews(Bundle savedInstanceState) {} protected Toolbar getToolbar() { return mToolbar; } protected String getTitle() { return null; } protected boolean isShowBack() { return true; } protected void setTitle(CharSequence title) { if (mToolbar != null) { mToolbar.setTitle(title); } } protected void setTitle(@StringRes int titleRes) { if (mToolbar != null) { mToolbar.setTitle(titleRes); } } protected void setSupportActionBar(Toolbar toolbar) { ((BaseActivity) getActivity()).setSupportActionBar(toolbar); } protected ActionBar getSupportActionBar() { return ((BaseActivity) getActivity()).getSupportActionBar(); } protected final void showLoading(@StringRes int textResId) { showLoading(getString(textResId)); } protected final void showLoading(String text) { cancelLoading(); if (mLoading == null) { mLoading = new LoadingDialog(getContext()); mLoading.setCancelable(false); mLoading.setCanceledOnTouchOutside(false); } mLoading.setTitle(text); mLoading.show(); } protected final void cancelLoading() { if (mLoading != null && mLoading.isShowing()) { mLoading.dismiss(); } } }
1,396
317
package com.googlecode.totallylazy.validations; import com.googlecode.totallylazy.functions.Function1; import com.googlecode.totallylazy.predicates.Predicate; import org.junit.Test; import static com.googlecode.totallylazy.predicates.Predicates.greaterThan; import static com.googlecode.totallylazy.matchers.IterableMatcher.hasExactly; import static com.googlecode.totallylazy.matchers.IterableMatcher.isEmpty; import static com.googlecode.totallylazy.validations.Validators.validateThat; import static org.hamcrest.MatcherAssert.assertThat; public class MapAndValidateTest { @Test public void appliesAMappingFunctionToTheOriginalValueAndValidatesTheResult() { LogicalValidator<String> integer = validateThat(isInteger()). castValidator(String.class). withMessage("Must be an integer"); Validator<String> greaterThanZero = integer.andIfSo(validateThat(parseInteger(), greaterThan(0)). withMessage("Must be greater than 0")); assertThat( greaterThanZero.validate("NOT AN INTEGER").allMessages(), hasExactly("Must be an integer")); assertThat( greaterThanZero.validate("0").allMessages(), hasExactly("Must be greater than 0")); assertThat( greaterThanZero.validate("1").allMessages(), isEmpty(String.class)); } private Predicate<String> isInteger() { return value -> { try{ Integer.parseInt(value); return true; }catch (Throwable e){ return false; } }; } private Function1<String, Integer> parseInteger() { return Integer::parseInt; } }
736
3,673
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #pragma once #include "open3d/core/CUDAUtils.h" #include "open3d/core/MemoryManager.h" #include "open3d/core/Tensor.h" #include "open3d/core/hashmap/HashBackendBuffer.h" namespace open3d { namespace core { enum class HashBackendType; class DeviceHashBackend { public: DeviceHashBackend(int64_t init_capacity, int64_t key_dsize, const std::vector<int64_t>& value_dsizes, const Device& device) : capacity_(init_capacity), key_dsize_(key_dsize), value_dsizes_(value_dsizes), device_(device) {} virtual ~DeviceHashBackend() {} /// Reserve expects a lot of extra memory space at runtime, /// since it consists of /// 1) dumping all key value pairs to a buffer /// 2) creating a new hash table /// 3) parallel inserting dumped key value pairs /// 4) deallocating old hash table virtual void Reserve(int64_t capacity) = 0; /// Parallel insert contiguous arrays of keys and values. virtual void Insert(const void* input_keys, const std::vector<const void*>& input_values, buf_index_t* output_buf_indices, bool* output_masks, int64_t count) = 0; /// Parallel find a contiguous array of keys. virtual void Find(const void* input_keys, buf_index_t* output_buf_indices, bool* output_masks, int64_t count) = 0; /// Parallel erase a contiguous array of keys. virtual void Erase(const void* input_keys, bool* output_masks, int64_t count) = 0; /// Parallel collect all iterators in the hash table virtual int64_t GetActiveIndices(buf_index_t* output_buf_indices) = 0; /// Clear stored map without reallocating memory. virtual void Clear() = 0; /// Get the size (number of valid entries) of the hash map. virtual int64_t Size() const = 0; /// Get the number of buckets of the hash map. virtual int64_t GetBucketCount() const = 0; /// Get the current load factor, defined as size / bucket count. virtual float LoadFactor() const = 0; /// Get the maximum capacity of the hash map. int64_t GetCapacity() const { return capacity_; } /// Get the current device. Device GetDevice() const { return device_; } /// Get the number of entries per bucket. virtual std::vector<int64_t> BucketSizes() const = 0; /// Get the key buffer that stores actual keys. Tensor GetKeyBuffer() { return buffer_->GetKeyBuffer(); } /// Get the value buffers that store actual array of values. std::vector<Tensor> GetValueBuffers() { return buffer_->GetValueBuffers(); } /// Get the i-th value buffer that store an actual value array. Tensor GetValueBuffer(size_t i = 0) { return buffer_->GetValueBuffer(i); } virtual void Allocate(int64_t capacity) = 0; virtual void Free() = 0; public: int64_t capacity_; int64_t key_dsize_; std::vector<int64_t> value_dsizes_; Device device_; std::shared_ptr<HashBackendBuffer> buffer_; }; /// Factory functions: /// - Default constructor switch is in DeviceHashBackend.cpp /// - Default CPU constructor is in CPU/CreateCPUHashBackend.cpp /// - Default CUDA constructor is in CUDA/CreateCUDAHashBackend.cu std::shared_ptr<DeviceHashBackend> CreateDeviceHashBackend( int64_t init_capacity, const Dtype& key_dtype, const SizeVector& key_element_shape, const std::vector<Dtype>& value_dtypes, const std::vector<SizeVector>& value_element_shapes, const Device& device, const HashBackendType& backend); std::shared_ptr<DeviceHashBackend> CreateCPUHashBackend( int64_t init_capacity, const Dtype& key_dtype, const SizeVector& key_element_shape, const std::vector<Dtype>& value_dtypes, const std::vector<SizeVector>& value_element_shapes, const Device& device, const HashBackendType& backend); std::shared_ptr<DeviceHashBackend> CreateCUDAHashBackend( int64_t init_capacity, const Dtype& key_dtype, const SizeVector& key_element_shape, const std::vector<Dtype>& value_dtypes, const std::vector<SizeVector>& value_element_shapes, const Device& device, const HashBackendType& backend); } // namespace core } // namespace open3d
2,153
1,233
<reponame>calvin681/mantis /* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.runtime.executor; import io.mantisrx.common.codec.Codecs; import io.mantisrx.runtime.Context; import io.mantisrx.runtime.Job; import io.mantisrx.runtime.MantisJob; import io.mantisrx.runtime.MantisJobProvider; import io.mantisrx.runtime.PortRequest; import io.mantisrx.runtime.ScalarToScalar; import io.mantisrx.runtime.computation.ScalarComputation; import io.mantisrx.runtime.sink.Sink; import io.mantisrx.runtime.source.Index; import io.mantisrx.runtime.source.Source; import java.util.LinkedList; import java.util.List; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; public class TestJob extends MantisJobProvider<Integer> { private List<Integer> itemsWritten = new LinkedList<Integer>(); public static void main(String[] args) { LocalJobExecutorNetworked.execute(new TestJob().getJobInstance()); } public List<Integer> getItemsWritten() { return itemsWritten; } @Override public Job<Integer> getJobInstance() { return MantisJob .<Integer> source(new Source<Integer>() { @Override public Observable<Observable<Integer>> call(Context t1, Index t2) { return Observable.just(Observable.range(0, 10)); } }) // doubles number .stage(new ScalarComputation<Integer, Integer>() { @Override public Observable<Integer> call(Context context, Observable<Integer> t1) { return t1.map(new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return t1 * t1; } }); } }, new ScalarToScalar.Config<Integer, Integer>() .codec(Codecs.integer())) // return only even numbers .stage(new ScalarComputation<Integer, Integer>() { @Override public Observable<Integer> call(Context context, Observable<Integer> t1) { return t1.filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer t1) { return ((t1 % 2) == 0); } }); } }, new ScalarToScalar.Config<Integer, Integer>() .codec(Codecs.integer())) .sink(new Sink<Integer>() { @Override public void call(Context context, PortRequest p, Observable<Integer> o) { o .toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { System.out.println(t1); itemsWritten.add(t1); } }); } }) .create(); } }
2,035
623
<filename>java/com/google/gerrit/sshd/ChannelIdTrackingUnknownChannelReferenceHandler.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * This file is based on sshd-contrib Apache SSHD Mina project. Original commit: * https://github.com/apache/mina-sshd/commit/11b33dee37b5b9c71a40a8a98a42007e3687131e */ package com.google.gerrit.sshd; import com.google.common.flogger.FluentLogger; import java.io.IOException; import org.apache.sshd.common.AttributeRepository.AttributeKey; import org.apache.sshd.common.SshConstants; import org.apache.sshd.common.channel.Channel; import org.apache.sshd.common.channel.ChannelListener; import org.apache.sshd.common.channel.exception.SshChannelNotFoundException; import org.apache.sshd.common.session.ConnectionService; import org.apache.sshd.common.session.Session; import org.apache.sshd.common.session.helpers.DefaultUnknownChannelReferenceHandler; import org.apache.sshd.common.util.buffer.Buffer; /** * Makes sure that the referenced &quot;unknown&quot; channel identifier is one that was assigned in * the past. <B>Note:</B> it relies on the fact that the default {@code ConnectionService} * implementation assigns channels identifiers in ascending order. * * @author <a href="mailto:<EMAIL>">Apache MINA SSHD Project</a> */ public class ChannelIdTrackingUnknownChannelReferenceHandler extends DefaultUnknownChannelReferenceHandler implements ChannelListener { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final AttributeKey<Integer> LAST_CHANNEL_ID_KEY = new AttributeKey<>(); public static final ChannelIdTrackingUnknownChannelReferenceHandler TRACKER = new ChannelIdTrackingUnknownChannelReferenceHandler(); public ChannelIdTrackingUnknownChannelReferenceHandler() { super(); } @Override public void channelInitialized(Channel channel) { int channelId = channel.getId(); Session session = channel.getSession(); Integer lastTracked = session.setAttribute(LAST_CHANNEL_ID_KEY, channelId); logger.atFine().log( "channelInitialized(%s) updated last tracked channel ID %s => %s", channel, lastTracked, channelId); } @Override public Channel handleUnknownChannelCommand( ConnectionService service, byte cmd, int channelId, Buffer buffer) throws IOException { Session session = service.getSession(); Integer lastTracked = session.getAttribute(LAST_CHANNEL_ID_KEY); if ((lastTracked != null) && (channelId <= lastTracked.intValue())) { // Use TRACE level in order to avoid messages flooding logger.atFinest().log( "handleUnknownChannelCommand(%s) apply default handling for %s on channel=%s (lastTracked=%s)", session, SshConstants.getCommandMessageName(cmd), channelId, lastTracked); return super.handleUnknownChannelCommand(service, cmd, channelId, buffer); } throw new SshChannelNotFoundException( channelId, "Received " + SshConstants.getCommandMessageName(cmd) + " on unassigned channel " + channelId + " (last assigned=" + lastTracked + ")"); } }
1,211
4,879
<filename>iphone/Maps/Classes/LocaleTranslator.h #pragma once #include <string> namespace locale_translator { std::string bcp47ToTwineLanguage(NSString const * bcp47LangName); } // namespace tts
72
654
<reponame>dcrec1/tray package qz.ws; public enum SocketMethod { PRINTERS_GET_DEFAULT("printers.getDefault", true, "access connected printers"), PRINTERS_FIND("printers.find", true, "access connected printers"), PRINTERS_DETAIL("printers.detail", true, "access connected printers"), PRINTERS_START_LISTENING("printers.startListening", true, "listen for printer status"), PRINTERS_GET_STATUS("printers.getStatus", false), PRINTERS_STOP_LISTENING("printers.stopListening", false), PRINT("print", true, "print to %s"), SERIAL_FIND_PORTS("serial.findPorts", true, "access serial ports"), SERIAL_OPEN_PORT("serial.openPort", true, "open a serial port"), SERIAL_SEND_DATA("serial.sendData", true, "send data over a serial port"), SERIAL_CLOSE_PORT("serial.closePort", true, "close a serial port"), SOCKET_OPEN_PORT("socket.open", true, "open a socket"), SOCKET_SEND_DATA("socket.sendData", true, "send data over a socket"), SOCKET_CLOSE_PORT("socket.close", true, "close a socket"), USB_LIST_DEVICES("usb.listDevices", true, "access USB devices"), USB_LIST_INTERFACES("usb.listInterfaces", true, "access USB devices"), USB_LIST_ENDPOINTS("usb.listEndpoints", true, "access USB devices"), USB_CLAIM_DEVICE("usb.claimDevice", true, "claim a USB device"), USB_CLAIMED("usb.isClaimed", false, "check USB claim status"), USB_SEND_DATA("usb.sendData", true, "use a USB device"), USB_READ_DATA("usb.readData", true, "use a USB device"), USB_OPEN_STREAM("usb.openStream", true, "use a USB device"), USB_CLOSE_STREAM("usb.closeStream", false, "use a USB device"), USB_RELEASE_DEVICE("usb.releaseDevice", false, "release a USB device"), HID_LIST_DEVICES("hid.listDevices", true, "access USB devices"), HID_START_LISTENING("hid.startListening", true, "listen for USB devices"), HID_STOP_LISTENING("hid.stopListening", false), HID_CLAIM_DEVICE("hid.claimDevice", true, "claim a USB device"), HID_CLAIMED("hid.isClaimed", false, "check USB claim status"), HID_SEND_DATA("hid.sendData", true, "use a USB device"), HID_READ_DATA("hid.readData", true, "use a USB device"), HID_SEND_FEATURE_REPORT("hid.sendFeatureReport", true, "use a USB device"), HID_GET_FEATURE_REPORT("hid.getFeatureReport", true, "use a USB device"), HID_OPEN_STREAM("hid.openStream", true, "use a USB device"), HID_CLOSE_STREAM("hid.closeStream", false, "use a USB device"), HID_RELEASE_DEVICE("hid.releaseDevice", false, "release a USB device"), FILE_LIST("file.list", true, "view the filesystem"), FILE_START_LISTENING("file.startListening", true, "listen for filesystem events"), FILE_STOP_LISTENING("file.stopListening", false), FILE_READ("file.read", true, "read the content of a file"), FILE_WRITE("file.write", true, "write to a file"), FILE_REMOVE("file.remove", true, "delete a file"), NETWORKING_DEVICE("networking.device", true), NETWORKING_DEVICES("networking.devices", true), NETWORKING_DEVICE_LEGACY("websocket.getNetworkInfo", true), GET_VERSION("getVersion", false), WEBSOCKET_STOP("websocket.stop", false), INVALID("", false); private String callName; private String dialogPrompt; private boolean dialogShown; SocketMethod(String callName, boolean dialogShown) { this(callName, dialogShown, "access local resources"); } SocketMethod(String callName, boolean dialogShown, String dialogPrompt) { this.callName = callName; this.dialogShown = dialogShown; this.dialogPrompt = dialogPrompt; } public boolean isDialogShown() { return dialogShown; } public String getDialogPrompt() { return dialogPrompt; } public static SocketMethod findFromCall(String call) { for(SocketMethod m : SocketMethod.values()) { if (m.callName.equals(call)) { return m; } } return INVALID; } public String getCallName() { return callName; } }
1,524
677
<filename>ohc-jmh/src/main/java/org/caffinitas/ohc/jmh/Utils.java /* * Copyright (C) 2014 <NAME>, Koeln, Germany, robert-stupp.de * * 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.caffinitas.ohc.jmh; import java.nio.ByteBuffer; import org.caffinitas.ohc.CacheSerializer; public final class Utils { public static final CacheSerializer<byte[]> byteArraySerializer = new CacheSerializer<byte[]>() { public void serialize(byte[] bytes, ByteBuffer buf) { buf.putInt(bytes.length); buf.put(bytes); } public byte[] deserialize(ByteBuffer buf) { byte[] arr = new byte[buf.getInt()]; buf.get(arr); return arr; } public int serializedSize(byte[] bytes) { return 4 + bytes.length; } }; public static final CacheSerializer<Integer> intSerializer = new CacheSerializer<Integer>() { public void serialize(Integer integer, ByteBuffer buf) { buf.putInt(integer); } public Integer deserialize(ByteBuffer buf) { return buf.getInt(); } public int serializedSize(Integer integer) { return 4; } }; }
742
3,428
{"id":"01222","group":"easy-ham-1","checksum":{"type":"MD5","value":"924583306d4cc0c089a9b295915439e4"},"text":"From <EMAIL> Wed Oct 2 11:45:18 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 1D72716F16\n\tfor <jm@localhost>; Wed, 2 Oct 2002 11:45:17 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 02 Oct 2002 11:45:17 +0100 (IST)\nReceived: from egwn.net (ns2.egwn.net [172.16.58.3]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g929n8K03014 for\n <<EMAIL>>; Wed, 2 Oct 2002 10:49:08 +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 g929k0f29598; Wed, 2 Oct 2002 11:46:00\n +0200\nReceived: from python (gw01.es3.egwn.net [212.9.66.13]) (authenticated) by\n egwn.net (8.11.6/8.11.6/EGWN) with ESMTP id g929jZf25241 for\n <<EMAIL>>; Wed, 2 Oct 2002 11:45:35 +0200\nFrom: <NAME> <<EMAIL>>\nTo: [email protected]\nSubject: freshrpms.net resources (was Re: use new apt to do null to RH8\n upgrade?)\nMessage-Id: <<EMAIL>0211<EMAIL>>\nIn-Reply-To: <<EMAIL>>\nReferences: <<EMAIL>>\n <<EMAIL>0020939580.6894-<EMAIL>>\n <<EMAIL>>\n <<EMAIL>2<EMAIL>.<EMAIL>>\n <<EMAIL>>\nOrganization: Electronic Group Interactive\nX-Mailer: Sylpheed version 0.8.3claws (GTK+ 1.2.10; i386-redhat-linux)\nReply-BY: Tue, 24 Jul 2000 19:02:00 +1000\nX-Operating-System: GNU/Linux power!\nX-Message-Flag: Try using a real operating system : GNU/Linux power!\nMIME-Version: 1.0\nContent-Type: text/plain; charset=US-ASCII\nContent-Transfer-Encoding: 7bit\nX-Mailscanner: Found to be clean, Found to be clean\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nReply-To: [email protected]\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: Wed, 2 Oct 2002 11:45:33 +0200\nDate: Wed, 2 Oct 2002 11:45:33 +0200\n\nOnce upon a time, Brian wrote :\n\n> Yeah, but I try to 'take it easy' on your server. The golden rule of\n> the internet: when you find a free resource, don't piss'em off! :) I\n> really appreciate your work; you get done the things I wish I could,\n> and I respect that.\n\nDon't worry too much : The day the server gets too busy, I'll cleanup and\npublish the addresses of some mirrors, as many ftp mirrors exist (I'm aware\nof at least 15), and even an apt one :-)\nFor now, the limit is far enough : When I unlocked the Psyche ISO images on\nMonday, the bandwidth usage on the current (ftp|http|rsync) freshrpms.net\nserver went up to 90Mbps sustained, which is not bad as the server has a\n100Mbps physical NIC! Of course, I'd get in trouble if it was always like\nthat, but the average used when no new Red Hat release is there is between\n2 and 4Mbps, which my company tolerates, as I've convinced them it's a\nuseful return to the community providing us the great operating system all\nour servers are running ;-)\n\nMatthias\n\n-- \n<NAME> World Trade Center\n------------- Edificio Norte 4 Planta\nSystem and Network Engineer 08039 Barcelona, Spain\nElectronic Group Interactive Phone : +34 936 00 23 23\n\n_______________________________________________\nRPM-List mailing list <<EMAIL>>\nhttp://lists.freshrpms.net/mailman/listinfo/rpm-list\n\n\n"}
1,609
3,645
/* * Copyright (c) 2013 <NAME> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Generate a frame packed video, by combining two views in a single surface. */ #include <string.h> #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "libavutil/rational.h" #include "libavutil/stereo3d.h" #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" #define LEFT 0 #define RIGHT 1 typedef struct FramepackContext { const AVClass *class; const AVPixFmtDescriptor *pix_desc; ///< agreed pixel format enum AVStereo3DType format; ///< frame pack type output AVFrame *input_views[2]; ///< input frames int64_t double_pts; ///< new pts for frameseq mode } FramepackContext; static const enum AVPixelFormat formats_supported[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_NONE }; static int query_formats(AVFilterContext *ctx) { // this will ensure that formats are the same on all pads AVFilterFormats *fmts_list = ff_make_format_list(formats_supported); if (!fmts_list) return AVERROR(ENOMEM); return ff_set_common_formats(ctx, fmts_list); } static av_cold void framepack_uninit(AVFilterContext *ctx) { FramepackContext *s = ctx->priv; // clean any leftover frame av_frame_free(&s->input_views[LEFT]); av_frame_free(&s->input_views[RIGHT]); } static int config_output(AVFilterLink *outlink) { AVFilterContext *ctx = outlink->src; FramepackContext *s = outlink->src->priv; int width = ctx->inputs[LEFT]->w; int height = ctx->inputs[LEFT]->h; AVRational time_base = ctx->inputs[LEFT]->time_base; AVRational frame_rate = ctx->inputs[LEFT]->frame_rate; // check size and fps match on the other input if (width != ctx->inputs[RIGHT]->w || height != ctx->inputs[RIGHT]->h) { av_log(ctx, AV_LOG_ERROR, "Left and right sizes differ (%dx%d vs %dx%d).\n", width, height, ctx->inputs[RIGHT]->w, ctx->inputs[RIGHT]->h); return AVERROR_INVALIDDATA; } else if (av_cmp_q(time_base, ctx->inputs[RIGHT]->time_base) != 0) { av_log(ctx, AV_LOG_ERROR, "Left and right time bases differ (%d/%d vs %d/%d).\n", time_base.num, time_base.den, ctx->inputs[RIGHT]->time_base.num, ctx->inputs[RIGHT]->time_base.den); return AVERROR_INVALIDDATA; } else if (av_cmp_q(frame_rate, ctx->inputs[RIGHT]->frame_rate) != 0) { av_log(ctx, AV_LOG_ERROR, "Left and right framerates differ (%d/%d vs %d/%d).\n", frame_rate.num, frame_rate.den, ctx->inputs[RIGHT]->frame_rate.num, ctx->inputs[RIGHT]->frame_rate.den); return AVERROR_INVALIDDATA; } s->pix_desc = av_pix_fmt_desc_get(outlink->format); if (!s->pix_desc) return AVERROR_BUG; // modify output properties as needed switch (s->format) { case AV_STEREO3D_FRAMESEQUENCE: time_base.den *= 2; frame_rate.num *= 2; s->double_pts = AV_NOPTS_VALUE; break; case AV_STEREO3D_COLUMNS: case AV_STEREO3D_SIDEBYSIDE: width *= 2; break; case AV_STEREO3D_LINES: case AV_STEREO3D_TOPBOTTOM: height *= 2; break; default: av_log(ctx, AV_LOG_ERROR, "Unknown packing mode."); return AVERROR_INVALIDDATA; } outlink->w = width; outlink->h = height; outlink->time_base = time_base; outlink->frame_rate = frame_rate; return 0; } static void horizontal_frame_pack(AVFilterLink *outlink, AVFrame *out, int interleaved) { AVFilterContext *ctx = outlink->src; FramepackContext *s = ctx->priv; int i, plane; if (interleaved) { const uint8_t *leftp = s->input_views[LEFT]->data[0]; const uint8_t *rightp = s->input_views[RIGHT]->data[0]; uint8_t *dstp = out->data[0]; int length = out->width / 2; int lines = out->height; for (plane = 0; plane < s->pix_desc->nb_components; plane++) { if (plane == 1 || plane == 2) { length = AV_CEIL_RSHIFT(out->width / 2, s->pix_desc->log2_chroma_w); lines = AV_CEIL_RSHIFT(out->height, s->pix_desc->log2_chroma_h); } for (i = 0; i < lines; i++) { int j; leftp = s->input_views[LEFT]->data[plane] + s->input_views[LEFT]->linesize[plane] * i; rightp = s->input_views[RIGHT]->data[plane] + s->input_views[RIGHT]->linesize[plane] * i; dstp = out->data[plane] + out->linesize[plane] * i; for (j = 0; j < length; j++) { // interpolate chroma as necessary if ((s->pix_desc->log2_chroma_w || s->pix_desc->log2_chroma_h) && (plane == 1 || plane == 2)) { *dstp++ = (*leftp + *rightp) / 2; *dstp++ = (*leftp + *rightp) / 2; } else { *dstp++ = *leftp; *dstp++ = *rightp; } leftp += 1; rightp += 1; } } } } else { for (i = 0; i < 2; i++) { const uint8_t *src[4]; uint8_t *dst[4]; int sub_w = s->input_views[i]->width >> s->pix_desc->log2_chroma_w; src[0] = s->input_views[i]->data[0]; src[1] = s->input_views[i]->data[1]; src[2] = s->input_views[i]->data[2]; dst[0] = out->data[0] + i * s->input_views[i]->width; dst[1] = out->data[1] + i * sub_w; dst[2] = out->data[2] + i * sub_w; av_image_copy(dst, out->linesize, src, s->input_views[i]->linesize, s->input_views[i]->format, s->input_views[i]->width, s->input_views[i]->height); } } } static void vertical_frame_pack(AVFilterLink *outlink, AVFrame *out, int interleaved) { AVFilterContext *ctx = outlink->src; FramepackContext *s = ctx->priv; int i; for (i = 0; i < 2; i++) { const uint8_t *src[4]; uint8_t *dst[4]; int linesizes[4]; int sub_h = s->input_views[i]->height >> s->pix_desc->log2_chroma_h; src[0] = s->input_views[i]->data[0]; src[1] = s->input_views[i]->data[1]; src[2] = s->input_views[i]->data[2]; dst[0] = out->data[0] + i * out->linesize[0] * (interleaved + s->input_views[i]->height * (1 - interleaved)); dst[1] = out->data[1] + i * out->linesize[1] * (interleaved + sub_h * (1 - interleaved)); dst[2] = out->data[2] + i * out->linesize[2] * (interleaved + sub_h * (1 - interleaved)); linesizes[0] = out->linesize[0] + interleaved * out->linesize[0]; linesizes[1] = out->linesize[1] + interleaved * out->linesize[1]; linesizes[2] = out->linesize[2] + interleaved * out->linesize[2]; av_image_copy(dst, linesizes, src, s->input_views[i]->linesize, s->input_views[i]->format, s->input_views[i]->width, s->input_views[i]->height); } } static av_always_inline void spatial_frame_pack(AVFilterLink *outlink, AVFrame *dst) { AVFilterContext *ctx = outlink->src; FramepackContext *s = ctx->priv; switch (s->format) { case AV_STEREO3D_SIDEBYSIDE: horizontal_frame_pack(outlink, dst, 0); break; case AV_STEREO3D_COLUMNS: horizontal_frame_pack(outlink, dst, 1); break; case AV_STEREO3D_TOPBOTTOM: vertical_frame_pack(outlink, dst, 0); break; case AV_STEREO3D_LINES: vertical_frame_pack(outlink, dst, 1); break; } } static int try_push_frame(AVFilterContext *ctx); static int filter_frame_left(AVFilterLink *inlink, AVFrame *frame) { FramepackContext *s = inlink->dst->priv; s->input_views[LEFT] = frame; return try_push_frame(inlink->dst); } static int filter_frame_right(AVFilterLink *inlink, AVFrame *frame) { FramepackContext *s = inlink->dst->priv; s->input_views[RIGHT] = frame; return try_push_frame(inlink->dst); } static int request_frame(AVFilterLink *outlink) { AVFilterContext *ctx = outlink->src; FramepackContext *s = ctx->priv; int ret, i; /* get a frame on the either input, stop as soon as a video ends */ for (i = 0; i < 2; i++) { if (!s->input_views[i]) { ret = ff_request_frame(ctx->inputs[i]); if (ret < 0) return ret; } } return 0; } static int try_push_frame(AVFilterContext *ctx) { FramepackContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; AVStereo3D *stereo; int ret, i; if (!(s->input_views[0] && s->input_views[1])) return 0; if (s->format == AV_STEREO3D_FRAMESEQUENCE) { if (s->double_pts == AV_NOPTS_VALUE) s->double_pts = s->input_views[LEFT]->pts; for (i = 0; i < 2; i++) { // set correct timestamps s->input_views[i]->pts = s->double_pts++; // set stereo3d side data stereo = av_stereo3d_create_side_data(s->input_views[i]); if (!stereo) return AVERROR(ENOMEM); stereo->type = s->format; // filter the frame and immediately relinquish its pointer ret = ff_filter_frame(outlink, s->input_views[i]); s->input_views[i] = NULL; if (ret < 0) return ret; } return ret; } else { AVFrame *dst = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!dst) return AVERROR(ENOMEM); spatial_frame_pack(outlink, dst); // get any property from the original frame ret = av_frame_copy_props(dst, s->input_views[LEFT]); if (ret < 0) { av_frame_free(&dst); return ret; } for (i = 0; i < 2; i++) av_frame_free(&s->input_views[i]); // set stereo3d side data stereo = av_stereo3d_create_side_data(dst); if (!stereo) { av_frame_free(&dst); return AVERROR(ENOMEM); } stereo->type = s->format; return ff_filter_frame(outlink, dst); } } #define OFFSET(x) offsetof(FramepackContext, x) #define V AV_OPT_FLAG_VIDEO_PARAM static const AVOption framepack_options[] = { { "format", "Frame pack output format", OFFSET(format), AV_OPT_TYPE_INT, { .i64 = AV_STEREO3D_SIDEBYSIDE }, 0, INT_MAX, .flags = V, .unit = "format" }, { "sbs", "Views are packed next to each other", 0, AV_OPT_TYPE_CONST, { .i64 = AV_STEREO3D_SIDEBYSIDE }, INT_MIN, INT_MAX, .flags = V, .unit = "format" }, { "tab", "Views are packed on top of each other", 0, AV_OPT_TYPE_CONST, { .i64 = AV_STEREO3D_TOPBOTTOM }, INT_MIN, INT_MAX, .flags = V, .unit = "format" }, { "frameseq", "Views are one after the other", 0, AV_OPT_TYPE_CONST, { .i64 = AV_STEREO3D_FRAMESEQUENCE }, INT_MIN, INT_MAX, .flags = V, .unit = "format" }, { "lines", "Views are interleaved by lines", 0, AV_OPT_TYPE_CONST, { .i64 = AV_STEREO3D_LINES }, INT_MIN, INT_MAX, .flags = V, .unit = "format" }, { "columns", "Views are interleaved by columns", 0, AV_OPT_TYPE_CONST, { .i64 = AV_STEREO3D_COLUMNS }, INT_MIN, INT_MAX, .flags = V, .unit = "format" }, { NULL }, }; AVFILTER_DEFINE_CLASS(framepack); static const AVFilterPad framepack_inputs[] = { { .name = "left", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame_left, .needs_fifo = 1, }, { .name = "right", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame_right, .needs_fifo = 1, }, { NULL } }; static const AVFilterPad framepack_outputs[] = { { .name = "packed", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_output, .request_frame = request_frame, }, { NULL } }; AVFilter ff_vf_framepack = { .name = "framepack", .description = NULL_IF_CONFIG_SMALL("Generate a frame packed stereoscopic video."), .priv_size = sizeof(FramepackContext), .priv_class = &framepack_class, .query_formats = query_formats, .inputs = framepack_inputs, .outputs = framepack_outputs, .uninit = framepack_uninit, };
7,091
507
import os from unittest import TestCase from bauh.gems.arch import aur FILE_DIR = os.path.dirname(os.path.abspath(__file__)) class AURModuleTest(TestCase): def test_map_srcinfo__only_one_pkgname(self): expected_fields = { 'pkgbase': 'bauh', 'pkgname': 'bauh', 'pkgver': '0.9.6', 'pkgrel': '2', 'url': 'https://github.com/vinifmor/bauh', 'arch': 'any', 'license': 'zlib/libpng', 'makedepends': ['git', 'python', 'python-pip', 'python-setuptools'], 'depends': [ 'python', 'python-colorama', 'python-pyaml', 'python-pyqt5', 'python-pyqt5-sip', 'python-requests', 'qt5-svg' ], 'optdepends': [ 'flatpak: required for Flatpak support', 'python-beautifulsoup4: for Native Web applications support', 'python-lxml: for Native Web applications support', 'snapd: required for Snap support' ], 'source': ['https://github.com/vinifmor/bauh/archive/0.9.6.tar.gz'], 'sha512sums': ['cb1820b8a41dccec746d91d71b7f524c2e3caf6b30b0cd9666598b8ad49302654d9ce9bd1a0a2a9612afebc27ef78a2a94ac10e4e6c183742effe4feeabaa7b2'] } with open(FILE_DIR + '/resources/bauh_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'bauh') for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key])) def test_map_srcinfo__one_name__only_specific_fields(self): expected_fields = { 'pkgver': '0.9.6', 'pkgrel': '2' } with open(FILE_DIR + '/resources/bauh_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'bauh', fields={*expected_fields.keys()}) self.assertEqual(len(expected_fields), len(res), "Expected: {}. Current: {}".format(len(expected_fields), len(res))) for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key])) def test_map_srcinfo__several_pkgnames__pkgname_specified_case_1(self): expected_fields = { 'pkgbase': 'mangohud', 'pkgname': 'mangohud', 'pkgver': '0.5.1', 'pkgrel': '3', 'pkgdesc': 'A Vulkan overlay layer for monitoring FPS, temperatures, CPU/GPU load and more', 'source': ['mangohud-0.5.1.tar.gz::https://github.com/flightlessmango/MangoHud/archive/v0.5.1.tar.gz'], 'sha256sums': ['3e91d4fc7369d46763894c13f3315133871dd02705072981770c3cf58e8081c6'], 'license': 'MIT', 'arch': 'x86_64', 'url': 'https://github.com/flightlessmango/MangoHud', 'makedepends': [ 'glslang', 'libglvnd', 'lib32-libglvnd', 'meson', 'python-mako', 'vulkan-headers', 'vulkan-icd-loader', 'lib32-vulkan-icd-loader', 'libxnvctrl' ], 'depends': ['gcc-libs', 'mangohud-common'], 'optdepends': ['bash: mangohud helper script', 'libxnvctrl: support for older NVIDIA GPUs'] } with open(FILE_DIR + '/resources/mangohud_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'mangohud') self.assertEqual(len(expected_fields), len(res), "Expected: {}. Current: {}".format(len(expected_fields), len(res))) for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() if isinstance(res[key], list): res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key])) def test_map_srcinfo__several_pkgnames__pkgname_specified_case_2(self): expected_fields = { 'pkgbase': 'mangohud', 'pkgname': 'mangohud-common', 'pkgver': '0.5.1', 'pkgrel': '3', 'pkgdesc': 'Common files for mangohud and lib32-mangohud', 'source': ['mangohud-0.5.1.tar.gz::https://github.com/flightlessmango/MangoHud/archive/v0.5.1.tar.gz'], 'sha256sums': ['3e91d4fc7369d46763894c13f3315133871dd02705072981770c3cf58e8081c6'], 'license': 'MIT', 'url': 'https://github.com/flightlessmango/MangoHud', 'arch': 'x86_64', 'makedepends': [ 'glslang', 'libglvnd', 'lib32-libglvnd', 'meson', 'python-mako', 'vulkan-headers', 'vulkan-icd-loader', 'lib32-vulkan-icd-loader', 'libxnvctrl' ], 'optdepends': ['bash: mangohud helper script'] } with open(FILE_DIR + '/resources/mangohud_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'mangohud-common') self.assertEqual(len(expected_fields), len(res), "Expected: {}. Current: {}".format(len(expected_fields), len(res))) for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() if isinstance(res[key], list): res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key])) def test_map_srcinfo__several_pkgnames__pkgname_specified_case_3(self): expected_fields = { 'pkgbase': 'mangohud', 'pkgname': 'lib32-mangohud', 'pkgver': '0.5.1', 'pkgrel': '3', 'pkgdesc': 'A Vulkan overlay layer for monitoring FPS, temperatures, CPU/GPU load and more (32-bit)', 'source': ['mangohud-0.5.1.tar.gz::https://github.com/flightlessmango/MangoHud/archive/v0.5.1.tar.gz'], 'sha256sums': ['3e91d4fc7369d46763894c13f3315133871dd02705072981770c3cf58e8081c6'], 'license': 'MIT', 'url': 'https://github.com/flightlessmango/MangoHud', 'arch': 'x86_64', 'makedepends': [ 'glslang', 'libglvnd', 'lib32-libglvnd', 'meson', 'python-mako', 'vulkan-headers', 'vulkan-icd-loader', 'lib32-vulkan-icd-loader', 'libxnvctrl' ], 'depends': ['mangohud', 'mangohud-common', 'lib32-gcc-libs'], 'optdepends': ['lib32-libxnvctrl: support for older NVIDIA GPUs'] } with open(FILE_DIR + '/resources/mangohud_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'lib32-mangohud') self.assertEqual(len(expected_fields), len(res), "Expected: {}. Current: {}".format(len(expected_fields), len(res))) for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() if isinstance(res[key], list): res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key])) def test_map_srcinfo__several_pkgnames__different_pkgname(self): expected_fields = { 'pkgbase': 'mangohud', 'pkgname': ['lib32-mangohud', 'mangohud', 'mangohud-common'], 'pkgver': '0.5.1', 'pkgrel': '3', 'pkgdesc': [ 'A Vulkan overlay layer for monitoring FPS, temperatures, CPU/GPU load and more (32-bit)', 'Common files for mangohud and lib32-mangohud', 'A Vulkan overlay layer for monitoring FPS, temperatures, CPU/GPU load and more', ], 'source': ['mangohud-0.5.1.tar.gz::https://github.com/flightlessmango/MangoHud/archive/v0.5.1.tar.gz'], 'sha256sums': ['3e91d4fc7369d46763894c13f3315133871dd02705072981770c3cf58e8081c6'], 'license': 'MIT', 'url': 'https://github.com/flightlessmango/MangoHud', 'arch': 'x86_64', 'makedepends': [ 'glslang', 'libglvnd', 'lib32-libglvnd', 'meson', 'python-mako', 'vulkan-headers', 'vulkan-icd-loader', 'lib32-vulkan-icd-loader', 'libxnvctrl' ], 'depends': ['mangohud', 'mangohud-common', 'lib32-gcc-libs', 'gcc-libs'], 'optdepends': ['lib32-libxnvctrl: support for older NVIDIA GPUs', 'bash: mangohud helper script', 'libxnvctrl: support for older NVIDIA GPUs'] } with open(FILE_DIR + '/resources/mangohud_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'xpto') self.assertEqual(len(expected_fields), len(res), "Expected: {}. Current: {}".format(len(expected_fields), len(res))) for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() if isinstance(res[key], list): res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key])) def test_map_srcinfo__several_names__pkgname_present__only_specific_fields(self): expected_fields = { 'pkgver': '0.5.1', 'pkgrel': '3' } with open(FILE_DIR + '/resources/mangohud_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'mangohud-commons', fields={*expected_fields.keys()}) self.assertEqual(len(expected_fields), len(res), "Expected: {}. Current: {}".format(len(expected_fields), len(res))) for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key])) def test_map_srcinfo__several_names__pkgname_not_present__only_specific_fields(self): expected_fields = { 'pkgname': ['mangohud', 'lib32-mangohud', 'mangohud-common'], 'pkgver': '0.5.1' } with open(FILE_DIR + '/resources/mangohud_srcinfo') as f: srcinfo = f.read() res = aur.map_srcinfo(srcinfo, 'xpto', fields={*expected_fields.keys()}) self.assertEqual(len(expected_fields), len(res), "Expected: {}. Current: {}".format(len(expected_fields), len(res))) for key, val in expected_fields.items(): self.assertIn(key, res, "key '{}' not in res".format(key)) if isinstance(val, list): val.sort() res[key].sort() self.assertEqual(val, res[key], "expected: {}. current: {}".format(val, res[key]))
5,684
852
<gh_stars>100-1000 #ifndef ParametrizedEngine_TkBfield_h #define ParametrizedEngine_TkBfield_h /** \class magfieldparam::TkBfield * * * B-field in Tracker volume - based on the TOSCA computation version 1103l * (tuned on MTCC measured field (fall 2006)) * * In: x[3]: coordinates (m) * Out: B[3]: Bx,By,Bz (T) (getBxyz) * Out: B[3]: Br,Bf,Bz (T) (getBrfz) * * Valid for r<1.15m and |z|<2.80m * * \author V.Karimaki 080228, 080407 * new float version V.I. October 2012 */ #include "BCyl.h" #include <string> namespace magfieldparam { class TkBfield { public: // Deprecated ctor, nominal field value specified with a string, eg. "3_8T" TkBfield(std::string T); // Ctor TkBfield(float fld = 3.8); /// B out in cartesian void getBxyz(float const* __restrict__ x, float* __restrict__ Bxyz) const; /// B out in cylindrical void getBrfz(float const* __restrict__ x, float* __restrict__ Brfz) const; private: BCycl<float> bcyl; }; } // namespace magfieldparam #endif
458
395
<gh_stars>100-1000 package timely.client.websocket; import java.util.List; import java.util.Map; import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class ClientHandler extends Endpoint { private final static Logger LOG = LoggerFactory.getLogger(ClientHandler.class); @Override public void onOpen(Session session, EndpointConfig config) { LOG.info("Websocket session {} opened.", session.getId()); session.addMessageHandler(new MessageHandler.Whole<String>() { @Override public void onMessage(String message) { LOG.info("Message received on Websocket session {}: {}", session.getId(), message); } }); } @Override public void onClose(Session session, CloseReason reason) { LOG.info("Websocket session {} closed.", session.getId()); } @Override public void onError(Session session, Throwable error) { LOG.error("Error occurred on Websocket session" + session.getId(), error); } public void beforeRequest(Map<String, List<String>> headers) { } }
469
6,240
/* * Copyright 2016 The Closure Compiler 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.javascript.jscomp; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ListMultimap; import com.google.common.collect.MultimapBuilder; import com.google.common.collect.Multiset; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.ArrayDeque; import java.util.Deque; /** * An AST traverser that keeps track of whether access to a generic resource are "guarded" or not. A * guarded use is one that will not cause runtime errors if the resource does not exist. The * resource (type {@code T} in the signature) is any value type computable from a node, such as a * qualified name or property name. It is up to the subclass to map the currently visited token to * the {@code T} in order to call {@link #isGuarded}, which depends entirely on the context from * ancestor nodes and previous calls to {@code #isGuarded} for the same resource. * * <p>More precisely, a resource may be guarded either <i>intrinsically</i> or <i>conditionally</i>, * as follows. A use is intrinsically guarded if it occurs in a context where its specific value is * immediately discarded, such as coercion to boolean or string. A use is conditionally guarded if * it occurs in a context conditioned on an intrinsically guarded use (such as the "then" or "else" * block of an "if", the second or third argument of a ternary operator, right-hand arguments of * logical operators, or later in a block in which an unconditional "throw" or "return" was found in * a guarded context). * * <p>For example, the following are all intrinsically guarded uses of {@code x}: * * <pre>{@code * // Coerced to boolean: * if (x); * x ? y : z; * x &amp;&amp; y; * Boolean(x); * !x; * x == y; x != y; x === y; x !== y; * x instanceof Foo; * typeof x === 'string'; * * // Coerced to string: * String(x); * typeof x; * * // Immediately discarded (but doesn't make much sense in my contexts): * x = y; * }</pre> * * <p>The following uses of {@code x} are conditionally guarded: * * <pre>{@code * if (x) x(); * !x ? null : x; * typeof x == 'function' ? x : () => {}; * x &amp;&amp; x.y; * !x || x.y; * if (!x) return; x(); * x ?? x = 3; * }</pre> * * Note that there is no logic to determine <i>which</i> branch is guarded, so any usages in either * branch will pass after such a check. As such, the following are also considered guarded, though a * human can easily see that this is spurious: * * <pre>{@code * if (!x) x(); * if (x) { } else x(); * !x &amp;&amp; x(); * var y = x != null ? null : x; * }</pre> * * Note also that the call or property access is not necessary to make a use unguarded: the final * example immediately above would be unguarded if it weren't for the {@code x != null} condition, * since it allows the value of {@code x} to leak out in an uncontrolled way. * * <p>This class overrides the {@link Callback} API methods with final methods of its own, and * defines the template method {@link #visitGuarded} to perform the normal work for individual * nodes. The only other API is {@link #isGuarded}, which allows checking if a {@code T} in the * current node's context is guarded, either intrinsically or conditionally. If it is intrinsically * guarded, then it may be recorded as a condition for the purpose of guarding future contexts. */ abstract class GuardedCallback<T> implements Callback { // Compiler is needed for coding convention (isPropertyTestFunction). private final AbstractCompiler compiler; // Map from short-circuiting conditional nodes (AND, OR, COALESCE, IF, and HOOK) to // the set of resources each node guards. This is saved separately from // just `guarded` because the guard must not go into effect until after // traversal of the first child is complete. Before traversing the second // child any node, its values in this map are moved into `guarded` and // `installedGuards` (the latter allowing removal at the correct time). private final SetMultimap<Node, T> registeredGuards = MultimapBuilder.hashKeys().hashSetValues().build(); // Set of currently-guarded resources. Elements are added to this set // just before traversing the second or later (i.e. "then" or "else") // child of a short-circuiting conditional node, and then removed after // traversing the last child. It is a multiset so that multiple adds // of the same resource require the same number of removals before the // resource becomes unguarded. private final Multiset<T> guarded = HashMultiset.create(); // Resources that are currently installed as guarded but will need to // be removed from `guarded` after visiting all the key nodes' children. private final ListMultimap<Node, T> installedGuards = MultimapBuilder.hashKeys().arrayListValues().build(); // A stack of `Context` objects describing the current node's context: // specifically, whether it is inherently safe, and a link to one or // more conditional nodes in the current statement directly above it // (for registering safe resources as guards). private final Deque<Context> contextStack = new ArrayDeque<>(); GuardedCallback(AbstractCompiler compiler) { this.compiler = compiler; } @Override public final boolean shouldTraverse(NodeTraversal traversal, Node n, Node parent) { // Note that shouldTraverse() operates primarily on `parent`, while visit() // uses `n`. This is intentional. To see why, consider traversing the // following tree: // // if (x) y; else z; // // 1. shouldTraverse(`if`): // a. parent is null, so pushes an EMPTY onto the context stack. // 2. shouldTraverse(`x`): // a. parent is `if`, so pushes Context(`if`, true); guards is empty. // 3. visit(`x`) // a. guarded and installedGuards are both empty, so nothing is removed. // b. visitGuarded(`x`) will call isGuarded("x"), which looks at the top // of the stack and sees that the context is safe (true) and that // there is a linked conditional node (the `if`); adds {`if`: "x"} // to registeredGuards. // b. Context(`if`, true) is popped off the stack. // 4. shouldTraverse(`y`): // a. parent is still `if`, but since `y` is the second child it is // no longer safe, so another EMPTY is pushed. // b. the {`if`: "x"} guard is moved from registered to installed. // 5. visit(`y`): // a. nothing is installed on `y` so no guards are removed. // b. visitGuarded(`y`) will call isGuarded("y"), which will return // false since "y" is neither intrinsically or conditionally guarded; // if we'd called isResourceRequired("x"), it would return false // because "x" is currently an element of guarded. // c. one empty context is popped. // 6. shouldTraverse(`z`), visit(`z`) // a. see steps 4-5, nothing really changes here. // 7. visit(`if`) // a. the installed {`if`: "x"} guard is removed. // c. pop the final empty context from the stack. if (parent == null) { // The first node gets an empty context. contextStack.push(Context.EMPTY); } else { // Before traversing any children, we update the stack contextStack.push(contextStack.peek().descend(compiler, parent, n)); // If the parent has any guards registered on it, then add them to both // `guarded` and `installedGuards`. if (parent != null && CAN_HAVE_GUARDS.contains(parent.getToken()) && registeredGuards.containsKey(parent)) { for (T resource : registeredGuards.removeAll(parent)) { guarded.add(resource); installedGuards.put(parent, resource); } } } return true; } @Override public final void visit(NodeTraversal traversal, Node n, Node parent) { // Remove any guards registered on this node by its children, which are no longer // relevant. This happens first because these were registered on a "parent", but // now this is that parent (i.e. `n` here vs `parent` in isGuarded). if (parent != null && CAN_HAVE_GUARDS.contains(n.getToken()) && installedGuards.containsKey(n)) { guarded.removeAll(installedGuards.removeAll(n)); } // Check for abrupt returns (`return` and `throw`). if (isAbrupt(n)) { // If found, any guards installed on a parent IF should be promoted to the // grandparent. This allows a small amount of flow-sensitivity, in that // if (!x) return; x(); // has the guard for `x` promoted from the `if` to the outer block, so that // it guards the next statement. promoteAbruptReturns(parent); } // Finally continue on to whatever the traversal would normally do. visitGuarded(traversal, n, parent); // After children have been traversed, pop the top of the conditional stack. contextStack.pop(); } private void promoteAbruptReturns(Node parent) { // If the parent is a BLOCK (e.g. `if (x) { return; }`) then go up one level. if (parent.isBlock()) { parent = parent.getParent(); } // If there were any guards registered the parent IF, then promote them up one level. if (parent.isIf() && installedGuards.containsKey(parent)) { Node grandparent = parent.getParent(); if (grandparent.isBlock() || grandparent.isScript()) { registeredGuards.putAll(grandparent, installedGuards.get(parent)); } } } /** * Performs specific traversal behavior. Should call {@link #isGuarded} * at least once. */ abstract void visitGuarded(NodeTraversal traversal, Node n, Node parent); /** * Determines if the given resource is guarded, either intrinsically or * conditionally. If the former, any ancestor conditional nodes are * registered as feature-testing the resource. */ boolean isGuarded(T resource) { // Check if this polyfill is already guarded. If so, return true right away. if (guarded.contains(resource)) { return true; } // If not, see if this is itself a feature check guard. This is // defined as a usage of the polyfill in such a way that throws // away the actual value and only cares about its truthiness or // typeof. We walk up the ancestor tree through a small set of // node types and if this is detected to be a guard, then the // conditional node is marked as a guard for this polyfill. Context context = contextStack.peek(); if (!context.safe) { return false; } // Loop over all the linked conditionals and register this as a guard. while (context != null && context.conditional != null) { registeredGuards.put(context.conditional, resource); context = context.linked; } return true; } // The context of a node, keeping track of whether it is safe for // possibly-undefined values, and whether there are any conditionals // upstream in the tree. private static class Context { // An empty instance: unsafe and with no linked conditional nodes. static final Context EMPTY = new Context(null, false, null); // The most recent conditional. final Node conditional; // Whether this position is safe for an undefined type. final boolean safe; // A very naive linked list for storing additional conditional nodes. final Context linked; Context(Node conditional, boolean safe, Context linked) { this.conditional = conditional; this.safe = safe; this.linked = linked; } // Returns a new Context with a new conditional node and safety status. // If the current context already has a conditional, then it is linked // so that both can be marked when necessary. Context link(Node newConditional, boolean newSafe) { return new Context(newConditional, newSafe, this.conditional != null ? this : null); } // Returns a new Context with a different safety bit, but doesn't // change anything else. Context propagate(boolean newSafe) { return newSafe == safe ? this : new Context(conditional, newSafe, linked); } // Returns a new context given the current context and the next parent // node. Child is only used to determine whether we're looking at the // first child or not. Context descend(AbstractCompiler compiler, Node parent, Node child) { boolean first = child == parent.getFirstChild(); switch (parent.getToken()) { case CAST: // Casts are irrelevant. return this; case COMMA: // `Promise, whatever` is safe. // `whatever, Promise` is same as outer context. return child == parent.getLastChild() ? this : propagate(true); case AND: // `Promise && whatever` never returns Promise itself, so it is safe. // `whatever && Promise` may return Promise, so return outer context. return first ? link(parent, true) : this; case OR: case COALESCE: // `Promise || whatever` and `Promise ?? whatever` // may return Promise (unsafe), but is itself a conditional. // `whatever || Promise` and `whatever ?? Promise` // is same as outer context. return first ? link(parent, false) : this; case HOOK: // `Promise ? whatever : whatever` is a safe conditional. // `whatever ? Promise : whatever` (etc) is same as outer context. return first ? link(parent, true) : this; case IF: // `if (Promise) whatever` is a safe conditional. // `if (whatever) { ... }` is nothing. // TODO(sdh): Handle do/while/for/for-of/for-in? return first ? link(parent, true) : EMPTY; case INSTANCEOF: case ASSIGN: // `Promise instanceof whatever` is safe, `whatever instanceof Promise` is not. // `Promise = whatever` is a bad idea, but it's safe w.r.t. polyfills. return propagate(first); case TYPEOF: case NOT: case EQ: case NE: case SHEQ: case SHNE: // `typeof Promise` is always safe, as is `Promise == whatever`, etc. return propagate(true); case CALL: // `String(Promise)` is safe, `Promise(whatever)` or `whatever(Promise)` is not. return propagate(!first && isPropertyTestFunction(compiler, parent)); case ROOT: // This case causes problems for isStatement() so handle it separately. return EMPTY; case OPTCHAIN_CALL: case OPTCHAIN_GETELEM: case OPTCHAIN_GETPROP: if (first) { // thisNode?.rest.of.chain // OR firstChild?.thisNode.rest.of.chain // For the first case `thisNode` should be considered intrinsically guarded. return link(parent, parent.isOptionalChainStart()); } else { // `first?.(thisNode)` // or `first?.[thisNode]` // or `first?.thisNode` return propagate(false); } default: // Expressions propagate linked conditionals; statements do not. return NodeUtil.isStatement(parent) ? EMPTY : propagate(false); } } } private static boolean isAbrupt(Node n) { return n.isReturn() || n.isThrow(); } // Extend the coding convention's idea of property test functions to also // include String() and Boolean(). private static boolean isPropertyTestFunction(AbstractCompiler compiler, Node n) { if (compiler.getCodingConvention().isPropertyTestFunction(n)) { return true; } Node target = n.getFirstChild(); if (target.isName()) { String name = target.getString(); return name.equals("String") || name.equals("Boolean"); } return false; } // Tokens that are allowed to have guards on them (no point doing a hash lookup on // any other type of node). private static final ImmutableSet<Token> CAN_HAVE_GUARDS = Sets.immutableEnumSet( Token.AND, Token.OR, Token.COALESCE, Token.HOOK, Token.IF, Token.BLOCK, Token.SCRIPT, Token.OPTCHAIN_CALL, Token.OPTCHAIN_GETELEM, Token.OPTCHAIN_GETPROP); }
5,796
392
/* * Copyright (c) 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package jsettlers.graphics.image.reader; import java.util.List; public final class Hashes { private final List<Long> hashes; public Hashes(List<Long> hashes) { this.hashes = hashes; } public int[] compareAndCreateMapping(Hashes other) { int[] mapping = new int[hashes.size()]; for (int i1 = 0; i1 < hashes.size(); i1++) { Long h1 = hashes.get(i1); int i2 = i1 < other.hashes.size() && h1.equals(other.hashes.get(i1)) ? i1 : other.hashes.indexOf(h1); mapping[i1] = i2; System.out.println(i1 + " -> " + i2); } return mapping; } public long hash() { long hashCode = 1L; long multiplier = 1L; for (Long hash : hashes) { multiplier *= 31L; hashCode += (hash + 27L) * multiplier; } return hashCode; } public List<Long> getHashes() { return hashes; } }
607
528
"""Hill-Climbing. """ import opytimizer.math.random as r import opytimizer.utils.exception as e import opytimizer.utils.logging as l from opytimizer.core import Optimizer logger = l.get_logger(__name__) class HC(Optimizer): """An HC class, inherited from Optimizer. This is the designed class to define HC-related variables and methods. References: <NAME>. The Algorithm Design Manual (2010). """ def __init__(self, params=None): """Initialization method. Args: params (dict): Contains key-value parameters to the meta-heuristics. """ logger.info('Overriding class: Optimizer -> HC.') # Overrides its parent class with the receiving params super(HC, self).__init__() # Mean of noise distribution self.r_mean = 0 # Variance of noise distribution self.r_var = 0.1 # Builds the class self.build(params) logger.info('Class overrided.') @property def r_mean(self): """float: Mean of noise distribution. """ return self._r_mean @r_mean.setter def r_mean(self, r_mean): if not isinstance(r_mean, (float, int)): raise e.TypeError('`r_mean` should be a float or integer') self._r_mean = r_mean @property def r_var(self): """float: Variance of noise distribution. """ return self._r_var @r_var.setter def r_var(self, r_var): if not isinstance(r_var, (float, int)): raise e.TypeError('`r_var` should be a float or integer') if r_var < 0: raise e.ValueError('`r_var` should be >= 0') self._r_var = r_var def update(self, space): """Wraps Hill Climbing over all agents and variables (p. 252). Args: space (Space): Space containing agents and update-related information. """ # Iterates through all agents for agent in space.agents: # Creates a gaussian noise vector noise = r.generate_gaussian_random_number( self.r_mean, self.r_var, size=(agent.n_variables, agent.n_dimensions)) # Updates agent's position agent.position += noise
972
3,121
import unittest import os import numpy as np from dotenv import load_dotenv import nlpaug.augmenter.audio as naa from nlpaug.util import AudioLoader class TestLoudness(unittest.TestCase): @classmethod def setUpClass(cls): env_config_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..', '.env')) load_dotenv(env_config_path) # https://freewavesamples.com/yamaha-v50-rock-beat-120-bpm cls.sample_wav_file = os.path.join( os.environ.get("TEST_DIR"), 'res', 'audio', 'Yamaha-V50-Rock-Beat-120bpm.wav' ) cls.audio, cls.sampling_rate = AudioLoader.load_audio(cls.sample_wav_file) def test_empty_input(self): audio = np.array([]) aug = naa.LoudnessAug() augmented_audio = aug.augment(audio) self.assertTrue(np.array_equal(audio, augmented_audio)) def test_substitute(self): aug = naa.LoudnessAug() augmented_audio = aug.augment(self.audio) self.assertFalse(np.array_equal(self.audio, augmented_audio)) self.assertEqual(len(self.audio), len(augmented_audio)) self.assertTrue(self.sampling_rate > 0)
534
336
# run 'scrapy runspider CDC_General_scraper.py' to scrape data from datetime import date import scrapy from scrapy.crawler import CrawlerProcess class CovidScraper(scrapy.Spider): name = "CDC_Scraper" start_urls = ["https://www.cdc.gov/coronavirus/2019-ncov/faq.html"] def parse(self, response): columns = { "question": [], "answer": [], "answer_html": [], "link": [], "name": [], "source": [], "category": [], "country": [], "region": [], "city": [], "lang": [], "last_update": [], } current_category = "" all_nodes = response.xpath("//*") for i,node in enumerate(all_nodes): # in category if node.attrib.get("class") == "onThisPageAnchor": current_category = node.attrib["title"] continue # in category if current_category: # in question if node.attrib.get("role") == "heading": current_question = node.css("::text").get() # in answer if node.attrib.get("class") == "card-body": current_answer = node.css(" ::text").getall() current_answer = " ".join(current_answer).strip() current_answer_html = node.getall() current_answer_html = " ".join(current_answer_html).strip() # add question-answer-pair to data dictionary columns["question"].append(current_question) columns["answer"].append(current_answer) columns["answer_html"].append(current_answer_html) columns["category"].append(current_category) # end of category if node.attrib.get("class") == "row": current_category = "" today = date.today() columns["link"] = ["https://www.cdc.gov/coronavirus/2019-ncov/faq.html"] * len(columns["question"]) columns["name"] = ["CDC General FAQ"] * len(columns["question"]) columns["source"] = ["Center for Disease Control and Prevention (CDC)"] * len(columns["question"]) columns["country"] = ["USA"] * len(columns["question"]) columns["region"] = [""] * len(columns["question"]) columns["city"] = [""] * len(columns["question"]) columns["lang"] = ["en"] * len(columns["question"]) columns["last_update"] = [today.strftime("%Y/%m/%d")] * len(columns["question"]) return columns if __name__ == "__main__": process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(CovidScraper) process.start()
1,370
892
{ "schema_version": "1.2.0", "id": "GHSA-8qwp-q6qh-937c", "modified": "2022-05-01T07:31:00Z", "published": "2022-05-01T07:31:00Z", "aliases": [ "CVE-2006-5717" ], "details": "Multiple cross-site scripting (XSS) vulnerabilities in Zend Google Data Client Library (ZendGData) Preview 0.2.0 allow remote attackers to inject arbitrary web script or HTML via unspecified parameters in (1) basedemo.php and (2) calenderdemo.php in samples/, and other unspecified files.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-5717" }, { "type": "WEB", "url": "http://securityreason.com/securityalert/1815" }, { "type": "WEB", "url": "http://www.armorize.com/resources/vulnerability.php?Keyword=Armorize-ADV-2006-0008" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/450245/100/0/threaded" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/20851" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
524
703
/* * This file is part of ClassGraph. * * Author: <NAME> * * Hosted at: https://github.com/classgraph/classgraph * * -- * * The MIT License (MIT) * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package nonapi.io.github.classgraph.reflection; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import nonapi.io.github.classgraph.concurrency.SingletonMap; import nonapi.io.github.classgraph.utils.LogNode; /** Reflection driver */ abstract class ReflectionDriver { private final SingletonMap<Class<?>, ClassMemberCache, Exception> classToClassMemberCache // = new SingletonMap<Class<?>, ClassMemberCache, Exception>() { @Override public ClassMemberCache newInstance(final Class<?> cls, final LogNode log) throws Exception, InterruptedException { return new ClassMemberCache(cls); } }; private static Method isAccessibleMethod; private static Method canAccessMethod; static { // Find deprecated methods to remove compile-time warnings // TODO Switch to using MethodHandles once this is fixed: // https://github.com/mojohaus/animal-sniffer/issues/67 try { isAccessibleMethod = AccessibleObject.class.getDeclaredMethod("isAccessible"); } catch (final Throwable t) { // Ignore } try { canAccessMethod = AccessibleObject.class.getDeclaredMethod("canAccess", Object.class); } catch (final Throwable t) { // Ignore } } /** Caches class members. */ public class ClassMemberCache { private final Map<String, List<Method>> methodNameToMethods = new HashMap<>(); private final Map<String, Field> fieldNameToField = new HashMap<>(); private ClassMemberCache(final Class<?> cls) throws Exception { // Iterate from class to its superclasses, and find initial interfaces to start traversing from final Set<Class<?>> visited = new HashSet<>(); final LinkedList<Class<?>> interfaceQueue = new LinkedList<Class<?>>(); for (Class<?> c = cls; c != null; c = c.getSuperclass()) { try { // Cache any declared methods and fields for (final Method m : getDeclaredMethods(c)) { cacheMethod(m); } for (final Field f : getDeclaredFields(c)) { cacheField(f); } // Find interfaces and superinterfaces implemented by this class or its superclasses if (c.isInterface() && visited.add(c)) { interfaceQueue.add(c); } for (final Class<?> iface : c.getInterfaces()) { if (visited.add(iface)) { interfaceQueue.add(iface); } } } catch (final Exception e) { // Skip } } // Traverse through interfaces looking for default methods while (!interfaceQueue.isEmpty()) { final Class<?> iface = interfaceQueue.remove(); try { for (final Method m : getDeclaredMethods(iface)) { cacheMethod(m); } } catch (final Exception e) { // Skip } for (final Class<?> superIface : iface.getInterfaces()) { if (visited.add(superIface)) { interfaceQueue.add(superIface); } } } } private void cacheMethod(final Method method) { List<Method> methodsForName = methodNameToMethods.get(method.getName()); if (methodsForName == null) { methodNameToMethods.put(method.getName(), methodsForName = new ArrayList<>()); } methodsForName.add(method); } private void cacheField(final Field field) { // Only put a field name to field mapping if it is absent, so that subclasses mask fields // of the same name in superclasses if (!fieldNameToField.containsKey(field.getName())) { fieldNameToField.put(field.getName(), field); } } } /** * Find a class by name. * * @param className * the class name * @return the class reference */ abstract Class<?> findClass(final String className) throws Exception; /** * Get declared methods for class. * * @param cls * the class * @return the declared methods */ abstract Method[] getDeclaredMethods(Class<?> cls) throws Exception; /** * Get declared constructors for class. * * @param <T> * the generic type * @param cls * the class * @return the declared constructors */ abstract <T> Constructor<T>[] getDeclaredConstructors(Class<T> cls) throws Exception; /** * Get declared fields for class. * * @param cls * the class * @return the declared fields */ abstract Field[] getDeclaredFields(Class<?> cls) throws Exception; /** * Get the value of a non-static field, boxing the value if necessary. * * @param object * the object instance to get the field value from * @param field * the non-static field * @return the value of the field */ abstract Object getField(final Object object, final Field field) throws Exception; /** * Set the value of a non-static field, unboxing the value if necessary. * * @param object * the object instance to get the field value from * @param field * the non-static field * @param value * the value to set */ abstract void setField(final Object object, final Field field, Object value) throws Exception; /** * Get the value of a static field, boxing the value if necessary. * * @param field * the static field * @return the static field */ abstract Object getStaticField(final Field field) throws Exception; /** * Set the value of a static field, unboxing the value if necessary. * * @param field * the static field * @param value * the value to set */ abstract void setStaticField(final Field field, Object value) throws Exception; /** * Invoke a non-static method, boxing the result if necessary. * * @param object * the object instance to invoke the method on * @param method * the non-static method * @param args * the method arguments (or {@code new Object[0]} if there are no args) * @return the return value (possibly a boxed value) */ abstract Object invokeMethod(final Object object, final Method method, final Object... args) throws Exception; /** * Invoke a static method, boxing the result if necessary. * * @param method * the static method * @param args * the method arguments (or {@code new Object[0]} if there are no args) * @return the return value (possibly a boxed value) */ abstract Object invokeStaticMethod(final Method method, final Object... args) throws Exception; /** * Make a field or method accessible. * * @param instance * the object instance, or null if static. * @param fieldOrMethod * the field or method. * * @return true if successful. */ abstract boolean makeAccessible(final Object instance, final AccessibleObject fieldOrMethod); /** * Check whether a field or method is accessible. * * <p> * N.B. this is overridden in Narcissus driver to just return true, since everything is accessible to JNI. * * @param instance * the object instance, or null if static. * @param fieldOrMethod * the field or method. * * @return true if accessible. */ boolean isAccessible(final Object instance, final AccessibleObject fieldOrMethod) { if (canAccessMethod != null) { // JDK 9+: use canAccess try { return (Boolean) canAccessMethod.invoke(fieldOrMethod, instance); } catch (final Throwable e) { // Ignore } } if (isAccessibleMethod != null) { // JDK 7/8: use isAccessible (deprecated in JDK 9+) try { return (Boolean) isAccessibleMethod.invoke(fieldOrMethod); } catch (final Throwable e) { // Ignore } } return false; } /** * Get the field of the class that has a given field name. * * @param cls * the class. * @param obj * the object instance, or null for a static field. * @param fieldName * The name of the field. * @return The {@link Field} object for the requested field name, or null if no such field was found in the * class. * @throws Exception * if the field could not be found */ private Field findField(final Class<?> cls, final Object obj, final String fieldName) throws Exception { final Field field = classToClassMemberCache.get(cls, /* log = */ null).fieldNameToField.get(fieldName); if (field != null) { if (!isAccessible(obj, field)) { // If field was found but is not accessible, try making it accessible and then returning it // (may result in a reflective access warning on stderr) makeAccessible(obj, field); } return field; } throw new NoSuchFieldException("Could not find field " + cls.getName() + "." + fieldName); } /** * Get the static field of the class that has a given field name. * * @param cls * the class. * @param fieldName * The name of the field. * @return The {@link Field} object for the requested field name, or null if no such field was found in the * class. * @throws Exception * if the field could not be found */ protected Field findStaticField(final Class<?> cls, final String fieldName) throws Exception { return findField(cls, null, fieldName); } /** * Get the non-static field of the class that has a given field name. * * @param obj * the object instance, or null for a static field. * @param fieldName * The name of the field. * @return The {@link Field} object for the requested field name, or null if no such field was found in the * class. * @throws Exception * if the field could not be found */ protected Field findInstanceField(final Object obj, final String fieldName) throws Exception { if (obj == null) { throw new IllegalArgumentException("obj cannot be null"); } return findField(obj.getClass(), obj, fieldName); } /** * Get a method by name and parameter types. * * @param cls * the class. * @param obj * the object instance, or null for a static method. * @param methodName * The name of the method. * @param paramTypes * The types of the parameters of the method. For primitive-typed parameters, use e.g. Integer.TYPE. * @return The {@link Method} object for the matching method, or null if no such method was found in the class. * @throws Exception * if the method could not be found. */ private Method findMethod(final Class<?> cls, final Object obj, final String methodName, final Class<?>... paramTypes) throws Exception { final List<Method> methodsForName = classToClassMemberCache.get(cls, null).methodNameToMethods .get(methodName); if (methodsForName != null) { // Return the first method that matches the signature that is already accessible boolean found = false; for (final Method method : methodsForName) { if (Arrays.equals(method.getParameterTypes(), paramTypes)) { found = true; if (isAccessible(obj, method)) { return method; } } } // If method was found but is not accessible, try making it accessible and then returning it // (may result in a reflective access warning on stderr) if (found) { for (final Method method : methodsForName) { if (Arrays.equals(method.getParameterTypes(), paramTypes) && makeAccessible(obj, method)) { return method; } } } throw new NoSuchMethodException( "Could not make method accessible: " + cls.getName() + "." + methodName); } throw new NoSuchMethodException("Could not find method " + cls.getName() + "." + methodName); } /** * Get a static method by name and parameter types. * * @param cls * the class. * @param methodName * The name of the method. * @param paramTypes * The types of the parameters of the method. For primitive-typed parameters, use e.g. Integer.TYPE. * @return The {@link Method} object for the matching method, or null if no such method was found in the class. * @throws Exception * if the method could not be found. */ protected Method findStaticMethod(final Class<?> cls, final String methodName, final Class<?>... paramTypes) throws Exception { return findMethod(cls, null, methodName, paramTypes); } /** * Get a non-static method by name and parameter types. * * @param obj * the object instance, or null for a static method. * @param methodName * The name of the method. * @param paramTypes * The types of the parameters of the method. For primitive-typed parameters, use e.g. Integer.TYPE. * @return The {@link Method} object for the matching method, or null if no such method was found in the class. * @throws Exception * if the method could not be found. */ protected Method findInstanceMethod(final Object obj, final String methodName, final Class<?>... paramTypes) throws Exception { if (obj == null) { throw new IllegalArgumentException("obj cannot be null"); } return findMethod(obj.getClass(), obj, methodName, paramTypes); } }
6,961
6,647
/* * Copyright 1999-2019 Seata.io Group. * * 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.seata.common.util; import io.seata.common.exception.NotSupportYetException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /** * The page util test. * * @author l<EMAIL>@<EMAIL> */ public class PageUtilTest { @Test public void testPageSql() { String sourceSql = "select * from test where a = 1"; String mysqlTargetSql = "select * from test where a = 1 limit 5 offset 0"; String oracleTargetSql = "select * from " + "( select ROWNUM rn, temp.* from (select * from test where a = 1) temp )" + " where rn between 1 and 5"; assertEquals(PageUtil.pageSql(sourceSql, "mysql", 1, 5), mysqlTargetSql); assertEquals(PageUtil.pageSql(sourceSql, "h2", 1, 5), mysqlTargetSql); assertEquals(PageUtil.pageSql(sourceSql, "postgresql", 1, 5), mysqlTargetSql); assertEquals(PageUtil.pageSql(sourceSql, "oceanbase", 1, 5), mysqlTargetSql); assertEquals(PageUtil.pageSql(sourceSql, "oracle", 1, 5), oracleTargetSql); assertThrows(NotSupportYetException.class, () -> PageUtil.pageSql(sourceSql, "xxx", 1, 5)); } @Test void testCountSql() { String sourceSql = "select * from test where a = 1"; String targetSql = "select count(1) from test where a = 1"; assertEquals(PageUtil.countSql(sourceSql, "mysql"), targetSql); assertEquals(PageUtil.countSql(sourceSql, "h2"), targetSql); assertEquals(PageUtil.countSql(sourceSql, "postgresql"), targetSql); assertEquals(PageUtil.countSql(sourceSql, "oceanbase"), targetSql); assertEquals(PageUtil.countSql(sourceSql, "oracle"), targetSql); assertThrows(NotSupportYetException.class, () -> PageUtil.countSql(sourceSql, "xxx")); } }
953
2,728
<gh_stars>1000+ # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from ._network_functions_operations import NetworkFunctionsOperations from ._devices_operations import DevicesOperations from ._operations import Operations from ._vendors_operations import VendorsOperations from ._vendor_skus_operations import VendorSkusOperations from ._vendor_sku_preview_operations import VendorSkuPreviewOperations from ._network_function_vendors_operations import NetworkFunctionVendorsOperations from ._network_function_vendor_skus_operations import NetworkFunctionVendorSkusOperations from ._vendor_network_functions_operations import VendorNetworkFunctionsOperations from ._role_instances_operations import RoleInstancesOperations __all__ = [ 'NetworkFunctionsOperations', 'DevicesOperations', 'Operations', 'VendorsOperations', 'VendorSkusOperations', 'VendorSkuPreviewOperations', 'NetworkFunctionVendorsOperations', 'NetworkFunctionVendorSkusOperations', 'VendorNetworkFunctionsOperations', 'RoleInstancesOperations', ]
381
1,431
/* ==================================================================== 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.poi.ss.formula.eval; import org.apache.poi.ss.usermodel.FormulaEvaluator; /** * An exception thrown by implementors of {@link FormulaEvaluator}, * when attempting to evaluate a formula which requires features * that POI does not (yet) support. * * <p>Where possible, a subclass of this should be thrown, to provide * more detail of what part of the formula couldn't be processed due * to a missing implementation */ public class NotImplementedException extends RuntimeException { private static final long serialVersionUID = -5840703336495141301L; public NotImplementedException(String message) { super(message); } public NotImplementedException(String message, NotImplementedException cause) { super(message, cause); } }
452
4,297
/* * 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.dolphinscheduler.common.task.mr; import org.apache.dolphinscheduler.common.enums.ProgramType; import org.apache.dolphinscheduler.common.process.ResourceInfo; import org.apache.dolphinscheduler.common.task.AbstractParameters; import java.util.ArrayList; import java.util.List; /** * mapreduce parameters */ public class MapReduceParameters extends AbstractParameters { /** * major jar */ private ResourceInfo mainJar; /** * major class */ private String mainClass; /** * arguments */ private String mainArgs; /** * other arguments */ private String others; /** * app name */ private String appName; /** * queue */ private String queue; /** * resource list */ private List<ResourceInfo> resourceList = new ArrayList<>(); /** * program type * 0 JAVA,1 SCALA,2 PYTHON */ private ProgramType programType; public String getMainClass() { return mainClass; } public void setMainClass(String mainClass) { this.mainClass = mainClass; } public String getMainArgs() { return mainArgs; } public void setMainArgs(String mainArgs) { this.mainArgs = mainArgs; } public String getOthers() { return others; } public void setOthers(String others) { this.others = others; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getQueue() { return queue; } public void setQueue(String queue) { this.queue = queue; } public List<ResourceInfo> getResourceList() { return this.resourceList; } public void setResourceList(List<ResourceInfo> resourceList) { this.resourceList = resourceList; } public void setMainJar(ResourceInfo mainJar) { this.mainJar = mainJar; } public ResourceInfo getMainJar() { return mainJar; } public ProgramType getProgramType() { return programType; } public void setProgramType(ProgramType programType) { this.programType = programType; } @Override public boolean checkParameters() { return this.mainJar != null && this.programType != null; } @Override public List<ResourceInfo> getResourceFilesList() { if (mainJar != null && !resourceList.contains(mainJar)) { resourceList.add(mainJar); } return resourceList; } @Override public String toString() { return "mainJar= " + mainJar + "mainClass=" + mainClass + "mainArgs=" + mainArgs + "queue=" + queue + "other mainArgs=" + others ; } }
1,363
623
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2016 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.viewstate.zap.utils; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ViewState { private static Logger logger = LogManager.getLogger(ViewState.class); private String type; protected String value; protected String name; public ViewState(String val, String type, String name) { this.value = val; this.type = type; this.name = name; } public String getType() { return this.type; } public String getValue() { return this.value; } public String getName() { return this.name; } public byte[] getDecodedValue() { byte[] val = null; try { if (getType().equalsIgnoreCase(ASPViewState.KEY)) { ASPViewState avs = (ASPViewState) this; val = avs.decode(); } if (getType().equalsIgnoreCase(JSFViewState.KEY)) { JSFViewState jvs = (JSFViewState) this; ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(b); o.writeObject(jvs.decode()); val = b.toString().getBytes(); } } catch (Exception e) { logger.error("Exception in getDecodedValue(): {}", e.getMessage(), e); } return val; } public String getEncodedValue(byte[] plain) { String val = null; try { if (getType().equalsIgnoreCase(ASPViewState.KEY)) { ASPViewState avs = (ASPViewState) this; val = avs.encode(plain); } if (getType().equalsIgnoreCase(JSFViewState.KEY)) { JSFViewState jvs = (JSFViewState) this; val = jvs.encode(plain); } } catch (Exception e) { logger.error("Exception in getEncodedValue(): {}", e.getMessage(), e); } return val; } }
1,174
6,497
<gh_stars>1000+ package com.sohu.cache.stats.instance.impl; import com.sohu.cache.alert.EmailComponent; import com.sohu.cache.constant.AppCheckEnum; import com.sohu.cache.constant.InstanceStatusEnum; import com.sohu.cache.dao.AppAuditDao; import com.sohu.cache.dao.AppDao; import com.sohu.cache.dao.InstanceDao; import com.sohu.cache.dao.MachineRelationDao; import com.sohu.cache.entity.*; import com.sohu.cache.machine.MachineCenter; import com.sohu.cache.machine.MachineDeployCenter; import com.sohu.cache.redis.AssistRedisService; import com.sohu.cache.redis.RedisCenter; import com.sohu.cache.redis.RedisConfigTemplateService; import com.sohu.cache.redis.RedisDeployCenter; import com.sohu.cache.stats.instance.InstanceDeployCenter; import com.sohu.cache.task.TaskService; import com.sohu.cache.task.constant.MachineSyncEnum; import com.sohu.cache.task.constant.TaskQueueEnum; import com.sohu.cache.task.entity.TaskQueue; import com.sohu.cache.util.ConstUtils; import com.sohu.cache.util.TypeUtil; import com.sohu.cache.web.enums.MachineTaskEnum; import com.sohu.cache.web.enums.PodStatusEnum; import com.sohu.cache.web.service.AppService; import com.sohu.cache.web.service.ResourceService; import com.sohu.cache.web.util.DateUtil; import com.sohu.cache.web.util.FreemakerUtils; import freemarker.template.Configuration; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.web.client.RestTemplate; import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.JedisDataException; import java.util.*; import java.util.concurrent.TimeUnit; /** * Created by yijunzhang on 14-11-26. */ @Service("instanceDeployCenter") public class InstanceDeployCenterImpl implements InstanceDeployCenter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private InstanceDao instanceDao; @Autowired private MachineRelationDao machineRelationDao; @Autowired @Lazy private RedisCenter redisCenter; @Autowired private RedisDeployCenter redisDeployCenter; @Autowired @Lazy private MachineCenter machineCenter; @Autowired private AppAuditDao appAuditDao; @Autowired private AppDao appDao; @Autowired private RedisConfigTemplateService redisConfigTemplateService; @Autowired EmailComponent emailComponent; @Autowired(required = false) RestTemplate restTemplate; @Autowired MachineDeployCenter machineDeployCenter; @Autowired TaskService taskService; @Autowired AssistRedisService assistRedisService; @Autowired private Configuration configuration; @Autowired private AppService appService; @Autowired private ResourceService resourceService; private final static String LINE_SEP = "\\n"; private final static String FAIL = "fail"; @Override public boolean startExistInstance(long appId, int instanceId) { Assert.isTrue(instanceId > 0L); InstanceInfo instanceInfo = instanceDao.getInstanceInfoById(instanceId); Assert.isTrue(instanceInfo != null); int type = instanceInfo.getType(); String host = instanceInfo.getIp(); int port = instanceInfo.getPort(); // 获取redis路径 SystemResource redisResource = resourceService.getResourceById(appDao.getAppDescById(appId).getVersionId()); String redisDir = redisResource == null ? ConstUtils.REDIS_DEFAULT_DIR : ConstUtils.getRedisDir(redisResource.getName()); // Redis资源校验&推包 Boolean installStatus = redisConfigTemplateService.checkAndInstallRedisResource(host, redisResource); if (!installStatus) { logger.info("{} is install :{}", host, redisResource.getName()); return false; } boolean isRun; if (TypeUtil.isRedisType(type)) { if (TypeUtil.isRedisSentinel(type)) { isRun = redisCenter.isRun(host, port); } else { isRun = redisCenter.isRun(appId, host, port); } if (isRun) { logger.warn("{}:{} instance is Running", host, port); } else { String runShell = ""; if (TypeUtil.isRedisCluster(type)) { runShell = redisDeployCenter.getRedisRunShell(true, host, port, redisDir); } else if (TypeUtil.isRedisSentinel(type)) { runShell = redisDeployCenter.getSentinelRunShell(host, port, redisDir); } else { runShell = redisDeployCenter.getRedisRunShell(false, host, port, redisDir); } boolean isRunShell = machineCenter.startProcessAtPort(host, port, runShell); if (!isRunShell) { logger.error("startProcessAtPort-> {}:{} shell= {} failed", host, port, runShell); return false; } else { logger.warn("{}:{} instance has Run", host, port); } if (TypeUtil.isRedisSentinel(type)) { isRun = redisCenter.isRun(host, port); } else { isRun = redisCenter.isRun(appId, host, port); } } } else { logger.error("type={} not match!", type); isRun = false; } if (isRun) { instanceInfo.setStatus(InstanceStatusEnum.GOOD_STATUS.getStatus()); instanceDao.update(instanceInfo); } // 重置所有sentinel实例状态 if (TypeUtil.isRedisSentinel(type)) { try { redisDeployCenter.sentinelReset(appId); } catch (Exception e) { logger.error("redis sentinel reset error :{}", e.getMessage(), e); } } return isRun; } @Override public boolean shutdownExistInstance(long appId, int instanceId) { Assert.isTrue(instanceId > 0L); InstanceInfo instanceInfo = instanceDao.getInstanceInfoById(instanceId); Assert.isTrue(instanceInfo != null); int type = instanceInfo.getType(); String host = instanceInfo.getIp(); int port = instanceInfo.getPort(); boolean isShutdown; if (TypeUtil.isRedisType(type)) { if (TypeUtil.isRedisSentinel(type)) { isShutdown = redisCenter.shutdown(host, port); // 重置reset sentinel实例状态 try { redisDeployCenter.sentinelReset(appId); } catch (Exception e) { logger.error("redis sentinel reset error :{}", e.getMessage(), e); } } else { isShutdown = redisCenter.shutdown(appId, host, port); } if (isShutdown) { logger.warn("{}:{} redis is shutdown", host, port); } else { logger.error("{}:{} redis shutdown error", host, port); } } else { logger.error("type={} not match!", type); isShutdown = false; } if (isShutdown) { instanceInfo.setStatus(InstanceStatusEnum.OFFLINE_STATUS.getStatus()); instanceDao.update(instanceInfo); } return isShutdown; } @Override public boolean forgetInstance(long appId, int instanceId) { Assert.isTrue(instanceId > 0L); InstanceInfo instanceInfo = instanceDao.getInstanceInfoById(instanceId); Assert.isTrue(instanceInfo != null); String host = instanceInfo.getIp(); int port = instanceInfo.getPort(); String nodeId = null; //获取应用下所有在线实例 List<InstanceInfo> instanceList = appService.getAppOnlineInstanceInfo(appId); //找到一个运行的节点用来执行cluster nodes InstanceInfo firstRunning = null; for (InstanceInfo instance : instanceList) { //todo: 节点cluster node不能包含handshake?否则nodeId一直在变 if (redisCenter.isRun(appId, instance.getIp(), instance.getPort())) { firstRunning = instance; break; } } //先获取被forget节点的node id(cluster myid) String clusterNodes = redisCenter.getClusterNodes(appId, firstRunning.getIp(), firstRunning.getPort()); //从其他在线节点拿到cluster nodes nodeId = getNodeIdFromClusterNodes(clusterNodes, host, port); logger.warn("app {} instance {}:{} instanceId {} cluster node id {} will be forgot. cluster nodes\n{}", appId, host, port, instanceId, nodeId, clusterNodes); if (StringUtils.isNotBlank(nodeId)) { int forgetCount = 0; String instanceIp; int instancePort; for (InstanceInfo instanceInfo1 : instanceList) { instanceIp = instanceInfo1.getIp(); instancePort = instanceInfo1.getPort(); if (redisCenter.forget(appId, instanceIp, instancePort, nodeId)) { forgetCount++; logger.warn("instance {}:{} in app {} forget instance {}:{}-{} successfully", instanceIp, instancePort, appId, host, port, nodeId); } else { logger.error("instance {}:{} in app {} forget instance {}:{}-{} failed", instanceIp, instancePort, appId, host, port, nodeId); } } if (forgetCount == instanceList.size()) { //所有在线节点forget成功 instanceDao.updateStatus(appId, host, port, InstanceStatusEnum.FORGET_STATUS.getStatus()); logger.warn("app {} forget&update instance {}:{} successfully. current cluster nodes\n{}", appId, host, port, redisCenter.getClusterNodes(appId, firstRunning.getIp(), firstRunning.getPort())); return true; } } else { //cluster nodes已经没有该节点,则直接将数据库状态改为InstanceStatusEnum.FORGET_STATUS.getStatus() instanceDao.updateStatus(appId, host, port, InstanceStatusEnum.FORGET_STATUS.getStatus()); logger.warn("app {} update instance(nodeId is null) {}:{} successfully. current cluster nodes\n{}", appId, host, port, redisCenter.getClusterNodes(appId, firstRunning.getIp(), firstRunning.getPort())); return true; } return false; } @Override public boolean clearFailInstances(long appId) { try { //验证app类型是cluster AppDesc appDesc = appService.getByAppId(appId); if (appDesc.getType() != ConstUtils.CACHE_TYPE_REDIS_CLUSTER) { logger.warn("app {} is not cluster!", appId); return false; } //找到一个运行的节点用来执行cluster nodes List<InstanceInfo> instanceList = appService.getAppOnlineInstanceInfo(appId); InstanceInfo firstRun = null; for (InstanceInfo instanceInfo : instanceList) { if (redisCenter.isRun(appId, instanceInfo.getIp(), instanceInfo.getPort())) { firstRun = instanceInfo; break; } } if (firstRun == null) { logger.warn("app {} can not find an running instance!", appId); return false; } String clusterNodes = redisCenter.getClusterNodes(appId, firstRun.getIp(), firstRun.getPort()); //拿到cluster nodes if (StringUtils.isNotBlank(clusterNodes)) { String nodeId, hostPort, host, role; int port, total = 0; //total统计该应用共forget的节点数 String[] lines = clusterNodes.split(LINE_SEP); if (lines != null && lines.length > 0) { for (String line : lines) { if (line.contains(FAIL)) { //todo:其他判断条件 int count = 0; String[] items = line.split(" "); if (items != null && items.length > 0) { nodeId = items[0]; hostPort = items[1].split("@")[0]; host = hostPort.split(":")[0]; port = Integer.parseInt(hostPort.split(":")[1]); role = items[2]; for (InstanceInfo instance : instanceList) { if (redisCenter.forget(appId, instance.getIp(), instance.getPort(), nodeId)) { count++; } } if (count == instanceList.size()) { //所有节点都forget了该nodeId total++; instanceDao.updateStatus(appId, host, port, InstanceStatusEnum.FORGET_STATUS.getStatus()); logger.warn("instance {}:{} id {} role {} was forgot by all online instances", host, port, nodeId, role); } } } } } clusterNodes = redisCenter.getClusterNodes(appId, firstRun.getIp(), firstRun.getPort()); //拿到cluster nodes logger.warn("app {} clear total {} fail nodes. current cluster nodes\n{}", appId, total, clusterNodes); return true; } } catch (Exception e) { logger.error("app {} clear fail nodes error!", appId, e); } return false; } private String getNodeIdFromClusterNodes(String clusterNodes, String host, int port) { String nodeId = null; String hostPort = host + ":" + port; if (StringUtils.isNotBlank(clusterNodes)) { String[] lines = clusterNodes.split(LINE_SEP); if (lines != null && lines.length > 0) { for (String line : lines) { if (line.contains(hostPort)) { String[] items = line.split(" "); if (items != null && items.length > 0) { nodeId = items[0]; break; } } } } } return nodeId; } @Override public String showInstanceRecentLog(int instanceId, int maxLineNum) { Assert.isTrue(instanceId > 0L); InstanceInfo instanceInfo = instanceDao.getInstanceInfoById(instanceId); Assert.isTrue(instanceInfo != null); try { return machineCenter.showInstanceRecentLog(instanceInfo, maxLineNum); } catch (Exception e) { logger.error(e.getMessage(), e); return ""; } } @Override public boolean modifyInstanceConfig(long appId, Long appAuditId, String host, int port, String instanceConfigKey, String instanceConfigValue) { Assert.isTrue(appAuditId != null && appAuditId > 0L); Assert.isTrue(StringUtils.isNotBlank(host)); Assert.isTrue(port > 0); Assert.isTrue(StringUtils.isNotBlank(instanceConfigKey)); Assert.isTrue(StringUtils.isNotBlank(instanceConfigValue)); boolean isModify = redisDeployCenter.modifyInstanceConfig(appId, host, port, instanceConfigKey, instanceConfigValue); if (isModify) { // 改变审核状态 appAuditDao.updateAppAudit(appAuditId, AppCheckEnum.APP_ALLOCATE_RESOURCE.value()); } return isModify; } public MachineSyncEnum podChangeStatus(String ip) { // 获取pod变更历史 MachineSyncEnum syncEnum = null; List<MachineRelation> relationList = machineRelationDao.getOnlinePodList(ip, PodStatusEnum.ONLINE.getValue()); if (CollectionUtils.isEmpty(relationList) || relationList.size() == 1) { return MachineSyncEnum.NO_CHANGE; } else { // 1.当前pod的变更信息 MachineRelation current_podinfo = relationList.get(0); // 2.上一次pod的变更信息 MachineRelation pre_podinfo = relationList.get(1); // 3.判定宿主机是否变更 String sourceIp = pre_podinfo.getRealIp();//源宿主机 String targetIp = current_podinfo.getRealIp();//目标宿主机 if (!sourceIp.equals(targetIp)) { int relationId = pre_podinfo.getId(); String key = String.format("%s-%s", sourceIp, targetIp); try { // 3.1 保证只有同一个宿主机/目标宿主机执行同步任务 (多个pod ip对应一个宿主机) boolean setlock = assistRedisService.setNx(key, "sync"); if (setlock) { long taskId = taskService.addMachineSyncTask(sourceIp, targetIp, ip, String.format("sourceMachine:%s tagetMachine:%s ", sourceIp, targetIp), 0); if (taskId > 0) { logger.info("add machine sync task tashid:{} ", taskId); machineDeployCenter.updateMachineRelation(relationId, taskId, MachineTaskEnum.SYNCING.getValue()); // 3.2 探测 taskId 执行情况 10s轮训一次 long start = System.currentTimeMillis(); while (true) { TaskQueue taskQueue = taskService.getTaskQueueById(taskId); if (taskQueue.getStatus() == TaskQueueEnum.TaskStatusEnum.SUCCESS.getStatus()) { // a).同步任务执行完成退出 syncEnum = MachineSyncEnum.SYNC_SUCCESS; break; } if (taskQueue.getStatus() == TaskQueueEnum.TaskStatusEnum.ABORT.getStatus()) { // b).机器同步异常 syncEnum = MachineSyncEnum.SYNC_ABORT; break; } logger.info("machine sync taskid:{} status:{} waitting .... sleep 10s ", taskId, taskQueue.getStatus()); TimeUnit.SECONDS.sleep(10); } String emailTitle = String.format("Pod重启机器同步任务报警"); String emailContent = String.format("Pod ip:%s 发生重启, 宿主机发生变更[%s]->[%s],机器同步任务id:(%s) 状态:(%s), 数据同步时间开销:(%s s)", ip, sourceIp, targetIp, taskId, syncEnum.getDesc(), (System.currentTimeMillis() - start) / 1000); emailComponent.sendMailToAdmin(emailTitle, emailContent); } } else { return MachineSyncEnum.SYNC_EXECUTING; } } catch (Exception e) { logger.error("machine sync get lock error :{}", e.getMessage(), e); return MachineSyncEnum.SYNC_ERROR; } finally { assistRedisService.del(key); } } else { syncEnum = MachineSyncEnum.NO_CHANGE; String emailTitle = String.format("Pod重启机器同步任务报警"); String emailContent = String.format("Pod ip:%s 发生重启, 宿主机未变更[%s]->[%s] 状态:(%s)", ip, sourceIp, targetIp, syncEnum.getDesc()); emailComponent.sendMailToAdmin(emailTitle, emailContent); } return syncEnum; } } @Override public List<InstanceAlertValueResult> checkAndStartExceptionInstance(String ip, Boolean isAlert) { // 1.获取容器心跳停止/运行中的实例列表 List<InstanceInfo> instanceInfos = instanceDao.checkHeartStopInstance(ip); List<InstanceAlertValueResult> recoverInstInfo = new ArrayList<>(); // 2.滚动检测实例列表 if (!CollectionUtils.isEmpty(instanceInfos)) { for (InstanceInfo instance : instanceInfos) { long appId = instance.getAppId(); int instanceId = instance.getId(); String host = instance.getIp(); int port = instance.getPort(); int type = instance.getType(); logger.info("checkAndStartExceptionInstance scroll check instance {}:{} ", host, port); //2.1 检测实例是否启动 if (redisCenter.isRun(appId, ip, port)) { continue; } // 2.2 异常实例恢复 startExistInstance(appId, instanceId); // 2.3 检测异常实例启动成功 & 加载完成数据 & 启动下一个实例 Jedis jedis = null; int retry = 1;//重试次数 try { if (TypeUtil.isRedisSentinel(type)) { jedis = redisCenter.getJedis(host, port); } else { jedis = redisCenter.getJedis(appId, host, port); } while (true) { // 等待节点加载数据 & PONG String ping = ""; try { ping = jedis.ping(); } catch (JedisDataException e) { String message = e.getMessage(); logger.warn(e.getMessage()); if (StringUtils.isNotBlank(message) && message.startsWith("LOADING")) { logger.warn("scroll restart {}:{} waiting loading data ,sleep 2s", host, port); TimeUnit.SECONDS.sleep(2); } } catch (Exception e) { logger.error("scroll restart {}:{} ping exception sleep 200ms :{} ", host, port, e.getMessage(), e); TimeUnit.MILLISECONDS.sleep(200); } if (ping.equalsIgnoreCase("PONG") || retry++ >= 15) { InstanceAlertValueResult instanceAlertValueResult = new InstanceAlertValueResult(); instanceAlertValueResult.setInstanceInfo(instance); instanceAlertValueResult.setOtherInfo(DateUtil.formatYYYYMMddHHMMSS(new Date()));//实例恢复时间 recoverInstInfo.add(instanceAlertValueResult); break; } } } catch (Exception e) { logger.error("checkAndStartExceptionInstance {}:{} {} ", host, port, e.getMessage(), e); } finally { if (jedis != null) { try { jedis.close(); } catch (Exception e) { logger.error("jedis close exception {}:{} {} ", host, port, e.getMessage(), e); } } } } if (isAlert) { // 邮件通知:实例信息 恢复时间 String emailTitle = String.format("Pod重启探测Redis实例报警"); Map<String, Object> context = new HashMap<>(); context.put("instanceAlertValueResultList", recoverInstInfo); String emailContent = FreemakerUtils.createText("instanceRecover.ftl", configuration, context); emailComponent.sendMailToAdmin(emailTitle, emailContent.toString()); } } else { logger.info("checkAndStartExceptionInstance ip:{} has instances is empty ", ip); } return recoverInstInfo; } }
13,196
4,901
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package libcore.java.util.zip; import java.io.ByteArrayOutputStream; import java.util.zip.Adler32; import java.util.zip.Deflater; import java.util.zip.Inflater; /* J2ObjC removed: not supported by Junit 4.11 (https://github.com/google/j2objc/issues/1318). import libcore.junit.junit3.TestCaseWithRules; import libcore.junit.util.ResourceLeakageDetector; */ import org.junit.Rule; import org.junit.rules.TestRule; public class InflaterTest extends junit.framework.TestCase /* J2ObjC removed: TestCaseWithRules */ { /* J2ObjC removed: not supported by Junit 4.11 (https://github.com/google/j2objc/issues/1318). @Rule public TestRule resourceLeakageDetectorRule = ResourceLeakageDetector.getRule(); */ public void testDefaultDictionary() throws Exception { assertRoundTrip(null); } public void testPresetCustomDictionary() throws Exception { assertRoundTrip("dictionary".getBytes("UTF-8")); } private static void assertRoundTrip(byte[] dictionary) throws Exception { // Construct a nice long input byte sequence. String expected = makeString(); byte[] expectedBytes = expected.getBytes("UTF-8"); // Compress the bytes, using the passed-in dictionary (or no dictionary). byte[] deflatedBytes = deflate(expectedBytes, dictionary); // Get ready to decompress deflatedBytes back to the original bytes ... Inflater inflater = new Inflater(); // We'll only supply the input a little bit at a time, so that zlib has to ask for more. final int CHUNK_SIZE = 16; int offset = 0; inflater.setInput(deflatedBytes, offset, CHUNK_SIZE); offset += CHUNK_SIZE; // If we used a dictionary to compress, check that we're asked for that same dictionary. if (dictionary != null) { // 1. there's no data available immediately... assertEquals(0, inflater.inflate(new byte[8])); // 2. ...because you need a dictionary. assertTrue(inflater.needsDictionary()); // 3. ...and that dictionary has the same Adler32 as the dictionary we used. assertEquals(adler32(dictionary), inflater.getAdler()); inflater.setDictionary(dictionary); } // Do the actual decompression, now the dictionary's set up appropriately... // We use a tiny output buffer to ensure that we call inflate multiple times, and // a tiny input buffer to ensure that zlib has to ask for more input. ByteArrayOutputStream inflatedBytes = new ByteArrayOutputStream(); byte[] buf = new byte[8]; while (inflatedBytes.size() != expectedBytes.length) { if (inflater.needsInput()) { int nextChunkByteCount = Math.min(CHUNK_SIZE, deflatedBytes.length - offset); inflater.setInput(deflatedBytes, offset, nextChunkByteCount); offset += nextChunkByteCount; } else { int inflatedByteCount = inflater.inflate(buf); if (inflatedByteCount > 0) { inflatedBytes.write(buf, 0, inflatedByteCount); } } } inflater.end(); assertEquals(expected, new String(inflatedBytes.toByteArray(), "UTF-8")); } private static String makeString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1024; ++i) { // This is arbitrary but convenient in that it gives our string // an easily-recognizable beginning and end. sb.append(i + 1024); } return sb.toString(); } /** * http://code.google.com/p/android/issues/detail?id=11755 */ public void testEmptyFileAndEmptyBuffer() throws Exception { byte[] emptyInput = deflate(new byte[0], null); Inflater inflater = new Inflater(); inflater.setInput(emptyInput); assertFalse(inflater.finished()); assertEquals(0, inflater.inflate(new byte[0], 0, 0)); assertTrue(inflater.finished()); inflater.end(); } private static byte[] deflate(byte[] input, byte[] dictionary) { Deflater deflater = new Deflater(); ByteArrayOutputStream deflatedBytes = new ByteArrayOutputStream(); try { if (dictionary != null) { deflater.setDictionary(dictionary); } deflater.setInput(input); deflater.finish(); byte[] buf = new byte[8]; while (!deflater.finished()) { int byteCount = deflater.deflate(buf); deflatedBytes.write(buf, 0, byteCount); } } finally { deflater.end(); } return deflatedBytes.toByteArray(); } private static int adler32(byte[] bytes) { Adler32 adler32 = new Adler32(); adler32.update(bytes); return (int) adler32.getValue(); } public void testInflaterCounts() throws Exception { Inflater inflater = new Inflater(); byte[] decompressed = new byte[32]; byte[] compressed = deflate(new byte[] { 1, 2, 3 }, null); assertEquals(11, compressed.length); // Feed in bytes [0, 5) to the first iteration. inflater.setInput(compressed, 0, 5); inflater.inflate(decompressed, 0, decompressed.length); assertEquals(5, inflater.getBytesRead()); assertEquals(5, inflater.getTotalIn()); assertEquals(2, inflater.getBytesWritten()); assertEquals(2, inflater.getTotalOut()); // Feed in bytes [5, 11) to the second iteration. assertEquals(true, inflater.needsInput()); inflater.setInput(compressed, 5, 6); assertEquals(1, inflater.inflate(decompressed, 0, decompressed.length)); assertEquals(11, inflater.getBytesRead()); assertEquals(11, inflater.getTotalIn()); assertEquals(3, inflater.getBytesWritten()); assertEquals(3, inflater.getTotalOut()); inflater.reset(); assertEquals(0, inflater.getBytesRead()); assertEquals(0, inflater.getTotalIn()); assertEquals(0, inflater.getBytesWritten()); assertEquals(0, inflater.getTotalOut()); inflater.end(); } }
2,737
310
/* !@ MIT License Copyright (c) 2019 Skylicht Technology CO., LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #pragma once #include "pch.h" #include "CAnimationClip.h" namespace Skylicht { class CAnimation { protected: std::vector<CAnimationClip*> m_clips; std::map<std::string, CAnimationClip*> m_clipName; public: CAnimation(); virtual ~CAnimation(); CAnimationClip* getAnim(const char *lpAnimName) { return m_clipName[lpAnimName]; } CAnimationClip* getAnim(int animID) { return m_clips[animID]; } int getAnimCount() { return (int)m_clips.size(); } void addClip(CAnimationClip* clip) { if (clip == NULL) return; m_clips.push_back(clip); m_clipName[clip->AnimName] = clip; } void sortAnimByName(); std::vector<CAnimationClip*>* getAllAnimClip() { return &m_clips; } std::map<std::string, CAnimationClip*>* getAllAnimNameClip() { return &m_clipName; } void removeAll(); void removeClip(const std::string& clipName); void renameClip(const std::string& oldName, const std::string& newName); }; }
735
7,892
<reponame>joshrose/audacity sound_type snd_make_delay(sound_type input, time_type delay, double feedback); sound_type snd_delay(sound_type input, time_type delay, double feedback); /* LISP: (snd-delay SOUND ANYNUM ANYNUM) */
80
455
<filename>StarEngine/jni/Actions/TimedMoveAction.cpp #include "TimedMoveAction.h" #include "../Objects/Object.h" #include "../Helpers/Math.h" #include "../Graphics/UI/UIObject.h" namespace star { TimedMoveAction::TimedMoveAction( float32 seconds, const vec2 & target, const std::function<void()> & callback ) : TimedAction(seconds, callback) , m_Direction(0, 0) , m_Target(target) , m_StartPosition(0,0) , m_Speed(0) , m_CurrentSeconds(0) , m_StartPosSet(false) { } TimedMoveAction::TimedMoveAction( const tstring & name, float32 seconds, const vec2 & target, const std::function<void()> & callback ) : TimedAction(name, seconds, callback) , m_Direction(0, 0) , m_Target(target) , m_StartPosition(0,0) , m_Speed(0) , m_CurrentSeconds(0) , m_StartPosSet(false) { } TimedMoveAction::TimedMoveAction( float32 seconds, const vec2 & direction, float32 speed, const std::function<void()> & callback ) : TimedAction(seconds, callback) , m_Direction(direction) , m_Target(0, 0) , m_StartPosition(0,0) , m_Speed(speed) , m_CurrentSeconds(0) , m_StartPosSet(false) { } TimedMoveAction::TimedMoveAction( const tstring & name, float32 seconds, const vec2 & direction, float32 speed, const std::function<void()> & callback ) : TimedAction(name, seconds, callback) , m_Direction(direction) , m_Target(0, 0) , m_StartPosition(0,0) , m_Speed(speed) , m_CurrentSeconds(0) , m_StartPosSet(false) { } TimedMoveAction::~TimedMoveAction() { } void TimedMoveAction::Initialize() { auto parent = dynamic_cast<UIObject*>(m_pParent); if(parent == nullptr) { if(!m_StartPosSet) { m_StartPosition = m_pParent->GetTransform()->GetWorldPosition().pos2D(); m_StartPosSet = true; } } else { if(!m_StartPosSet) { m_StartPosition = parent->GetPosition().pos2D(); m_StartPosSet = true; } m_Callback = [&, parent] () { if(m_Speed == 0.0f) { parent->Translate(m_Target); } }; } TimedAction::Initialize(); } void TimedMoveAction::Update(const Context & context) { auto parent = dynamic_cast<UIObject*>(m_pParent); if(parent == nullptr) { vec2 curPos = m_pParent->GetTransform()->GetWorldPosition().pos2D(); float32 dt = float32(context.time->DeltaTime().GetSeconds()); if(m_Speed == 0.0f) { m_CurrentSeconds += dt; m_pParent->GetTransform()->Translate( Lerp<vec2>(m_StartPosition, m_Target, m_CurrentSeconds / m_Seconds) ); } else { m_pParent->GetTransform()->Translate( curPos + m_Direction * m_Speed * dt ); } } else { vec2 curPos = parent->GetPosition().pos2D(); float32 dt = float32(context.time->DeltaTime().GetSeconds()); if(m_Speed == 0.0f) { m_CurrentSeconds += dt; parent->Translate( Lerp<vec2>(m_StartPosition, m_Target, m_CurrentSeconds / m_Seconds) ); } else { parent->Translate( curPos + m_Direction * m_Speed * dt ); } } } void TimedMoveAction::SetStartPosition(const vec2 & pos) { m_StartPosition = pos; m_StartPosSet = true; } void TimedMoveAction::Restart() { auto parent = dynamic_cast<UIObject*>(m_pParent); if(parent == nullptr) { m_pParent->GetTransform()->Translate(m_StartPosition); } else { parent->Translate(m_StartPosition); } m_CurrentSeconds = 0; } }
1,723
4,879
#include "platform/country_file.hpp" #include "platform/mwm_version.hpp" #include "base/assert.hpp" #include <sstream> #include "defines.hpp" using namespace std; namespace { /// \returns file name (m_name) with extension dependent on the file param. /// The extension could be .mwm.routing or just .mwm. /// The method is used for old (two components) mwm support. string GetNameWithExt(string const & countryFile, MapFileType file) { switch (file) { case MapFileType::Map: return countryFile + DATA_FILE_EXTENSION; case MapFileType::Diff: return countryFile + DIFF_FILE_EXTENSION; case MapFileType::Count: CHECK(false, (countryFile)); } UNREACHABLE(); } } // namespace namespace platform { CountryFile::CountryFile() : m_mapSize(0) {} CountryFile::CountryFile(string const & name) : m_name(name), m_mapSize(0) {} string const & CountryFile::GetName() const { return m_name; } void CountryFile::SetRemoteSize(MwmSize mapSize) { m_mapSize = mapSize; } MwmSize CountryFile::GetRemoteSize() const { return m_mapSize; } string GetFileName(string const & countryFile, MapFileType type) { return GetNameWithExt(countryFile, type); } string DebugPrint(CountryFile const & file) { ostringstream os; os << "CountryFile [" << file.m_name << "]"; return os.str(); } } // namespace platform
447
377
<reponame>sirAgg/nebula //------------------------------------------------------------------------------ // streamtexturepool.cc // (C)2017-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "render/stdneb.h" #include "coregraphics/streamtexturepool.h" #if __VULKAN__ namespace CoreGraphics { __ImplementClass(CoreGraphics::StreamTexturePool, 'STXP', Vulkan::VkStreamTexturePool); } #else #error "StreamTextureLoader class not implemented on this platform!" #endif
135
369
// Copyright (c) 2017-2021, Mudit<NAME>.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "RT1051DriverSEMC.hpp" #include "critical.hpp" #include "board/clock_config.h" namespace drivers { RT1051DriverSEMC::RT1051DriverSEMC(std::string name) : DriverSEMC(std::move(name)) { SwitchToPLL2ClockSource(); } void RT1051DriverSEMC::Enable() {} void RT1051DriverSEMC::Disable() {} void RT1051DriverSEMC::SwitchToPLL2ClockSource() { cpp_freertos::CriticalSection::Enter(); if (!pll2Driver) { pll2Driver = std::make_shared<RT1051DriverPLL2>(); } CLOCK_SetMux(kCLOCK_SemcMux, SemcMuxPLL2Clock); cpp_freertos::CriticalSection::Exit(); } void RT1051DriverSEMC::SwitchToPeripheralClockSource() { cpp_freertos::CriticalSection::Enter(); CLOCK_SetMux(kCLOCK_SemcMux, SemcMuxPeripheralClock); pll2Driver.reset(); cpp_freertos::CriticalSection::Exit(); } } // namespace drivers
482
484
/* * Copyright 2017 Xiaomi, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xiaomi.shepher.interceptor; import com.xiaomi.shepher.common.Auth; import com.xiaomi.shepher.exception.ShepherException; import com.xiaomi.shepher.util.AuthStrategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * The {@link AuthorizationInterceptor} checks user's authorization. * * Created by weichuyang on 16-7-14. */ public class AuthorizationInterceptor extends HandlerInterceptorAdapter { @Autowired private AuthStrategy authStrategy; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Auth annotation = getAnnotation(handlerMethod); if (annotation != null && !authStrategy.validate(request, annotation.value())) { throw ShepherException.createNoAuthorizationException(); } } return true; } private Auth getAnnotation(HandlerMethod handlerMethod) { Auth annotation = handlerMethod.getMethodAnnotation(Auth.class); Class<?> beanType = handlerMethod.getBeanType(); if (beanType.isAnnotationPresent(Auth.class)) { annotation = beanType.getAnnotation(Auth.class); } return annotation; } }
699
1,615
/** * Created by MomoLuaNative. * Copyright (c) 2020, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package android; import org.luaj.vm2.Log; import org.junit.Assert; import org.junit.Test; /** * Created by Xiong.Fangyu on 2019-06-24 */ public class HandlerTest { @Test public void createHandler() { SLooper.prepare(); final SHandler handler = new SHandler(); new Thread(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { Log.i("in thread"); Assert.assertEquals(handler.mLooper, SLooper.myLooper()); Log.i("after test"); } }); } }).start(); SLooper.loop(); } @Test public void quit() { SLooper.prepare(); final SHandler handler = new SHandler(); new Thread(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { SLooper.myLooper().quit(); } }); } }).start(); SLooper.loop(); Log.i("after looper"); } }
800
5,169
{ "name": "FilesProvider", "version": "0.24.0", "summary": "FileManager replacement for Local and Remote (WebDAV/FTP/Dropbox/OneDrive/SMB2) files on iOS and macOS.", "description": "This Swift library provide a swifty way to deal with local and remote files \nand directories in same way. For now Local, WebDAV and Dropbox providers are ready to use.\n SMB2, FTP and AmazonS3 is planned for future.", "homepage": "https://github.com/amosavian/FileProvider", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "https://twitter.com/amosavian", "swift_version": "4.0", "platforms": { "ios": "8.0", "osx": "10.10", "tvos": "9.0" }, "source": { "git": "https://github.com/amosavian/FileProvider.git", "tag": "0.24.0" }, "source_files": "Sources/**/*.swift", "exclude_files": "Sources/Exclude", "libraries": "xml2" }
365
323
{ "name": "hw---n4", "description": "NRF52840 board", "files": [ "config.ts", "basepins.d.ts", "device.d.ts" ], "card": { "name": "N4", "description": "Board based on Nordic NRF52840", "learnMoreUrl": "https://arcade.makecode.com/hardware#n4", "cardType": "hw", "imageUrl": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4BAMAAACHjORcAAAAD1BMVEX/gTUAP63///+kg58AAADcmUjBAAAB50lEQVRo3u2YC3KEIAxAHW4AJzC5Qr2B3P9MJSGIulgtZl1byThs+D2S8G27L2XpGrABLwR6n9O5VgscEMeU5vx/B4aoTRjvFYABkYAx9wRgihz9qkyKYIaMPrdshgwchzsD2V2dnZJQ8yV+fuutNuE9gd6T8/FEVAEmGRuw8sT2XndSHnNJqV/07fXVgA3YgA14OdAqSwM+FQhZddbia7VDLmbFIXA7oLb7QAA3z/IYjrrTJwoXAsjIAkSqDmn6rIwKS34cDiJHlNjWMWACUgUZM40tblBrt7IfkYpdVJgcFVgDuasAgWIkFoItWwiTqRGAHMyZy3buMnuNwHEvuhzqgT04Miltp/xloOO/n0ARuN6pNwQiL/B6oFMHQh1wPXOzaa2LIdhNIGgDUQmY/w0AhcJTQHy9e9w5IGgDUR0IH7eQFhuiZgwLt3v9LCPK/WwXVhbX4SEg38/yBHE7O+U4MD5TikCoAsamRaCtA9otIFQAc/jdzol9DLh94G8+TK8FYnGTnQD+RhrwhsDjt157En8Y2OSNYha5frvqSqDBru8plY8oJpZQ2kthqooKNdiS3nRoyJig0IfUybAe1JBdVsUsNfgB2He5F5J9Agxm4LpqH2jYhuwyexQiRuUmx2GhcINnyzfOJXvHTJa1sgAAAABJRU5ErkJggg==" }, "compileServiceVariant": "nrf52840", "cppDependencies": { "accelerometer": "file:../accelerometer" }, "dependencies": { "core---nrf52": "file:../core---nrf52", "screen---st7735": "file:../screen---st7735", "mixer---nrf52": "file:../mixer---nrf52", "game": "file:../game" }, "public": true, "skipLocalization": true, "additionalFilePath": "../hw", "yotta": { "optionalConfig": { "DEVICE_JACDAC_DEBUG": 1 }, "config": { "DEVICE_USB": 0, "DEVICE_WEBUSB": 0 } }, "experimentalHw": true, "dalDTS": { "corePackage": "../core---nrf52" } }
1,140
4,538
<gh_stars>1000+ /** ***************************************************************************************** * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved. ***************************************************************************************** * @file gap_callback_le.h * @brief This file contains function prototype for all GAP roles. * @details * @author ranhui * @date 2016-02-18 * @version v0.1 * ************************************************************************************* */ /*============================================================================* * Define to prevent recursive inclusion *============================================================================*/ #ifndef GAP_CALLBACK_LE_H #define GAP_CALLBACK_LE_H #ifdef __cplusplus extern "C" { #endif /*============================================================================* * Header Files *============================================================================*/ #include <bt_flags.h> #include <gap_storage_le.h> #include <gap_le_types.h> /** @defgroup GAP_CB_MSG_MODULE GAP Callback Message * @brief GAP Callback Message * @{ */ /*============================================================================* * Macros *============================================================================*/ /** @defgroup Gap_CB_Msg_Exported_Macros GAP Callback Msg Exported Macros * @{ */ /** @defgroup GAP_LE_MSG_Types GAP LE Msg Types * @{ */ //gap_le.h #define GAP_MSG_LE_MODIFY_WHITE_LIST 0x01 //!<Response msg type for le_modify_white_list #define GAP_MSG_LE_SET_RAND_ADDR 0x02 //!<Response msg type for le_set_rand_addr #if F_BT_LE_GAP_CENTRAL_SUPPORT #define GAP_MSG_LE_SET_HOST_CHANN_CLASSIF 0x03 //!<Response msg type for le_set_host_chann_classif #endif #if F_BT_LE_4_2_DATA_LEN_EXT_SUPPORT #define GAP_MSG_LE_WRITE_DEFAULT_DATA_LEN 0x04 //!<Response msg type for le_write_default_data_len #endif //gap_conn_le.h #define GAP_MSG_LE_READ_RSSI 0x10 //!<Response msg type for le_read_rssi #if F_BT_LE_4_2_DATA_LEN_EXT_SUPPORT #define GAP_MSG_LE_SET_DATA_LEN 0x13 //!<Response msg type for le_set_data_len #define GAP_MSG_LE_DATA_LEN_CHANGE_INFO 0x14 //!<Notification msg type for data length changed #endif #if F_BT_LE_GAP_CENTRAL_SUPPORT #define GAP_MSG_LE_CONN_UPDATE_IND 0x15 //!<Indication for le connection parameter update #endif #define GAP_MSG_LE_CREATE_CONN_IND 0x16 //!<Indication for create le connection #if F_BT_LE_5_0_SET_PHYS_SUPPORT #define GAP_MSG_LE_PHY_UPDATE_INFO 0x17 //!<Indication for le phyical update information #endif #if F_BT_LE_READ_REMOTE_FEATS #define GAP_MSG_LE_REMOTE_FEATS_INFO 0x19 //!<Information for remote device supported features #endif //gap_bond_le.h #define GAP_MSG_LE_BOND_MODIFY_INFO 0x20 //!<Notification msg type for bond modify #if F_BT_LE_ATT_SIGNED_WRITE_SUPPORT #define GAP_MSG_LE_GATT_SIGNED_STATUS_INFO 0x23 //!<Notification msg type for le signed status information #endif //gap_scan.h #if F_BT_LE_GAP_SCAN_SUPPORT #define GAP_MSG_LE_SCAN_INFO 0x30 //!<Notification msg type for le scan #if F_BT_LE_PRIVACY_SUPPORT #define GAP_MSG_LE_DIRECT_ADV_INFO 0x31 //!<Notification msg type for le direct adv info #endif #endif //gap_adv.h #if F_BT_LE_GAP_PERIPHERAL_SUPPORT #define GAP_MSG_LE_ADV_UPDATE_PARAM 0x40 //!<Response msg type for le_adv_update_param #endif #define GAP_MSG_LE_GAP_STATE_MSG 0xB0 /** End of GAP_LE_MSG_Types * @} */ /** End of Gap_CB_Msg_Exported_Macros * @} */ /*============================================================================* * Types *============================================================================*/ /** @defgroup Gap_CB_Msg_Exported_Types GAP Callback Msg Exported Types * @{ */ typedef struct { uint16_t cause; } T_LE_CAUSE; /** @brief Response of le modify white list request.*/ typedef struct { T_GAP_WHITE_LIST_OP operation; uint16_t cause; } T_LE_MODIFY_WHITE_LIST_RSP; /** @brief Response of le set random address request. */ typedef struct { uint16_t cause; } T_LE_SET_RAND_ADDR_RSP; #if F_BT_LE_GAP_CENTRAL_SUPPORT /** @brief Response of le set channel classification request. */ typedef struct { uint16_t cause; } T_LE_SET_HOST_CHANN_CLASSIF_RSP; #endif /** @brief Response for read rssi.*/ typedef struct { uint8_t conn_id; int8_t rssi; uint16_t cause; } T_LE_READ_RSSI_RSP; #if F_BT_LE_4_2_DATA_LEN_EXT_SUPPORT /** @brief Response for set data length, which is used for BT4.2 data length extension.*/ typedef struct { uint8_t conn_id; uint16_t cause; } T_LE_SET_DATA_LEN_RSP; /** @brief Notification for data length change info, which is used for BT4.2 data length extension.*/ typedef struct { uint8_t conn_id; uint16_t max_tx_octets; uint16_t max_tx_time; uint16_t max_rx_octets; uint16_t max_rx_time; } T_LE_DATA_LEN_CHANGE_INFO; #endif #if F_BT_LE_GAP_CENTRAL_SUPPORT /** @brief Indication for connection paramete update.*/ typedef struct { uint8_t conn_id; uint16_t conn_interval_min; uint16_t conn_interval_max; uint16_t conn_latency; uint16_t supervision_timeout; } T_LE_CONN_UPDATE_IND; #endif /** @brief Indication of le connectiona. */ typedef struct { uint8_t bd_addr[6];/**< Bluetooth address of remote device */ T_GAP_REMOTE_ADDR_TYPE remote_addr_type; /**< Address type of remote device */ } T_LE_CREATE_CONN_IND; #if F_BT_LE_5_0_SET_PHYS_SUPPORT /** @brief Notification information when phy changed.*/ typedef struct { uint8_t conn_id; uint16_t cause; T_GAP_PHYS_TYPE tx_phy; T_GAP_PHYS_TYPE rx_phy; } T_LE_PHY_UPDATE_INFO; #endif #if F_BT_LE_READ_REMOTE_FEATS /** @brief Information for remote device features.*/ typedef struct { uint8_t conn_id; uint16_t cause; uint8_t remote_feats[8]; } T_LE_REMOTE_FEATS_INFO; #endif //gap_bond_le.h /** @brief Bond information modify type*/ typedef enum { LE_BOND_DELETE, LE_BOND_ADD, LE_BOND_CLEAR, LE_BOND_FULL, LE_BOND_KEY_MISSING, } T_LE_BOND_MODIFY_TYPE; /** @brief Structure for modify bonding information.*/ typedef struct { T_LE_BOND_MODIFY_TYPE type; T_LE_KEY_ENTRY *p_entry; } T_LE_BOND_MODIFY_INFO; #if F_BT_LE_ATT_SIGNED_WRITE_SUPPORT /** @brief Structure for LE signed information.*/ typedef struct { uint8_t conn_id; uint16_t cause; bool update_local; uint32_t local_sign_count; uint32_t remote_sign_count; } T_LE_GATT_SIGNED_STATUS_INFO; #endif //gap_scan.h #if F_BT_LE_GAP_SCAN_SUPPORT /** @brief Information of le scan information. */ typedef struct { uint8_t bd_addr[6];/**< Bluetooth address of remote device. */ T_GAP_REMOTE_ADDR_TYPE remote_addr_type;/**< Address type of remote device. */ T_GAP_ADV_EVT_TYPE adv_type;/**< Advertising event type. */ int8_t rssi; /**< RSSI. */ uint8_t data_len; uint8_t data[31]; } T_LE_SCAN_INFO; #if F_BT_LE_PRIVACY_SUPPORT /** @brief Information of le direct advertising. */ typedef struct { uint8_t bd_addr[6]; T_GAP_REMOTE_ADDR_TYPE remote_addr_type; uint8_t direct_bd_addr[6]; T_GAP_DIRECT_ADDR_TYPE direct_addr_type; T_GAP_ADV_EVT_TYPE direct_adv_type; int8_t rssi; } T_LE_DIRECT_ADV_INFO; #endif #endif //gap_adv.h #if F_BT_LE_GAP_PERIPHERAL_SUPPORT /** @brief LE advertising paramter update result.*/ typedef struct { uint16_t cause; } T_LE_ADV_UPDATE_PARAM_RSP; #endif /** @brief GAP LE Callback Data*/ typedef union { T_LE_CAUSE le_cause; //gap_le.h T_LE_MODIFY_WHITE_LIST_RSP *p_le_modify_white_list_rsp; T_LE_SET_RAND_ADDR_RSP *p_le_set_rand_addr_rsp; #if F_BT_LE_GAP_CENTRAL_SUPPORT T_LE_SET_HOST_CHANN_CLASSIF_RSP *p_le_set_host_chann_classif_rsp; #endif //gap_conn_le.h T_LE_READ_RSSI_RSP *p_le_read_rssi_rsp; #if F_BT_LE_4_2_DATA_LEN_EXT_SUPPORT T_LE_SET_DATA_LEN_RSP *p_le_set_data_len_rsp; T_LE_DATA_LEN_CHANGE_INFO *p_le_data_len_change_info; #endif #if F_BT_LE_GAP_CENTRAL_SUPPORT T_LE_CONN_UPDATE_IND *p_le_conn_update_ind; #endif T_LE_CREATE_CONN_IND *p_le_create_conn_ind; #if F_BT_LE_5_0_SET_PHYS_SUPPORT T_LE_PHY_UPDATE_INFO *p_le_phy_update_info; #endif #if F_BT_LE_READ_REMOTE_FEATS T_LE_REMOTE_FEATS_INFO *p_le_remote_feats_info; #endif //gap_bond_le.h T_LE_BOND_MODIFY_INFO *p_le_bond_modify_info; #if F_BT_LE_ATT_SIGNED_WRITE_SUPPORT T_LE_GATT_SIGNED_STATUS_INFO *p_le_gatt_signed_status_info; #endif //gap_scan.h #if F_BT_LE_GAP_SCAN_SUPPORT T_LE_SCAN_INFO *p_le_scan_info; #if F_BT_LE_PRIVACY_SUPPORT T_LE_DIRECT_ADV_INFO *p_le_direct_adv_info; #endif #endif //gap_adv.h #if F_BT_LE_GAP_PERIPHERAL_SUPPORT T_LE_ADV_UPDATE_PARAM_RSP *p_le_adv_update_param_rsp; #endif void *p_gap_state_msg; } T_LE_CB_DATA; /** End of Gap_CB_Msg_Exported_Types * @} */ /** End of GAP_CB_MSG_MODULE * @} */ #ifdef __cplusplus } #endif #endif /* GAP_MSG_H */
4,778
562
<filename>recipes/parg/all/test_package/test_package.c #include <stdio.h> #include <stdlib.h> #include "parg.h" int main(int argc, char *argv[]) { struct parg_state ps; int c; parg_init(&ps); while ((c = parg_getopt(&ps, argc, argv, "hs:v")) != -1) { switch (c) { case 1: printf("nonoption '%s'\n", ps.optarg); break; case 'h': printf("Usage: testparg [-h] [-v] [-s STRING]\n"); return EXIT_SUCCESS; break; case 's': printf("option -s with argument '%s'\n", ps.optarg); break; case 'v': printf("testparg 1.0.0\n"); return EXIT_SUCCESS; break; case '?': if (ps.optopt == 's') { printf("option -s requires an argument\n"); } else { printf("unknown option -%c\n", ps.optopt); } return EXIT_FAILURE; break; default: printf("error: unhandled option -%c\n", c); return EXIT_FAILURE; break; } } for (c = ps.optind; c < argc; ++c) { printf("nonoption '%s'\n", argv[c]); } return EXIT_SUCCESS; }
484
617
#! /usr/bin/env python import os import subprocess import tempfile import yaml class Kind(object): """ KinD is an acronym for K8s in Docker. More documentation about the tool can be found here https://github.com/kubernetes-sigs/kind. """ def __init__(self, name, config='tools/minicluster/kind_config.yaml'): self.name = name self.config = config self.kubeconfig = None def create(self): cmd = ["kind", "create", "cluster", "--name={}".format(self.name)] if self.config is not None: cmd.append("--config={}".format(self.config)) try: return subprocess.call(cmd) == 0 except Exception as e: print("Failed to create kind cluster: {}".format(e)) return False def teardown(self): cmd = ["kind", "delete", "cluster", "--name={}".format(self.name)] try: return subprocess.call(cmd) == 0 except Exception as e: print("Failed to delete kind cluster: {}".format(e)) return False def get_port(self): cmd = "docker port {}-control-plane 6443/tcp".format(self.name) return os.popen(cmd).read().strip() def is_running(self): ctn_name = "{}-control-plane".format(self.name) docker_cmd = "docker ps | grep {}".format(ctn_name) cmd = ["/bin/bash", "-c", docker_cmd] return subprocess.call(cmd) == 0 def get_kubeconfig(self): if self.kubeconfig is not None: return self.kubeconfig home = os.getenv("HOME") config_filename = "kind-config-{}".format(self.name) config_location = "{}/.kube/{}".format(home, config_filename) # Networking with docker means that localhost doesnt point to # the host network, so we need to change the kubeconfig to # point to the ip of the container as seen by the # other containers. new_config = self._rewrite_config(config_location) # Create a new directory for the new config, use the same name for # the file as the old one. dirname = tempfile.mkdtemp(prefix="/tmp/") new_config_location = os.path.join(dirname, config_filename) with open(new_config_location, 'w') as fh: fh.write(new_config) print("hacked kubeconfig for osx + docker weirdness: {}".format( new_config_location)) self.kubeconfig = new_config_location return new_config_location def _rewrite_config(self, prev_config_path): with open(prev_config_path, 'r') as fh: prev_config = yaml.safe_load(fh) ctn_name = "{}-control-plane".format(self.name) cmd = "docker inspect --format " cmd += "'{{ .NetworkSettings.IPAddress }}' " cmd += ctn_name ip = os.popen(cmd).read().strip() cluster = prev_config["clusters"][0]["cluster"] cluster["insecure-skip-tls-verify"] = True cluster["server"] = "https://{}:6443".format(ip) del cluster["certificate-authority-data"] return yaml.dump(prev_config)
1,343
2,151
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #ifndef __NUMBER_LONGNAMES_H__ #define __NUMBER_LONGNAMES_H__ #include "unicode/uversion.h" #include "number_utils.h" #include "number_modifiers.h" U_NAMESPACE_BEGIN namespace number { namespace impl { class LongNameHandler : public MicroPropsGenerator, public UMemory { public: static LongNameHandler forCurrencyLongNames(const Locale &loc, const CurrencyUnit &currency, const PluralRules *rules, const MicroPropsGenerator *parent, UErrorCode &status); static LongNameHandler forMeasureUnit(const Locale &loc, const MeasureUnit &unit, const MeasureUnit &perUnit, const UNumberUnitWidth &width, const PluralRules *rules, const MicroPropsGenerator *parent, UErrorCode &status); void processQuantity(DecimalQuantity &quantity, MicroProps &micros, UErrorCode &status) const U_OVERRIDE; private: SimpleModifier fModifiers[StandardPlural::Form::COUNT]; const PluralRules *rules; const MicroPropsGenerator *parent; LongNameHandler(const PluralRules *rules, const MicroPropsGenerator *parent) : rules(rules), parent(parent) {} static LongNameHandler forCompoundUnit(const Locale &loc, const MeasureUnit &unit, const MeasureUnit &perUnit, const UNumberUnitWidth &width, const PluralRules *rules, const MicroPropsGenerator *parent, UErrorCode &status); static void simpleFormatsToModifiers(const UnicodeString *simpleFormats, Field field, SimpleModifier *output, UErrorCode &status); static void multiSimpleFormatsToModifiers(const UnicodeString *leadFormats, UnicodeString trailFormat, Field field, SimpleModifier *output, UErrorCode &status); }; } // namespace impl } // namespace number U_NAMESPACE_END #endif //__NUMBER_LONGNAMES_H__ #endif /* #if !UCONFIG_NO_FORMATTING */
804
363
# -*- coding: utf-8 -*- ''' A module for shelling out. Keep in mind that this module is insecure, in that it can give whomever has access to the master root execution access to all salt minions. ''' # Import python libs import functools import glob import logging import os import shutil import subprocess import sys import time import traceback import fnmatch import base64 import re import tempfile import hubblestack.utils.args import hubblestack.utils.data import hubblestack.utils.files import hubblestack.utils.path import hubblestack.utils.platform import hubblestack.utils.stringutils import hubblestack.utils.timed_subprocess import hubblestack.grains.extra import hubblestack.utils.user import hubblestack.grains.extra from hubblestack.exceptions import CommandExecutionError, TimedProcTimeoutError, \ HubbleInvocationError from hubblestack.log import LOG_LEVELS # Only available on POSIX systems, nonfatal on windows try: import pwd import grp except ImportError: pass if hubblestack.utils.platform.is_windows(): from hubblestack.utils.win_runas import runas as win_runas from hubblestack.utils.win_functions import escape_argument as _cmd_quote HAS_WIN_RUNAS = True else: from shlex import quote as _cmd_quote HAS_WIN_RUNAS = False # Define the module's virtual name __virtualname__ = 'cmd' # Set up logging log = logging.getLogger(__name__) DEFAULT_SHELL = hubblestack.grains.extra.shell()['shell'] # Overwriting the cmd python module makes debugging modules with pdb a bit # harder so lets do it this way instead. def __virtual__(): return __virtualname__ def run_stdout(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', password=<PASSWORD>, prepend_path=None, success_retcodes=None, **kwargs): ''' Execute a command, and only return the standard out :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. .. warning:: For versions 2018.3.3 and above on macosx while using runas, to pass special characters to the command you need to escape the characters on the shell. Example: .. code-block:: bash cmd.run_stdout 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <hubblestack.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: 2019.2.0 :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'" A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, password=password, success_retcodes=success_retcodes, **kwargs) return ret['stdout'] if not hide_output else '' def _python_shell_default(python_shell, __pub_jid): ''' Set python_shell default based on remote execution and __opts__['cmd_safe'] ''' try: # Default to python_shell=True when run directly from remote execution # system. Cross-module calls won't have a jid. if __pub_jid and python_shell is None: return True elif __opts__.get('cmd_safe', True) is False and python_shell is None: # Override-switch for python_shell return True except NameError: pass return python_shell def _is_valid_shell(shell): ''' Attempts to search for valid shells on a system and see if a given shell is in the list ''' if hubblestack.utils.platform.is_windows(): return True # Don't even try this for Windows shells = '/etc/shells' available_shells = [] if os.path.exists(shells): try: with hubblestack.utils.files.fopen(shells, 'r') as shell_fp: lines = [hubblestack.utils.stringutils.to_unicode(x) for x in shell_fp.read().splitlines()] for line in lines: if line.startswith('#'): continue else: available_shells.append(line) except OSError: return True else: # No known method of determining available shells return None if shell in available_shells: return True else: return False def _check_loglevel(level='info'): ''' Retrieve the level code for use in logging.Logger.log(). ''' try: level = level.lower() if level == 'quiet': return None else: return LOG_LEVELS[level] except (AttributeError, KeyError): log.error( 'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling ' 'back to \'info\'.', level, ', '.join(sorted(LOG_LEVELS, reverse=True)) ) return LOG_LEVELS['info'] def _check_cb(cb_): ''' If the callback is None or is not callable, return a lambda that returns the value passed. ''' if cb_ is not None: if hasattr(cb_, '__call__'): return cb_ else: log.error('log_callback is not callable, ignoring') return lambda x: x def _check_avail(cmd): ''' Check to see if the given command can be run ''' if isinstance(cmd, list): cmd = ' '.join([str(x) if not isinstance(x, str) else x for x in cmd]) bret = True wret = False if __mods__['config.get']('cmd_blacklist_glob'): blist = __mods__['config.get']('cmd_blacklist_glob', []) for comp in blist: if fnmatch.fnmatch(cmd, comp): # BAD! you are blacklisted bret = False if __mods__['config.get']('cmd_whitelist_glob', []): blist = __mods__['config.get']('cmd_whitelist_glob', []) for comp in blist: if fnmatch.fnmatch(cmd, comp): # GOOD! You are whitelisted wret = True break else: # If no whitelist set then alls good! wret = True return bret and wret def _parse_env(env): if not env: env = {} if isinstance(env, list): env = hubblestack.utils.data.repack_dictlist(env) if not isinstance(env, dict): env = {} return env def _run(cmd, cwd=None, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, output_encoding=None, output_loglevel='debug', log_callback=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, prepend_path=None, rstrip=True, umask=None, timeout=None, with_communicate=True, reset_system_locale=True, ignore_retcode=False, saltenv='base', pillarenv=None, pillar_override=None, password=<PASSWORD>, bg=False, encoded_cmd=False, success_retcodes=None, **kwargs): ''' Do the DRY thing and only call subprocess.Popen() once ''' if 'pillar' in kwargs and not pillar_override: pillar_override = kwargs['pillar'] if output_loglevel != 'quiet' and _is_valid_shell(shell) is False: log.warning( 'Attempt to run a shell command with what may be an invalid shell! ' 'Check to ensure that the shell <%s> is valid for this user.', shell ) output_loglevel = _check_loglevel(output_loglevel) log_callback = _check_cb(log_callback) use_sudo = False if runas is None and '__context__' in globals(): runas = __context__.get('runas') if password is None and '__context__' in globals(): password = __context__.<PASSWORD>('runas_password') # Set the default working directory to the home directory of the user # salt-minion is running as. Defaults to home directory of user under which # the minion is running. if not cwd: cwd = os.path.expanduser('~{0}'.format('' if not runas else runas)) # make sure we can access the cwd # when run from sudo or another environment where the euid is # changed ~ will expand to the home of the original uid and # the euid might not have access to it. See issue #1844 if not os.access(cwd, os.R_OK): cwd = '/' if hubblestack.utils.platform.is_windows(): cwd = os.path.abspath(os.sep) else: # Handle edge cases where numeric/other input is entered, and would be # yaml-ified into non-string types cwd = str(cwd) if bg: ignore_retcode = True if not hubblestack.utils.platform.is_windows(): if not os.path.isfile(shell) or not os.access(shell, os.X_OK): msg = 'The shell {0} is not available'.format(shell) raise CommandExecutionError(msg) if shell.lower().strip() == 'powershell': # Strip whitespace if isinstance(cmd, str): cmd = cmd.strip() # If we were called by script(), then fakeout the Windows # shell to run a Powershell script. # Else just run a Powershell command. stack = traceback.extract_stack(limit=2) # extract_stack() returns a list of tuples. # The last item in the list [-1] is the current method. # The third item[2] in each tuple is the name of that method. if stack[-2][2] == 'script': cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd elif encoded_cmd: cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd) else: cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"')) ret = {} # If the pub jid is here then this is a remote ex or salt call command and needs to be # checked if blacklisted if '__pub_jid' in kwargs: if not _check_avail(cmd): raise CommandExecutionError( 'The shell command "{0}" is not permitted'.format(cmd) ) env = _parse_env(env) for bad_env_key in (x for x, y in iter(env.items()) if y is None): log.error('Environment variable \'%s\' passed without a value. ' 'Setting value to an empty string', bad_env_key) env[bad_env_key] = '' def _get_stripped(cmd): # Return stripped command string copies to improve logging. if isinstance(cmd, list): return [x.strip() if isinstance(x, str) else x for x in cmd] elif isinstance(cmd, str): return cmd.strip() else: return cmd if output_loglevel is not None: # Always log the shell commands at INFO unless quiet logging is # requested. The command output is what will be controlled by the # 'loglevel' parameter. msg = ( 'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format( '\'' if not isinstance(cmd, list) else '', _get_stripped(cmd), 'as user \'{0}\' '.format(runas) if runas else '', 'in group \'{0}\' '.format(group) if group else '', cwd, '. Executing command in the background, no output will be ' 'logged.' if bg else '' ) ) log.info(log_callback(msg)) if runas and hubblestack.utils.platform.is_windows(): if not HAS_WIN_RUNAS: msg = 'missing salt/utils/win_runas.py' raise CommandExecutionError(msg) if isinstance(cmd, (list, tuple)): cmd = ' '.join(cmd) return win_runas(cmd, runas, password, cwd) if runas and hubblestack.utils.platform.is_darwin(): # We need to insert the user simulation into the command itself and not # just run it from the environment on macOS as that method doesn't work # properly when run as root for certain commands. if isinstance(cmd, (list, tuple)): cmd = ' '.join(map(_cmd_quote, cmd)) # Ensure directory is correct before running command cmd = 'cd -- {dir} && {{ {cmd}\n }}'.format(dir=_cmd_quote(cwd), cmd=cmd) # Ensure environment is correct for a newly logged-in user by running # the command under bash as a login shell cmd = '/bin/bash -l -c {cmd}'.format(cmd=_cmd_quote(cmd)) # Ensure the login is simulated correctly (note: su runs sh, not bash, # which causes the environment to be initialised incorrectly, which is # fixed by the previous line of code) cmd = 'su -l {0} -c {1}'.format(_cmd_quote(runas), _cmd_quote(cmd)) # Set runas to None, because if you try to run `su -l` after changing # user, su will prompt for the password of the user and cause salt to # hang. runas = None if runas: # Save the original command before munging it try: pwd.getpwnam(runas) except KeyError: raise CommandExecutionError( 'User \'{0}\' is not available'.format(runas) ) if group: if hubblestack.utils.platform.is_windows(): msg = 'group is not currently available on Windows' raise HubbleInvocationError(msg) if not hubblestack.utils.path.which_bin(['sudo']): msg = 'group argument requires sudo but not found' raise CommandExecutionError(msg) try: grp.getgrnam(group) except KeyError: raise CommandExecutionError( 'Group \'{0}\' is not available'.format(runas) ) else: use_sudo = True if runas or group: try: # Getting the environment for the runas user # Use markers to thwart any stdout noise # There must be a better way to do this. import uuid marker = '<<<' + str(uuid.uuid4()) + '>>>' marker_b = marker.encode(__salt_system_encoding__) py_code = ( 'import sys, os, itertools; ' 'sys.stdout.write(\"' + marker + '\"); ' 'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); ' 'sys.stdout.write(\"' + marker + '\");' ) if use_sudo: env_cmd = ['sudo'] # runas is optional if use_sudo is set. if runas: env_cmd.extend(['-u', runas]) if group: env_cmd.extend(['-g', group]) if shell != DEFAULT_SHELL: env_cmd.extend(['-s', '--', shell, '-c']) else: env_cmd.extend(['-i', '--']) env_cmd.extend([sys.executable]) elif __grains__['os'] in ['FreeBSD']: env_cmd = ('su', '-', runas, '-c', "{0} -c {1}".format(shell, sys.executable)) else: env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable) msg = 'env command: {0}'.format(env_cmd) log.debug(log_callback(msg)) env_bytes, env_encoded_err = subprocess.Popen( env_cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE ).communicate(hubblestack.utils.stringutils.to_bytes(py_code)) marker_count = env_bytes.count(marker_b) if marker_count == 0: # Possibly PAM prevented the login log.error( 'Environment could not be retrieved for user \'%s\': ' 'stderr=%r stdout=%r', runas, env_encoded_err, env_bytes ) # Ensure that we get an empty env_runas dict below since we # were not able to get the environment. env_bytes = b'' elif marker_count != 2: raise CommandExecutionError( 'Environment could not be retrieved for user \'{0}\'', info={'stderr': repr(env_encoded_err), 'stdout': repr(env_bytes)} ) else: # Strip the marker env_bytes = env_bytes.split(marker_b)[1] env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2))) env_runas = dict( (hubblestack.utils.stringutils.to_str(k), hubblestack.utils.stringutils.to_str(v)) for k, v in iter(env_runas.items()) ) env_runas.update(env) # Fix platforms like Solaris that don't set a USER env var in the # user's default environment as obtained above. if env_runas.get('USER') != runas: env_runas['USER'] = runas # Fix some corner cases where shelling out to get the user's # environment returns the wrong home directory. runas_home = os.path.expanduser('~{0}'.format(runas)) if env_runas.get('HOME') != runas_home: env_runas['HOME'] = runas_home env = env_runas except ValueError as exc: log.exception('Error raised retrieving environment for user %s', runas) raise CommandExecutionError( 'Environment could not be retrieved for user \'{0}\': {1}'.format( runas, exc ) ) if reset_system_locale is True: if not hubblestack.utils.platform.is_windows(): # Default to C! # Salt only knows how to parse English words # Don't override if the user has passed LC_ALL env.setdefault('LC_CTYPE', 'C') env.setdefault('LC_NUMERIC', 'C') env.setdefault('LC_TIME', 'C') env.setdefault('LC_COLLATE', 'C') env.setdefault('LC_MONETARY', 'C') env.setdefault('LC_MESSAGES', 'C') env.setdefault('LC_PAPER', 'C') env.setdefault('LC_NAME', 'C') env.setdefault('LC_ADDRESS', 'C') env.setdefault('LC_TELEPHONE', 'C') env.setdefault('LC_MEASUREMENT', 'C') env.setdefault('LC_IDENTIFICATION', 'C') env.setdefault('LANGUAGE', 'C') else: # On Windows set the codepage to US English. if python_shell: cmd = 'chcp 437 > nul & ' + cmd if clean_env: run_env = env else: if hubblestack.utils.platform.is_windows(): import nt run_env = nt.environ.copy() else: run_env = os.environ.copy() run_env.update(env) if prepend_path: run_env['PATH'] = ':'.join((prepend_path, run_env['PATH'])) if python_shell is None: python_shell = False new_kwargs = {'cwd': cwd, 'shell': python_shell, 'env': run_env, 'stdin': str(stdin) if stdin is not None else stdin, 'stdout': stdout, 'stderr': stderr, 'with_communicate': with_communicate, 'timeout': timeout, 'bg': bg, } if 'stdin_raw_newlines' in kwargs: new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines'] if umask is not None: _umask = str(umask).lstrip('0') if _umask == '': msg = 'Zero umask is not allowed.' raise CommandExecutionError(msg) try: _umask = int(_umask, 8) except ValueError: raise CommandExecutionError("Invalid umask: '{0}'".format(umask)) else: _umask = None if runas or group or umask: new_kwargs['preexec_fn'] = functools.partial( hubblestack.utils.user.chugid_and_umask, runas, _umask, group) if not hubblestack.utils.platform.is_windows(): # close_fds is not supported on Windows platforms if you redirect # stdin/stdout/stderr if new_kwargs['shell'] is True: new_kwargs['executable'] = shell new_kwargs['close_fds'] = True if not os.path.isabs(cwd) or not os.path.isdir(cwd): raise CommandExecutionError( 'Specified cwd \'{0}\' either not absolute or does not exist' .format(cwd) ) if python_shell is not True \ and not hubblestack.utils.platform.is_windows() \ and not isinstance(cmd, list): cmd = hubblestack.utils.args.shlex_split(cmd) if success_retcodes is None: success_retcodes = [0] else: try: success_retcodes = [int(i) for i in hubblestack.utils.args.split_input( success_retcodes )] except ValueError: raise HubbleInvocationError( 'success_retcodes must be a list of integers' ) # This is where the magic happens try: proc = hubblestack.utils.timed_subprocess.TimedProc(cmd, **new_kwargs) except (OSError, IOError) as exc: msg = ( 'Unable to run command \'{0}\' with the context \'{1}\', ' 'reason: '.format( cmd if output_loglevel is not None else 'REDACTED', new_kwargs ) ) try: if exc.filename is None: msg += 'command not found' else: msg += '{0}: {1}'.format(exc, exc.filename) except AttributeError: # Both IOError and OSError have the filename attribute, so this # is a precaution in case the exception classes in the previous # try/except are changed. msg += 'unknown' raise CommandExecutionError(msg) try: proc.run() except TimedProcTimeoutError as exc: ret['stdout'] = str(exc) ret['stderr'] = '' ret['retcode'] = None ret['pid'] = proc.process.pid # ok return code for timeouts? ret['retcode'] = 1 return ret if output_loglevel != 'quiet' and output_encoding is not None: log.debug('Decoding output from command %s using %s encoding', cmd, output_encoding) try: out = hubblestack.utils.stringutils.to_unicode( proc.stdout, encoding=output_encoding) except TypeError: # stdout is None out = '' except UnicodeDecodeError: out = hubblestack.utils.stringutils.to_unicode( proc.stdout, encoding=output_encoding, errors='replace') if output_loglevel != 'quiet': log.error( 'Failed to decode stdout from command %s, non-decodable ' 'characters have been replaced', cmd ) try: err = hubblestack.utils.stringutils.to_unicode( proc.stderr, encoding=output_encoding) except TypeError: # stderr is None err = '' except UnicodeDecodeError: err = hubblestack.utils.stringutils.to_unicode( proc.stderr, encoding=output_encoding, errors='replace') if output_loglevel != 'quiet': log.error( 'Failed to decode stderr from command %s, non-decodable ' 'characters have been replaced', cmd ) if rstrip: if out is not None: out = out.rstrip() if err is not None: err = err.rstrip() ret['pid'] = proc.process.pid ret['retcode'] = proc.process.returncode if ret['retcode'] in success_retcodes: ret['retcode'] = 0 ret['stdout'] = out ret['stderr'] = err try: if ignore_retcode: __context__['retcode'] = 0 else: __context__['retcode'] = ret['retcode'] except NameError: # Ignore the context error during grain generation pass # Log the output if output_loglevel is not None: if not ignore_retcode and ret['retcode'] != 0: if output_loglevel < LOG_LEVELS['error']: output_loglevel = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) ) log.error(log_callback(msg)) if ret['stdout']: log.log(output_loglevel, 'stdout: {0}'.format(log_callback(ret['stdout']))) if ret['stderr']: log.log(output_loglevel, 'stderr: {0}'.format(log_callback(ret['stderr']))) if ret['retcode']: log.log(output_loglevel, 'retcode: {0}'.format(ret['retcode'])) return ret def _run_quiet(cmd, cwd=None, stdin=None, output_encoding=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, success_retcodes=None): ''' Helper for running commands quietly for minion startup ''' return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, output_encoding=output_encoding, output_loglevel='quiet', log_callback=None, shell=shell, python_shell=python_shell, env=env, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override, success_retcodes=success_retcodes)['stdout'] def _run_all_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, output_encoding=None, success_retcodes=None): ''' Helper for running commands quietly for minion startup. Returns a dict of return data. output_loglevel argument is ignored. This is here for when we alias cmd.run_all directly to _run_all_quiet in certain chicken-and-egg situations where modules need to work both before and after the __mods__ dictionary is populated (cf dracr.py) ''' return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, output_encoding=output_encoding, output_loglevel='quiet', log_callback=None, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override, success_retcodes=success_retcodes) def run_all(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', redirect_stderr=False, password=<PASSWORD>, encoded_cmd=False, prepend_path=None, success_retcodes=None, **kwargs): ''' Execute the passed command and return a dict of return data :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. .. warning:: For versions 2018.3.3 and above on macosx while using runas, to pass special characters to the command you need to escape the characters on the shell. Example: .. code-block:: bash cmd.run_all 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <hubblestack.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool encoded_cmd: Specify if the supplied command is encoded. Only applies to shell 'powershell'. .. versionadded:: 2018.3.0 :param bool redirect_stderr: If set to ``True``, then stderr will be redirected to stdout. This is helpful for cases where obtaining both the retcode and output is desired, but it is not desired to have the output separated into both stdout and stderr. .. versionadded:: 2015.8.2 :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param bool bg: If ``True``, run command in background and do not await or deliver its results .. versionadded:: 2016.3.6 :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: 2019.2.0 :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'" A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, stderr=stderr, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) if hide_output: ret['stdout'] = ret['stderr'] = '' return ret def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, umask=None, output_encoding=None, log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', password=<PASSWORD>, success_retcodes=None, **kwargs): ''' Helper for running commands quietly for minion startup. Returns same as the retcode() function. ''' return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, group=group, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, umask=umask, output_encoding=output_encoding, output_loglevel='quiet', log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, password=password, success_retcodes=success_retcodes, **kwargs) def retcode(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', password=<PASSWORD>, success_retcodes=None, **kwargs): ''' Execute a shell command and return the command's return code. :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. .. warning:: For versions 2018.3.3 and above on macosx while using runas, to pass special characters to the command you need to escape the characters on the shell. Example: .. code-block:: bash cmd.retcode 'echo '\\''h=\\"baz\\"'\\\''' runas=macuser :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <hubblestack.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param int timeout: A timeout in seconds for the executed process to return. :rtype: int :rtype: None :returns: Return Code as an int or None if there was an exception. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: 2019.2.0 :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' cmd.retcode "file /bin/bash" A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, password=password, success_retcodes=success_retcodes, **kwargs) return ret['retcode'] def run(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', bg=False, password=<PASSWORD>, encoded_cmd=False, raise_err=False, prepend_path=None, success_retcodes=None, **kwargs): r''' Execute the passed command and return the output as a string :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. .. warning:: For versions 2018.3.3 and above on macosx while using runas, to pass special characters to the command you need to escape the characters on the shell. Example: .. code-block:: bash cmd.run 'echo '\''h=\"baz\"'\''' runas=macuser :param str group: Group to run command as. Not currently supported on Windows. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If ``False``, let python handle the positional arguments. Set to ``True`` to use shell features, such as pipes or redirection. :param bool bg: If ``True``, run command in background and do not await or deliver it's results .. versionadded:: 2016.3.0 :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <hubblestack.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool encoded_cmd: Specify if the supplied command is encoded. Only applies to shell 'powershell'. :param bool raise_err: If ``True`` and the command has a nonzero exit code, a CommandExecutionError exception will be raised. .. warning:: This function does not process commands through a shell unless the python_shell flag is set to True. This means that any shell-specific functionality such as 'echo' or the use of pipes, redirection or &&, should either be migrated to cmd.shell or have the python_shell=True flag set here. The use of python_shell=True means that the shell will accept _any_ input including potentially malicious commands such as 'good_command;rm -rf /'. Be absolutely certain that you have sanitized your input prior to using python_shell=True :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: 2019.2.0 :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'" Specify an alternate shell with the shell parameter: .. code-block:: bash salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell' A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' cmd.run cmd='sed -e s/=/:/g' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, shell=shell, python_shell=python_shell, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, env=env, clean_env=clean_env, prepend_path=prepend_path, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, bg=bg, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) log_callback = _check_cb(log_callback) lvl = _check_loglevel(output_loglevel) if lvl is not None: if not ignore_retcode and ret['retcode'] != 0: if lvl < LOG_LEVELS['error']: lvl = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) ) log.error(log_callback(msg)) if raise_err: raise CommandExecutionError( log_callback(ret['stdout'] if not hide_output else '') ) log.log(lvl, 'output: %s', log_callback(ret['stdout'])) return ret['stdout'] if not hide_output else ''
26,462
582
<reponame>Sphericone/archi /******************************************************************************* * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * <NAME> (Borland) - initial API and implementation *******************************************************************************/ package org.eclipse.draw2d; import java.util.Iterator; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PointList; /** * Base superclass for all polylines/polygons * * @since 3.5 */ @SuppressWarnings("rawtypes") public abstract class AbstractPointListShape extends Shape { PointList points = new PointList(); /** * @see org.eclipse.draw2d.IFigure#containsPoint(int, int) */ @Override public boolean containsPoint(int x, int y) { if (!super.containsPoint(x, y)) { return false; } return shapeContainsPoint(x, y) || childrenContainsPoint(x, y); } /** * Returns <code>true</code> if the point <code>(x, y)</code> is contained * within one of the child figures. * * @param x * The X coordinate * @param y * The Y coordinate * @return <code>true</code> if the point (x,y) is contained in one of the * child figures */ protected boolean childrenContainsPoint(int x, int y) { for (Iterator it = getChildren().iterator(); it.hasNext();) { IFigure nextChild = (IFigure) it.next(); if (nextChild.containsPoint(x, y)) { return true; } } return false; } /** * Returns <code>true</code> if the point <code>(x, y)</code> is contained * within this figure. * * @param x * The X coordinate * @param y * The Y coordinate * @return <code>true</code> if the point (x,y) is contained in this figure */ abstract protected boolean shapeContainsPoint(int x, int y); /** * Adds the passed point to this figure. * * @param pt * the Point to be added to this figure */ public void addPoint(Point pt) { points.addPoint(pt); repaint(); } /** * @return the first point in this figure */ public Point getStart() { return points.getFirstPoint(); } /** * Returns the last point in this Figure. * * @return the last point */ public Point getEnd() { return points.getLastPoint(); } /** * Returns the points in this figure <B>by reference</B>. If the returned * list is modified, this figure must be informed by calling * {@link #setPoints(PointList)}. Failure to do so will result in layout and * paint problems. * * @return this Polyline's points */ public PointList getPoints() { return points; } /** * Inserts a given point at a specified index in this figure. * * @param pt * the point to be added * @param index * the position in this figure where the point is to be added */ public void insertPoint(Point pt, int index) { points.insertPoint(pt, index); repaint(); } /** * Erases this figure and removes all of its {@link Point Points}. */ public void removeAllPoints() { erase(); points.removeAllPoints(); } /** * Removes a point from this figure. * * @param index * the position of the point to be removed */ public void removePoint(int index) { erase(); points.removePoint(index); repaint(); } /** * Sets the start point of this figure * * @param start * the point that will become the first point in this figure */ public void setStart(Point start) { if (points.size() == 0) { addPoint(start); } else { setPoint(start, 0); } } /** * Sets the end point of this figure * * @param end * the point that will become the last point in this figure */ public void setEnd(Point end) { if (points.size() < 2) { addPoint(end); } else { setPoint(end, points.size() - 1); } } /** * Sets the points at both extremes of this figure * * @param start * the point to become the first point in this figure * @param end * the point to become the last point in this figure */ public void setEndpoints(Point start, Point end) { setStart(start); setEnd(end); } /** * Sets the point at <code>index</code> to the Point <code>pt</code>. If * you're going to set multiple Points, use {@link #setPoints(PointList)}. * * @param pt * the point * @param index * the index */ public void setPoint(Point pt, int index) { erase(); points.setPoint(pt, index); repaint(); } /** * Sets the list of points to be used by this figure. Removes any previously * existing points. This figure will hold onto the given list by reference. * * @param points * new set of points */ public void setPoints(PointList points) { erase(); this.points = points; repaint(); } }
2,381
507
# terrascript/resource/turbot/turbot.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:29:24 UTC) import terrascript class turbot_file(terrascript.Resource): pass class turbot_folder(terrascript.Resource): pass class turbot_google_directory(terrascript.Resource): pass class turbot_grant(terrascript.Resource): pass class turbot_grant_activation(terrascript.Resource): pass class turbot_ldap_directory(terrascript.Resource): pass class turbot_local_directory(terrascript.Resource): pass class turbot_local_directory_user(terrascript.Resource): pass class turbot_mod(terrascript.Resource): pass class turbot_policy_setting(terrascript.Resource): pass class turbot_profile(terrascript.Resource): pass class turbot_resource(terrascript.Resource): pass class turbot_saml_directory(terrascript.Resource): pass class turbot_shadow_resource(terrascript.Resource): pass class turbot_smart_folder(terrascript.Resource): pass class turbot_smart_folder_attachment(terrascript.Resource): pass class turbot_turbot_directory(terrascript.Resource): pass __all__ = [ "turbot_file", "turbot_folder", "turbot_google_directory", "turbot_grant", "turbot_grant_activation", "turbot_ldap_directory", "turbot_local_directory", "turbot_local_directory_user", "turbot_mod", "turbot_policy_setting", "turbot_profile", "turbot_resource", "turbot_saml_directory", "turbot_shadow_resource", "turbot_smart_folder", "turbot_smart_folder_attachment", "turbot_turbot_directory", ]
631
348
{"nom":"Villedieu-sur-Indre","circ":"1ère circonscription","dpt":"Indre","inscrits":2007,"abs":1016,"votants":991,"blancs":25,"nuls":13,"exp":953,"res":[{"nuance":"REM","nom":"<NAME>","voix":351},{"nuance":"FN","nom":"Mme <NAME>","voix":202},{"nuance":"SOC","nom":"<NAME>","voix":118},{"nuance":"FI","nom":"Mme <NAME>","voix":101},{"nuance":"LR","nom":"Mme <NAME>","voix":72},{"nuance":"DVD","nom":"<NAME>","voix":39},{"nuance":"ECO","nom":"Mme <NAME>","voix":20},{"nuance":"ECO","nom":"M. <NAME>","voix":15},{"nuance":"DLF","nom":"Mme <NAME>","voix":11},{"nuance":"DIV","nom":"M. <NAME>","voix":8},{"nuance":"EXG","nom":"Mme <NAME>","voix":7},{"nuance":"COM","nom":"M. <NAME>","voix":6},{"nuance":"EXG","nom":"Mme <NAME>","voix":3}]}
295
6,114
package com.baidu.disconf.web.service.config.dao.impl; import org.springframework.stereotype.Service; import com.baidu.disconf.web.service.config.bo.ConfigHistory; import com.baidu.disconf.web.service.config.dao.ConfigHistoryDao; import com.baidu.dsp.common.dao.AbstractDao; /** * Created by knightliao on 15/12/25. */ @Service public class ConfigHistoryDaoImpl extends AbstractDao<Long, ConfigHistory> implements ConfigHistoryDao { }
152
1,132
package javarepl.expressions; import com.googlecode.totallylazy.Sequence; import javarepl.rendering.TypeRenderer; import static javarepl.Utils.canonicalName; public final class Method extends Expression { private final java.lang.reflect.Type type; private final String name; private final Sequence<Class<?>> arguments; public Method(String source, java.lang.reflect.Type type, String name, Sequence<Class<?>> arguments) { super(source); this.type = type; this.name = name; this.arguments = arguments; } public String name() { return name; } public java.lang.reflect.Type type() { return type; } public Sequence<Class<?>> arguments() { return arguments; } public String signature() { return TypeRenderer.renderType(type) + " " + name + arguments.map(canonicalName()).toString("(", ", ", ")"); } public String key() { return name + arguments.map(canonicalName()).toString(", "); } }
379
879
package org.zstack.network.l2.vxlan.vxlanNetwork; import org.springframework.http.HttpMethod; import org.zstack.header.network.l2.APIDeleteL2NetworkEvent; import org.zstack.header.network.l2.APIDeleteL2NetworkMsg; import org.zstack.header.rest.NoSDK; import org.zstack.header.rest.RestRequest; @RestRequest( path = "/l2-networks/vxlan/{uuid}", method = HttpMethod.DELETE, responseClass = APIDeleteL2NetworkEvent.class ) @NoSDK public class APIDeleteVxlanL2Network extends APIDeleteL2NetworkMsg { public static APIDeleteL2NetworkMsg __example__() { APIDeleteL2NetworkMsg msg = new APIDeleteL2NetworkMsg(); msg.setUuid(uuid()); return msg; } }
292
389
/* * Copyright 2014 <NAME>, Inc. */ package gw.internal.gosu.ir.transform.util; import gw.internal.gosu.parser.*; import gw.lang.parser.IDynamicFunctionSymbol; import gw.lang.parser.IReducedDynamicFunctionSymbol; import gw.lang.reflect.IType; import gw.lang.reflect.IPropertyInfo; import gw.lang.reflect.PropertyInfoBuilder; import gw.lang.reflect.IPropertyInfoDelegate; import gw.lang.reflect.gs.IGosuClass; import gw.lang.reflect.java.IJavaType; import gw.lang.reflect.java.JavaTypes; import gw.lang.reflect.java.IJavaPropertyInfo; import gw.lang.reflect.java.IJavaPropertyDescriptor; import gw.lang.reflect.java.IJavaClassMethod; import gw.lang.parser.Keyword; import gw.lang.reflect.java.JavaTypes; public class NameResolver { public static String getGetterName( IPropertyInfo pi ) { if( pi instanceof GosuPropertyInfo) { //## todo: in parser make compilation error for case where a getFoo method is defined in the presence of a Foo property ReducedDynamicPropertySymbol dps = ((GosuPropertyInfo)pi).getDps(); return getGetterNameForDPS( dps ); } else if( pi instanceof IJavaPropertyInfo && !(pi instanceof LengthProperty) ) { return ((IJavaPropertyInfo)pi).getPropertyDescriptor().getReadMethod().getName(); } else if( pi instanceof PropertyInfoBuilder.BuiltPropertyInfo ) { if( pi.getAccessor() instanceof JavaPropertyInfo.PropertyAccessorAdaptor ) { return ((JavaPropertyInfo.PropertyAccessorAdaptor)pi.getAccessor()).getGetterMethod().getName(); } else { PropertyInfoBuilder.BuiltPropertyInfo bpi = (PropertyInfoBuilder.BuiltPropertyInfo)pi; if( bpi.getJavaMethodName() != null ) { return bpi.getJavaMethodName(); } return "get" + bpi.getName(); } } else if( pi instanceof IPropertyInfoDelegate) { return getGetterName( ((IPropertyInfoDelegate)pi).getSource() ); } throw new IllegalArgumentException( "Unexpected property type: " + pi.getClass() ); } public static String getGetterNameForDPS( ReducedDynamicPropertySymbol dps ) { return getFunctionName(dps.getGetterDfs()); } public static String getGetterNameForDPS( DynamicPropertySymbol dps ) { return getFunctionName(dps.getGetterDfs()); } public static String getSetterName( IPropertyInfo pi ) { if( pi instanceof GosuPropertyInfo) { //## todo: in parser make compilation error for case where a getFoo method is defined in the presence of a Foo property ReducedDynamicPropertySymbol dps = ((GosuPropertyInfo)pi).getDps(); return getSetterNameForDPS( dps ); } else if( pi instanceof IJavaPropertyInfo && !(pi instanceof LengthProperty) ) { return ((IJavaPropertyInfo)pi).getPropertyDescriptor().getWriteMethod().getName(); } else if( pi instanceof PropertyInfoBuilder.BuiltPropertyInfo ) { if( pi.getAccessor() instanceof JavaPropertyInfo.PropertyAccessorAdaptor ) { return ((JavaPropertyInfo.PropertyAccessorAdaptor)pi.getAccessor()).getSetterMethod().getName(); } else { PropertyInfoBuilder.BuiltPropertyInfo bpi = (PropertyInfoBuilder.BuiltPropertyInfo)pi; if( bpi.getJavaMethodName() != null ) { return bpi.getJavaMethodName(); } return "set" + bpi.getName(); } } else if( pi instanceof IPropertyInfoDelegate) { return getSetterName( ((IPropertyInfoDelegate)pi).getSource() ); } throw new IllegalArgumentException( "Unexpected property type: " + pi.getClass() ); } public static String getSetterNameForDPS( ReducedDynamicPropertySymbol dps ) { return getFunctionName( dps.getSetterDfs() ); } public static String getSetterNameForDPS( DynamicPropertySymbol dps ) { return getFunctionName( dps.getSetterDfs() ); } public static String getFunctionName( ReducedDynamicFunctionSymbol dfs ) { String strName = dfs.getDisplayName(); if( strName.startsWith( "@" ) ) { final IType returnType = dfs.getReturnType(); if( returnType == JavaTypes.pVOID() ) { strName = Keyword.KW_set + strName.substring( 1 ); } else { strName = resolveCorrectGetterMethodPrefixForBooleanDFS( dfs ) + strName.substring( 1 ); } } return strName; } public static String getFunctionName( DynamicFunctionSymbol dfs ) { String strName = dfs.getDisplayName(); if( strName.startsWith( "@" ) ) { final IType returnType = dfs.getReturnType(); if( returnType == JavaTypes.pVOID() ) { strName = Keyword.KW_set + strName.substring( 1 ); } else { strName = resolveCorrectGetterMethodPrefixForBooleanDFS( dfs ) + strName.substring( 1 ); } } return strName; } private static String resolveCorrectGetterMethodPrefixForBooleanDFS( IDynamicFunctionSymbol dfs ) { while( dfs.getBackingDfs() != null && dfs.getBackingDfs() != dfs ) { dfs = dfs.getBackingDfs(); } IType returnType = dfs.getReturnType(); if (returnType == JavaTypes.pBOOLEAN() || returnType == JavaTypes.BOOLEAN()) { IDynamicFunctionSymbol rootDFS = dfs; while (rootDFS.getSuperDfs() != null) { rootDFS = rootDFS.getSuperDfs(); while( rootDFS.getBackingDfs() != null && rootDFS.getBackingDfs() != rootDFS ) { rootDFS = rootDFS.getBackingDfs(); } } if (rootDFS.getGosuClass() != null && IGosuClass.ProxyUtil.isProxy(rootDFS.getGosuClass())) { IType proxiedType = IGosuClass.ProxyUtil.getProxiedType(rootDFS.getGosuClass()); IPropertyInfo propertyInfo = proxiedType.getTypeInfo().getProperty(dfs.getDisplayName().substring(1)); if (propertyInfo instanceof IJavaPropertyInfo) { IJavaPropertyDescriptor propertyDescriptor = ((IJavaPropertyInfo) propertyInfo).getPropertyDescriptor(); IJavaClassMethod readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { if (readMethod.getName().startsWith("is")) { return "is"; } else { boolean b = readMethod.getName().startsWith("get"); assert b; return "get"; } } } } // default to "is" for other boolean properties return "is"; } else { // Everything else defaults to "get" return "get"; } } private static String resolveCorrectGetterMethodPrefixForBooleanDFS( IReducedDynamicFunctionSymbol dfs ) { while( dfs.getBackingDfs() != null && dfs.getBackingDfs() != dfs ) { dfs = dfs.getBackingDfs(); } IType returnType = dfs.getReturnType(); if (returnType == JavaTypes.pBOOLEAN() || returnType == JavaTypes.BOOLEAN()) { IReducedDynamicFunctionSymbol rootDFS = dfs; while (rootDFS.getSuperDfs() != null) { rootDFS = rootDFS.getSuperDfs(); } if (rootDFS.getGosuClass() != null && IGosuClass.ProxyUtil.isProxy(rootDFS.getGosuClass())) { IType proxiedType = IGosuClass.ProxyUtil.getProxiedType(rootDFS.getGosuClass()); IPropertyInfo propertyInfo = proxiedType.getTypeInfo().getProperty(dfs.getDisplayName().substring(1)); if (propertyInfo instanceof IJavaPropertyInfo) { IJavaPropertyDescriptor propertyDescriptor = ((IJavaPropertyInfo) propertyInfo).getPropertyDescriptor(); IJavaClassMethod readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { if (readMethod.getName().startsWith("is")) { return "is"; } else { boolean b = readMethod.getName().startsWith("get"); assert b; return "get"; } } } } // default to "is" for other boolean properties return "is"; } else { // Everything else defaults to "get" return "get"; } } }
3,251
340
package com.vincentbrison.openlibraries.android.dualcache; /** * This cache interface describe the way an object should be serialized/deserialized into a * byte array. * @param <T> is the class of object to serialized/deserialized. */ public interface CacheSerializer<T> { /** * Deserialization of a String into an object. * @param data is the byte array representing the serialized data. * @return the deserialized data. */ T fromString(String data); /** * Serialization of an object into String. * @param object is the object to serialize. * @return the result of the serialization into a byte array. */ String toString(T object); }
223
677
<filename>src/Microsoft.Health.Fhir.Shared.Api.UnitTests/Controllers/openid-configuration.json { "authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", "token_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": [ "client_secret_post", "private_key_jwt", "client_secret_basic" ], "jwks_uri": "https://login.microsoftonline.com/common/discovery/v2.0/keys", "response_modes_supported": [ "query", "fragment", "form_post" ], "subject_types_supported": [ "pairwise" ], "id_token_signing_alg_values_supported": [ "RS256" ], "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/logout", "response_types_supported": [ "code", "id_token", "code id_token", "id_token token" ], "scopes_supported": [ "openid", "profile", "email", "offline_access" ], "issuer": "https://login.microsoftonline.com/{tenantid}/v2.0", "claims_supported": [ "sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email" ], "request_uri_parameter_supported": false, "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", "tenant_region_scope": null, "cloud_instance_name": "microsoftonline.com", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", "rbac_url": "https://pas.windows.net" }
940
1,301
<reponame>trailofbits/mcsema #!/usr/bin/env python3 # Copyright (c) 2020 Trail of Bits, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import shutil import stat import colors import util tags_dir = "tags" bin_dir = "bin" def try_find(locations, basename): for p in locations: maybe = os.path.join(p, basename) if os.path.isfile(maybe): print(" > " + colors.green("Found " + maybe)) new_file = os.path.join(bin_dir, basename) shutil.copyfile(maybe, new_file) st = os.stat(new_file) os.chmod(new_file, st.st_mode | stat.S_IEXEC) return True return False def main(): # TODO: Make it portable locations = [ "/usr/bin", "/bin"] current = set() # If `bin` does not exist create it first if not os.path.isdir(bin_dir): os.mkdir(bin_dir) for f in os.listdir(bin_dir): current.add(f) for f in os.listdir(tags_dir): basename = util.strip_whole_config(f) if not basename: continue if basename in current: print(" > " + basename + " is present in " + tags_dir) continue if not try_find(locations, basename): print(" > " + colors.red(basename + " not found anywhere")) if __name__ == '__main__': main()
765
420
# Copyright (c) 2012-2016 Seafile Ltd. """ This file contains error messages from ccnet or seafile that will be translated. """ from django.utils.translation import ugettext as _ # create_group rpc msg = _("The group has already created") msg = _("Failed to create group") # create_org_group rpc msg = _("The group has already created in this org.") msg = _("Failed to create org group.") # group_add_member rpc msg = _("Permission error: only group staff can add member") msg = _("Group does not exist") msg = _("Group is full") msg = _("Failed to add member to group") # group_remove_member rpc msg = _("Only group staff can remove member") msg = _("Group does not exist") msg = _("Can not remove myself")
214
2,106
from odo import append, drop from ..compute.core import compute from ..dispatch import dispatch from ..expr.expressions import Expr from ..expr.literal import BoundSymbol @dispatch(Expr, BoundSymbol) def compute_down(expr, data, **kwargs): return compute(expr, data.data, **kwargs) @dispatch(Expr, BoundSymbol) def pre_compute(expr, data, **kwargs): return pre_compute(expr, data.data, **kwargs) @dispatch(BoundSymbol, object) def append(a, b, **kwargs): return append(a.data, b, **kwargs) @dispatch(BoundSymbol) def drop(d): return drop(d.data)
206
831
package p1.p2; class Java { public void f(int a) { } public void g() { int r = R.layout.mai<caret>n; } }
56
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-cvvj-7g8w-wqc7", "modified": "2022-05-01T06:37:53Z", "published": "2022-05-01T06:37:53Z", "aliases": [ "CVE-2006-0171" ], "details": "PHP remote file include vulnerability in index.php in OrjinWeb E-commerce allows remote attackers to execute arbitrary code via a URL in the page parameter. NOTE: it is not clear, but OrjinWeb might be an application service, in which case it should not be included in CVE.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-0171" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/24097" }, { "type": "WEB", "url": "http://www.osvdb.org/22387" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/421312/100/0/threaded" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/16199" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
519
1,473
/* * Copyright 2017 NAVER Corp. * * 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.navercorp.pinpoint.bootstrap.instrument.matcher; import com.navercorp.pinpoint.bootstrap.instrument.matcher.operand.ClassInternalNameMatcherOperand; import com.navercorp.pinpoint.bootstrap.instrument.matcher.operand.InterfaceInternalNameMatcherOperand; import com.navercorp.pinpoint.bootstrap.instrument.matcher.operand.MatcherOperand; import com.navercorp.pinpoint.bootstrap.instrument.matcher.operator.AndMatcherOperator; import com.navercorp.pinpoint.bootstrap.instrument.matcher.operator.OrMatcherOperator; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.*; /** * @author jaehong.kim */ public class DefaultMultiClassBasedMatcherTest { @Test public void getMatcherOperandWithMultiClassName() { // (class OR class) DefaultMultiClassBasedMatcher matcher = new DefaultMultiClassBasedMatcher(Arrays.asList("java.lang.String", "java.lang.Thread")); assertTrue(matcher.getBaseClassNames().contains("java.lang.String")); assertTrue(matcher.getBaseClassNames().contains("java.lang.Thread")); MatcherOperand operand = matcher.getMatcherOperand(); assertTrue(operand instanceof OrMatcherOperator); OrMatcherOperator operator = (OrMatcherOperator) operand; assertTrue(operator.getLeftOperand() instanceof ClassInternalNameMatcherOperand); ClassInternalNameMatcherOperand leftOperand = (ClassInternalNameMatcherOperand) operator.getLeftOperand(); assertEquals("java/lang/String", leftOperand.getClassInternalName()); assertTrue(operator.getRightOperand() instanceof ClassInternalNameMatcherOperand); ClassInternalNameMatcherOperand rightOperand = (ClassInternalNameMatcherOperand) operator.getRightOperand(); assertEquals("java/lang/Thread", rightOperand.getClassInternalName()); } @Test public void getMatcherOperandWithMultiClassNameAndAdditional() { // (class OR class) AND interface InterfaceInternalNameMatcherOperand additional = new InterfaceInternalNameMatcherOperand("java/lang/Runnable", false); DefaultMultiClassBasedMatcher matcher = new DefaultMultiClassBasedMatcher(Arrays.asList("java.lang.String", "java.lang.Thread"), additional); assertTrue(matcher.getBaseClassNames().contains("java.lang.String")); assertTrue(matcher.getBaseClassNames().contains("java.lang.Thread")); MatcherOperand operand = matcher.getMatcherOperand(); assertTrue(operand instanceof AndMatcherOperator); AndMatcherOperator operator = (AndMatcherOperator) operand; // (class OR class) assertTrue(operator.getLeftOperand() instanceof OrMatcherOperator); // ... AND interface assertTrue(operator.getRightOperand() instanceof InterfaceInternalNameMatcherOperand); InterfaceInternalNameMatcherOperand rightOperand = (InterfaceInternalNameMatcherOperand) operator.getRightOperand(); assertEquals("java/lang/Runnable", rightOperand.getInterfaceInternalName()); } }
1,184
1,682
package com.linkedin.r2.transport.http.client.rest; import com.linkedin.common.callback.Callback; import com.linkedin.common.util.None; import com.linkedin.r2.message.rest.RestResponse; import com.linkedin.r2.message.rest.RestResponseBuilder; import com.linkedin.r2.transport.http.client.AsyncPool; import com.linkedin.r2.transport.http.client.PoolStats; import com.linkedin.r2.util.Cancellable; import io.netty.channel.Channel; import io.netty.channel.embedded.EmbeddedChannel; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Collection; /** * @author <NAME> * @version $Revision: $ */ public class TestChannelPoolHandler { @Test(dataProvider = "connectionClose") public void testConnectionClose(String headerName, String headerValue) { EmbeddedChannel ch = new EmbeddedChannel(new ChannelPoolHandler()); FakePool pool = new FakePool(); ch.attr(ChannelPoolHandler.CHANNEL_POOL_ATTR_KEY).set(pool); RestResponse response = new RestResponseBuilder().setHeader(headerName, headerValue).build(); ch.writeInbound(response); Assert.assertTrue(pool.isDisposeCalled()); Assert.assertFalse(pool.isPutCalled()); } @Test(dataProvider = "connectionKeepAlive") public void testConnectionKeepAlive(String headerName, String headerValue) { EmbeddedChannel ch = new EmbeddedChannel(new ChannelPoolHandler()); FakePool pool = new FakePool(); ch.attr(ChannelPoolHandler.CHANNEL_POOL_ATTR_KEY).set(pool); RestResponse response = new RestResponseBuilder().setHeader(headerName, headerValue).build(); ch.writeInbound(response); Assert.assertFalse(pool.isDisposeCalled()); Assert.assertTrue(pool.isPutCalled()); } @DataProvider(name = "connectionClose") public Object[][] createTestData1() { return new Object[][] { {"Connection", "close"}, {"connection", "foo, close, bar"}, {"CONNECTION", "Keep-Alive, Close"} }; } @DataProvider(name = "connectionKeepAlive") public Object[][] createTestData2() { return new Object[][] { {"Connection", "Keep-Alive"}, {"connection", "keep-alive"}, {"CONNECTION", "foo, bar"}, {"foo", "baz"} }; } private static class FakePool implements AsyncPool<Channel> { private boolean _isPutCalled = false; private boolean _isDisposeCalled = false; public boolean isPutCalled() { return _isPutCalled; } public boolean isDisposeCalled() { return _isDisposeCalled; } @Override public String getName() { return null; } @Override public void start() { } @Override public void shutdown(Callback<None> callback) { } @Override public Collection<Callback<Channel>> cancelWaiters() { return null; } @Override public PoolStats getStats() { return null; } @Override public void dispose(Channel obj) { _isDisposeCalled = true; } @Override public void put(Channel obj) { _isPutCalled = true; } @Override public Cancellable get(Callback<Channel> callback) { return null; } } }
1,225
1,014
{ "BVN": { "short_name": "Buenaventura Mining Company Inc", "long_name": "Compa\u00f1\u00eda de Minas Buenaventura S.A.A.", "summary": "Compa\u00c3\u00b1\u00c3\u00ada de Minas Buenaventura S.A.A., a precious metals company, engages in the exploration, mining, concentration, smelting, and marketing of polymetallic ores and metals in Peru, the United States, Europe, and Asia. It explores for gold, silver, lead, zinc, and copper metals. The company operates four operating mining units, including Uchucchacua, Orcopampa, Julcani, and Tambomayo in Peru; and San Gabriel, a mining unit under development stage. It also owns interests in Colquijirca, La Zanja, Yanacocha, Cerro Verde, El Brocal, Coimolache, Yumpaq, San Gregorio, and Tambomayo mines, as well as Trapiche, a mining unit at the development stage. In addition, the company produces manganese sulphate, which is used in agriculture and mining industries. Further, it provides energy generation and transmission services through hydroelectric power plants; insurance brokerage services; industrial activities; and construction and engineering services. The company was incorporated in 1953 and is based in Lima, Peru.", "currency": "USD", "sector": "Basic Materials", "industry": "Other Precious Metals & Mining", "exchange": "NYQ", "market": "us_market", "country": "Peru", "state": null, "city": "Lima", "zipcode": "27", "website": "http://www.buenaventura.com", "market_cap": "Mid Cap" }, "MBU.F": { "short_name": "CIA DE MIN. BUEN. B ADR 1", "long_name": "Compa\u00f1\u00eda de Minas Buenaventura S.A.A.", "summary": "Compa\u00c3\u00b1\u00c3\u00ada de Minas Buenaventura S.A.A., a precious metals company, engages in the exploration, mining, concentration, smelting, and marketing of polymetallic ores and metals in Peru, the United States, Europe, and Asia. It explores for gold, silver, lead, zinc, and copper metals. The company operates four operating mining units, including Uchucchacua, Orcopampa, Julcani, and Tambomayo in Peru; and San Gabriel, a mining unit under development stage. It also owns interests in Colquijirca, La Zanja, Yanacocha, Cerro Verde, El Brocal, Coimolache, Yumpaq, and San Gregorio mines, as well as Trapiche, a mining unit at the development stage. In addition, the company produces manganese sulphate, which is used in agriculture and mining industries. Further, it provides energy generation and transmission services through hydroelectric power plants; chemical processing services; insurance brokerage services; and industrial activities. The company was founded in 1953 and is based in Lima, Peru.", "currency": "EUR", "sector": "Basic Materials", "industry": "Other Precious Metals & Mining", "exchange": "FRA", "market": "dr_market", "country": "Peru", "state": null, "city": "Lima", "zipcode": "27", "website": "http://www.buenaventura.com", "market_cap": "Mid Cap" } }
1,098
1,040
// Copyright (c) <NAME> // Licensed under the MIT License #ifndef __INTERNAL_H__ #define __INTERNAL_H__ #include "panel.h" #include "hsystems.h" #include "esystems.h" #include "orbitersdk.h" class ShipInternal { public: VESSEL* parent; Valve* Valves[25]; Tank* Tanks[20]; FCell *FC[3]; Battery *BT[5]; Socket *Sock[10]; Manifold *Man[5]; DCbus *DC[10]; ACbus *AC[3]; Heater* HT[6]; Fan *Fans[2]; inst_MFD *MFDS[3]; Docker* Dk[1]; Clock *Clk; CW *cw[15]; Switch *Nav_mode_switch; Switch *Vern_mode_switch; Switch *Intr_mode_switch; char dig[10]; int mjd_d; H_system H_systems; E_system E_systems; Panel PanelList[6]; // float Flow; float Cabin_temp; float Cabin_press; float Cabin_dp; float Dock_temp; float Dock_press; float Dock_dp; float Fan_dp; ShipInternal(); ~ShipInternal(); void Init(VESSEL *vessel); void MakePanels(VESSEL *vessel); void Save(FILEHANDLE scn); void Load(FILEHANDLE scn,void *def_vs); void Refresh(double dt); }; #endif
447
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.dataprotection.generated; import com.azure.core.util.Context; /** Samples for DataProtectionOperations List. */ public final class DataProtectionOperationsListSamples { /* * x-ms-original-file: specification/dataprotection/resource-manager/Microsoft.DataProtection/stable/2021-07-01/examples/Operations/List.json */ /** * Sample code: Returns the list of supported REST operations. * * @param manager Entry point to DataProtectionManager. */ public static void returnsTheListOfSupportedRESTOperations( com.azure.resourcemanager.dataprotection.DataProtectionManager manager) { manager.dataProtectionOperations().list(Context.NONE); } }
280
1,155
package org.zalando.intellij.swagger.annotator.swagger; import com.intellij.psi.PsiElement; import org.zalando.intellij.swagger.traversal.JsonTraversal; public class JsonUnusedRefAnnotator extends UnusedRefAnnotator { public JsonUnusedRefAnnotator() { super(new JsonTraversal()); } @Override public PsiElement getPsiElement(final PsiElement psiElement) { return psiElement.getParent().getParent().getParent(); } @Override public PsiElement getSearchablePsiElement(final PsiElement psiElement) { return psiElement.getParent().getParent(); } }
198
2,402
<reponame>timemachine3030/node-soap { "Envelope":{ "Body":{ "Fault":{ "faultcode":"soapenv:Server.userException", "faultstring":"You have entered an invalid email address or password. Please try again.", "detail":{ "invalidCredentialsFault":{ "code":"INVALID_LOGIN_CREDENTIALS", "message":"You have entered an invalid email address or password. Please try again." }, "hostname":"partners-java10009.bos.netledger.com" } } } } }
248
5,460
<gh_stars>1000+ from .responses import CloudFormationResponse url_bases = [r"https?://cloudformation\.(.+)\.amazonaws\.com"] url_paths = { "{0}/$": CloudFormationResponse.dispatch, "{0}/cloudformation_(?P<region>[^/]+)/cfnresponse$": CloudFormationResponse.cfnresponse, }
104
1,397
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import import tensorflow as tf import numpy as np def sparse_balanced_crossentropy(logits, labels): """ Calculates a class frequency balanced crossentropy loss from sparse labels. Args: logits (tf.Tensor): logits prediction for which to calculate crossentropy error labels (tf.Tensor): sparse labels used for crossentropy error calculation Returns: tf.Tensor: Tensor scalar representing the mean loss """ epsilon = tf.constant(np.finfo(np.float32).tiny) num_classes = tf.cast(tf.shape(logits)[-1], tf.int32) probs = tf.nn.softmax(logits) probs += tf.cast(tf.less(probs, epsilon), tf.float32) * epsilon log = -1. * tf.log(probs) onehot_labels = tf.one_hot(labels, num_classes) class_frequencies = tf.stop_gradient(tf.bincount( labels, minlength=num_classes, dtype=tf.float32)) weights = (1. / (class_frequencies + tf.constant(1e-8))) weights *= (tf.cast(tf.reduce_prod(tf.shape(labels)), tf.float32) / tf.cast(num_classes, tf.float32)) new_shape = (([1, ] * len(labels.get_shape().as_list())) + [logits.get_shape().as_list()[-1]]) weights = tf.reshape(weights, new_shape) loss = tf.reduce_mean(tf.reduce_sum(onehot_labels * log * weights, axis=-1)) return loss def dice_loss(logits, labels, num_classes, smooth=1e-5, include_background=True, only_present=False): """Calculates a smooth Dice coefficient loss from sparse labels. Args: logits (tf.Tensor): logits prediction for which to calculate crossentropy error labels (tf.Tensor): sparse labels used for crossentropy error calculation num_classes (int): number of class labels to evaluate on smooth (float): smoothing coefficient for the loss computation include_background (bool): flag to include a loss on the background label or not only_present (bool): flag to include only labels present in the inputs or not Returns: tf.Tensor: Tensor scalar representing the loss """ # Get a softmax probability of the logits predictions and a one hot # encoding of the labels tensor probs = tf.nn.softmax(logits) onehot_labels = tf.one_hot( indices=labels, depth=num_classes, dtype=tf.float32, name='onehot_labels') # Compute the Dice similarity coefficient label_sum = tf.reduce_sum(onehot_labels, axis=[1, 2, 3], name='label_sum') pred_sum = tf.reduce_sum(probs, axis=[1, 2, 3], name='pred_sum') intersection = tf.reduce_sum(onehot_labels * probs, axis=[1, 2, 3], name='intersection') per_sample_per_class_dice = (2. * intersection + smooth) per_sample_per_class_dice /= (label_sum + pred_sum + smooth) # Include or exclude the background label for the computation if include_background: flat_per_sample_per_class_dice = tf.reshape( per_sample_per_class_dice, (-1, )) flat_label = tf.reshape(label_sum, (-1, )) else: flat_per_sample_per_class_dice = tf.reshape( per_sample_per_class_dice[:, 1:], (-1, )) flat_label = tf.reshape(label_sum[:, 1:], (-1, )) # Include or exclude non-present labels for the computation if only_present: masked_dice = tf.boolean_mask(flat_per_sample_per_class_dice, tf.logical_not(tf.equal(flat_label, 0))) else: masked_dice = tf.boolean_mask( flat_per_sample_per_class_dice, tf.logical_not(tf.is_nan(flat_per_sample_per_class_dice))) dice = tf.reduce_mean(masked_dice) loss = 1. - dice return loss
1,662
457
package io.purplejs.http; import java.util.List; import java.util.Map; import java.util.function.Function; import com.google.common.base.Splitter; import com.google.common.collect.ForwardingMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.net.MediaType; import static com.google.common.net.HttpHeaders.ACCEPT; // TODO: Support multiple headers with same key! public final class Headers extends ForwardingMap<String, String> { private final Map<String, String> map; public Headers() { this.map = Maps.newHashMap(); } @Override protected Map<String, String> delegate() { return this.map; } public List<MediaType> getAccept() { return parseList( ACCEPT, MediaType::parse ); } private <T> List<T> parseList( final String key, final Function<String, T> parser ) { final String value = getOrDefault( key, "" ); final Iterable<String> values = Splitter.on( ',' ).trimResults().omitEmptyStrings().split( value ); final List<T> list = Lists.newArrayList(); for ( final String item : values ) { list.add( parser.apply( item ) ); } return list; } }
479
1,615
<reponame>mmdongxin/MLN<filename>MLN-iOS/MLN/Classes/MUICore/Exporter/MLNUIGlobalVarExporterMacro.h // // MLNUIGlobalVarExporterMacro.h // MLNUICore // // Created by MoMo on 2019/8/1. // #ifndef MLNUIGlobalVarExporterMacro_h #define MLNUIGlobalVarExporterMacro_h #import "MLNUIExporterMacro.h" /** 标记导出全局变量类开始 */ #define LUAUI_EXPORT_GLOBAL_VAR_BEGIN()\ + (NSArray<NSDictionary *> *)mlnui_globalVarMap \ {\ return @[\ /** 导出全局变量类到Lua @param LUA_NAME Lua中变量名称 @param LUA_VALUES 包含所有变量的字典 */ #define LUAUI_EXPORT_GLOBAL_VAR(LUA_NAME, LUA_VALUES) \ @{kGlobalVarLuaName: (@#LUA_NAME),\ kGlobalVarMap: LUA_VALUES},\ /** 导出全局变量结束 */ #define LUAUI_EXPORT_GLOBAL_VAR_END() \ ];\ }\ LUAUI_EXPORT_TYPE(MLNUIExportTypeGlobalVar) #endif /* MLNUIGlobalVarExporterMacro_h */
440
454
<gh_stars>100-1000 package io.smallrye.mutiny.converters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import java.io.IOException; import org.junit.jupiter.api.Test; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.converters.multi.MultiReactorConverters; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class MultiConvertToTest { @SuppressWarnings("unchecked") @Test public void testCreatingAFlux() { Flux<Integer> flux = Multi.createFrom().item(1).convert().with(MultiReactorConverters.toFlux()); assertThat(flux).isNotNull(); assertThat(flux.blockFirst()).isEqualTo(1); } @SuppressWarnings("unchecked") @Test public void testCreatingAFluxFromNull() { Flux<Integer> flux = Multi.createFrom().item((Integer) null).convert().with(MultiReactorConverters.toFlux()); assertThat(flux).isNotNull(); assertThat(flux.blockFirst()).isNull(); } @SuppressWarnings("unchecked") @Test public void testCreatingAFluxWithFailure() { Flux<Integer> flux = Multi.createFrom().<Integer> failure(new IOException("boom")).convert() .with(MultiReactorConverters.toFlux()); assertThat(flux).isNotNull(); try { flux.blockFirst(); fail("Exception expected"); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class).hasCauseInstanceOf(IOException.class); } } @SuppressWarnings("unchecked") @Test public void testCreatingAMono() { Mono<Integer> mono = Multi.createFrom().item(1).convert().with(MultiReactorConverters.toMono()); assertThat(mono).isNotNull(); assertThat(mono.block()).isEqualTo(1); } @SuppressWarnings("unchecked") @Test public void testCreatingAMonoFromNull() { Mono<Integer> mono = Multi.createFrom().item((Integer) null).convert().with(MultiReactorConverters.toMono()); assertThat(mono).isNotNull(); assertThat(mono.block()).isNull(); } @SuppressWarnings("unchecked") @Test public void testCreatingAMonoWithFailure() { Mono<Integer> mono = Multi.createFrom().<Integer> failure(new IOException("boom")).convert() .with(MultiReactorConverters.toMono()); assertThat(mono).isNotNull(); try { mono.block(); fail("Exception expected"); } catch (Exception e) { assertThat(e).isInstanceOf(RuntimeException.class).hasCauseInstanceOf(IOException.class); } } }
1,089
1,530
<gh_stars>1000+ /* * This file is part of ClassGraph. * * Author: <NAME> * * Hosted at: https://github.com/classgraph/classgraph * * -- * * The MIT License (MIT) * * Copyright (c) 2019 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.classgraph.issues.issue407; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import org.junit.jupiter.api.Test; import org.ops4j.pax.url.mvn.MavenResolvers; import io.github.classgraph.ClassGraph; import io.github.classgraph.ScanResult; /** * Test. */ public class Issue407Test { /** * Test. * * @throws IOException * Signals that an I/O exception has occurred. */ @Test public void issue407Test() throws IOException { // Resolve and download scala-library final File resolvedFile = MavenResolvers.createMavenResolver(null, null).resolve("com.google.guava", "guava", null, null, "25.0-jre"); assertThat(resolvedFile).isFile(); // Create a new custom class loader final ClassLoader classLoader = new URLClassLoader(new URL[] { resolvedFile.toURI().toURL() }, null); // Scan the classpath -- used to throw an exception for Stack, since companion object inherits // from different class try (ScanResult scanResult = new ClassGraph() // .acceptPackages("com.google.thirdparty.publicsuffix") // .overrideClassLoaders(classLoader) // .scan()) { final List<String> classNames = scanResult // .getAllClasses() // .getNames(); assertThat(classNames).contains("com.google.thirdparty.publicsuffix.PublicSuffixPatterns"); } } }
1,009