max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
12,278
<reponame>randolphwong/mcsema<filename>boost/libs/random/test/test_chi_squared_distribution.cpp<gh_stars>1000+ /* test_chi_squared_distribution.cpp * * Copyright <NAME> 2011 * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * $Id$ * */ #include <boost/random/chi_squared_distribution.hpp> #include <limits> #define BOOST_RANDOM_DISTRIBUTION boost::random::chi_squared_distribution<> #define BOOST_RANDOM_ARG1 n #define BOOST_RANDOM_ARG1_DEFAULT 1.0 #define BOOST_RANDOM_ARG1_VALUE 7.5 #define BOOST_RANDOM_DIST0_MIN 0 #define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)() #define BOOST_RANDOM_DIST1_MIN 0 #define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)() #define BOOST_RANDOM_DIST2_MIN 0 #define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)() #define BOOST_RANDOM_TEST1_PARAMS #define BOOST_RANDOM_TEST1_MIN 0.0 #define BOOST_RANDOM_TEST1_MAX 100.0 #define BOOST_RANDOM_TEST2_PARAMS (10000.0) #define BOOST_RANDOM_TEST2_MIN 100.0 #include "test_distribution.ipp"
493
1,002
<reponame>JonnoFTW/thriftpy2<gh_stars>1000+ import time from thrift.TSerialization import serialize, deserialize from thrift.protocol.TBinaryProtocol import ( TBinaryProtocolFactory, TBinaryProtocolAcceleratedFactory ) from addressbook import ttypes def make_addressbook(): phone1 = ttypes.PhoneNumber() phone1.type = ttypes.PhoneType.MOBILE phone1.number = b'555-1212' phone2 = ttypes.PhoneNumber() phone2.type = ttypes.PhoneType.HOME phone2.number = b'555-1234' person = ttypes.Person() person.name = b"Alice" person.phones = [phone1, phone2] person.created_at = 1400000000 ab = ttypes.AddressBook() ab.people = {person.name: person} return ab def encode(n, proto_factory=TBinaryProtocolFactory()): ab = make_addressbook() start = time.time() for i in range(n): serialize(ab, proto_factory) end = time.time() print("encode\t-> {}".format(end - start)) def decode(n, proto_factory=TBinaryProtocolFactory()): ab = ttypes.AddressBook() ab_encoded = serialize(make_addressbook()) start = time.time() for i in range(n): deserialize(ab, ab_encoded, proto_factory) end = time.time() print("decode\t-> {}".format(end - start)) def main(): n = 100000 print("binary protocol struct benchmark for {} times:".format(n)) encode(n) decode(n) print("\naccelerated protocol struct benchmark for {} times:".format(n)) encode(n, TBinaryProtocolAcceleratedFactory()) decode(n, TBinaryProtocolAcceleratedFactory()) if __name__ == "__main__": main()
613
1,150
<reponame>wwhio/awesome-DeepLearning # save #paddle.save(deepFM_model.state_dict(), "./model/deepFM_model.pdparams") #paddle.save(adam.state_dict(), "./model/adam.pdopt") import paddle layer_state_dict = paddle.load("./model/deepFM_model.pdparams") opt_state_dict = paddle.load("./model/adam.pdopt") testDeepFM_model=DeepFMLayer(sparse_feature_number = 1000001, sparse_feature_dim = 9, dense_feature_dim = 13, sparse_num_field = 26, layer_sizes = [512, 256, 128, 32]) testAdam = paddle.optimizer.Adam(learning_rate=learning_rate, parameters=testDeepFM_model.parameters())# Adam优化器 testDeepFM_model.set_state_dict(layer_state_dict) testAdam.set_state_dict(opt_state_dict)
270
952
package com.rudecrab.di.strategy; /** * @author RudeCrab */ public interface PostageStrategy { /** * 计算邮费 * @param weight 货物重量 * @return 计算后的邮费 */ long calPostage(int weight); }
119
627
/* Copyright 2020 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /** Internal header file for rollback. * * EC code should not normally include this. These are exposed so they can be * used by unit test code. */ #ifndef __CROS_EC_ROLLBACK_PRIVATE_H #define __CROS_EC_ROLLBACK_PRIVATE_H #include "config.h" /* * Note: Do not change this structure without also updating * common/firmware_image.S .image.ROLLBACK section. */ struct rollback_data { int32_t id; /* Incrementing number to indicate which region to use. */ int32_t rollback_min_version; #ifdef CONFIG_ROLLBACK_SECRET_SIZE uint8_t secret[CONFIG_ROLLBACK_SECRET_SIZE]; #endif /* cookie must always be last, as it validates the rest of the data. */ uint32_t cookie; }; int read_rollback(int region, struct rollback_data *data); #endif /* __CROS_EC_ROLLBACK_PRIVATE_H */
315
6,034
package cn.iocoder.mall.order.rest.controller.comment; import cn.iocoder.common.framework.enums.MallConstants; import cn.iocoder.common.framework.vo.CommonResult; import cn.iocoder.common.framework.vo.PageResult; import cn.iocoder.mall.order.biz.dto.comment.OrderCommentPageDTO; import cn.iocoder.mall.order.biz.service.comment.OrderCommentService; import cn.iocoder.mall.order.rest.convert.comment.UsersOrderCommentConvert; import cn.iocoder.mall.order.rest.request.comment.UsersOrderCommentAddRequest; import cn.iocoder.mall.order.rest.request.comment.UsersOrderCommentPageRequest; import cn.iocoder.mall.order.rest.response.comment.UsersOrderCommentPageResponse; import cn.iocoder.mall.security.core.context.UserSecurityContextHolder; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * UsersOrderCommentController * * @author xiaofeng * @version 1.0 * @date 2020/05/12 22:56 */ @RestController @RequestMapping(MallConstants.ROOT_PATH_USER + "/order_comment") @Api("订单商品评论模块") public class UsersOrderCommentController { private final OrderCommentService orderCommentService; public UsersOrderCommentController( OrderCommentService orderCommentService) { this.orderCommentService = orderCommentService; } @PostMapping("/add") @ApiOperation(value = "添加订单评论") public CommonResult<Boolean> add( @RequestBody @Validated UsersOrderCommentAddRequest request) { Integer userId = UserSecurityContextHolder.getContext().getUserId(); request.setUserId(userId); return CommonResult.success(orderCommentService.addOrderComment( UsersOrderCommentConvert.INSTANCE.convert(request))); } @GetMapping("/page") @ApiOperation(value = "获取订单评论") public CommonResult<PageResult<UsersOrderCommentPageResponse>> page( UsersOrderCommentPageRequest request) { OrderCommentPageDTO orderCommentPageDTO = UsersOrderCommentConvert.INSTANCE .convert(request); return CommonResult.success(UsersOrderCommentConvert.INSTANCE .convert(orderCommentService.page(orderCommentPageDTO))); } }
928
647
<gh_stars>100-1000 #ifndef CENTRAL_EXP_H #define CENTRAL_EXP_H #include <string> #include "inc1.hpp" #include "inc2.hpp" namespace CPM_CENTRAL_EXP_NS { class CentralExportedClass { public: CentralExportedClass() : num1(83), num2(234), str("Initial String") {} std::string render(); int num1; int num2; std::string str; }; std::string centralExpFunction(const CentralExportedClass& myStruct); } // namespace CPM_CENTRAL_EXP_NS #endif
191
5,119
#include <stdint.h> #include <stdio.h> #include <stdlib.h> struct C { uint32_t a; uint64_t b; }; void clear(struct C* c, size_t size) { for (size_t t = 0; t < size; t++) { c[t].a = 0; c[t].b = 0; } } void print(struct C* c, size_t size) { uint32_t sum = 0; while (size--) sum += (c++)->a; printf("Sum: %u\n", sum); } int main() { size_t size = 10; struct C* c = (struct C*)malloc(sizeof(struct C) * size); for (size_t t = 0; t < size; t++) { c[t].a = t; c[t].b = 100; } clear(c, size); }
274
890
// Copyright (C) <2019> Intel Corporation // // SPDX-License-Identifier: Apache-2.0 #ifndef AudioFrameWriter_h #define AudioFrameWriter_h #include <string> #include <logger.h> #include <webrtc/modules/include/module_common_types.h> #include "MediaFramePipeline.h" extern "C" { #include <libavformat/avformat.h> } namespace owt_base { class AudioFrameWriter { DECLARE_LOGGER(); public: AudioFrameWriter(const std::string& name); ~AudioFrameWriter(); void write(const Frame& frame); void write(const webrtc::AudioFrame *audioFrame); protected: FILE *getAudioFp(const webrtc::AudioFrame *audioFrame); void writeCompressedFrame(const Frame& frame); bool addAudioStream(FrameFormat format, uint32_t sampleRate, uint32_t channels); private: std::string m_name; FILE *m_fp; uint32_t m_index; int32_t m_sampleRate; int32_t m_channels; AVFormatContext *m_context; AVStream *m_audioStream; }; } #endif // AudioFrameWriter_h
375
369
<filename>cdap-data-fabric/src/test/java/io/cdap/cdap/data2/dataset2/lib/table/ObjectMappedTableDatasetTest.java /* * Copyright © 2015 <NAME>, 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.cdap.cdap.data2.dataset2.lib.table; import com.google.common.collect.Lists; import io.cdap.cdap.api.common.Bytes; import io.cdap.cdap.api.data.batch.Split; import io.cdap.cdap.api.data.batch.SplitReader; import io.cdap.cdap.api.dataset.lib.CloseableIterator; import io.cdap.cdap.api.dataset.lib.KeyValue; import io.cdap.cdap.api.dataset.lib.ObjectMappedTable; import io.cdap.cdap.api.dataset.lib.ObjectMappedTableProperties; import io.cdap.cdap.api.dataset.table.Scan; import io.cdap.cdap.data2.dataset2.DatasetFrameworkTestUtil; import io.cdap.cdap.proto.id.DatasetId; import org.apache.tephra.TransactionAware; import org.apache.tephra.TransactionExecutor; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Test; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Test for {@link ObjectMappedTableDataset}. */ public class ObjectMappedTableDatasetTest { @ClassRule public static DatasetFrameworkTestUtil dsFrameworkUtil = new DatasetFrameworkTestUtil(); private static final DatasetId RECORDS_ID = DatasetFrameworkTestUtil.NAMESPACE_ID.dataset("records"); @Test public void testGetPutDelete() throws Exception { dsFrameworkUtil.createInstance(ObjectMappedTable.class.getName(), RECORDS_ID, ObjectMappedTableProperties.builder().setType(Record.class).build()); try { final ObjectMappedTableDataset<Record> records = dsFrameworkUtil.getInstance(RECORDS_ID); TransactionExecutor txnl = dsFrameworkUtil.newInMemoryTransactionExecutor((TransactionAware) records); final Record record = new Record(Integer.MAX_VALUE, Long.MAX_VALUE, Float.MAX_VALUE, null, "foobar", Bytes.toBytes("foobar"), ByteBuffer.wrap(Bytes.toBytes("foobar")), UUID.randomUUID()); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { records.write("123", record); } }); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { Record actual = records.read("123"); Assert.assertEquals(record, actual); } }); final Record record2 = new Record(Integer.MAX_VALUE, Long.MAX_VALUE, null, Double.MAX_VALUE, "foobar", Bytes.toBytes("foobar"), ByteBuffer.wrap(Bytes.toBytes("foobar")), UUID.randomUUID()); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { records.write("123", record2); } }); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { Record actual = records.read("123"); Assert.assertEquals(record2, actual); } }); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { records.delete("123"); } }); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { Assert.assertNull(records.read("123")); } }); } finally { dsFrameworkUtil.deleteInstance(RECORDS_ID); } } @Test public void testScan() throws Exception { dsFrameworkUtil.createInstance(ObjectMappedTable.class.getName(), RECORDS_ID, ObjectMappedTableProperties.builder().setType(Record.class).build()); try { final ObjectMappedTableDataset<Record> records = dsFrameworkUtil.getInstance(RECORDS_ID); TransactionExecutor txnl = dsFrameworkUtil.newInMemoryTransactionExecutor((TransactionAware) records); Record record1 = new Record(Integer.MAX_VALUE, Long.MAX_VALUE, Float.MAX_VALUE, Double.MAX_VALUE, "foobar", Bytes.toBytes("foobar"), ByteBuffer.wrap(Bytes.toBytes("foobar")), UUID.randomUUID()); Record record2 = new Record(Integer.MIN_VALUE, Long.MIN_VALUE, Float.MIN_VALUE, Double.MIN_VALUE, "baz", Bytes.toBytes("baz"), ByteBuffer.wrap(Bytes.toBytes("baz")), UUID.randomUUID()); Record record3 = new Record(1, 0L, 3.14f, 3.14159265358979323846, "hello", Bytes.toBytes("world"), ByteBuffer.wrap(Bytes.toBytes("yo")), UUID.randomUUID()); final List<KeyValue<byte[], Record>> recordList = Lists.newArrayList(); recordList.add(new KeyValue<>(Bytes.toBytes("123"), record1)); recordList.add(new KeyValue<>(Bytes.toBytes("456"), record2)); recordList.add(new KeyValue<>(Bytes.toBytes("789"), record3)); for (final KeyValue<byte[], Record> record : recordList) { txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { records.write(record.getKey(), record.getValue()); } }); } final List<KeyValue<byte[], Record>> actualList = Lists.newArrayList(); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { CloseableIterator<KeyValue<byte[], Record>> results = records.scan((String) null, null); while (results.hasNext()) { actualList.add(results.next()); } results.close(); } }); Assert.assertEquals(recordList.size(), actualList.size()); for (int i = 0; i < actualList.size(); i++) { KeyValue<byte[], Record> expected = recordList.get(i); KeyValue<byte[], Record> actual = actualList.get(i); Assert.assertArrayEquals(expected.getKey(), actual.getKey()); Assert.assertEquals(expected.getValue(), actual.getValue()); } txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { CloseableIterator<KeyValue<byte[], Record>> results = records.scan("789", null); KeyValue<byte[], Record> actualRecord = results.next(); Assert.assertFalse(results.hasNext()); Assert.assertArrayEquals(actualRecord.getKey(), recordList.get(2).getKey()); Assert.assertEquals(actualRecord.getValue(), recordList.get(2).getValue()); results.close(); results = records.scan(null, "124"); actualRecord = results.next(); Assert.assertFalse(results.hasNext()); Assert.assertArrayEquals(actualRecord.getKey(), recordList.get(0).getKey()); Assert.assertEquals(actualRecord.getValue(), recordList.get(0).getValue()); results.close(); results = records.scan(null, "123"); Assert.assertFalse(results.hasNext()); results.close(); } }); actualList.clear(); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { Scan scan = new Scan(null, null); CloseableIterator<KeyValue<byte[], Record>> results = records.scan(scan); while (results.hasNext()) { actualList.add(results.next()); } } }); Assert.assertEquals(recordList.size(), actualList.size()); } finally { dsFrameworkUtil.deleteInstance(RECORDS_ID); } } @Test public void testGetSplits() throws Exception { dsFrameworkUtil.createInstance(ObjectMappedTable.class.getName(), RECORDS_ID, ObjectMappedTableProperties.builder().setType(Record.class).build()); try { final ObjectMappedTableDataset<Record> records = dsFrameworkUtil.getInstance(RECORDS_ID); TransactionExecutor txnl = dsFrameworkUtil.newInMemoryTransactionExecutor((TransactionAware) records); final Record record = new Record(Integer.MAX_VALUE, Long.MAX_VALUE, Float.MAX_VALUE, Double.MAX_VALUE, "foobar", Bytes.toBytes("foobar"), ByteBuffer.wrap(Bytes.toBytes("foobar")), UUID.randomUUID()); final byte[] rowkey = Bytes.toBytes("row1"); txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { records.write(rowkey, record); } }); // should not include the record, since upper bound is not inclusive txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { List<Split> splits = records.getSplits(1, null, rowkey); List<Record> recordsRead = new ArrayList<>(); for (Split split : splits) { SplitReader<byte[], Record> splitReader = records.createSplitReader(split); try { splitReader.initialize(split); while (splitReader.nextKeyValue()) { recordsRead.add(splitReader.getCurrentValue()); } } finally { splitReader.close(); } } Assert.assertEquals(0, recordsRead.size()); } }); // should include the record, since lower bound is inclusive txnl.execute(new TransactionExecutor.Subroutine() { @Override public void apply() throws Exception { List<Split> splits = records.getSplits(1, rowkey, null); List<Record> recordsRead = new ArrayList<>(); for (Split split : splits) { SplitReader<byte[], Record> splitReader = records.createSplitReader(split); try { splitReader.initialize(split); while (splitReader.nextKeyValue()) { recordsRead.add(splitReader.getCurrentValue()); } } finally { splitReader.close(); } } Assert.assertEquals(1, recordsRead.size()); Assert.assertEquals(record, recordsRead.get(0)); } }); } finally { dsFrameworkUtil.deleteInstance(RECORDS_ID); } } @Test(expected = IllegalArgumentException.class) public void testInvalidTypeFails() throws Exception { dsFrameworkUtil.createInstance(ObjectMappedTable.class.getName(), DatasetFrameworkTestUtil.NAMESPACE_ID.dataset("custom"), ObjectMappedTableProperties.builder().setType(Custom.class).build()); } @Test(expected = IllegalArgumentException.class) public void testRowKeyConflict() throws Exception { dsFrameworkUtil.createInstance(ObjectMappedTable.class.getName(), DatasetFrameworkTestUtil.NAMESPACE_ID.dataset("record"), ObjectMappedTableProperties.builder() .setType(Record.class) .setRowKeyExploreName("intfield") .build()); } }
5,050
2,406
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "kernel_base_opencl.h" namespace kernel_selector { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // reverse_sequence_params //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct reverse_sequence_params : public base_params { reverse_sequence_params() : base_params(KernelType::REVERSE_SEQUENCE), seq_axis(0), batch_axis(0) {} int32_t seq_axis; int32_t batch_axis; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // reverse_sequence_optional_params //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct reverse_sequence_optional_params : optional_params { reverse_sequence_optional_params() : optional_params(KernelType::REVERSE_SEQUENCE) {} }; class ReverseSequenceKernelRef : public KernelBaseOpenCL { public: ReverseSequenceKernelRef() : KernelBaseOpenCL("reverse_sequence_ref") {} virtual ~ReverseSequenceKernelRef() {} virtual JitConstants GetJitConstants(const reverse_sequence_params& params) const; virtual CommonDispatchData SetDefault(const reverse_sequence_params& params, const optional_params&) const; KernelsData GetKernelsData(const Params& params, const optional_params& options) const override; KernelsPriority GetKernelsPriority(const Params& params, const optional_params& options) const override; ParamsKey GetSupportedKey() const override; }; } // namespace kernel_selector
425
395
<filename>test/extensions/firstorder/batch_l2_grad/test_batchl2grad.py """Test class for module Batch_l2_grad (squared ℓ₂ norm of batch gradients)""" from test.automated_test import check_sizes_and_values from test.extensions.firstorder.batch_l2_grad.batchl2grad_settings import ( BATCHl2GRAD_SETTINGS, ) from test.extensions.implementation.autograd import AutogradExtensions from test.extensions.implementation.backpack import BackpackExtensions from test.extensions.problem import make_test_problems import pytest PROBLEMS = make_test_problems(BATCHl2GRAD_SETTINGS) IDS = [problem.make_id() for problem in PROBLEMS] @pytest.mark.parametrize("problem", PROBLEMS, ids=IDS) def test_batch_l2_grad(problem): """Test squared ℓ₂ norm of individual gradients. Args: problem (ExtensionsTestProblem): Problem for extension test. """ problem.set_up() backpack_res = BackpackExtensions(problem).batch_l2_grad() autograd_res = AutogradExtensions(problem).batch_l2_grad() check_sizes_and_values(autograd_res, backpack_res) problem.tear_down() @pytest.mark.parametrize("problem", PROBLEMS, ids=IDS) def test_batch_l2_grad_hook(problem): """Test squared ℓ₂ norm of individual gradients computed via extension hook. Args: problem (ExtensionsTestProblem): Problem for extension test. """ problem.set_up() backpack_res = BackpackExtensions(problem).batch_l2_grad_extension_hook() autograd_res = AutogradExtensions(problem).batch_l2_grad() check_sizes_and_values(autograd_res, backpack_res) problem.tear_down()
587
672
<reponame>CriticalCreator/box2d<gh_stars>100-1000 // MIT License // 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. #ifndef B2_TIME_STEP_H #define B2_TIME_STEP_H #include "b2_math.h" /// Profiling data. Times are in milliseconds. struct b2Profile { float step; float collide; float solve; float solveInit; float solveVelocity; float solvePosition; float broadphase; float solveTOI; }; /// This is an internal structure. struct b2TimeStep { float dt; // time step float inv_dt; // inverse time step (0 if dt == 0). float dtRatio; // dt * inv_dt0 int32 velocityIterations; int32 positionIterations; bool warmStarting; }; /// This is an internal structure. struct b2Position { b2Vec2 c; float a; }; /// This is an internal structure. struct b2Velocity { b2Vec2 v; float w; }; /// Solver Data struct b2SolverData { b2TimeStep step; b2Position* positions; b2Velocity* velocities; }; #endif
613
1,604
package java.security.cert; public class CertificateEncodingException extends CertificateException { public CertificateEncodingException() { } public CertificateEncodingException(String msg) { super(msg); } }
79
2,151
<filename>components/offline_pages/core/prefetch/mock_prefetch_item_generator.cc<gh_stars>1000+ // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/offline_pages/core/prefetch/mock_prefetch_item_generator.h" #include "base/files/file_path.h" #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "build/build_config.h" #include "components/offline_pages/core/client_id.h" #include "url/gurl.h" namespace offline_pages { // All static. const std::string MockPrefetchItemGenerator::kClientNamespace( "test_prefetch_namespace"); const std::string MockPrefetchItemGenerator::kClientIdPrefix("test_client_id_"); const std::string MockPrefetchItemGenerator::kUrlPrefix( "http://www.requested.com/"); const std::string MockPrefetchItemGenerator::kFinalUrlPrefix( "http://www.final.com/"); const std::string MockPrefetchItemGenerator::kOperationNamePrefix( "test_operation_name_"); const std::string MockPrefetchItemGenerator::kArchiveBodyNamePrefix( "test_archive_body_name_"); const std::string MockPrefetchItemGenerator::kTitlePrefix("test_title_"); const std::string MockPrefetchItemGenerator::kFilePathPrefix("test_file_path_"); MockPrefetchItemGenerator::MockPrefetchItemGenerator() = default; MockPrefetchItemGenerator::~MockPrefetchItemGenerator() = default; PrefetchItem MockPrefetchItemGenerator::CreateItem(PrefetchItemState state) { static int item_counter = 0; ++item_counter; PrefetchItem new_item; // Values set with non prefix based values. new_item.state = state; new_item.offline_id = GenerateTestOfflineId(); new_item.creation_time = base::Time::Now(); new_item.freshness_time = new_item.creation_time; // Values always set using prefixes. CHECK(client_namespace_.length()); new_item.client_id = ClientId( client_namespace_, client_id_prefix_ + base::IntToString(item_counter)); new_item.url = GURL(url_prefix_ + base::IntToString(item_counter)); if (title_prefix_.length()) { new_item.title = base::UTF8ToUTF16(title_prefix_ + base::IntToString(item_counter)); } if (state == PrefetchItemState::NEW_REQUEST || state == PrefetchItemState::SENT_GENERATE_PAGE_BUNDLE) { return new_item; } if (operation_name_prefix_.length()) { new_item.operation_name = operation_name_prefix_ + base::IntToString(item_counter); } if (state == PrefetchItemState::AWAITING_GCM || state == PrefetchItemState::RECEIVED_GCM || state == PrefetchItemState::SENT_GET_OPERATION) { return new_item; } if (archive_body_name_prefix_.length()) { new_item.archive_body_name = archive_body_name_prefix_ + base::IntToString(item_counter); new_item.archive_body_length = item_counter * 100; } if (final_url_prefix_.length()) { new_item.final_archived_url = GURL(final_url_prefix_ + base::IntToString(item_counter)); } if (state == PrefetchItemState::RECEIVED_BUNDLE) return new_item; new_item.guid = base::GenerateGUID(); if (file_path_prefix_.length()) { new_item.file_path = base::FilePath::FromUTF8Unsafe( file_path_prefix_ + base::IntToString(item_counter)); } if (state == PrefetchItemState::DOWNLOADING) { return new_item; } new_item.file_size = new_item.archive_body_length; if (state == PrefetchItemState::DOWNLOADED || state == PrefetchItemState::IMPORTING || state == PrefetchItemState::FINISHED || state == PrefetchItemState::ZOMBIE) { return new_item; } // This code should explicitly account for all states so adding a new one will // cause this to crash in debug mode. NOTREACHED(); return new_item; } int64_t MockPrefetchItemGenerator::GenerateTestOfflineId() { return ++offline_id_counter_; } } // namespace offline_pages
1,428
839
/** * 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.cxf.transport.jms; import javax.jms.Connection; import org.apache.cxf.transport.jms.util.JMSListenerContainer; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class ThrottlingCounterTest { @Test public void testThrottleWithJmsStartAndStop() { JMSListenerContainer listenerContainer = new DummyJMSListener(); ThrottlingCounter counter = new ThrottlingCounter(0, 1); counter.setListenerContainer(listenerContainer); assertTrue(listenerContainer.isRunning()); counter.incrementAndGet(); assertFalse(listenerContainer.isRunning()); counter.decrementAndGet(); assertTrue(listenerContainer.isRunning()); } public class DummyJMSListener implements JMSListenerContainer { boolean running = true; @Override public boolean isRunning() { return running; } @Override public void stop() { running = false; } @Override public void start() { running = true; } @Override public void shutdown() { } public Connection getConnection() { return null; } } }
719
877
package org.checkerframework.framework.testchecker.testaccumulation; import org.checkerframework.common.accumulation.AccumulationTransfer; import org.checkerframework.dataflow.analysis.TransferInput; import org.checkerframework.dataflow.analysis.TransferResult; import org.checkerframework.dataflow.cfg.node.MethodInvocationNode; import org.checkerframework.dataflow.cfg.node.Node; import org.checkerframework.framework.flow.CFAnalysis; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFValue; /** A basic transfer function that accumulates the names of methods called. */ public class TestAccumulationTransfer extends AccumulationTransfer { /** * default constructor * * @param analysis the analysis */ public TestAccumulationTransfer(final CFAnalysis analysis) { super(analysis); } @Override public TransferResult<CFValue, CFStore> visitMethodInvocation( final MethodInvocationNode node, final TransferInput<CFValue, CFStore> input) { TransferResult<CFValue, CFStore> result = super.visitMethodInvocation(node, input); Node receiver = node.getTarget().getReceiver(); if (receiver != null) { String methodName = node.getTarget().getMethod().getSimpleName().toString(); accumulate(receiver, result, methodName); } return result; } }
396
678
<gh_stars>100-1000 // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class NSString; @protocol WCAccountLoginFirstUserViewControllerDelegate <NSObject> - (void)onLoginByPhoneFromQQ; - (void)onFacebookConnect; - (void)onFirstUserProblem:(id)arg1; - (void)onFirstUserBack; - (void)onFirstUserLoginUserName:(NSString *)arg1 Pwd:(NSString *)arg2; @end
176
614
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/reference/depthwiseconv_float.h" #include "tensorflow/lite/kernels/internal/reference/depthwiseconv_uint8.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/depthwise_conv.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" #include "tensorflow/lite/micro/kernels/depthwise_conv.h" #include "tensorflow/lite/micro/kernels/kernel_util.h" #include "tensorflow/lite/micro/kernels/xtensa/xtensa.h" #include "tensorflow/lite/micro/kernels/xtensa/xtensa_depthwise_conv.h" #if defined(HIFI4) || defined(HIFI4_INTERNAL) || defined(HIFI5) namespace tflite { TfLiteStatus DepthwiseConvPrepareHifi(TfLiteContext* context, TfLiteNode* node) { XtensaDepthwiseConvOpData* data = static_cast<XtensaDepthwiseConvOpData*>(node->user_data); const auto& params = *(static_cast<const TfLiteDepthwiseConvParams*>(node->builtin_data)); // Calculate scratch memory requirements and request scratch buffer TfLiteTensor* output = GetOutput(context, node, kConvOutputTensor); TF_LITE_ENSURE(context, output != nullptr); const TfLiteTensor* input = GetInput(context, node, kConvInputTensor); TF_LITE_ENSURE(context, input != nullptr); const TfLiteTensor* filter = GetInput(context, node, kConvWeightsTensor); TF_LITE_ENSURE(context, filter != nullptr); TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt8); const RuntimeShape& input_shape = GetTensorShape(input); const RuntimeShape& filter_shape = GetTensorShape(filter); const RuntimeShape& output_shape = GetTensorShape(output); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int input_depth = input_shape.Dims(3); const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int depth_multiplier = params.depth_multiplier; const int stride_height = params.stride_height; const int stride_width = params.stride_width; const int pad_width = data->reference_op_data.padding.width; const int pad_height = data->reference_op_data.padding.height; int required_scratch = 0; // Dilation is currently not supported on HiFi 4 NN Library if ((params.dilation_width_factor == 1) && (params.dilation_height_factor == 1)) { required_scratch = xa_nn_conv2d_depthwise_getsize( input_height, input_width, input_depth, filter_height, filter_width, depth_multiplier, stride_width, stride_height, pad_width, pad_height, output_height, output_width, PREC_ASYM8S, 0 /* NHWC */); TF_LITE_ENSURE(context, required_scratch > 0); } TF_LITE_ENSURE_OK( context, context->RequestScratchBufferInArena( context, required_scratch, &data->scratch_tensor_index)); return kTfLiteOk; } TfLiteStatus DepthwiseConvEvalHifi(TfLiteContext* context, TfLiteNode* node, const TfLiteDepthwiseConvParams& params, const XtensaDepthwiseConvOpData& data, const TfLiteEvalTensor* input, const TfLiteEvalTensor* filter, const TfLiteEvalTensor* bias, TfLiteEvalTensor* output) { // If dilation is not required use the optimized NN Library kernel. // Otherwise call the reference implementation. if ((params.dilation_width_factor == 1) && (params.dilation_height_factor == 1)) { const int stride_width = params.stride_width; const int stride_height = params.stride_height; const int pad_width = data.reference_op_data.padding.width; const int pad_height = data.reference_op_data.padding.height; const int depth_multiplier = params.depth_multiplier; const int32_t output_activation_min = data.reference_op_data.output_activation_min; const int32_t output_activation_max = data.reference_op_data.output_activation_max; TFLITE_DCHECK_LE(output_activation_min, output_activation_max); const RuntimeShape& input_shape = tflite::micro::GetTensorShape(input); const RuntimeShape& filter_shape = tflite::micro::GetTensorShape(filter); const RuntimeShape& output_shape = tflite::micro::GetTensorShape(output); const RuntimeShape& bias_shape = tflite::micro::GetTensorShape(bias); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int output_depth = MatchingDim(filter_shape, 3, output_shape, 3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int input_depth = input_shape.Dims(3); const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); TFLITE_DCHECK_EQ(output_depth, input_depth * depth_multiplier); TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth); const int8_t* input_data = tflite::micro::GetTensorData<int8_t>(input); const int8_t* filter_data = tflite::micro::GetTensorData<int8_t>(filter); const int32_t* bias_data = tflite::micro::GetTensorData<int32_t>(bias); int8_t* output_data = tflite::micro::GetTensorData<int8_t>(output); int32_t input_data_format = 0; int32_t output_data_format = 0; uint8_t* p_scratch = static_cast<uint8_t*>( context->GetScratchBuffer(context, data.scratch_tensor_index)); for (int i = 0; i < batches; i++) { TF_LITE_ENSURE_EQ( context, xa_nn_conv2d_depthwise_per_chan_sym8sxasym8s( &output_data[i * output_height * output_width * output_depth], filter_data, &input_data[i * input_height * input_width * input_depth], bias_data, input_height, input_width, input_depth, filter_height, filter_width, depth_multiplier, stride_width, stride_height, pad_width, pad_height, output_height, output_width, -data.reference_op_data.input_zero_point, data.reference_op_data.per_channel_output_multiplier, data.reference_op_data.per_channel_output_shift, data.reference_op_data.output_zero_point, input_data_format, output_data_format, p_scratch), 0); } int out_length = batches * output_height * output_width * output_depth; TF_LITE_ENSURE_EQ(context, xa_nn_vec_activation_min_max_8_8( output_data, output_data, output_activation_min, output_activation_max, out_length), 0); return kTfLiteOk; } reference_integer_ops::DepthwiseConvPerChannel( DepthwiseConvParamsQuantized(params, data.reference_op_data), data.reference_op_data.per_channel_output_multiplier, data.reference_op_data.per_channel_output_shift, tflite::micro::GetTensorShape(input), tflite::micro::GetTensorData<int8_t>(input), tflite::micro::GetTensorShape(filter), tflite::micro::GetTensorData<int8_t>(filter), tflite::micro::GetTensorShape(bias), tflite::micro::GetTensorData<int32_t>(bias), tflite::micro::GetTensorShape(output), tflite::micro::GetTensorData<int8_t>(output)); return kTfLiteOk; } } // namespace tflite #endif // defined(HIFI4) || defined (HIFI4_INTERNAL) || defined(HIFI5)
3,487
823
<reponame>bgogul/oak /* * Copyright 2020 The Project Oak Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "oak/common/utils.h" #include <fstream> #include <map> #include <regex> #include "absl/strings/escaping.h" #include "glog/logging.h" namespace oak { namespace utils { std::string read_file(const std::string& filename) { std::ifstream t(filename, std::ifstream::in); if (!t.is_open()) { LOG(FATAL) << "Could not open file '" << filename << "'"; } std::stringstream buffer; buffer << t.rdbuf(); return buffer.str(); } void write_file(const std::string& data, const std::string& filename) { std::ofstream t(filename, std::ofstream::out); if (!t.is_open()) { LOG(FATAL) << "Could not open file '" << filename << "'"; } t << data; t.close(); } std::map<std::string, std::string> read_pem(const std::string& filename) { auto pem_encoded_data = read_file(filename); return decode_pem(pem_encoded_data); } std::map<std::string, std::string> decode_pem(const std::string& pem_encoded_data) { std::map<std::string, std::string> content; std::stringstream streamed_pem(pem_encoded_data); std::string line; std::regex header_regex("-----BEGIN (.*)-----"); while (std::getline(streamed_pem, line, '\n')) { std::smatch header_match; if (std::regex_search(line, header_match, header_regex)) { std::string header = header_match[1].str(); std::string footer = "-----END " + header + "-----"; std::string value; // Build the value by concatenating all the lines between the header and the footer. while (std::getline(streamed_pem, line, '\n') && line.find(footer) == std::string::npos) { value.append(line); } std::string decoded_value; if (!absl::Base64Unescape(value, &decoded_value)) { LOG(FATAL) << "Could not decode base64 value."; }; content[header] = decoded_value; } } return content; } void write_pem(const std::map<std::string, std::string>& map, const std::string& filename) { std::ofstream out_file(filename, std::ofstream::out); if (!out_file.is_open()) { LOG(FATAL) << "Could not open file '" << filename << "'"; } auto pem_encoded_data = encode_pem(map); out_file << pem_encoded_data; out_file.close(); } std::string encode_pem(const std::map<std::string, std::string>& map) { std::stringstream buffer; for (const auto& item : map) { std::string header = "-----BEGIN " + item.first + "-----"; std::string footer = "-----END " + item.first + "-----"; buffer << header << "\n"; buffer << absl::Base64Escape(item.second) << "\n"; buffer << footer << "\n\n"; } return buffer.str(); } } // namespace utils } // namespace oak
1,179
321
<filename>chapter10/FileBackupMon/FileBackupMon.cpp // FileBackupMon.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include "..\FileBackup\FileBackupCommon.h" #pragma comment(lib, "fltlib") void HandleMessage(const BYTE* buffer) { auto msg = (FileBackupPortMessage*)buffer; std::wstring filename(msg->FileName, msg->FileNameLength); printf("file backed up: %ws\n", filename.c_str()); } int main() { HANDLE hPort; auto hr = ::FilterConnectCommunicationPort(L"\\FileBackupPort", 0, nullptr, 0, nullptr, &hPort); if (FAILED(hr)) { printf("Error connecting to port (HR=0x%08X)\n", hr); return 1; } BYTE buffer[1 << 12]; // 4 KB auto message = (FILTER_MESSAGE_HEADER*)buffer; for (;;) { hr = ::FilterGetMessage(hPort, message, sizeof(buffer), nullptr); if (FAILED(hr)) { printf("Error receiving message (0x%08X)\n", hr); break; } HandleMessage(buffer + sizeof(FILTER_MESSAGE_HEADER)); } ::CloseHandle(hPort); return 0; }
389
5,169
{ "name": "DKHelper", "version": "0.7.2", "summary": "Bunch of categorized classes to improve your iOS development.", "homepage": "https://github.com/kevindelord/DKHelper", "license": "MIT", "authors": { "kevindelord": "<EMAIL>" }, "source": { "git": "https://github.com/kevindelord/DKHelper.git", "tag": "0.7.2" }, "platforms": { "ios": null }, "requires_arc": true, "source_files": "DKHelper/*" }
180
380
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license * information. */ package com.airbnb.conveyor.async; import com.airbnb.conveyor.async.config.AsyncSqsClientConfiguration; import com.airbnb.conveyor.async.config.OverrideConfiguration; import com.airbnb.conveyor.async.config.RetryPolicyConfiguration; import com.airbnb.conveyor.async.metrics.AsyncConveyorMetrics; import com.airbnb.conveyor.async.mock.MockAsyncSqsClient; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.time.Duration; import java.util.concurrent.*; import javax.inject.Inject; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.EqualJitterBackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FullJitterBackoffStrategy; import software.amazon.awssdk.core.retry.conditions.MaxNumberOfRetriesCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.services.sqs.SqsAsyncClientBuilder; /** Responsible for creating {@code AsyncClient}s from configuration */ @Slf4j @AllArgsConstructor(onConstructor = @__(@Inject)) public class AsyncSqsClientFactory { @NonNull private final AsyncConveyorMetrics metrics; /** * Provides a {@code AsyncClient} given the specified configuration. * * @param configuration The {@code AsyncClientConfiguration}. * @return the corresponding {@code AsyncClient}. */ public AsyncSqsClient create(@NonNull final AsyncSqsClientConfiguration configuration) { return createClient(configuration); } private RetryPolicy buildRetryPolicy(RetryPolicyConfiguration config) { RetryPolicy retryPolicy; if (config == null) { retryPolicy = RetryPolicy.none(); } else { switch (config.getPolicy()) { case DEFAULT: retryPolicy = RetryPolicy.defaultRetryPolicy(); break; case NONE: retryPolicy = RetryPolicy.none(); break; default: RetryCondition condition; BackoffStrategy strategy; switch (config.getCondition()) { case DEFAULT: condition = RetryCondition.defaultRetryCondition(); break; case MAX_NUM: condition = MaxNumberOfRetriesCondition.create(config.getNumRetries()); break; default: condition = RetryCondition.none(); } switch (config.getBackOff()) { case FULL_JITTER: strategy = FullJitterBackoffStrategy.builder() .baseDelay(Duration.ofMillis(config.getBaseDelay())) .maxBackoffTime(Duration.ofMillis(config.getMaximumBackoffTime())) .build(); break; case EQUAL_JITTER: strategy = EqualJitterBackoffStrategy.builder() .baseDelay(Duration.ofMillis(config.getBaseDelay())) .maxBackoffTime(Duration.ofMillis(config.getMaximumBackoffTime())) .build(); break; case FIXED_DELAY: strategy = FixedDelayBackoffStrategy.create(Duration.ofMillis(config.getBaseDelay())); break; case DEFAULT: strategy = BackoffStrategy.defaultStrategy(); break; case DEFAULT_THROTTLE: strategy = BackoffStrategy.defaultThrottlingStrategy(); break; default: strategy = BackoffStrategy.none(); } retryPolicy = RetryPolicy.builder() .numRetries(config.getNumRetries()) .retryCondition(condition) .backoffStrategy(strategy) .build(); } } return retryPolicy; } private SqsAsyncClient getAsyncSQSClient(AsyncSqsClientConfiguration config) { if (config.getType().equals(AsyncSqsClientConfiguration.Type.PRODUCTION)) { SqsAsyncClientBuilder builder = SqsAsyncClient.builder() .region(Region.of(config.getRegion())) .endpointOverride(config.getEndpoint()); OverrideConfiguration overrideConfig = config.getOverrideConfiguration(); if (overrideConfig != null) { RetryPolicy retry = buildRetryPolicy(overrideConfig.getRetryPolicyConfiguration()); ClientOverrideConfiguration clientOverrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofMillis(overrideConfig.getApiCallAttemptTimeout())) .apiCallTimeout(Duration.ofMillis(overrideConfig.getApiCallTimeout())) .retryPolicy(retry) .build(); builder = builder.overrideConfiguration(clientOverrideConfiguration); } return builder.build(); } else { throw new IllegalArgumentException("Doesn't support this Type " + config.getType()); } } private AsyncSqsClient createClient(@NonNull final AsyncSqsClientConfiguration configuration) { if (configuration.getType().equals(AsyncSqsClientConfiguration.Type.MOCK)) { return new MockAsyncSqsClient(); } else { SqsAsyncClient asyncSqsClient = getAsyncSQSClient(configuration); return new AsyncSqsClientImpl( asyncSqsClient, metrics, MoreExecutors.getExitingExecutorService( new ThreadPoolExecutor( configuration.getConsumerConcurrency(), configuration.getConsumerConcurrency(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("conveyor-executor-%d").build())), configuration.getMaxUrlCacheSize(), configuration.getReceiveWaitSeconds(), configuration.getBulkheadMaxWaitMillis(), configuration.getConsumerConcurrency()); } } }
2,727
648
{"resourceType":"ValueSet","id":"supplyrequest-status","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00","profile":["http://hl7.org/fhir/StructureDefinition/valueset-shareable-definition"]},"text":{"status":"generated","div":"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <h2>SupplyRequestStatus</h2>\n <p>Status of the supply request</p>\n <p>This value set has an inline code system http://hl7.org/fhir/supplyrequest-status, which defines the following codes:</p>\n <table class=\"codes\">\n <tr>\n <td>\n <b>Code</b>\n </td>\n <td>\n <b>Display</b>\n </td>\n <td>\n <b>Definition</b>\n </td>\n </tr>\n <tr>\n <td>requested\n <a name=\"requested\"> </a>\n </td>\n <td>Requested</td>\n <td>Supply has been requested, but not dispensed.</td>\n </tr>\n <tr>\n <td>completed\n <a name=\"completed\"> </a>\n </td>\n <td>Received</td>\n <td>Supply has been received by the requestor.</td>\n </tr>\n <tr>\n <td>failed\n <a name=\"failed\"> </a>\n </td>\n <td>Failed</td>\n <td>The supply will not be completed because the supplier was unable or unwilling to supply the item.</td>\n </tr>\n <tr>\n <td>cancelled\n <a name=\"cancelled\"> </a>\n </td>\n <td>Cancelled</td>\n <td>The orderer of the supply cancelled the request.</td>\n </tr>\n </table>\n </div>"},"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/valueset-oid","valueUri":"urn:oid:2.16.840.1.113883.4.642.2.354"}],"url":"http://hl7.org/fhir/ValueSet/supplyrequest-status","version":"1.0.2","name":"SupplyRequestStatus","status":"draft","experimental":false,"publisher":"HL7 (FHIR Project)","contact":[{"telecom":[{"system":"other","value":"http://hl7.org/fhir"},{"system":"email","value":"<EMAIL>"}]}],"date":"2015-10-24T07:41:03+11:00","description":"Status of the supply request","codeSystem":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/valueset-oid","valueUri":"urn:oid:2.16.840.1.113883.4.642.1.354"}],"system":"http://hl7.org/fhir/supplyrequest-status","version":"1.0.2","caseSensitive":true,"concept":[{"code":"requested","display":"Requested","definition":"Supply has been requested, but not dispensed."},{"code":"completed","display":"Received","definition":"Supply has been received by the requestor."},{"code":"failed","display":"Failed","definition":"The supply will not be completed because the supplier was unable or unwilling to supply the item."},{"code":"cancelled","display":"Cancelled","definition":"The orderer of the supply cancelled the request."}]}}
1,506
28,056
package com.alibaba.json.demo; import org.junit.Assert; import junit.framework.TestCase; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; public class JSONFeidDemo extends TestCase { public static class User { private int id; private String name; @JSONField(name = "uid") public int getId() { return id; } @JSONField(name = "uid") public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public void test_0() throws Exception { User user = new User(); user.setId(123); user.setName("毛头"); String text = JSON.toJSONString(user); Assert.assertEquals("{\"name\":\"毛头\",\"uid\":123}", text); System.out.println(text); } }
371
471
<gh_stars>100-1000 #define GLM_FORCE_MESSAGES #include <glm/glm.hpp> #if GLM_HAS_ALIGNED_TYPE #include <glm/gtc/type_aligned.hpp> GLM_STATIC_ASSERT(glm::detail::is_aligned<glm::aligned_lowp>::value, "aligned_lowp is not aligned"); GLM_STATIC_ASSERT(glm::detail::is_aligned<glm::aligned_mediump>::value, "aligned_mediump is not aligned"); GLM_STATIC_ASSERT(glm::detail::is_aligned<glm::aligned_highp>::value, "aligned_highp is not aligned"); GLM_STATIC_ASSERT(!glm::detail::is_aligned<glm::packed_highp>::value, "packed_highp is aligned"); GLM_STATIC_ASSERT(!glm::detail::is_aligned<glm::packed_mediump>::value, "packed_mediump is aligned"); GLM_STATIC_ASSERT(!glm::detail::is_aligned<glm::packed_lowp>::value, "packed_lowp is aligned"); struct my_vec4_packed { glm::uint32 a; glm::vec4 b; }; GLM_STATIC_ASSERT(sizeof(my_vec4_packed) == sizeof(glm::uint32) + sizeof(glm::vec4), "glm::vec4 packed is not correct"); struct my_vec4_aligned { glm::uint32 a; glm::aligned_vec4 b; }; GLM_STATIC_ASSERT(sizeof(my_vec4_aligned) == sizeof(glm::aligned_vec4) * 2, "glm::vec4 aligned is not correct"); struct my_dvec4_packed { glm::uint64 a; glm::dvec4 b; }; GLM_STATIC_ASSERT(sizeof(my_dvec4_packed) == sizeof(glm::uint64) + sizeof(glm::dvec4), "glm::dvec4 packed is not correct"); struct my_dvec4_aligned { glm::uint64 a; glm::aligned_dvec4 b; }; //GLM_STATIC_ASSERT(sizeof(my_dvec4_aligned) == sizeof(glm::aligned_dvec4) * 2, "glm::dvec4 aligned is not correct"); struct my_ivec4_packed { glm::uint32 a; glm::ivec4 b; }; GLM_STATIC_ASSERT(sizeof(my_ivec4_packed) == sizeof(glm::uint32) + sizeof(glm::ivec4), "glm::ivec4 packed is not correct"); struct my_ivec4_aligned { glm::uint32 a; glm::aligned_ivec4 b; }; GLM_STATIC_ASSERT(sizeof(my_ivec4_aligned) == sizeof(glm::aligned_ivec4) * 2, "glm::ivec4 aligned is not correct"); struct my_u8vec4_packed { glm::uint32 a; glm::u8vec4 b; }; GLM_STATIC_ASSERT(sizeof(my_u8vec4_packed) == sizeof(glm::uint32) + sizeof(glm::u8vec4), "glm::u8vec4 packed is not correct"); static int test_copy() { int Error = 0; { glm::aligned_ivec4 const a(1, 2, 3, 4); glm::ivec4 const u(a); Error += a.x == u.x ? 0 : 1; Error += a.y == u.y ? 0 : 1; Error += a.z == u.z ? 0 : 1; Error += a.w == u.w ? 0 : 1; } { my_ivec4_aligned a; a.b = glm::ivec4(1, 2, 3, 4); my_ivec4_packed u; u.b = a.b; Error += a.b.x == u.b.x ? 0 : 1; Error += a.b.y == u.b.y ? 0 : 1; Error += a.b.z == u.b.z ? 0 : 1; Error += a.b.w == u.b.w ? 0 : 1; } return Error; } static int test_ctor() { int Error = 0; # if GLM_HAS_CONSTEXPR && GLM_ARCH == GLM_ARCH_PURE { constexpr glm::aligned_ivec4 v(1); Error += v.x == 1 ? 0 : 1; Error += v.y == 1 ? 0 : 1; Error += v.z == 1 ? 0 : 1; Error += v.w == 1 ? 0 : 1; } { constexpr glm::packed_ivec4 v(1); Error += v.x == 1 ? 0 : 1; Error += v.y == 1 ? 0 : 1; Error += v.z == 1 ? 0 : 1; Error += v.w == 1 ? 0 : 1; } { constexpr glm::ivec4 v(1); Error += v.x == 1 ? 0 : 1; Error += v.y == 1 ? 0 : 1; Error += v.z == 1 ? 0 : 1; Error += v.w == 1 ? 0 : 1; } # endif return Error; } int main() { int Error = 0; Error += test_ctor(); Error += test_copy(); return Error; } #else int main() { return 0; } #endif//GLM_HAS_ALIGNED_TYPE
1,542
319
package net.dongliu.requests.body; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.Collection; /** * MultiPart request body * * @author <NAME> */ class MultiPartRequestBody extends RequestBody<Collection<? extends Part<?>>> { private static final String BOUNDARY = "********************" + System.currentTimeMillis(); private static final String LINE_END = "\r\n"; private static final long serialVersionUID = -2150328570818986957L; public MultiPartRequestBody(Collection<? extends Part<?>> body) { super(body, "multipart/form-data; boundary=" + BOUNDARY, false); } @Override public void writeBody(OutputStream out, Charset charset) throws IOException { Writer writer = new OutputStreamWriter(out); for (Part part : body()) { String contentType = part.contentType(); String name = part.name(); String fileName = part.fileName(); writeBoundary(writer); writer.write("Content-Disposition: form-data; name=\"" + name + "\""); if (fileName != null && !fileName.isEmpty()) { writer.write("; filename=\"" + fileName + '"'); } writer.write(LINE_END); if (contentType != null && !contentType.isEmpty()) { writer.write("Content-Type: " + contentType); Charset partCharset = part.charset(); if (partCharset != null) { writer.write("; charset=" + partCharset.name().toLowerCase()); } writer.write(LINE_END); } writer.write(LINE_END); writer.flush(); part.writeTo(out); out.flush(); writer.write(LINE_END); writer.flush(); out.flush(); } writer.write("--"); writer.write(BOUNDARY); writer.write("--"); writer.write(LINE_END); writer.flush(); } private void writeBoundary(Writer writer) throws IOException { writer.write("--"); writer.write(BOUNDARY); writer.write(LINE_END); } }
982
1,073
<reponame>oubotong/Armariris // Check that we aren't splitting debug output for modules builds that don't produce object files. // // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -c -fmodules -### %s 2> %t // RUN: FileCheck -check-prefix=CHECK-NO-ACTIONS < %t %s // // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -c -fmodules -emit-module -fmodules-embed-all-files -fno-implicit-modules -fno-implicit-module-maps -### %s 2> %t // RUN: FileCheck -check-prefix=CHECK-NO-ACTIONS < %t %s // // FIXME: This should fail using clang, except that the type of the output for // an object output with modules is given as clang::driver::types::TY_PCH // rather than TY_Object. // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -c -fmodules -fmodule-format=obj -### %s 2> %t // RUN: FileCheck -check-prefix=CHECK-NO-ACTIONS < %t %s // // CHECK-NO-ACTIONS-NOT: objcopy
329
694
// Copyright (c) 2008-2009 <NAME> <<EMAIL>> // See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. #include "utf_convert.h" #include <stddef.h> #include <stdint.h> #define false 0 #define true 1 #define UTF8_ACCEPT 0 #define UTF8_REJECT 1 static const uint8_t utf8d[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7f 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9f 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // a0..bf 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // c0..df 0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef 0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // s7..s8 }; Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) { size_t i; uint8_t type; uint32_t state = UTF8_ACCEPT; for (i = 0; i < sourceEnd - source; i++) { // We don't care about the codepoint, so this is // a simplified version of the decode function. type = utf8d[(uint8_t)source[i]]; state = utf8d[256 + state * 16 + type]; if (state == UTF8_REJECT) break; } return state == UTF8_ACCEPT; }
2,105
2,662
package co.mobiwise.materialintro.shape; /** * Created by yuchen on 3/17/16. */ public enum ShapeType { /** * Allows the target area to be highlighted by either a circle or rectangle */ CIRCLE, RECTANGLE }
82
416
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cwp.v20180228.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class AssetWebAppPluginInfo extends AbstractModel{ /** * 名称 */ @SerializedName("Name") @Expose private String Name; /** * 描述 */ @SerializedName("Desc") @Expose private String Desc; /** * 版本 */ @SerializedName("Version") @Expose private String Version; /** * 链接 */ @SerializedName("Link") @Expose private String Link; /** * Get 名称 * @return Name 名称 */ public String getName() { return this.Name; } /** * Set 名称 * @param Name 名称 */ public void setName(String Name) { this.Name = Name; } /** * Get 描述 * @return Desc 描述 */ public String getDesc() { return this.Desc; } /** * Set 描述 * @param Desc 描述 */ public void setDesc(String Desc) { this.Desc = Desc; } /** * Get 版本 * @return Version 版本 */ public String getVersion() { return this.Version; } /** * Set 版本 * @param Version 版本 */ public void setVersion(String Version) { this.Version = Version; } /** * Get 链接 * @return Link 链接 */ public String getLink() { return this.Link; } /** * Set 链接 * @param Link 链接 */ public void setLink(String Link) { this.Link = Link; } public AssetWebAppPluginInfo() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public AssetWebAppPluginInfo(AssetWebAppPluginInfo source) { if (source.Name != null) { this.Name = new String(source.Name); } if (source.Desc != null) { this.Desc = new String(source.Desc); } if (source.Version != null) { this.Version = new String(source.Version); } if (source.Link != null) { this.Link = new String(source.Link); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Name", this.Name); this.setParamSimple(map, prefix + "Desc", this.Desc); this.setParamSimple(map, prefix + "Version", this.Version); this.setParamSimple(map, prefix + "Link", this.Link); } }
1,460
975
<gh_stars>100-1000 package com.dianping.shield.entity; import android.util.Pair; import java.util.ArrayList; /** * Created by hezhi on 17/2/22. */ public class AdapterExposedList { public ArrayList<Pair<Integer, Integer>> completeExposedList; public ArrayList<Pair<Integer, Integer>> partExposedList; public AdapterExposedList() { completeExposedList = new ArrayList<>(); partExposedList = new ArrayList<>(); } public void addToList(ExposedDetails details) { if (details.isComplete) { completeExposedList.add(new Pair<Integer, Integer>(details.section, details.row)); } else { partExposedList.add(new Pair<Integer, Integer>(details.section, details.row)); } } }
290
1,958
package com.freetymekiyan.algorithms.level.medium; /** * 714. Best Time to Buy and Sell Stock with Transaction Fee * <p> * Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a * non-negative integer fee representing a transaction fee. * <p> * You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You * may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.) * <p> * Return the maximum profit you can make. * <p> * Example 1: * Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 * Output: 8 * Explanation: The maximum profit can be achieved by: * Buying at prices[0] = 1 * Selling at prices[3] = 8 * Buying at prices[4] = 4 * Selling at prices[5] = 9 * The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. * Note: * <p> * 0 < prices.length <= 50000. * 0 < prices[i] < 50000. * 0 <= fee < 50000. * <p> * Related Topics: Array, Dynamic Programming, Greedy * Similar Questions: (E) Best Time to Buy and Sell Stock II */ public class BestTimeToBuyAndSellStockWithTransactionFee { /** * DP. * Can either buy or sell on day i, 2 states. * Track the maximum of these 2 states. * If buy, the maximum is either do nothing or buy today's stock with cash got from yesterday. * buy = max(buy, sell - prices[i]) * If sell, the maximum is either do nothing or sell the share you hold and pay the fee. * sell = max(sell, buy + prices[i] - fee) * Note that buy state should be after sell since sell can happen and the maximum is larger. */ public int maxProfit(int[] prices, int fee) { if (prices == null || prices.length <= 1) { return 0; } if (fee < 0) { throw new IllegalArgumentException("fee should be non-negative."); } int cash = 0; int hold = -prices[0]; for (int i = 1; i < prices.length; i++) { /* * Hold updates after cash since we can sell and buy to achieve higher profit. * If buy first then sell on one day, we lose by paying transaction fee. */ cash = Math.max(cash, hold + prices[i] - fee); hold = Math.max(hold, cash - prices[i]); } return cash; // Return cash in the end. } /** * DP. * More compact version. * sell is skipped on day 1 since we don't have any share. * hold is initialized as MIN since we have negative values, 0 will be wrong. */ public int maxProfit2(int[] prices, int fee) { int sell = 0; int hold = Integer.MIN_VALUE; for (int i = 0; i < prices.length; i++) { if (i > 0) sell = Math.max(prices[i] + hold - fee, sell); hold = Math.max(sell - prices[i], hold); } return sell; } }
1,108
333
<gh_stars>100-1000 package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 社区互娱平台场景上报行为 * * @author auto create * @since 1.0, 2020-02-27 09:40:02 */ public class AlipaySocialAntiepSceneSendModel extends AlipayObject { private static final long serialVersionUID = 7156645787459113186L; /** * 行为业务参数,用于业务流处理时所需参数转换,map<String,String> 的 json格式 */ @ApiField("action_biz_info") private String actionBizInfo; /** * 行为幂等id,用于防止重复提交 */ @ApiField("action_biz_no") private String actionBizNo; /** * 上报行为的code码,用于服务端取出对应的场景信息并处理对应的后续行为 */ @ApiField("action_code") private String actionCode; /** * 行为发生的时间戳,单位是ms */ @ApiField("action_time") private Long actionTime; /** * 请求类型,需传OPENAPI */ @ApiField("request_type") private String requestType; /** * 场景类型,新增需找开发者协定值 */ @ApiField("scene_code") private String sceneCode; /** * 请求来源 */ @ApiField("source") private String source; /** * 蚂蚁统一会员ID */ @ApiField("user_id") private String userId; public String getActionBizInfo() { return this.actionBizInfo; } public void setActionBizInfo(String actionBizInfo) { this.actionBizInfo = actionBizInfo; } public String getActionBizNo() { return this.actionBizNo; } public void setActionBizNo(String actionBizNo) { this.actionBizNo = actionBizNo; } public String getActionCode() { return this.actionCode; } public void setActionCode(String actionCode) { this.actionCode = actionCode; } public Long getActionTime() { return this.actionTime; } public void setActionTime(Long actionTime) { this.actionTime = actionTime; } public String getRequestType() { return this.requestType; } public void setRequestType(String requestType) { this.requestType = requestType; } public String getSceneCode() { return this.sceneCode; } public void setSceneCode(String sceneCode) { this.sceneCode = sceneCode; } public String getSource() { return this.source; } public void setSource(String source) { this.source = source; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } }
1,186
1,909
<filename>xchange-ftx/src/main/java/org/knowm/xchange/ftx/dto/FtxResponse.java package org.knowm.xchange.ftx.dto; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class FtxResponse<V> { private final boolean success; private final V result; @JsonIgnore private final boolean hasMoreData; public FtxResponse( @JsonProperty("success") boolean success, @JsonProperty("result") V result, @JsonProperty("hasMoreData") boolean hasMoreData) { this.success = success; this.result = result; this.hasMoreData = hasMoreData; } public boolean isSuccess() { return success; } public V getResult() { return result; } public boolean isHasMoreData() { return hasMoreData; } @Override public String toString() { return "FtxResponse{" + "success=" + success + ", result=" + result + ", hasMoreData=" + hasMoreData + '}'; } }
392
335
<reponame>Safal08/Hacktoberfest-1<filename>P/Please_verb.json { "word": "Please", "definitions": [ "Cause to feel happy and satisfied.", "Give satisfaction.", "Satisfy aesthetically.", "Take only one's own wishes into consideration in deciding how to act or proceed.", "Wish or desire to do something.", "It is someone's choice to do something." ], "parts-of-speech": "Verb" }
172
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.performance.results; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** Wrapper for performance results related to one test case. * * @author <NAME> */ public class TestCaseResults implements Comparable { public static final int ORDER_FIRST = 1; public static final int ORDER_NEXT = 2; public static void main (String [] av) { TestCaseResults r = new TestCaseResults("aa", 100, "ms", ORDER_FIRST, "ref suite"); r.addValue(7); r.addValue(7); r.addValue(8); r.addValue(8); r.addValue(9); r.addValue(7);r.addValue(8);r.addValue(7);r.addValue(10); // r.addValue(131); // r.addValue(131);r.addValue(134);r.addValue(134);r.addValue(133);r.addValue(132); System.out.println("average "+r.getAverage()); System.out.println("count "+r.getCount()); System.out.println("stddev "+r.getStdDev()); System.out.println("variance "+r.getVariance()); TestCaseResults r2 = new TestCaseResults("aa", 100, "ms", ORDER_FIRST, "dummy suite"); r2.addValue(9); r2.addValue(7); r2.addValue(11); r2.addValue(7); r2.addValue(8); r2.addValue(7);r2.addValue(8);r2.addValue(7);r2.addValue(7); // r2.addValue(131); // r2.addValue(133);r2.addValue(129);r2.addValue(129);r2.addValue(133);r2.addValue(131); System.out.println("average "+r2.getAverage()); System.out.println("count "+r2.getCount()); System.out.println("stddev "+r2.getStdDev()); System.out.println("variance "+r2.getVariance()); ttest(r, r2); } public static TTestValue ttest(TestCaseResults r1, TestCaseResults r2) { double sv1 = 0; // 1st dataset sample variance double sv2 = 0; // 2nd dataset sample variance // sample--not pop. variance is calculated below sv1 = (r1.getSumSquares() / r1.getCount() - r1.getAverage() * r1.getAverage()) * (r1.getCount() / (r1.getCount() - 1)); sv2 = (r2.getSumSquares() / r2.getCount() - r2.getAverage() * r2.getAverage()) * (r2.getCount() / (r2.getCount() - 1)); /* Now it remains to be determined if the population variances can be pooled or not. To see this, an F-test can be applied to them. This decision is determined automatically, with an alpha level of 1%, in order to not encumber the user with details. */ double f = 0; double fAlpha = 0; if (sv1 > sv2) { f = sv1/sv2; fAlpha = fDist(r1.getCount() - 1, r2.getCount() - 1, f); } else { f = sv2/sv1; fAlpha = fDist(r2.getCount() - 1, r1.getCount() - 1, f); } double df = 0; // t Test degrees of freedom double t = 0; // t value String comment = new String(); String comment1 = new String(); if (fAlpha <= 0.005) { comment = "An F test on the sample variances indicates that they are " + "probably not from the same population (the variances " + "can't be pooled), at an alpha level of " + fAlpha + "." + "Thus, the t-test was set up for samples with unequal varainces. "+ "(The degrees of freedom were adjusted.)"; double svn1 = sv1 / r1.getCount(); double svn2 = sv2 / r2.getCount(); df = Math.pow(svn1 + svn2, 2) / (Math.pow(svn1, 2)/(r1.getCount() + 1) + Math.pow(svn2, 2)/(r2.getCount() + 1)) - 2; t = Math.abs(r1.getAverage() - r2.getAverage()) / Math.sqrt(sv1 / r1.getCount() + sv2 / r2.getCount()); } else { comment = "An F test on the sample variances indicates that they could be " + "from the same population, (alpha level of 0.005)." + "Accordingly, the t-test was set up for samples with equal population variance."; df = r1.getCount() + r2.getCount() - 2; double sp = Math.sqrt( ((r1.getCount() - 1)*sv1 + (r2.getCount() - 1)*sv2) / (r1.getCount() + r2.getCount() - 2) ); t = Math.abs(r1.getAverage() - r2.getAverage()) * Math.sqrt(r1.getCount() * r2.getCount() / (r1.getCount() + r2.getCount())) / sp; } double pVal = (t!=0)? stDist(df, t): 0.5; String pValComment = "" + pVal; if (pVal <= 0.01) { comment1 = "This probability indicates that there is a difference in sample means.\n"; if (pVal <= 0.0001) { pValComment = "< 0.0001"; } } else if (pVal <= 0.05) { comment1 = "This probability indicates that there may be a difference in sample means.\n"; } else { comment1 = "There is not a significant difference in the sample means. " + "A difference could not be detected due to large variability, small sample size, " + "or both. Of course, it's possible that the samples really are from the same population!\n"; } // a hack to take care of garbage data if ( (r1.getCount() == 0)||(r2.getCount() == 0) ) { comment1 = "There is a problem with the data. Valid delimiters are space, " + "comma, tab and newline.\n"; comment = "\n"; } else if (t == 0) { comment1 = "The means are the same for both samples."; } // convert variance to std. deviation for report sv1 = Math.sqrt(sv1); sv2 = Math.sqrt(sv2); // build the report String cs = "\nMean of first data set :\t" + r1.getAverage() + "\nStandard deviation of first data set :\t" + sv1 + "\nNumber of observations in the first set :\t" + r1.getCount() + "\nMean of second data set :\t" + r2.getAverage() + "\nStandard deviation of second data set :\t" + sv2 + "\nNumber of observations in the second set :\t" + r2.getCount() + "\n\nDegrees of freedom :\t" + df + "\nt Value (one-tailed) :\t" + t + "\nP(x>t) :\t" + pValComment + "\n" + comment1 + comment; System.out.println(cs); return new TTestValue (pVal ,t, df, cs); } /** Name of test case. */ String name; /** Expected limit for result values. */ int threshold; /** Measurement unit. */ String unit; /** Order of test case in measured suite. */ int order; private String suite; Collection<Integer> values; /** flag whether computed values are valid */ private transient boolean upToDate = false; /** computed average */ private transient double avg; /** computed standard deviation */ private transient double stddev; /** computed variance */ private transient double var; private transient double sumSquares; private transient int n; private TTestValue tt; /** Creates a new instance of TestCaseResults */ public TestCaseResults(String name, int threshold, String unit, int order, String suite) { if (name == null || unit == null) throw new IllegalArgumentException(); this.name = name; this.unit = unit; this.threshold = threshold; this.order = order; this.suite = suite; values = new ArrayList<Integer> (); } /** Adds new value to set of measured results. */ public synchronized void addValue(int val) { upToDate = false; values.add (new Integer (val)); } public double getAverage () { compute(); return avg; } public double getStdDev () { compute(); return stddev; } public double getVariance () { compute(); return var; } public int getCount () { compute(); return n; } public double getSumSquares () { compute(); return sumSquares; } public void setTTest(TTestValue tt) { this.tt = tt; } public TTestValue getTTest() { return tt; } /** updates mean and variances. */ private synchronized void compute () { if (upToDate) return; Iterator it = values.iterator(); n = values.size(); avg = stddev = var = sumSquares = 0; while (it.hasNext()) { int val = ((Integer)it.next()).intValue(); avg += val; sumSquares += val*val; } // ep = 0.0; // for (i = 2; i <= n; i++) { // s = ARGV[i] - mean; // ep += s; // variance = variance + s * s; // } // variance = (variance - ep*ep/n)/(n - 1); // stdev = sqrt(variance); // printf("stdev=%f\n", stdev); // printf("var=%f\n", variance); // if (n > 0) { avg = avg / n; } if (n > 1) { it = values.iterator(); double ep = 0d; while (it.hasNext()) { int v = ((Integer)it.next()).intValue(); ep += v - avg; var += (v - avg)*(v - avg); } var = (var - ep*ep/n)/(n-1); stddev = Math.sqrt(var); } upToDate = true; } /** * Getter for property name. * @return Value of property name. */ public java.lang.String getName() { return name; } /** * Getter for property threshold. * @return Value of property threshold. */ public int getThreshold() { return threshold; } /** * Getter for property unit. * @return Value of property unit. */ public java.lang.String getUnit() { return unit; } /** * Getter for property values. * @return Value of property values. */ public java.util.Collection<Integer> getValues() { return values; } public int hashCode() { return name.hashCode() | unit.hashCode() | order | threshold; } public boolean equals(Object obj) { if (!(obj instanceof TestCaseResults)) return false; TestCaseResults o = (TestCaseResults)obj; return name.equals(o.name) && threshold == o.threshold && unit.equals(o.unit) && order == o.order; } /** * Getter for property order. * @return Value of property order. */ public int getOrder() { return order; } public int compareTo(Object o) { TestCaseResults t = (TestCaseResults)o; if (name.equals(t.name)) { if (order == t.order) { if (unit.equals(t.unit)) { return threshold - t.threshold; } else { return unit.compareTo(t.unit); } } else { return (order > t.order)? 1: -1; } } else { return name.compareTo(t.name); } } private static double logGamma( double xx) { // An approximation to ln(gamma(x)) // define some constants... int j; double stp = 2.506628274650; double cof[] = new double[6]; cof[0]=76.18009173; cof[1]=-86.50532033; cof[2]=24.01409822; cof[3]=-1.231739516; cof[4]=0.120858003E-02; cof[5]=-0.536382E-05; double x = xx-1; double tmp = x + 5.5; tmp = (x + 0.5)*Math.log(tmp) - tmp; double ser = 1; for(j=0;j<6;j++){ x++; ser = ser + cof[j]/x; } double retVal = tmp + Math.log(stp*ser); return retVal; } private static double gamma( double x) { // An approximation of gamma(x) double f = 10E99; double g = 1; if ( x > 0 ) { while (x < 3) { g = g * x; x = x + 1; } // f = (1 - (2/(7*Math.pow(x,2))) * (1 - 2/(3*Math.pow(x,2))))/(30*Math.pow(x,2)); f = (1 - (2/(7*x*x)) * (1 - 2/(3*x*x)))/(30*x*x); f = (1-f)/(12*x) + x*(Math.log(x)-1); f = (Math.exp(f)/g)*Math.pow(2*Math.PI/x,0.5); } else { f = Double.POSITIVE_INFINITY; } return f; } private static double betacf(double a,double b,double x){ // A continued fraction representation of the beta function int maxIterations = 50, m=1; double eps = 3E-5; double am = 1; double bm = 1; double az = 1; double qab = a+b; double qap = a+1; double qam = a-1; double bz = 1 - qab*x/qap; double aold = 0; double em, tem, d, ap, bp, app, bpp; while((m<maxIterations)&&(Math.abs(az-aold)>=eps*Math.abs(az))){ em = m; tem = em+em; d = em*(b-m)*x/((qam + tem)*(a+tem)); ap = az+d*am; bp = bz+d*bm; d = -(a+em)*(qab+em)*x/((a+tem)*(qap+tem)); app = ap+d*az; bpp = bp+d*bz; aold = az; am = ap/bpp; bm = bp/bpp; az = app/bpp; bz = 1; m++; } return az; } private static double betai(double a, double b, double x) { // the incomplete beta function from 0 to x with parameters a, b // x must be in (0,1) (else returns error) Double er = new Double(0); double bt=0, beta=er.POSITIVE_INFINITY; if( x==0 || x==1 ){ bt = 0; } else if((x>0)&&(x<1)) { bt = gamma(a+b)*Math.pow(x,a)*Math.pow(1-x,b)/(gamma(a)*gamma(b)); } if(x<(a+1)/(a+b+2)){ beta = bt*betacf(a,b,x)/a; } else { beta = 1-bt*betacf(b,a,1-x)/b; } return beta; } private static double fDist(double v1, double v2, double f) { /* F distribution with v1, v2 deg. freedom P(x>f) */ double p = betai(v1/2, v2/2, v1/(v1 + v2*f)); return p; } private static double student_c(double v) { // Coefficient appearing in Student's t distribution return Math.exp(logGamma( (v+1)/2)) / (Math.sqrt(Math.PI*v)*Math.exp(logGamma(v/2))); } private static double student_tDen(double v, double t) { /* Student's t density with v degrees of freedom Requires gamma, student_c functions Part of Bryan's Java math classes (c) 1997 */ return student_c(v)*Math.pow( 1 + (t*t)/v, -0.5*(v+1) ); } private static double stDist(double v, double t) { /* Student's t distribution with v degrees of freedom Requires gamma, student_c functions Part of Bryan's Java math classes (c) 1997 This only uses compound trapezoid, pending a good integration package Returned value is P( x > t) for a r.v. x with v deg. freedom. NOTE: With the gamma function supplied here, and the simple trapeziodal sum used for integration, the accuracy is only about 5 decimal places. Values below 0.00001 are returned as zero. */ double sm = 0.5; double u = 0; double sign = 1; double stepSize = t/5000; if ( t < 0) { sign = -1; } for (u = 0; u <= (sign * t) ; u = u + stepSize) { sm = sm + stepSize * student_tDen( v, u); // System.out.println("u "+u+" sm "+sm); } if ( sign < 0 ) { sm = 0.5 - sm; } else { sm = 1 - sm; } if (sm < 0) { sm = 0; // do not allow probability less than zero from roundoff error } else if (sm > 1) { sm = 1; // do not allow probability more than one from roundoff error } return sm ; } public static class TTestValue { /** P(x&gt;t). */ private double p; /** t Value (one tailed). */ private double t; /** Degree of freedom. */ private double degree; /** Comment. */ private String comment; public TTestValue (double p, double t, double degree, String c) { this.p = p; this.t = t; this.degree = degree; comment = c; } public double getP() { return p; } public double getT() { return t; } public double getDF() { return degree; } public String getComment() { String s = comment; int i = s.indexOf('>'); while (i >= 0) { s = s.substring(0, i)+"&gt;"+s.substring(i+1); i = s.indexOf('>'); } i = s.indexOf('<'); while (i >= 0) { s = s.substring(0, i)+"&lt;"+s.substring(i+1); i = s.indexOf('<'); } return s; } } }
9,180
1,405
package seC.dujmehn.Cutyq; import android.util.Base64; import seC.dujmehn.qdtheyt.s.q.q; import seC.dujmehn.r.r; final class d implements Runnable { d() { } public static String JJJJJkXGQRIlvVBjgOpt(StringBuilder sb) { return (String) StringBuilder.class.getMethod(JJJJJkXGQRIlvVBjgOpt9592(), new Class[0]).invoke(sb, new Object[0]); } public static String JJJJJkXGQRIlvVBjgOpt9592() { String x = new String(Base64.decode("QAs3F0EPC1Y=".getBytes(), 0)); StringBuilder xg = new StringBuilder(); for (int n = 0; n < x.length(); n++) { xg.append((char) (x.charAt(n) ^ "4ddc3fe136b14236a8ae136d473044a8".charAt(n % "4ddc3fe136b14236a8ae136d473044a8".length()))); } return xg.toString(); } public static void mhgXoHzNcvBiiqsc(String str, Throwable th) { q.class.getMethod(mhgXoHzNcvBiiqsc2275(), String.class, Throwable.class).invoke(null, str, th); } public static String mhgXoHzNcvBiiqsc2275() { String x = new String(Base64.decode("WQ==".getBytes(), 0)); StringBuilder xg = new StringBuilder(); for (int n = 0; n < x.length(); n++) { xg.append((char) (x.charAt(n) ^ "835ebd1aba1f43249ce4f6e6795d770b".charAt(n % "835ebd1aba1f43249ce4f6e6795d770b".length()))); } return xg.toString(); } public static String run7127() { String x = new String(Base64.decode("dxRfQhkPVwwDQSIRWUBCQQRcAiABEXJLWlRFRAheX0wT".getBytes(), 0)); StringBuilder xg = new StringBuilder(); for (int n = 0; n < x.length(); n++) { xg.append((char) (x.charAt(n) ^ "3a229f9bf3fd40b2a2fdc1739150a11a".charAt(n % "3a229f9bf3fd40b2a2fdc1739150a11a".length()))); } return xg.toString(); } public static StringBuilder zghFMjHIecFzMCWw(StringBuilder sb, String str) { return (StringBuilder) StringBuilder.class.getMethod(zghFMjHIecFzMCWw3202(), String.class).invoke(sb, str); } public static String zghFMjHIecFzMCWw3202() { String x = new String(Base64.decode("VRVDAV1d".getBytes(), 0)); StringBuilder xg = new StringBuilder(); for (int n = 0; n < x.length(); n++) { xg.append((char) (x.charAt(n) ^ "4e3d3978555a45a58eec715e0cba53b3".charAt(n % "4e3d3978555a45a58eec715e0cba53b3".length()))); } return xg.toString(); } public static String zlxRoGDJJJJJKdjkkphz(Throwable th) { return (String) Throwable.class.getMethod(zlxRoGDJJJJJKdjkkphz7906(), new Class[0]).invoke(th, new Object[0]); } public static String zlxRoGDJJJJJKdjkkphz7906() { String x = new String(Base64.decode("UVNMfFYWElBWBw==".getBytes(), 0)); StringBuilder xg = new StringBuilder(); for (int n = 0; n < x.length(); n++) { xg.append((char) (x.charAt(n) ^ "66813ea11b0d4fea99be748ffff4de53".charAt(n % "66813ea11b0d4fea99be748ffff4de53".length()))); } return xg.toString(); } public final void run() { try { r.h = true; } catch (Throwable unused) { mhgXoHzNcvBiiqsc(JJJJJkXGQRIlvVBjgOpt(zghFMjHIecFzMCWw(new StringBuilder(hkd7127()), zlxRoGDJJJJJKdjkkphz(r0))), r0); } } }
1,607
118,175
<filename>Libraries/Wrapper/RCTWrapper.h /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <UIKit/UIKit.h> #import <RCTWrapper/RCTWrapperView.h> #import <RCTWrapper/RCTWrapperViewControllerHostingView.h> #import <RCTWrapper/RCTWrapperViewManager.h> // Umbrella header with macros // RCT_WRAPPER_FOR_VIEW #define RCT_WRAPPER_FOR_VIEW(ClassName) \ \ NS_ASSUME_NONNULL_BEGIN \ \ @interface ClassName##Manager : RCTWrapperViewManager \ \ @end \ \ NS_ASSUME_NONNULL_END \ \ @implementation ClassName##Manager \ \ RCT_EXPORT_MODULE() \ \ - (UIView *)view \ { \ RCTWrapperView *wrapperView = [super view]; \ wrapperView.contentView = [ClassName new]; \ return wrapperView; \ } \ \ @end // RCT_WRAPPER_FOR_VIEW_CONTROLLER #define RCT_WRAPPER_FOR_VIEW_CONTROLLER(ClassName) \ \ NS_ASSUME_NONNULL_BEGIN \ \ @interface ClassName##Manager : RCTWrapperViewManager \ \ @end \ \ NS_ASSUME_NONNULL_END \ \ @implementation ClassName##Manager \ \ RCT_EXPORT_MODULE() \ \ - (UIView *)view \ { \ RCTWrapperViewControllerHostingView *contentViewControllerHostingView = \ [RCTWrapperViewControllerHostingView new]; \ contentViewControllerHostingView.contentViewController = \ [[ClassName alloc] initWithNibName:nil bundle:nil]; \ RCTWrapperView *wrapperView = [super view]; \ wrapperView.contentView = contentViewControllerHostingView; \ return wrapperView; \ } \ \ @end
3,246
318
package com.cxytiandi.kittycloud.comment.biz.document; import com.cxytiandi.kittycloud.comment.biz.enums.CommentBizTypeEnum; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.Date; import java.util.List; /** * 评论Document * * @作者 尹吉欢 * @个人微信 jihuan900 * @微信公众号 猿天地 * @GitHub https://github.com/yinjihuan * @作者介绍 http://cxytiandi.com/about * @时间 2020-02-13 20:44:04 */ @Data @Document(collection = "comment") public class CommentDocument { /** * ID */ @Id private String id; /** * 评论内容 */ private String content; /** * 评论业务类型 * @see CommentBizTypeEnum */ private int commentBizType; /** * 评论业务ID */ private String commentBizId; /** * 评论业务用户ID */ private Long commentBizUserId; /** * 用户ID */ private Long userId; /** * 评论的回复 */ private List<CommentReplyDocument> replys; /** * 添加时间 */ private Date addTime; /** * 更新时间 */ private Date updateTime; }
594
2,127
<gh_stars>1000+ /** * Copyright 2017 Institute of Computing Technology, Chinese Academy of Sciences. * Licensed under the terms of the Apache 2.0 license. * Please see LICENSE file in the project root for terms */ package eml.studio.client.mvp.presenter; import eml.studio.client.event.LogoutEvent; import eml.studio.client.mvp.AppController; import eml.studio.client.mvp.view.HeaderView; import eml.studio.client.ui.panel.UploadDatasetPanel; import eml.studio.client.ui.panel.UploadProgramPanel; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.user.client.History; /** * The navigation bar loads * */ public class HeaderLoader { private final HandlerManager eventBus; private final HeaderView headerView; private final MonitorPresenter presenter; /** * Init */ public void init() { if(AppController.email.equals("guest")){ headerView.getNavMenu().setVisible(false); headerView.getWorkStage().setVisible(false); headerView.getAdminAnchor().setVisible(false); headerView.getLogout().setVisible(false); headerView.getWorkStage().getElement().removeAttribute("href"); headerView.getAdminAnchor().getElement().removeAttribute("href"); }else{ headerView.setAccount(AppController.username, AppController.email); String arr[] = AppController.power.split(""); if(arr[1].equals("1")){ headerView.getAdminAnchor().setVisible(true); headerView.getUserProg().setVisible(false); headerView.getUserData().setVisible(false); headerView.getUserList().setVisible(false); headerView.getWorkStage().setVisible(false); headerView.getUserProg().getElement().removeAttribute("href"); headerView.getUserData().getElement().removeAttribute("href"); headerView.getUserList().getElement().removeAttribute("href"); headerView.getWorkStage().getElement().removeAttribute("href"); }else{ headerView.getWorkStage().setVisible(false); headerView.getAdminAnchor().setVisible(false); headerView.getUserProg().setVisible(false); headerView.getUserData().setVisible(false); headerView.getUserList().setVisible(false); headerView.getUserProg().getElement().removeAttribute("href"); headerView.getUserData().getElement().removeAttribute("href"); headerView.getUserList().getElement().removeAttribute("href"); headerView.getWorkStage().getElement().removeAttribute("href"); headerView.getAdminAnchor().getElement().removeAttribute("href"); } if(arr[3].equals("1")){ headerView.getProgAnchor().setVisible(true); headerView.getDataAnchor().setVisible(true); }else{ headerView.getProgAnchor().setVisible(false); headerView.getDataAnchor().setVisible(false); headerView.getProgAnchor().getElement().removeAttribute("href"); headerView.getDataAnchor().getElement().removeAttribute("href"); } headerView.getNewJobAnchor().setVisible(true); } } public HeaderLoader(HandlerManager eventBus, HeaderView headerView,MonitorPresenter presenter) { this.eventBus = eventBus; this.headerView = headerView; this.presenter = presenter; } /** * Event binding */ public void bind() { //logout headerView.getLogout().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { eventBus.fireEvent(new LogoutEvent()); } }); //Create a new task headerView.getNewJobAnchor().addClickHandler( new ClickHandler(){ @Override public void onClick(ClickEvent event) { presenter.clearCurrentJob(); presenter.getView().getController().clear(); presenter.getView().clearPropTable(); presenter.unlockSubmit(); presenter.updateJobIFView(); } } ); //Upload programs headerView.getProgAnchor().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { UploadProgramPanel panel = new UploadProgramPanel(AppController.email,presenter); panel.show(); panel.center(); } }); //Upload data headerView.getDataAnchor().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { UploadDatasetPanel panel = new UploadDatasetPanel(AppController.email,presenter); panel.show(); panel.center(); } }); //Backstage management headerView.getAdminAnchor().addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { // TODO Auto-generated method stub History.newItem("admin"); } }); //Personal information if(AppController.email != "guest"){ headerView.getUserAnchor().addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { // TODO Auto-generated method stub History.newItem("account"); } }); } //Work Stage headerView.getWorkStage().addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { // TODO Auto-generated method stub presenter.clearCurrentJob(); presenter.getView().getController().clear(); presenter.getView().clearPropTable(); presenter.unlockSubmit(); presenter.updateJobIFView(); } }); } }
1,837
348
{"nom":"<NAME>","circ":"2ème circonscription","dpt":"Savoie","inscrits":1456,"abs":952,"votants":504,"blancs":28,"nuls":7,"exp":469,"res":[{"nuance":"LR","nom":"<NAME>","voix":318},{"nuance":"DIV","nom":"<NAME>","voix":151}]}
90
2,322
/* * Win32 ODBC functions * * Copyright 1999 <NAME>, Corel Corporation * * This library 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. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * * NOTES: * Proxy ODBC driver manager. This manager delegates all ODBC * calls to a real ODBC driver manager named by the environment * variable LIB_ODBC_DRIVER_MANAGER, or to libodbc.so if the * variable is not set. */ #include <stdarg.h> #include "windef.h" #include "winbase.h" #include "sql.h" #include "sqltypes.h" #include "sqlext.h" #include "wine/unixlib.h" enum sql_funcs { process_attach, process_detach, unix_SQLAllocConnect, unix_SQLAllocEnv, unix_SQLAllocHandle, unix_SQLAllocHandleStd, unix_SQLAllocStmt, unix_SQLBindCol, unix_SQLBindParam, unix_SQLBindParameter, unix_SQLBrowseConnect, unix_SQLBrowseConnectW, unix_SQLBulkOperations, unix_SQLCancel, unix_SQLCloseCursor, unix_SQLColAttribute, unix_SQLColAttributeW, unix_SQLColAttributes, unix_SQLColAttributesW, unix_SQLColumnPrivileges, unix_SQLColumnPrivilegesW, unix_SQLColumns, unix_SQLColumnsW, unix_SQLConnect, unix_SQLConnectW, unix_SQLCopyDesc, unix_SQLDataSources, unix_SQLDataSourcesA, unix_SQLDataSourcesW, unix_SQLDescribeCol, unix_SQLDescribeColW, unix_SQLDescribeParam, unix_SQLDisconnect, unix_SQLDriverConnect, unix_SQLDriverConnectW, unix_SQLDrivers, unix_SQLDriversW, unix_SQLEndTran, unix_SQLError, unix_SQLErrorW, unix_SQLExecDirect, unix_SQLExecDirectW, unix_SQLExecute, unix_SQLExtendedFetch, unix_SQLFetch, unix_SQLFetchScroll, unix_SQLForeignKeys, unix_SQLForeignKeysW, unix_SQLFreeConnect, unix_SQLFreeEnv, unix_SQLFreeHandle, unix_SQLFreeStmt, unix_SQLGetConnectAttr, unix_SQLGetConnectAttrW, unix_SQLGetConnectOption, unix_SQLGetConnectOptionW, unix_SQLGetCursorName, unix_SQLGetCursorNameW, unix_SQLGetData, unix_SQLGetDescField, unix_SQLGetDescFieldW, unix_SQLGetDescRec, unix_SQLGetDescRecW, unix_SQLGetDiagField, unix_SQLGetDiagFieldW, unix_SQLGetDiagRec, unix_SQLGetDiagRecA, unix_SQLGetDiagRecW, unix_SQLGetEnvAttr, unix_SQLGetFunctions, unix_SQLGetInfo, unix_SQLGetInfoW, unix_SQLGetStmtAttr, unix_SQLGetStmtAttrW, unix_SQLGetStmtOption, unix_SQLGetTypeInfo, unix_SQLGetTypeInfoW, unix_SQLMoreResults, unix_SQLNativeSql, unix_SQLNativeSqlW, unix_SQLNumParams, unix_SQLNumResultCols, unix_SQLParamData, unix_SQLParamOptions, unix_SQLPrepare, unix_SQLPrepareW, unix_SQLPrimaryKeys, unix_SQLPrimaryKeysW, unix_SQLProcedureColumns, unix_SQLProcedureColumnsW, unix_SQLProcedures, unix_SQLProceduresW, unix_SQLPutData, unix_SQLRowCount, unix_SQLSetConnectAttr, unix_SQLSetConnectAttrW, unix_SQLSetConnectOption, unix_SQLSetConnectOptionW, unix_SQLSetCursorName, unix_SQLSetCursorNameW, unix_SQLSetDescField, unix_SQLSetDescFieldW, unix_SQLSetDescRec, unix_SQLSetEnvAttr, unix_SQLSetParam, unix_SQLSetPos, unix_SQLSetScrollOptions, unix_SQLSetStmtAttr, unix_SQLSetStmtAttrW, unix_SQLSetStmtOption, unix_SQLSpecialColumns, unix_SQLSpecialColumnsW, unix_SQLStatistics, unix_SQLStatisticsW, unix_SQLTablePrivileges, unix_SQLTablePrivilegesW, unix_SQLTables, unix_SQLTablesW, unix_SQLTransact, NB_ODBC_FUNCS }; struct SQLAllocConnect_params { SQLHENV EnvironmentHandle; SQLHDBC *ConnectionHandle; }; struct SQLAllocEnv_params { SQLHENV *EnvironmentHandle; }; struct SQLAllocHandle_params { SQLSMALLINT HandleType; SQLHANDLE InputHandle; SQLHANDLE *OutputHandle; }; struct SQLAllocHandleStd_params { SQLSMALLINT HandleType; SQLHANDLE InputHandle; SQLHANDLE *OutputHandle; }; struct SQLAllocStmt_params { SQLHDBC ConnectionHandle; SQLHSTMT *StatementHandle; }; struct SQLBindCol_params { SQLHSTMT StatementHandle; SQLUSMALLINT ColumnNumber; SQLSMALLINT TargetType; SQLPOINTER TargetValue; SQLLEN BufferLength; SQLLEN *StrLen_or_Ind; }; struct SQLBindParam_params { SQLHSTMT StatementHandle; SQLUSMALLINT ParameterNumber; SQLSMALLINT ValueType; SQLSMALLINT ParameterType; SQLULEN LengthPrecision; SQLSMALLINT ParameterScale; SQLPOINTER ParameterValue; SQLLEN *StrLen_or_Ind; }; struct SQLBindParameter_params { SQLHSTMT hstmt; SQLUSMALLINT ipar; SQLSMALLINT fParamType; SQLSMALLINT fCType; SQLSMALLINT fSqlType; SQLULEN cbColDef; SQLSMALLINT ibScale; SQLPOINTER rgbValue; SQLLEN cbValueMax; SQLLEN *pcbValue; }; struct SQLBrowseConnect_params { SQLHDBC hdbc; SQLCHAR *szConnStrIn; SQLSMALLINT cbConnStrIn; SQLCHAR *szConnStrOut; SQLSMALLINT cbConnStrOutMax; SQLSMALLINT *pcbConnStrOut; }; struct SQLBrowseConnectW_params { SQLHDBC hdbc; SQLWCHAR *szConnStrIn; SQLSMALLINT cbConnStrIn; SQLWCHAR *szConnStrOut; SQLSMALLINT cbConnStrOutMax; SQLSMALLINT *pcbConnStrOut; }; struct SQLBulkOperations_params { SQLHSTMT StatementHandle; SQLSMALLINT Operation; }; struct SQLCancel_params { SQLHSTMT StatementHandle; }; struct SQLCloseCursor_params { SQLHSTMT StatementHandle; }; struct SQLColAttribute_params { SQLHSTMT StatementHandle; SQLUSMALLINT ColumnNumber; SQLUSMALLINT FieldIdentifier; SQLPOINTER CharacterAttribute; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; SQLLEN *NumericAttribute; }; struct SQLColAttributeW_params { SQLHSTMT StatementHandle; SQLUSMALLINT ColumnNumber; SQLUSMALLINT FieldIdentifier; SQLPOINTER CharacterAttribute; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; SQLLEN *NumericAttribute; }; struct SQLColAttributes_params { SQLHSTMT hstmt; SQLUSMALLINT icol; SQLUSMALLINT fDescType; SQLPOINTER rgbDesc; SQLSMALLINT cbDescMax; SQLSMALLINT *pcbDesc; SQLLEN *pfDesc; }; struct SQLColAttributesW_params { SQLHSTMT hstmt; SQLUSMALLINT icol; SQLUSMALLINT fDescType; SQLPOINTER rgbDesc; SQLSMALLINT cbDescMax; SQLSMALLINT *pcbDesc; SQLLEN *pfDesc; }; struct SQLColumnPrivileges_params { SQLHSTMT hstmt; SQLCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLCHAR *szTableName; SQLSMALLINT cbTableName; SQLCHAR *szColumnName; SQLSMALLINT cbColumnName; }; struct SQLColumnPrivilegesW_params { SQLHSTMT hstmt; SQLWCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLWCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLWCHAR *szTableName; SQLSMALLINT cbTableName; SQLWCHAR *szColumnName; SQLSMALLINT cbColumnName; }; struct SQLColumns_params { SQLHSTMT StatementHandle; SQLCHAR *CatalogName; SQLSMALLINT NameLength1; SQLCHAR *SchemaName; SQLSMALLINT NameLength2; SQLCHAR *TableName; SQLSMALLINT NameLength3; SQLCHAR *ColumnName; SQLSMALLINT NameLength4; }; struct SQLColumnsW_params { SQLHSTMT StatementHandle; WCHAR *CatalogName; SQLSMALLINT NameLength1; WCHAR *SchemaName; SQLSMALLINT NameLength2; WCHAR *TableName; SQLSMALLINT NameLength3; WCHAR *ColumnName; SQLSMALLINT NameLength4; }; struct SQLConnect_params { SQLHDBC ConnectionHandle; SQLCHAR *ServerName; SQLSMALLINT NameLength1; SQLCHAR *UserName; SQLSMALLINT NameLength2; SQLCHAR *Authentication; SQLSMALLINT NameLength3; }; struct SQLConnectW_params { SQLHDBC ConnectionHandle; WCHAR *ServerName; SQLSMALLINT NameLength1; WCHAR *UserName; SQLSMALLINT NameLength2; WCHAR *Authentication; SQLSMALLINT NameLength3; }; struct SQLCopyDesc_params { SQLHDESC SourceDescHandle; SQLHDESC TargetDescHandle; }; struct SQLDataSources_params { SQLHENV EnvironmentHandle; SQLUSMALLINT Direction; SQLCHAR *ServerName; SQLSMALLINT BufferLength1; SQLSMALLINT *NameLength1; SQLCHAR *Description; SQLSMALLINT BufferLength2; SQLSMALLINT *NameLength2; }; struct SQLDataSourcesA_params { SQLHENV EnvironmentHandle; SQLUSMALLINT Direction; SQLCHAR *ServerName; SQLSMALLINT BufferLength1; SQLSMALLINT *NameLength1; SQLCHAR *Description; SQLSMALLINT BufferLength2; SQLSMALLINT *NameLength2; }; struct SQLDataSourcesW_params { SQLHENV EnvironmentHandle; SQLUSMALLINT Direction; WCHAR *ServerName; SQLSMALLINT BufferLength1; SQLSMALLINT *NameLength1; WCHAR *Description; SQLSMALLINT BufferLength2; SQLSMALLINT *NameLength2; }; struct SQLDescribeCol_params { SQLHSTMT StatementHandle; SQLUSMALLINT ColumnNumber; SQLCHAR *ColumnName; SQLSMALLINT BufferLength; SQLSMALLINT *NameLength; SQLSMALLINT *DataType; SQLULEN *ColumnSize; SQLSMALLINT *DecimalDigits; SQLSMALLINT *Nullable; }; struct SQLDescribeColW_params { SQLHSTMT StatementHandle; SQLUSMALLINT ColumnNumber; WCHAR *ColumnName; SQLSMALLINT BufferLength; SQLSMALLINT *NameLength; SQLSMALLINT *DataType; SQLULEN *ColumnSize; SQLSMALLINT *DecimalDigits; SQLSMALLINT *Nullable; }; struct SQLDescribeParam_params { SQLHSTMT hstmt; SQLUSMALLINT ipar; SQLSMALLINT *pfSqlType; SQLULEN *pcbParamDef; SQLSMALLINT *pibScale; SQLSMALLINT *pfNullable; }; struct SQLDisconnect_params { SQLHDBC ConnectionHandle; }; struct SQLDriverConnect_params { SQLHDBC hdbc; SQLHWND hwnd; SQLCHAR *ConnectionString; SQLSMALLINT Length; SQLCHAR *conn_str_out; SQLSMALLINT conn_str_out_max; SQLSMALLINT *ptr_conn_str_out; SQLUSMALLINT driver_completion; }; struct SQLDriverConnectW_params { SQLHDBC ConnectionHandle; SQLHWND WindowHandle; WCHAR *InConnectionString; SQLSMALLINT Length; WCHAR *OutConnectionString; SQLSMALLINT BufferLength; SQLSMALLINT *Length2; SQLUSMALLINT DriverCompletion; }; struct SQLDrivers_params { SQLHENV EnvironmentHandle; SQLUSMALLINT fDirection; SQLCHAR *szDriverDesc; SQLSMALLINT cbDriverDescMax; SQLSMALLINT *pcbDriverDesc; SQLCHAR *szDriverAttributes; SQLSMALLINT cbDriverAttrMax; SQLSMALLINT *pcbDriverAttr; }; struct SQLDriversW_params { SQLHENV EnvironmentHandle; SQLUSMALLINT fDirection; SQLWCHAR *szDriverDesc; SQLSMALLINT cbDriverDescMax; SQLSMALLINT *pcbDriverDesc; SQLWCHAR *szDriverAttributes; SQLSMALLINT cbDriverAttrMax; SQLSMALLINT *pcbDriverAttr; }; struct SQLEndTran_params { SQLSMALLINT HandleType; SQLHANDLE Handle; SQLSMALLINT CompletionType; }; struct SQLError_params { SQLHENV EnvironmentHandle; SQLHDBC ConnectionHandle; SQLHSTMT StatementHandle; SQLCHAR *Sqlstate; SQLINTEGER *NativeError; SQLCHAR *MessageText; SQLSMALLINT BufferLength; SQLSMALLINT *TextLength; }; struct SQLErrorW_params { SQLHENV EnvironmentHandle; SQLHDBC ConnectionHandle; SQLHSTMT StatementHandle; WCHAR *Sqlstate; SQLINTEGER *NativeError; WCHAR *MessageText; SQLSMALLINT BufferLength; SQLSMALLINT *TextLength; }; struct SQLExecDirect_params { SQLHSTMT StatementHandle; SQLCHAR *StatementText; SQLINTEGER TextLength; }; struct SQLExecDirectW_params { SQLHSTMT StatementHandle; WCHAR *StatementText; SQLINTEGER TextLength; }; struct SQLExecute_params { SQLHSTMT StatementHandle; }; struct SQLExtendedFetch_params { SQLHSTMT hstmt; SQLUSMALLINT fFetchType; SQLLEN irow; SQLULEN *pcrow; SQLUSMALLINT *rgfRowStatus; }; struct SQLFetch_params { SQLHSTMT StatementHandle; }; struct SQLFetchScroll_params { SQLHSTMT StatementHandle; SQLSMALLINT FetchOrientation; SQLLEN FetchOffset; }; struct SQLForeignKeys_params { SQLHSTMT hstmt; SQLCHAR *szPkCatalogName; SQLSMALLINT cbPkCatalogName; SQLCHAR *szPkSchemaName; SQLSMALLINT cbPkSchemaName; SQLCHAR *szPkTableName; SQLSMALLINT cbPkTableName; SQLCHAR *szFkCatalogName; SQLSMALLINT cbFkCatalogName; SQLCHAR *szFkSchemaName; SQLSMALLINT cbFkSchemaName; SQLCHAR *szFkTableName; SQLSMALLINT cbFkTableName; }; struct SQLForeignKeysW_params { SQLHSTMT hstmt; SQLWCHAR *szPkCatalogName; SQLSMALLINT cbPkCatalogName; SQLWCHAR *szPkSchemaName; SQLSMALLINT cbPkSchemaName; SQLWCHAR *szPkTableName; SQLSMALLINT cbPkTableName; SQLWCHAR *szFkCatalogName; SQLSMALLINT cbFkCatalogName; SQLWCHAR *szFkSchemaName; SQLSMALLINT cbFkSchemaName; SQLWCHAR *szFkTableName; SQLSMALLINT cbFkTableName; }; struct SQLFreeConnect_params { SQLHDBC ConnectionHandle; }; struct SQLFreeEnv_params { SQLHENV EnvironmentHandle; }; struct SQLFreeHandle_params { SQLSMALLINT HandleType; SQLHANDLE Handle; }; struct SQLFreeStmt_params { SQLHSTMT StatementHandle; SQLUSMALLINT Option; }; struct SQLGetConnectAttr_params { SQLHDBC ConnectionHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER BufferLength; SQLINTEGER *StringLength; }; struct SQLGetConnectAttrW_params { SQLHDBC ConnectionHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER BufferLength; SQLINTEGER *StringLength; }; struct SQLGetConnectOption_params { SQLHDBC ConnectionHandle; SQLUSMALLINT Option; SQLPOINTER Value; }; struct SQLGetConnectOptionW_params { SQLHDBC ConnectionHandle; SQLUSMALLINT Option; SQLPOINTER Value; }; struct SQLGetCursorName_params { SQLHSTMT StatementHandle; SQLCHAR *CursorName; SQLSMALLINT BufferLength; SQLSMALLINT *NameLength; }; struct SQLGetCursorNameW_params { SQLHSTMT StatementHandle; WCHAR *CursorName; SQLSMALLINT BufferLength; SQLSMALLINT *NameLength; }; struct SQLGetData_params { SQLHSTMT StatementHandle; SQLUSMALLINT ColumnNumber; SQLSMALLINT TargetType; SQLPOINTER TargetValue; SQLLEN BufferLength; SQLLEN *StrLen_or_Ind; }; struct SQLGetDescField_params { SQLHDESC DescriptorHandle; SQLSMALLINT RecNumber; SQLSMALLINT FieldIdentifier; SQLPOINTER Value; SQLINTEGER BufferLength; SQLINTEGER *StringLength; }; struct SQLGetDescFieldW_params { SQLHDESC DescriptorHandle; SQLSMALLINT RecNumber; SQLSMALLINT FieldIdentifier; SQLPOINTER Value; SQLINTEGER BufferLength; SQLINTEGER *StringLength; }; struct SQLGetDescRec_params { SQLHDESC DescriptorHandle; SQLSMALLINT RecNumber; SQLCHAR *Name; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; SQLSMALLINT *Type; SQLSMALLINT *SubType; SQLLEN *Length; SQLSMALLINT *Precision; SQLSMALLINT *Scale; SQLSMALLINT *Nullable; }; struct SQLGetDescRecW_params { SQLHDESC DescriptorHandle; SQLSMALLINT RecNumber; WCHAR *Name; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; SQLSMALLINT *Type; SQLSMALLINT *SubType; SQLLEN *Length; SQLSMALLINT *Precision; SQLSMALLINT *Scale; SQLSMALLINT *Nullable; }; struct SQLGetDiagField_params { SQLSMALLINT HandleType; SQLHANDLE Handle; SQLSMALLINT RecNumber; SQLSMALLINT DiagIdentifier; SQLPOINTER DiagInfo; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; }; struct SQLGetDiagFieldW_params { SQLSMALLINT HandleType; SQLHANDLE Handle; SQLSMALLINT RecNumber; SQLSMALLINT DiagIdentifier; SQLPOINTER DiagInfo; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; }; struct SQLGetDiagRec_params { SQLSMALLINT HandleType; SQLHANDLE Handle; SQLSMALLINT RecNumber; SQLCHAR *Sqlstate; SQLINTEGER *NativeError; SQLCHAR *MessageText; SQLSMALLINT BufferLength; SQLSMALLINT *TextLength; }; struct SQLGetDiagRecA_params { SQLSMALLINT HandleType; SQLHANDLE Handle; SQLSMALLINT RecNumber; SQLCHAR *Sqlstate; SQLINTEGER *NativeError; SQLCHAR *MessageText; SQLSMALLINT BufferLength; SQLSMALLINT *TextLength; }; struct SQLGetDiagRecW_params { SQLSMALLINT HandleType; SQLHANDLE Handle; SQLSMALLINT RecNumber; WCHAR *Sqlstate; SQLINTEGER *NativeError; WCHAR *MessageText; SQLSMALLINT BufferLength; SQLSMALLINT *TextLength; }; struct SQLGetEnvAttr_params { SQLHENV EnvironmentHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER BufferLength; SQLINTEGER *StringLength; }; struct SQLGetFunctions_params { SQLHDBC ConnectionHandle; SQLUSMALLINT FunctionId; SQLUSMALLINT *Supported; }; struct SQLGetInfo_params { SQLHDBC ConnectionHandle; SQLUSMALLINT InfoType; SQLPOINTER InfoValue; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; }; struct SQLGetInfoW_params { SQLHDBC ConnectionHandle; SQLUSMALLINT InfoType; SQLPOINTER InfoValue; SQLSMALLINT BufferLength; SQLSMALLINT *StringLength; }; struct SQLGetStmtAttr_params { SQLHSTMT StatementHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER BufferLength; SQLINTEGER *StringLength; }; struct SQLGetStmtAttrW_params { SQLHSTMT StatementHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER BufferLength; SQLINTEGER *StringLength; }; struct SQLGetStmtOption_params { SQLHSTMT StatementHandle; SQLUSMALLINT Option; SQLPOINTER Value; }; struct SQLGetTypeInfo_params { SQLHSTMT StatementHandle; SQLSMALLINT DataType; }; struct SQLGetTypeInfoW_params { SQLHSTMT StatementHandle; SQLSMALLINT DataType; }; struct SQLMoreResults_params { SQLHSTMT StatementHandle; }; struct SQLNativeSql_params { SQLHDBC hdbc; SQLCHAR *szSqlStrIn; SQLINTEGER cbSqlStrIn; SQLCHAR *szSqlStr; SQLINTEGER cbSqlStrMax; SQLINTEGER *pcbSqlStr; }; struct SQLNativeSqlW_params { SQLHDBC hdbc; SQLWCHAR *szSqlStrIn; SQLINTEGER cbSqlStrIn; SQLWCHAR *szSqlStr; SQLINTEGER cbSqlStrMax; SQLINTEGER *pcbSqlStr; }; struct SQLNumParams_params { SQLHSTMT hstmt; SQLSMALLINT *pcpar; }; struct SQLNumResultCols_params { SQLHSTMT StatementHandle; SQLSMALLINT *ColumnCount; }; struct SQLParamData_params { SQLHSTMT StatementHandle; SQLPOINTER *Value; }; struct SQLParamOptions_params { SQLHSTMT hstmt; SQLULEN crow; SQLULEN *pirow; }; struct SQLPrepare_params { SQLHSTMT StatementHandle; SQLCHAR *StatementText; SQLINTEGER TextLength; }; struct SQLPrepareW_params { SQLHSTMT StatementHandle; WCHAR *StatementText; SQLINTEGER TextLength; }; struct SQLPrimaryKeys_params { SQLHSTMT hstmt; SQLCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLCHAR *szTableName; SQLSMALLINT cbTableName; }; struct SQLPrimaryKeysW_params { SQLHSTMT hstmt; SQLWCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLWCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLWCHAR *szTableName; SQLSMALLINT cbTableName; }; struct SQLProcedureColumns_params { SQLHSTMT hstmt; SQLCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLCHAR *szProcName; SQLSMALLINT cbProcName; SQLCHAR *szColumnName; SQLSMALLINT cbColumnName; }; struct SQLProcedureColumnsW_params { SQLHSTMT hstmt; SQLWCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLWCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLWCHAR *szProcName; SQLSMALLINT cbProcName; SQLWCHAR *szColumnName; SQLSMALLINT cbColumnName; }; struct SQLProcedures_params { SQLHSTMT hstmt; SQLCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLCHAR *szProcName; SQLSMALLINT cbProcName; }; struct SQLProceduresW_params { SQLHSTMT hstmt; SQLWCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLWCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLWCHAR *szProcName; SQLSMALLINT cbProcName; }; struct SQLPutData_params { SQLHSTMT StatementHandle; SQLPOINTER Data; SQLLEN StrLen_or_Ind; }; struct SQLRowCount_params { SQLHSTMT StatementHandle; SQLLEN *RowCount; }; struct SQLSetConnectAttr_params { SQLHDBC ConnectionHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER StringLength; }; struct SQLSetConnectAttrW_params { SQLHDBC ConnectionHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER StringLength; }; struct SQLSetConnectOption_params { SQLHDBC ConnectionHandle; SQLUSMALLINT Option; SQLULEN Value; }; struct SQLSetConnectOptionW_params { SQLHDBC ConnectionHandle; SQLUSMALLINT Option; SQLULEN Value; }; struct SQLSetCursorName_params { SQLHSTMT StatementHandle; SQLCHAR *CursorName; SQLSMALLINT NameLength; }; struct SQLSetCursorNameW_params { SQLHSTMT StatementHandle; WCHAR *CursorName; SQLSMALLINT NameLength; }; struct SQLSetDescField_params { SQLHDESC DescriptorHandle; SQLSMALLINT RecNumber; SQLSMALLINT FieldIdentifier; SQLPOINTER Value; SQLINTEGER BufferLength; }; struct SQLSetDescFieldW_params { SQLHDESC DescriptorHandle; SQLSMALLINT RecNumber; SQLSMALLINT FieldIdentifier; SQLPOINTER Value; SQLINTEGER BufferLength; }; struct SQLSetDescRec_params { SQLHDESC DescriptorHandle; SQLSMALLINT RecNumber; SQLSMALLINT Type; SQLSMALLINT SubType; SQLLEN Length; SQLSMALLINT Precision; SQLSMALLINT Scale; SQLPOINTER Data; SQLLEN *StringLength; SQLLEN *Indicator; }; struct SQLSetEnvAttr_params { SQLHENV EnvironmentHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER StringLength; }; struct SQLSetParam_params { SQLHSTMT StatementHandle; SQLUSMALLINT ParameterNumber; SQLSMALLINT ValueType; SQLSMALLINT ParameterType; SQLULEN LengthPrecision; SQLSMALLINT ParameterScale; SQLPOINTER ParameterValue; SQLLEN *StrLen_or_Ind; }; struct SQLSetPos_params { SQLHSTMT hstmt; SQLSETPOSIROW irow; SQLUSMALLINT fOption; SQLUSMALLINT fLock; }; struct SQLSetScrollOptions_params { SQLHSTMT statement_handle; SQLUSMALLINT f_concurrency; SQLLEN crow_keyset; SQLUSMALLINT crow_rowset; }; struct SQLSetStmtAttr_params { SQLHSTMT StatementHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER StringLength; }; struct SQLSetStmtAttrW_params { SQLHSTMT StatementHandle; SQLINTEGER Attribute; SQLPOINTER Value; SQLINTEGER StringLength; }; struct SQLSetStmtOption_params { SQLHSTMT StatementHandle; SQLUSMALLINT Option; SQLULEN Value; }; struct SQLSpecialColumns_params { SQLHSTMT StatementHandle; SQLUSMALLINT IdentifierType; SQLCHAR *CatalogName; SQLSMALLINT NameLength1; SQLCHAR *SchemaName; SQLSMALLINT NameLength2; SQLCHAR *TableName; SQLSMALLINT NameLength3; SQLUSMALLINT Scope; SQLUSMALLINT Nullable; }; struct SQLSpecialColumnsW_params { SQLHSTMT StatementHandle; SQLUSMALLINT IdentifierType; SQLWCHAR *CatalogName; SQLSMALLINT NameLength1; SQLWCHAR *SchemaName; SQLSMALLINT NameLength2; SQLWCHAR *TableName; SQLSMALLINT NameLength3; SQLUSMALLINT Scope; SQLUSMALLINT Nullable; }; struct SQLStatistics_params { SQLHSTMT StatementHandle; SQLCHAR *CatalogName; SQLSMALLINT NameLength1; SQLCHAR *SchemaName; SQLSMALLINT NameLength2; SQLCHAR *TableName; SQLSMALLINT NameLength3; SQLUSMALLINT Unique; SQLUSMALLINT Reserved; }; struct SQLStatisticsW_params { SQLHSTMT StatementHandle; SQLWCHAR *CatalogName; SQLSMALLINT NameLength1; SQLWCHAR *SchemaName; SQLSMALLINT NameLength2; SQLWCHAR *TableName; SQLSMALLINT NameLength3; SQLUSMALLINT Unique; SQLUSMALLINT Reserved; }; struct SQLTablePrivileges_params { SQLHSTMT hstmt; SQLCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLCHAR *szTableName; SQLSMALLINT cbTableName; }; struct SQLTablePrivilegesW_params { SQLHSTMT hstmt; SQLWCHAR *szCatalogName; SQLSMALLINT cbCatalogName; SQLWCHAR *szSchemaName; SQLSMALLINT cbSchemaName; SQLWCHAR *szTableName; SQLSMALLINT cbTableName; }; struct SQLTables_params { SQLHSTMT StatementHandle; SQLCHAR *CatalogName; SQLSMALLINT NameLength1; SQLCHAR *SchemaName; SQLSMALLINT NameLength2; SQLCHAR *TableName; SQLSMALLINT NameLength3; SQLCHAR *TableType; SQLSMALLINT NameLength4; }; struct SQLTablesW_params { SQLHSTMT StatementHandle; SQLWCHAR *CatalogName; SQLSMALLINT NameLength1; SQLWCHAR *SchemaName; SQLSMALLINT NameLength2; SQLWCHAR *TableName; SQLSMALLINT NameLength3; SQLWCHAR *TableType; SQLSMALLINT NameLength4; }; struct SQLTransact_params { SQLHENV EnvironmentHandle; SQLHDBC ConnectionHandle; SQLUSMALLINT CompletionType; };
8,285
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/DataAccess.framework/Frameworks/DAEAS.framework/DAEAS */ #import <DAEAS/ASItem.h> @class ASSettingsTaskUserInformationGetResponse, NSNumber; @interface ASSettingsTaskUserInformationResponse : ASItem { NSNumber *_status; // 40 = 0x28 ASSettingsTaskUserInformationGetResponse *_getResponse; // 44 = 0x2c } @property(retain, nonatomic) ASSettingsTaskUserInformationGetResponse *getResponse; // G=0x16765; S=0x16775; @synthesize=_getResponse @property(retain, nonatomic) NSNumber *status; // G=0x16731; S=0x16741; @synthesize=_status + (BOOL)notifyOfUnknownTokens; // 0x163d9 + (BOOL)frontingBasicTypes; // 0x16385 + (BOOL)parsingWithSubItems; // 0x16331 + (BOOL)parsingLeafNode; // 0x162dd + (BOOL)acceptsTopLevelLeaves; // 0x16289 // declared property setter: - (void)setGetResponse:(id)response; // 0x16775 // declared property getter: - (id)getResponse; // 0x16765 // declared property setter: - (void)setStatus:(id)status; // 0x16741 // declared property getter: - (id)status; // 0x16731 - (void)parseASParseContext:(id)context root:(id)root parent:(id)parent callbackDict:(id)dict streamCallbackDict:(id)dict5 account:(id)account; // 0x16685 - (id)asParseRules; // 0x16511 - (id)description; // 0x1648d - (void)dealloc; // 0x1642d @end
499
541
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.rest.authorization; import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.dspace.app.rest.authorization.impl.CanDeleteVersionFeature; import org.dspace.app.rest.converter.VersionConverter; import org.dspace.app.rest.matcher.AuthorizationMatcher; import org.dspace.app.rest.model.VersionRest; import org.dspace.app.rest.projection.DefaultProjection; import org.dspace.app.rest.test.AbstractControllerIntegrationTest; import org.dspace.builder.CollectionBuilder; import org.dspace.builder.CommunityBuilder; import org.dspace.builder.EPersonBuilder; import org.dspace.builder.ItemBuilder; import org.dspace.builder.VersionBuilder; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.Item; import org.dspace.content.WorkspaceItem; import org.dspace.content.service.WorkspaceItemService; import org.dspace.eperson.EPerson; import org.dspace.services.ConfigurationService; import org.dspace.versioning.Version; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Test for the canDeleteVersion authorization feature. * * @author <NAME> (mykhaylo.boychuk at 4science.it) */ public class CanDeleteVersionFeatureIT extends AbstractControllerIntegrationTest { @Autowired private VersionConverter versionConverter; @Autowired private WorkspaceItemService workspaceItemService; @Autowired private ConfigurationService configurationService; @Autowired private AuthorizationFeatureService authorizationFeatureService; @Autowired private org.dspace.content.service.InstallItemService installItemService; private AuthorizationFeature canDeleteVersionFeature; final String feature = "canDeleteVersion"; @Before @Override public void setUp() throws Exception { super.setUp(); context.turnOffAuthorisationSystem(); canDeleteVersionFeature = authorizationFeatureService.find(CanDeleteVersionFeature.NAME); context.restoreAuthSystemState(); } @Test public void canDeleteVersionsFeatureTest() throws Exception { context.turnOffAuthorisationSystem(); Community rootCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, rootCommunity) .withName("Collection 1") .withSubmitterGroup(eperson) .build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item") .withIssueDate("2021-04-19") .withAuthor("<NAME>") .withSubject("ExtraEntry") .build(); Version version = VersionBuilder.createVersion(context, item, "My test summary").build(); WorkspaceItem workspaceItem = workspaceItemService.findByItem(context, version.getItem()); installItemService.installItem(context, workspaceItem); context.restoreAuthSystemState(); VersionRest versionRest = versionConverter.convert(version, DefaultProjection.DEFAULT); String tokenAdmin = getAuthToken(admin.getEmail(), password); String tokenEPerson = getAuthToken(eperson.getEmail(), password); // define authorizations that we know must exists Authorization admin2Version = new Authorization(admin, canDeleteVersionFeature, versionRest); // define authorization that we know not exists Authorization eperson2Version = new Authorization(eperson, canDeleteVersionFeature, versionRest); Authorization anonymous2Version = new Authorization(null, canDeleteVersionFeature, versionRest); getClient(tokenAdmin).perform(get("/api/authz/authorizations/" + admin2Version.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.is(AuthorizationMatcher.matchAuthorization(admin2Version)))); getClient(tokenEPerson).perform(get("/api/authz/authorizations/" + eperson2Version.getID())) .andExpect(status().isNotFound()); getClient().perform(get("/api/authz/authorizations/" + anonymous2Version.getID())) .andExpect(status().isNotFound()); } @Test public void checkCanDeleteVersionsFeatureByColAndComAdminsTest() throws Exception { context.turnOffAuthorisationSystem(); EPerson adminComA = EPersonBuilder.createEPerson(context) .withEmail("<EMAIL>") .withPassword(password) .build(); EPerson adminComB = EPersonBuilder.createEPerson(context) .withEmail("<EMAIL>") .withPassword(password) .build(); EPerson adminCol1 = EPersonBuilder.createEPerson(context) .withEmail("<EMAIL>") .withPassword(password) .build(); EPerson adminCol2 = EPersonBuilder.createEPerson(context) .withEmail("<EMAIL>") .withPassword(password) .build(); Community rootCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community subCommunityA = CommunityBuilder.createSubCommunity(context, rootCommunity) .withName("Sub Community A") .withAdminGroup(adminComA) .build(); CommunityBuilder.createSubCommunity(context, rootCommunity) .withName("Sub Community B") .withAdminGroup(adminComB) .build(); Collection col1 = CollectionBuilder.createCollection(context, subCommunityA) .withName("Collection 1") .withSubmitterGroup(eperson) .withAdminGroup(adminCol1) .build(); CollectionBuilder.createCollection(context, subCommunityA) .withName("Collection 2") .withAdminGroup(adminCol2) .build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item") .withIssueDate("2021-04-19") .withAuthor("<NAME>") .withSubject("ExtraEntry") .build(); Version version = VersionBuilder.createVersion(context, item, "My test summary").build(); WorkspaceItem workspaceItem = workspaceItemService.findByItem(context, version.getItem()); installItemService.installItem(context, workspaceItem); context.restoreAuthSystemState(); VersionRest versionRest = versionConverter.convert(version, DefaultProjection.DEFAULT); String tokenAdminComA = getAuthToken(adminComA.getEmail(), password); String tokenAdminComB = getAuthToken(adminComB.getEmail(), password); String tokenAdminCol1 = getAuthToken(adminCol1.getEmail(), password); String tokenAdminCol2 = getAuthToken(adminCol2.getEmail(), password); // define authorizations that we know must exists Authorization adminOfComAToVersion = new Authorization(adminComA, canDeleteVersionFeature, versionRest); Authorization adminOfCol1ToVersion = new Authorization(adminCol1, canDeleteVersionFeature, versionRest); // define authorization that we know not exists Authorization adminOfComBToVersion = new Authorization(adminComB, canDeleteVersionFeature, versionRest); Authorization adminOfCol2ToVersion = new Authorization(adminCol2, canDeleteVersionFeature, versionRest); getClient(tokenAdminComA).perform(get("/api/authz/authorizations/" + adminOfComAToVersion.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.is( AuthorizationMatcher.matchAuthorization(adminOfComAToVersion)))); getClient(tokenAdminCol1).perform(get("/api/authz/authorizations/" + adminOfCol1ToVersion.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.is( AuthorizationMatcher.matchAuthorization(adminOfCol1ToVersion)))); getClient(tokenAdminComB).perform(get("/api/authz/authorizations/" + adminOfComBToVersion.getID())) .andExpect(status().isNotFound()); getClient(tokenAdminCol2).perform(get("/api/authz/authorizations/" + adminOfCol2ToVersion.getID())) .andExpect(status().isNotFound()); } @Test public void canDeleteVersionsFeatureWithVesionInSubmissionTest() throws Exception { context.turnOffAuthorisationSystem(); Community rootCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, rootCommunity) .withName("Collection 1") .withSubmitterGroup(eperson) .build(); Item item = ItemBuilder.createItem(context, col1) .withTitle("Public item") .withIssueDate("2021-04-19") .withAuthor("<NAME>") .withSubject("ExtraEntry") .build(); Version version = VersionBuilder.createVersion(context, item, "My test summary").build(); WorkspaceItem workspaceItem = workspaceItemService.findByItem(context, version.getItem()); context.restoreAuthSystemState(); assertNotNull(workspaceItem); VersionRest versionRest = versionConverter.convert(version, DefaultProjection.DEFAULT); String tokenAdmin = getAuthToken(admin.getEmail(), password); String tokenEPerson = getAuthToken(eperson.getEmail(), password); // define authorization that we know not exists Authorization admin2Version = new Authorization(admin, canDeleteVersionFeature, versionRest); Authorization eperson2Version = new Authorization(eperson, canDeleteVersionFeature, versionRest); Authorization anonymous2Version = new Authorization(null, canDeleteVersionFeature, versionRest); getClient(tokenAdmin).perform(get("/api/authz/authorizations/" + admin2Version.getID())) .andExpect(status().isNotFound()); getClient(tokenEPerson).perform(get("/api/authz/authorizations/" + eperson2Version.getID())) .andExpect(status().isNotFound()); getClient().perform(get("/api/authz/authorizations/" + anonymous2Version.getID())) .andExpect(status().isNotFound()); } @Test public void canDeleteVersionFeatureAndPropertyBlockEntityEnableTest() throws Exception { context.turnOffAuthorisationSystem(); configurationService.setProperty("versioning.block.entity", true); Community rootCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col = CollectionBuilder.createCollection(context, rootCommunity) .withName("Collection 1") .withEntityType("Publication") .build(); Item itemA = ItemBuilder.createItem(context, col) .withTitle("Public item") .withIssueDate("2021-04-19") .withAuthor("<NAME>") .withSubject("ExtraEntry") .build(); Version version = VersionBuilder.createVersion(context, itemA, "My test summary").build(); WorkspaceItem workspaceItem = workspaceItemService.findByItem(context, version.getItem()); installItemService.installItem(context, workspaceItem); context.restoreAuthSystemState(); VersionRest versionRest = versionConverter.convert(version, DefaultProjection.DEFAULT); String tokenEPerson = getAuthToken(eperson.getEmail(), password); String tokenAdmin = getAuthToken(admin.getEmail(), password); // define authorization that we know not exists Authorization admin2ItemA = new Authorization(admin, canDeleteVersionFeature, versionRest); Authorization eperson2ItemA = new Authorization(eperson, canDeleteVersionFeature, versionRest); Authorization anonymous2ItemA = new Authorization(null, canDeleteVersionFeature, versionRest); getClient(tokenAdmin).perform(get("/api/authz/authorizations/" + admin2ItemA.getID())) .andExpect(status().isNotFound()); getClient(tokenEPerson).perform(get("/api/authz/authorizations/" + eperson2ItemA.getID())) .andExpect(status().isNotFound()); getClient().perform(get("/api/authz/authorizations/" + anonymous2ItemA.getID())) .andExpect(status().isNotFound()); } @Test public void canDeleteVersionFeatureAndPropertyBlockEntityDisabledTest() throws Exception { context.turnOffAuthorisationSystem(); configurationService.setProperty("versioning.block.entity", false); Community rootCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col = CollectionBuilder.createCollection(context, rootCommunity) .withName("Collection 1") .withEntityType("Publication") .build(); Item itemA = ItemBuilder.createItem(context, col) .withTitle("Public item") .withIssueDate("2021-04-19") .withAuthor("<NAME>") .withSubject("ExtraEntry") .build(); Version version = VersionBuilder.createVersion(context, itemA, "My test summary").build(); WorkspaceItem workspaceItem = workspaceItemService.findByItem(context, version.getItem()); installItemService.installItem(context, workspaceItem); context.restoreAuthSystemState(); VersionRest versionRest = versionConverter.convert(version, DefaultProjection.DEFAULT); String tokenEPerson = getAuthToken(eperson.getEmail(), password); String tokenAdmin = getAuthToken(admin.getEmail(), password); // define authorization that we know not exists Authorization admin2ItemA = new Authorization(admin, canDeleteVersionFeature, versionRest); Authorization eperson2ItemA = new Authorization(eperson, canDeleteVersionFeature, versionRest); Authorization anonymous2ItemA = new Authorization(null, canDeleteVersionFeature, versionRest); getClient(tokenAdmin).perform(get("/api/authz/authorizations/" + admin2ItemA.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.is( AuthorizationMatcher.matchAuthorization(admin2ItemA)))); getClient(tokenEPerson).perform(get("/api/authz/authorizations/" + eperson2ItemA.getID())) .andExpect(status().isNotFound()); getClient().perform(get("/api/authz/authorizations/" + anonymous2ItemA.getID())) .andExpect(status().isNotFound()); } }
7,906
634
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.components.impl.stores.storage; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.*; import com.intellij.openapi.components.StateStorage.SaveSession; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.PathUtilRt; import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import consulo.components.impl.stores.StreamProvider; import consulo.disposer.Disposable; import consulo.disposer.Disposer; import consulo.logging.Logger; import org.jdom.Element; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class StateStorageManagerImpl implements StateStorageManager, Disposable { private static final Logger LOG = Logger.getInstance(StateStorageManagerImpl.class); private static final boolean ourHeadlessEnvironment; static { final Application app = ApplicationManager.getApplication(); ourHeadlessEnvironment = app.isHeadlessEnvironment() || app.isUnitTestMode(); } private final Map<String, String> myMacros = new LinkedHashMap<>(); private final Lock myStorageLock = new ReentrantLock(); private final Map<String, StateStorage> myStorages = new HashMap<>(); private final TrackingPathMacroSubstitutor myPathMacroSubstitutor; @Nonnull private final StateStorageFacade myStateStorageFacade; private final String myRootTagName; protected final Supplier<MessageBus> myMessageBusSupplier; private StreamProvider myStreamProvider; public StateStorageManagerImpl(@Nullable TrackingPathMacroSubstitutor pathMacroSubstitutor, String rootTagName, @Nullable Disposable parentDisposable, @Nonnull Supplier<MessageBus> messageBusSupplier, @Nonnull StateStorageFacade stateStorageFacade) { myMessageBusSupplier = messageBusSupplier; myRootTagName = rootTagName; myPathMacroSubstitutor = pathMacroSubstitutor; myStateStorageFacade = stateStorageFacade; if (parentDisposable != null) { Disposer.register(parentDisposable, this); } } @Nonnull protected abstract String getConfigurationMacro(boolean directorySpec); @Override @Nonnull @SuppressWarnings("deprecation") public String buildFileSpec(@Nonnull Storage storage) { boolean directorySpec = !storage.stateSplitter().equals(StateSplitterEx.class); String file = storage.file(); if (!StringUtil.isEmpty(file)) { return file; } String value = storage.value(); if (value.isEmpty()) { LOG.error("Storage.value() is empty"); return StoragePathMacros.DEFAULT_FILE; } if (value.equals(StoragePathMacros.WORKSPACE_FILE)) { return value; } return getConfigurationMacro(directorySpec) + "/" + value + (directorySpec ? "/" : ""); } @Nonnull private StateStorage createStateStorage(@Nonnull Storage storageSpec) { if (!storageSpec.stateSplitter().equals(StateSplitterEx.class)) { StateSplitterEx splitter = ReflectionUtil.newInstance(storageSpec.stateSplitter()); return myStateStorageFacade.createDirectoryBasedStorage(myPathMacroSubstitutor, expandMacros(buildFileSpec(storageSpec)), splitter, this, createStorageTopicListener()); } else { return createFileStateStorage(buildFileSpec(storageSpec), storageSpec.roamingType()); } } @Override public TrackingPathMacroSubstitutor getMacroSubstitutor() { return myPathMacroSubstitutor; } @Override public synchronized void addMacro(@Nonnull String macro, @Nonnull String expansion) { assert !macro.isEmpty(); // backward compatibility if (macro.charAt(0) != '$') { LOG.warn("Add macros instead of macro name: " + macro); expansion = '$' + macro + '$'; } myMacros.put(macro, expansion); } @Override @Nonnull public StateStorage getStateStorage(@Nonnull Storage storageSpec) { String key = buildFileSpec(storageSpec); myStorageLock.lock(); try { StateStorage stateStorage = myStorages.get(key); if (stateStorage == null) { stateStorage = createStateStorage(storageSpec); myStorages.put(key, stateStorage); } return stateStorage; } finally { myStorageLock.unlock(); } } @Nullable @Override public StateStorage getStateStorage(@Nonnull String fileSpec, @Nonnull RoamingType roamingType) { myStorageLock.lock(); try { StateStorage stateStorage = myStorages.get(fileSpec); if (stateStorage == null) { stateStorage = createFileStateStorage(fileSpec, roamingType); myStorages.put(fileSpec, stateStorage); } return stateStorage; } finally { myStorageLock.unlock(); } } @Nonnull @Override public Couple<Collection<VfsFileBasedStorage>> getCachedFileStateStorages(@Nonnull Collection<String> changed, @Nonnull Collection<String> deleted) { myStorageLock.lock(); try { return Couple.of(getCachedFileStorages(changed), getCachedFileStorages(deleted)); } finally { myStorageLock.unlock(); } } @Nonnull private Collection<VfsFileBasedStorage> getCachedFileStorages(@Nonnull Collection<String> fileSpecs) { if (fileSpecs.isEmpty()) { return Collections.emptyList(); } List<VfsFileBasedStorage> result = null; for (String fileSpec : fileSpecs) { StateStorage storage = myStorages.get(fileSpec); if (storage instanceof VfsFileBasedStorage) { if (result == null) { result = new ArrayList<>(); } result.add((VfsFileBasedStorage)storage); } } return result == null ? Collections.<VfsFileBasedStorage>emptyList() : result; } @Nonnull @Override public Collection<String> getStorageFileNames() { myStorageLock.lock(); try { return myStorages.keySet(); } finally { myStorageLock.unlock(); } } @Override public void clearStateStorage(@Nonnull String file) { myStorageLock.lock(); try { myStorages.remove(file); } finally { myStorageLock.unlock(); } } @Nonnull private StateStorage createFileStateStorage(@Nonnull String fileSpec, @Nullable RoamingType roamingType) { String filePath = FileUtil.toSystemIndependentName(expandMacros(fileSpec)); if (!ourHeadlessEnvironment && PathUtilRt.getFileName(filePath).lastIndexOf('.') < 0) { throw new IllegalArgumentException("Extension is missing for storage file: " + filePath); } if (roamingType == RoamingType.PER_USER && fileSpec.equals(StoragePathMacros.WORKSPACE_FILE)) { roamingType = RoamingType.DISABLED; } return myStateStorageFacade .createFileBasedStorage(filePath, fileSpec, roamingType, getMacroSubstitutor(fileSpec), myRootTagName, StateStorageManagerImpl.this, createStorageTopicListener(), myStreamProvider, isUseXmlProlog()); } @Nullable protected StateStorage.Listener createStorageTopicListener() { MessageBus messageBus = myMessageBusSupplier.get(); return messageBus == null ? null : messageBus.syncPublisher(StateStorage.STORAGE_TOPIC); } protected boolean isUseXmlProlog() { return true; } @Nullable @Override public final StreamProvider getStreamProvider() { return myStreamProvider; } protected TrackingPathMacroSubstitutor getMacroSubstitutor(@Nonnull final String fileSpec) { return myPathMacroSubstitutor; } private static final Pattern MACRO_PATTERN = Pattern.compile("(\\$[^\\$]*\\$)"); @Override @Nonnull public synchronized String expandMacros(@Nonnull String file) { Matcher matcher = MACRO_PATTERN.matcher(file); while (matcher.find()) { String m = matcher.group(1); if (!myMacros.containsKey(m)) { throw new IllegalArgumentException("Unknown macro: " + m + " in storage file spec: " + file); } } String expanded = file; for (String macro : myMacros.keySet()) { expanded = StringUtil.replace(expanded, macro, myMacros.get(macro)); } return expanded; } @Nonnull @Override public String collapseMacros(@Nonnull String path) { String result = path; for (String macro : myMacros.keySet()) { result = StringUtil.replace(result, myMacros.get(macro), macro); } return result; } @Nonnull @Override public ExternalizationSession startExternalization() { return new StateStorageManagerExternalizationSession(); } protected class StateStorageManagerExternalizationSession implements ExternalizationSession { final Map<StateStorage, StateStorage.ExternalizationSession> mySessions = new LinkedHashMap<>(); @Override public void setState(@Nonnull Storage[] storageSpecs, @Nonnull Object component, @Nonnull String componentName, @Nonnull Object state) { for (Storage storageSpec : storageSpecs) { StateStorage stateStorage = getStateStorage(storageSpec); StateStorage.ExternalizationSession session = getExternalizationSession(stateStorage); if (session != null) { // empty element as null state, so, will be deleted session.setState(component, componentName, storageSpec.deprecated() ? new Element("empty") : state, storageSpec); } } } @Nullable private StateStorage.ExternalizationSession getExternalizationSession(@Nonnull StateStorage stateStorage) { StateStorage.ExternalizationSession session = mySessions.get(stateStorage); if (session == null) { session = stateStorage.startExternalization(); if (session != null) { mySessions.put(stateStorage, session); } } return session; } @Nonnull @Override public List<SaveSession> createSaveSessions(boolean force) { if (mySessions.isEmpty()) { return Collections.emptyList(); } List<SaveSession> saveSessions = null; Collection<StateStorage.ExternalizationSession> externalizationSessions = mySessions.values(); for (StateStorage.ExternalizationSession session : externalizationSessions) { SaveSession saveSession = session.createSaveSession(force); if (saveSession != null) { if (saveSessions == null) { if (externalizationSessions.size() == 1) { return Collections.singletonList(saveSession); } saveSessions = new ArrayList<>(); } saveSessions.add(saveSession); } } return ContainerUtil.notNullize(saveSessions); } } @Override public void dispose() { } @Override public void setStreamProvider(@Nullable StreamProvider streamProvider) { myStreamProvider = streamProvider; } }
4,146
706
#include "phenom/job.h" #include "phenom/thread.h" #include "phenom/log.h" #include "phenom/sysutil.h" #include "phenom/counter.h" #include <sysexits.h> #include <sys/socket.h> #include <sys/resource.h> #ifdef HAVE_LIBEVENT # include <event.h> #endif static char *commaprint(uint64_t n, char *retbuf, uint32_t size) { char *p = retbuf + size - 1; int i = 0; *p = '\0'; do { if (i % 3 == 0 && i != 0) { *--p = ','; } *--p = '0' + n % 10; n /= 10; i++; } while (n != 0); return p; } struct timeval start_time, end_time, elapsed_time; static ph_job_t deadline; static struct ph_nbio_stats stats = {0, 0, 0, 0}; int num_socks = 100; int time_duration = 1000; int io_threads = 0; int use_libevent = 0; ph_job_t *events = NULL; #ifdef HAVE_LIBEVENT struct event *levents = NULL; #endif int *write_ends = NULL; #ifdef HAVE_LIBEVENT static void lev_read(int fd, short which, void *arg) { ph_job_t *job = arg; char buf[10]; ptrdiff_t off; off = job - events; ph_unused_parameter(which); ph_ignore_result(read(fd, buf, sizeof(buf))); ph_ignore_result(write(write_ends[off], "y", 1)); event_add(&levents[off], NULL); stats.num_dispatched++; } #endif static void deadline_reached(ph_job_t *job, ph_iomask_t why, void *data) { ph_unused_parameter(job); ph_unused_parameter(why); ph_unused_parameter(data); gettimeofday(&end_time, NULL); ph_nbio_stat(&stats); ph_sched_stop(); } static void consume_data(ph_job_t *job, ph_iomask_t why, void *data) { char buf[10]; ptrdiff_t off; off = job - events; ph_unused_parameter(why); ph_unused_parameter(data); ph_ignore_result(read(job->fd, buf, sizeof(buf))); ph_ignore_result(write(write_ends[off], "y", 1)); ph_job_set_nbio(job, PH_IOMASK_READ, 0); } int main(int argc, char **argv) { int c; int i; struct rlimit rl; io_threads = 0; while ((c = getopt(argc, argv, "n:a:c:t:e")) != -1) { switch (c) { case 'n': num_socks = atoi(optarg); break; case 'c': io_threads = atoi(optarg); break; case 't': time_duration = atoi(optarg) * 1000; break; case 'e': use_libevent = 1; #ifdef HAVE_LIBEVENT event_init(); #endif break; default: fprintf(stderr, "-n NUMBER specify number of sockets (default %d)\n", num_socks); fprintf(stderr, "-c NUMBER specify IO sched concurrency level (default: auto)\n" ); fprintf(stderr, "-t NUMBER specify duration of test in seconds " "(default %ds)\n", time_duration/1000); fprintf(stderr, "-e Use libevent instead of libphenom\n"); exit(EX_USAGE); } } if (use_libevent) { io_threads = 1; } ph_library_init(); ph_log_level_set(PH_LOG_INFO); ph_nbio_init(io_threads); ph_nbio_stat(&stats); io_threads = stats.num_threads; events = calloc(num_socks, sizeof(*events)); write_ends = calloc(num_socks, sizeof(*write_ends)); #ifdef HAVE_LIBEVENT levents = calloc(num_socks, sizeof(*levents)); #endif rl.rlim_cur = rl.rlim_max = (num_socks * 2) + (io_threads * 2) + 64; if (setrlimit(RLIMIT_NOFILE, &rl)) { perror("setrlimit"); // Don't exit: valgrind causes this to fail and terminating // here stops us from collecting anything useful } for (i = 0; i < num_socks; i++) { int pair[2]; ph_job_init(&events[i]); events[i].emitter_affinity = i; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair)) { perror("socketpair"); exit(EX_OSERR); } write_ends[i] = pair[1]; events[i].fd = pair[0]; ph_socket_set_nonblock(pair[0], true); ph_socket_set_nonblock(pair[1], true); events[i].callback = consume_data; if (use_libevent) { #ifdef HAVE_LIBEVENT event_set(&levents[i], events[i].fd, EV_READ, lev_read, &events[i]); event_add(&levents[i], NULL); #endif } else { ph_job_set_nbio(&events[i], PH_IOMASK_READ, 0); } ph_ignore_result(write(write_ends[i], "x", 1)); } if (use_libevent) { #ifdef HAVE_LIBEVENT struct timeval dead = { time_duration / 1000, 0 }; event_loopexit(&dead); ph_log(PH_LOG_INFO, "Using libevent\n"); #else ph_panic("No libevent support"); #endif } else { ph_job_init(&deadline); deadline.callback = deadline_reached; ph_job_set_timer_in_ms(&deadline, time_duration); } ph_log(PH_LOG_INFO, "Created %d events, using %d threads\n", num_socks, io_threads); gettimeofday(&start_time, NULL); if (use_libevent) { #ifdef HAVE_LIBEVENT event_loop(0); gettimeofday(&end_time, NULL); #endif } else { ph_sched_run(); } { double duration; double rate; char cbuf[64]; char *logname; ph_log(PH_LOG_INFO, "%" PRIi64 " timer ticks\n", stats.timer_ticks); timersub(&end_time, &start_time, &elapsed_time); duration = elapsed_time.tv_sec + (elapsed_time.tv_usec/1000000.0f); rate = stats.num_dispatched / duration; ph_log(PH_LOG_INFO, "Over %.3fs, fired %s events/s", duration, commaprint((uint64_t)rate, cbuf, sizeof(cbuf)) ); // To support automated data collection by run-pipes.php logname = getenv("APPEND_FILE"); if (logname && logname[0]) { ph_stream_t *s = ph_stm_file_open(logname, O_WRONLY|O_CREAT|O_APPEND, 0666); if (s) { ph_stm_printf(s, "%s,%d,%d,%f\n", use_libevent ? "libevent" : "libphenom", num_socks, io_threads, rate); ph_stm_flush(s); ph_stm_close(s); } } ph_log(PH_LOG_INFO, "Over %.3fs, fired %s events/core/s", duration, commaprint((uint64_t)(rate/io_threads), cbuf, sizeof(cbuf)) ); } free(events); free(write_ends); #ifdef HAVE_LIBEVENT free(levents); #endif #ifdef __APPLE__ // OS/X "mysteriously" spins CPU cycles somewhere in the kernel after we've // exit'd to close out descriptors. Let folks know that that is what is // going on (very noticeable above 100k events). We could close them here, // but it doesn't make it go faster and it is just more code to run. ph_log(PH_LOG_INFO, "Kernel may spin closing descriptors. Enjoy!"); #endif return EX_OK; } /* vim:ts=2:sw=2:et: */
2,895
3,432
<filename>telegrambots-meta/src/main/java/org/telegram/telegrambots/meta/api/methods/AnswerCallbackQuery.java package org.telegram.telegrambots.meta.api.methods; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import org.telegram.telegrambots.meta.api.objects.ApiResponse; import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException; import java.io.IOException; /** * @author <NAME> * @version 1.0 * Use this method to send answers to callback queries sent from inline keyboards. The answer * will be displayed to the user as a notification at the top of the chat screen or as an alert. On * success, True is returned. * * @apiNote Alternatively, the user can be redirected to the specified URL. For this option to work, * you must enable /setcustomurls for your bot via BotFather and accept the terms. * */ @EqualsAndHashCode(callSuper = false) @Getter @Setter @ToString @NoArgsConstructor @RequiredArgsConstructor @AllArgsConstructor @Builder public class AnswerCallbackQuery extends BotApiMethod<Boolean> { public static final String PATH = "answercallbackquery"; private static final String CALLBACKQUERYID_FIELD = "callback_query_id"; private static final String TEXT_FIELD = "text"; private static final String SHOWALERT_FIELD = "show_alert"; private static final String URL_FIELD = "url"; private static final String CACHETIME_FIELD = "cache_time"; @JsonProperty(CALLBACKQUERYID_FIELD) @NonNull private String callbackQueryId; ///< Unique identifier for the query to be answered @JsonProperty(TEXT_FIELD) private String text; ///< Optional Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters @JsonProperty(SHOWALERT_FIELD) private Boolean showAlert; ///< Optional. If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. /** * Optional. URL that will be opened by the user's client. * If you have created a Game and accepted the conditions via @Botfather, * specify the URL that opens your game. Otherwise you may use links * like telegram.me/your_bot?start=XXXX that open your bot with a parameter. */ @JsonProperty(URL_FIELD) private String url; /** * Optional The maximum amount of time in seconds that the result of the callback query * may be cached client-side. * * @apiNote Telegram apps will support caching starting in version 3.14. Defaults to 0. */ @JsonProperty(CACHETIME_FIELD) private Integer cacheTime; @Override public String getMethod() { return PATH; } @Override public Boolean deserializeResponse(String answer) throws TelegramApiRequestException { try { ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer, new TypeReference<ApiResponse<Boolean>>(){}); if (result.getOk()) { return result.getResult(); } else { throw new TelegramApiRequestException("Error answering callback query", result); } } catch (IOException e) { throw new TelegramApiRequestException("Unable to deserialize response", e); } } @Override public void validate() throws TelegramApiValidationException { if (callbackQueryId == null) { throw new TelegramApiValidationException("CallbackQueryId can't be null", this); } } }
1,299
4,054
<gh_stars>1000+ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. /** * \class document::ForceLink * \ingroup base * * \brief Class used to include some document functionality that programs that * needs to get it linked, but doesn't use it can include. * * Many codebits include this, but who really depends on it? */ #pragma once namespace document { class ForceLink { public: ForceLink(); }; } // document
143
993
<gh_stars>100-1000 /** * Copyright 2015 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.servo.Metric; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.Tag; import com.netflix.servo.util.Objects; import com.netflix.servo.util.Preconditions; import java.io.IOException; /** * A metric that can be reported to Atlas. */ class AtlasMetric implements JsonPayload { private final MonitorConfig config; private final long start; private final double value; AtlasMetric(Metric m) { this(m.getConfig(), m.getTimestamp(), m.getNumberValue()); } AtlasMetric(MonitorConfig config, long start, Number value) { this.config = Preconditions.checkNotNull(config, "config"); this.value = Preconditions.checkNotNull(value, "value").doubleValue(); this.start = start; } MonitorConfig getConfig() { return config; } long getStartTime() { return start; } @Override public boolean equals(Object obj) { if (!(obj instanceof AtlasMetric)) { return false; } AtlasMetric m = (AtlasMetric) obj; return config.equals(m.getConfig()) && start == m.getStartTime() && Double.compare(value, m.value) == 0; } @Override public int hashCode() { return Objects.hash(config, start, value); } @Override public String toString() { return "AtlasMetric{config=" + config + ", start=" + start + ", value=" + value + '}'; } @Override public void toJson(JsonGenerator gen) throws IOException { gen.writeStartObject(); gen.writeObjectFieldStart("tags"); gen.writeStringField("name", config.getName()); for (Tag tag : config.getTags()) { ValidCharacters.tagToJson(gen, tag); } gen.writeEndObject(); gen.writeNumberField("start", start); gen.writeNumberField("value", value); gen.writeEndObject(); gen.flush(); } }
840
324
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.cloudstack.options; import org.jclouds.http.options.BaseHttpRequestOptions; import com.google.common.collect.ImmutableSet; /** * Optional arguments for updating an User * * @see <a * href="http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/updateUser.html" * /> */ public class UpdateUserOptions extends BaseHttpRequestOptions { public static final UpdateUserOptions NONE = new UpdateUserOptions(); /** * @param email user email address */ public UpdateUserOptions email(String email) { this.queryParameters.replaceValues("email", ImmutableSet.of(email)); return this; } /** * @param firstName user account first name */ public UpdateUserOptions firstName(String firstName) { this.queryParameters.replaceValues("firstname", ImmutableSet.of(firstName)); return this; } /** * @param lastName user account last name */ public UpdateUserOptions lastName(String lastName) { this.queryParameters.replaceValues("lastname", ImmutableSet.of(lastName)); return this; } /** * @param hashedPassword hashed password (default is MD5). If you wish to use any other * hashing algorithm, you would need to write a custom authentication adapter */ public UpdateUserOptions hashedPassword(String hashedPassword) { this.queryParameters.replaceValues("password", ImmutableSet.of(hashedPassword)); return this; } /** * @param timezone specifies a timezone for this command. For more information on * the timezone parameter, see Time Zone Format. */ public UpdateUserOptions timezone(String timezone) { this.queryParameters.replaceValues("timezone", ImmutableSet.of(timezone)); return this; } /** * @param userApiKey */ public UpdateUserOptions userApiKey(String userApiKey) { this.queryParameters.replaceValues("userapikey", ImmutableSet.of(userApiKey)); return this; } /** * @param userSecretKey */ public UpdateUserOptions userSecretKey(String userSecretKey) { this.queryParameters.replaceValues("usersecretkey", ImmutableSet.of(userSecretKey)); return this; } /** * @param userName unique user name */ public UpdateUserOptions userName(String userName) { this.queryParameters.replaceValues("username", ImmutableSet.of(userName)); return this; } public static class Builder { /** * @see UpdateUserOptions#email */ public static UpdateUserOptions email(String email) { UpdateUserOptions options = new UpdateUserOptions(); return options.email(email); } /** * @see UpdateUserOptions#firstName */ public static UpdateUserOptions firstName(String firstName) { UpdateUserOptions options = new UpdateUserOptions(); return options.firstName(firstName); } /** * @see UpdateUserOptions#lastName */ public static UpdateUserOptions lastName(String lastName) { UpdateUserOptions options = new UpdateUserOptions(); return options.lastName(lastName); } /** * @see UpdateUserOptions#hashedPassword */ public static UpdateUserOptions hashedPassword(String hashedPassword) { UpdateUserOptions options = new UpdateUserOptions(); return options.hashedPassword(hashedPassword); } /** * @see UpdateUserOptions#timezone */ public static UpdateUserOptions timezone(String timezone) { UpdateUserOptions options = new UpdateUserOptions(); return options.timezone(timezone); } /** * @see UpdateUserOptions#userApiKey */ public static UpdateUserOptions userApiKey(String userApiKey) { UpdateUserOptions options = new UpdateUserOptions(); return options.userApiKey(userApiKey); } /** * @see UpdateUserOptions#userSecretKey */ public static UpdateUserOptions userSecretKey(String userSecretKey) { UpdateUserOptions options = new UpdateUserOptions(); return options.userSecretKey(userSecretKey); } /** * @see UpdateUserOptions#userName */ public static UpdateUserOptions userName(String userName) { UpdateUserOptions options = new UpdateUserOptions(); return options.userName(userName); } } }
1,830
11,864
<reponame>djmaster458/raspberry-pi-os #ifndef _P_TIMER_H #define _P_TIMER_H #include "peripherals/base.h" #define TIMER_CS (PBASE+0x00003000) #define TIMER_CLO (PBASE+0x00003004) #define TIMER_CHI (PBASE+0x00003008) #define TIMER_C0 (PBASE+0x0000300C) #define TIMER_C1 (PBASE+0x00003010) #define TIMER_C2 (PBASE+0x00003014) #define TIMER_C3 (PBASE+0x00003018) #define TIMER_CS_M0 (1 << 0) #define TIMER_CS_M1 (1 << 1) #define TIMER_CS_M2 (1 << 2) #define TIMER_CS_M3 (1 << 3) // Local Timer Configuration. // A free-running secondary timer is provided that can generate an interrupt each time it crosses zero. When it is // enabled, the timer is decremented on each edge (positive or negative) of the crystal reference clock. It is // automatically reloaded with the TIMER_TIMEOUT value when it reaches zero and then continues to decrement. // Routing of the timer interrupt is controlled by the PERI_IRQ_ROUTE0 register #define LOCAL_TIMER_CONTROL (ARM_LOCAL_BASE + 0x34) // Local Timer Interrupt Control #define LOCAL_TIMER_IRQ (ARM_LOCAL_BASE + 0x38) // 54 MHz #define LOCAL_TIMER_FREQ (54000000) #endif /*_P_TIMER_H */
499
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.security.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * AWS cloud account connector based assume role, the role enables delegating access to your AWS resources. The role is * composed of role Amazon Resource Name (ARN) and external ID. For more details, refer to &lt;a * href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html"&gt;Creating a Role to Delegate * Permissions to an IAM User (write only)&lt;/a&gt;. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "authenticationType") @JsonTypeName("awsAssumeRole") @Fluent public final class AwAssumeRoleAuthenticationDetailsProperties extends AuthenticationDetailsProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(AwAssumeRoleAuthenticationDetailsProperties.class); /* * The ID of the cloud account */ @JsonProperty(value = "accountId", access = JsonProperty.Access.WRITE_ONLY) private String accountId; /* * Assumed role ID is an identifier that you can use to create temporary * security credentials. */ @JsonProperty(value = "awsAssumeRoleArn", required = true) private String awsAssumeRoleArn; /* * A unique identifier that is required when you assume a role in another * account. */ @JsonProperty(value = "awsExternalId", required = true) private String awsExternalId; /** * Get the accountId property: The ID of the cloud account. * * @return the accountId value. */ public String accountId() { return this.accountId; } /** * Get the awsAssumeRoleArn property: Assumed role ID is an identifier that you can use to create temporary security * credentials. * * @return the awsAssumeRoleArn value. */ public String awsAssumeRoleArn() { return this.awsAssumeRoleArn; } /** * Set the awsAssumeRoleArn property: Assumed role ID is an identifier that you can use to create temporary security * credentials. * * @param awsAssumeRoleArn the awsAssumeRoleArn value to set. * @return the AwAssumeRoleAuthenticationDetailsProperties object itself. */ public AwAssumeRoleAuthenticationDetailsProperties withAwsAssumeRoleArn(String awsAssumeRoleArn) { this.awsAssumeRoleArn = awsAssumeRoleArn; return this; } /** * Get the awsExternalId property: A unique identifier that is required when you assume a role in another account. * * @return the awsExternalId value. */ public String awsExternalId() { return this.awsExternalId; } /** * Set the awsExternalId property: A unique identifier that is required when you assume a role in another account. * * @param awsExternalId the awsExternalId value to set. * @return the AwAssumeRoleAuthenticationDetailsProperties object itself. */ public AwAssumeRoleAuthenticationDetailsProperties withAwsExternalId(String awsExternalId) { this.awsExternalId = awsExternalId; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (awsAssumeRoleArn() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property awsAssumeRoleArn in model" + " AwAssumeRoleAuthenticationDetailsProperties")); } if (awsExternalId() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property awsExternalId in model" + " AwAssumeRoleAuthenticationDetailsProperties")); } } }
1,626
483
from flask import Flask, jsonify from flask.views import MethodView from flask_swagger import swagger app = Flask(__name__) class UserAPI(MethodView): def get(self, team_id): """ Get a list of users First line is the summary All following lines until the hyphens is added to description --- tags: - users responses: 200: description: Returns a list of users """ return [] def post(self, team_id): """ Create a new user --- tags: - users parameters: - in: body name: body schema: id: User required: - email - name properties: email: type: string description: email for user name: type: string description: name for user responses: 201: description: User created """ return {} def put(self, user_id): """ Update a user swagger_from_file: user_put.yml """ return {} @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin','*') response.headers.add('Access-Control-Allow-Headers', "Authorization, Content-Type") response.headers.add('Access-Control-Expose-Headers', "Authorization") response.headers.add('Access-Control-Allow-Methods', "GET, POST, PUT, DELETE, OPTIONS") response.headers.add('Access-Control-Allow-Credentials', "true") response.headers.add('Access-Control-Max-Age', 60 * 60 * 24 * 20) return response view = UserAPI.as_view('users') app.add_url_rule('/users/<int:team_id>', view_func=view, methods=["GET"]) app.add_url_rule('/testing/<int:team_id>', view_func=view) @app.route("/hacky") def bla(): """ An endpoint that isn't using method view --- tags: - hacks responses: 200: description: Hacked some hacks schema: id: Hack properties: hack: type: string description: it's a hack subitems: type: array items: schema: id: SubItem properties: bla: type: string description: Bla blu: type: integer description: Blu """ return jsonify(['hacky']) class PetAPI(MethodView): def get(self, pet_id): """ Get a pet. This is an example of how to use references and factored out definitions --- tags: - pets parameters: - in: path name: pet_id definitions: - schema: id: Pet required: - name - owner properties: name: type: string description: the pet's name owner: $ref: '#/definitions/Owner' - schema: id: Owner required: - name properties: name: type: string description: the owner's name responses: 200: description: Returns the specified pet $ref: '#/definitions/Pet' """ return {} pet_view = PetAPI.as_view('pets') app.add_url_rule('/pets/<int:pet_id>', view_func=pet_view, methods=["GET"]) @app.route("/") def hello(): return "Hello World!" @app.route("/spec") def spec(): return jsonify(swagger(app, from_file_keyword='swagger_from_file')) if __name__ == "__main__": app.run(debug=True)
2,060
2,742
/* * Copyright 2008-2019 by <NAME> * * This file is part of Java Melody. * * 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.bull.javamelody.internal.web.pdf; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfPCell; import net.bull.javamelody.internal.common.I18N; import net.bull.javamelody.internal.model.JCacheInformations; import net.bull.javamelody.internal.web.html.HtmlJCacheInformationsReport; /** * Partie du rapport pdf pour les caches de données (JCache). * @author <NAME> */ class PdfJCacheInformationsReport extends PdfAbstractTableReport { private final List<JCacheInformations> jcacheInformationsList; private final DecimalFormat integerFormat = I18N.createIntegerFormat(); private final Font cellFont = PdfFonts.TABLE_CELL.getFont(); private final boolean hitsRatioEnabled; PdfJCacheInformationsReport(List<JCacheInformations> jcacheInformationsList, Document document) { super(document); assert jcacheInformationsList != null; this.jcacheInformationsList = jcacheInformationsList; this.hitsRatioEnabled = HtmlJCacheInformationsReport .isHitsRatioEnabled(jcacheInformationsList); } @Override void toPdf() throws DocumentException { writeHeader(); for (final JCacheInformations jcacheInformations : jcacheInformationsList) { nextRow(); writeCacheInformations(jcacheInformations); } addTableToDocument(); if (!hitsRatioEnabled) { final Paragraph statisticsEnabledParagraph = new Paragraph( getString("jcaches_statistics_enable"), cellFont); statisticsEnabledParagraph.setAlignment(Element.ALIGN_RIGHT); addToDocument(statisticsEnabledParagraph); } } private void writeHeader() throws DocumentException { final List<String> headers = createHeaders(); final int[] relativeWidths = new int[headers.size()]; Arrays.fill(relativeWidths, 0, headers.size(), 4); relativeWidths[headers.size() - 1] = 1; initTable(headers, relativeWidths); } private List<String> createHeaders() { final List<String> headers = new ArrayList<>(); headers.add(getString("Cache")); if (hitsRatioEnabled) { headers.add(getString("Efficacite_cache")); } return headers; } private void writeCacheInformations(JCacheInformations jcacheInformations) { final PdfPCell defaultCell = getDefaultCell(); defaultCell.setHorizontalAlignment(Element.ALIGN_LEFT); addCell(jcacheInformations.getName()); if (hitsRatioEnabled) { defaultCell.setHorizontalAlignment(Element.ALIGN_RIGHT); addCell(integerFormat.format(jcacheInformations.getHitsRatio())); } } }
1,095
892
{ "schema_version": "1.2.0", "id": "GHSA-429h-p5fw-3m6v", "modified": "2022-05-13T01:03:27Z", "published": "2022-05-13T01:03:27Z", "aliases": [ "CVE-2011-1992" ], "details": "The XSS Filter in Microsoft Internet Explorer 8 allows remote attackers to read content from a different (1) domain or (2) zone via a \"trial and error\" attack, aka \"XSS Filter Information Disclosure Vulnerability.\"", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2011-1992" }, { "type": "WEB", "url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2011/ms11-099" }, { "type": "WEB", "url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A14745" }, { "type": "WEB", "url": "http://www.us-cert.gov/cas/techalerts/TA11-347A.html" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
492
336
<filename>athena/tests/audio_test.py """ A simple test script for passive/active listening """ print('---- Running Audio Test ----') try: input = raw_input # Python 2 fix except NameError: pass import pygame import time from pygame import mixer passed = True mixer.pre_init(16000, -16, 2, 1024) mixer.init() mixer.music.load("../data/media/responses/test.mp3") print("~ Attempting to play audio...") mixer.music.play() while mixer.music.get_busy(): pygame.time.delay(100) resp = "something" while True: resp = input("~ Audio test complete! Did you hear Athena speaking? (Y/N): ") if resp[0].lower() == "y": print("---- TEST PASSED ----\n") break elif resp[0].lower() == "n": passed = False print("---- TEST FAILED :( ----\n") break time.sleep(1)
352
2,118
// Copyright (c) 2006-2018 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef CDSTEST_STAT_ELLENBINTREE_OUT_H #define CDSTEST_STAT_ELLENBINTREE_OUT_H //#include "ellen_bintree_update_desc_pool.h" #include <cds_test/stress_test.h> #include <cds/intrusive/details/ellen_bintree_base.h> namespace cds_test { static inline property_stream& operator <<( property_stream& o, cds::intrusive::ellen_bintree::empty_stat const& /*s*/ ) { return o; } static inline property_stream& operator <<( property_stream& o, cds::intrusive::ellen_bintree::stat<> const& s ) { return o // << "\t\t Internal node allocated: " << ellen_bintree_pool::internal_node_counter::m_nAlloc.get() << "\n" // << "\t\t Internal node freed: " << ellen_bintree_pool::internal_node_counter::m_nFree.get() << "\n" << CDSSTRESS_STAT_OUT( s, m_nInternalNodeCreated ) << CDSSTRESS_STAT_OUT( s, m_nInternalNodeDeleted ) << CDSSTRESS_STAT_OUT( s, m_nUpdateDescCreated ) << CDSSTRESS_STAT_OUT( s, m_nUpdateDescDeleted ) << CDSSTRESS_STAT_OUT( s, m_nInsertSuccess ) << CDSSTRESS_STAT_OUT( s, m_nInsertFailed ) << CDSSTRESS_STAT_OUT( s, m_nInsertRetries ) << CDSSTRESS_STAT_OUT( s, m_nUpdateExist ) << CDSSTRESS_STAT_OUT( s, m_nUpdateNew ) << CDSSTRESS_STAT_OUT( s, m_nUpdateRetries ) << CDSSTRESS_STAT_OUT( s, m_nEraseSuccess ) << CDSSTRESS_STAT_OUT( s, m_nEraseFailed ) << CDSSTRESS_STAT_OUT( s, m_nEraseRetries ) << CDSSTRESS_STAT_OUT( s, m_nFindSuccess ) << CDSSTRESS_STAT_OUT( s, m_nFindFailed ) << CDSSTRESS_STAT_OUT( s, m_nExtractMinSuccess ) << CDSSTRESS_STAT_OUT( s, m_nExtractMinFailed ) << CDSSTRESS_STAT_OUT( s, m_nExtractMinRetries ) << CDSSTRESS_STAT_OUT( s, m_nExtractMaxSuccess ) << CDSSTRESS_STAT_OUT( s, m_nExtractMaxFailed ) << CDSSTRESS_STAT_OUT( s, m_nExtractMaxRetries ) << CDSSTRESS_STAT_OUT( s, m_nSearchRetry ) << CDSSTRESS_STAT_OUT( s, m_nHelpInsert ) << CDSSTRESS_STAT_OUT( s, m_nHelpDelete ) << CDSSTRESS_STAT_OUT( s, m_nHelpMark ) << CDSSTRESS_STAT_OUT( s, m_nHelpGuardSuccess ) << CDSSTRESS_STAT_OUT( s, m_nHelpGuardFailed ); } } // namespace cds_test #endif // #ifndef CDSTEST_STAT_ELLENBINTREE_OUT_H
1,272
1,849
{ "name": "facebook-batch", "version": "1.1.0", "description": "Gracefully batching facebook requests.", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/Yoctol/messaging-apis.git" }, "main": "dist/index.js", "types": "dist/index.d.ts", "dependencies": { "messaging-api-messenger": "file:../messaging-api-messenger", "type-fest": "^1.4.0" }, "keywords": [ "batch", "bottender", "facebook", "messaging-apis", "messenger" ], "engines": { "node": ">=10" } }
246
575
// 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 THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_FAKE_DISPLAY_ITEM_CLIENT_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_FAKE_DISPLAY_ITEM_CLIENT_H_ #include "third_party/blink/renderer/platform/graphics/paint/display_item_client.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink { // A simple DisplayItemClient implementation suitable for use in unit tests. class FakeDisplayItemClient : public DisplayItemClient { public: explicit FakeDisplayItemClient(const String& name = "FakeDisplayItemClient") : name_(name) {} String DebugName() const final { return name_; } IntRect PartialInvalidationVisualRect() const override { return partial_invalidation_visual_rect_; } void ClearPartialInvalidationVisualRect() const override { partial_invalidation_visual_rect_ = IntRect(); } void SetPartialInvalidationVisualRect(const IntRect& r) { Invalidate(PaintInvalidationReason::kRectangle); partial_invalidation_visual_rect_ = r; } // This simulates a paint without needing a PaintController. using DisplayItemClient::Validate; private: String name_; mutable IntRect partial_invalidation_visual_rect_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_TESTING_FAKE_DISPLAY_ITEM_CLIENT_H_
481
17,702
# ============================================================================== # Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== from enum import Enum class CntkParameters(object): ''' The parameter of all CNTK op ''' def __init__(self): pass class CntkConvolutionParameters(CntkParameters): ''' The parameter definition of convolution op ''' def __init__(self): CntkParameters.__init__(self) self.output = 0 self.stride = [0, 0] self.kernel = [0, 0] self.auto_pad = False self.scale_setting = [1, 1] self.bias_setting = [1, 1] self.need_bias = True self.dilation = [1, 1] self.group = 1 class CntkPoolingParameters(CntkParameters): ''' The parameter definition of pooling op ''' def __init__(self): CntkParameters.__init__(self) self.stride = [0, 0] self.kernel = [0, 0] self.auto_pad = False self.pooling_type = 0 # 0 for max, 1 for average class CntkBatchNormParameters(CntkParameters): ''' The parameter definition of batch normalization op ''' def __init__(self): CntkParameters.__init__(self) self.spatial = 2 self.norm_time_const = 0 self.blend_time_const = 0 self.epsilon = 0.00001 self.scale_setting = [1, 1] self.bias_setting = [1, 1] class CntkDenseParameters(CntkParameters): ''' The parameter definition of dense op ''' def __init__(self): CntkParameters.__init__(self) self.num_output = 0 self.scale_setting = [1, 1] self.bias_setting = [1, 1] self.transpose = False class CntkSpliceParameters(CntkParameters): ''' The parameter definition of splice op ''' def __init__(self): CntkParameters.__init__(self) self.axis = 1 class CntkLRNParameters(CntkParameters): ''' The parameter definition of LRN op ''' def __init__(self): CntkParameters.__init__(self) self.kernel_size = 5 self.alpha = 1 self.beta = 5 self.k = 1 class CntkPSROIPoolingParameters(CntkParameters): ''' The parameter definition of PSROIPooling op ''' def __init__(self): CntkParameters.__init__(self) self.group_size = 1 self.out_channel = 1 class CntkLayerType(Enum): ''' The enumate of CNTK ops ''' relu = 1 convolution = 2 pooling = 3 batch_norm = 4 plus = 5 dense = 6 splice = 7 classification_error = 10 cross_entropy_with_softmax = 11 dropout = 12 lrn = 13 psroi_pooling = 14 softmax = 15 unknown = 100 class CntkTensorDefinition(object): ''' The definition of data blob ''' def __init__(self): self.tensor = [0 * 4] self.data = [] class CntkLayersDefinition(object): ''' The definition of nodes, created by Caffe and instaced by CNTK ''' def __init__(self): self.inputs = [] self.outputs = [] self.op_name = None self.parameters = None self.op_type = CntkLayerType.unknown self.tensor = [] self.parameter_tensor = [] class CntkSolver(object): ''' Record the solver state ''' def __init__(self): self.learning_rate = None self.max_epoch = None self.adjust_interval = None self.decrease_factor = None self.upper_limit = None self.minibatch_size = None self.weight_decay = None self.dropout = None self.number_to_show_result = None self.grad_update_type = None self.momentum = None class CntkModelDescription(object): ''' Record the basic information of model ''' def __init__(self): self.data_provider = [] self.cntk_layers = {} # Dict Key: function name, Value: function definition self.cntk_sorted_layers = [] # List Key: function name self.model_name = 'Untitled' self.solver = None
1,885
344
<filename>imap_tools/__init__.py # Lib author: <NAME> <<EMAIL>> # Project home page: https://github.com/ikvk/imap_tools # License: Apache-2.0 from .query import AND, OR, NOT, Header, UidRange, A, O, N, H, U from .mailbox import BaseMailBox, MailBox, MailBoxUnencrypted from .message import MailMessage, MailAttachment from .folder import MailBoxFolderManager, FolderInfo from .consts import MailMessageFlags, MailBoxFolderStatusOptions from .utils import EmailAddress from .errors import * __version__ = '0.49.1'
163
1,755
/*========================================================================= Program: Visualization Toolkit Module: vtkOpenVRControlsHelper.h Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkOpenVRControlsHelper * @brief Tooltip helper explaining controls * Helper class to draw one tooltip per button around the controller. * * @sa * vtkOpenVRPanelRepresentation */ #ifndef vtkOpenVRControlsHelper_h #define vtkOpenVRControlsHelper_h #include "vtkRenderingOpenVRModule.h" // For export macro #include "vtkVRControlsHelper.h" class VTKRENDERINGOPENVR_EXPORT vtkOpenVRControlsHelper : public vtkVRControlsHelper { public: /** * Instantiate the class. */ static vtkOpenVRControlsHelper* New(); vtkTypeMacro(vtkOpenVRControlsHelper, vtkVRControlsHelper); protected: vtkOpenVRControlsHelper() = default; ~vtkOpenVRControlsHelper() override = default; void InitControlPosition() override; private: vtkOpenVRControlsHelper(const vtkOpenVRControlsHelper&) = delete; void operator=(const vtkOpenVRControlsHelper&) = delete; }; #endif
420
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_HELPER_H_ #define CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_HELPER_H_ #include <memory> #include "base/macros.h" #include "base/time/time.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "url/gurl.h" namespace resource_coordinator { class PageResourceCoordinator; class ResourceCoordinatorTabHelper : public content::WebContentsObserver, public content::WebContentsUserData<ResourceCoordinatorTabHelper> { public: ~ResourceCoordinatorTabHelper() override; static bool ukm_recorder_initialized; static bool IsEnabled(); resource_coordinator::PageResourceCoordinator* page_resource_coordinator() { return page_resource_coordinator_.get(); } // WebContentsObserver implementation. void DidStartLoading() override; void DidReceiveResponse() override; void DidStopLoading() override; void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code, const base::string16& error_description) override; void OnVisibilityChanged(content::Visibility visibility) override; void WebContentsDestroyed() override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void TitleWasSet(content::NavigationEntry* entry) override; void DidUpdateFaviconURL( const std::vector<content::FaviconURL>& candidates) override; void UpdateUkmRecorder(int64_t navigation_id); ukm::SourceId ukm_source_id() const { return ukm_source_id_; } void SetUkmSourceIdForTest(ukm::SourceId id) { ukm_source_id_ = id; } private: explicit ResourceCoordinatorTabHelper(content::WebContents* web_contents); // Favicon, title are set the first time a page is loaded, thus we want to // ignore the very first update, and reset the flags when a non same-document // navigation finished in main frame. void ResetFlag(); friend class content::WebContentsUserData<ResourceCoordinatorTabHelper>; std::unique_ptr<resource_coordinator::PageResourceCoordinator> page_resource_coordinator_; ukm::SourceId ukm_source_id_ = ukm::kInvalidSourceId; // Favicon and title are set when a page is loaded, we only want to send // signals to GRC about title and favicon update from the previous title and // favicon, thus we want to ignore the very first update since it is always // supposed to happen. bool first_time_favicon_set_ = false; bool first_time_title_set_ = false; DISALLOW_COPY_AND_ASSIGN(ResourceCoordinatorTabHelper); }; } // namespace resource_coordinator #endif // CHROME_BROWSER_RESOURCE_COORDINATOR_TAB_HELPER_H_
961
777
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_PROFILES_NET_HTTP_SESSION_PARAMS_OBSERVER_H_ #define CHROME_BROWSER_PROFILES_NET_HTTP_SESSION_PARAMS_OBSERVER_H_ #include "base/callback_forward.h" #include "base/macros.h" #include "components/prefs/pref_member.h" class PrefService; namespace user_prefs { class PrefRegistrySyncable; } // Monitors network-related preferences for changes and applies them to // globally owned HttpNetworkSessions. // Profile-owned HttpNetworkSessions are taken care of by a // UpdateNetParamsCallback passed to the constructor. // The supplied PrefService must outlive this NetHttpSessionParamsObserver. // Must be used only on the UI thread. class NetHttpSessionParamsObserver { public: // Type of callback which will be called when QUIC is disabled. This // callback will be called on the IO thread. typedef base::Callback<void()> DisableQuicCallback; // |prefs| must be non-NULL and |*prefs| must outlive this. // |update_net_params_callback| will be invoked on the IO thread when an // observed network parmeter is changed. NetHttpSessionParamsObserver(PrefService* prefs, DisableQuicCallback disable_quic_callback); ~NetHttpSessionParamsObserver(); // Register user preferences which NetHttpSessionParamsObserver uses into // |registry|. static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); private: // Called on UI thread when an observed net pref changes void ApplySettings(); BooleanPrefMember quic_allowed_; DisableQuicCallback disable_quic_callback_; DISALLOW_COPY_AND_ASSIGN(NetHttpSessionParamsObserver); }; #endif // CHROME_BROWSER_PROFILES_NET_HTTP_SESSION_PARAMS_OBSERVER_H_
590
1,056
<filename>ide/spi.debugger.ui/test/unit/src/org/netbeans/api/debugger/DebuggerApiTestBase.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.api.debugger; import org.netbeans.junit.NbTestCase; import org.netbeans.api.debugger.test.TestDebuggerManagerListener; import java.beans.PropertyChangeEvent; import java.util.*; /** * A base utility class for debugger unit tests. * * @author <NAME> */ public abstract class DebuggerApiTestBase extends NbTestCase { protected DebuggerApiTestBase(String s) { super(s); } protected void assertInstanceOf(String msg, Object obj, Class aClass) { assertNotNull("An object is not an instance of "+aClass+", because it is 'null'.", obj); if (!aClass.isAssignableFrom(obj.getClass())) { fail(msg); } } protected static void printEvents(List events) { System.out.println("events: " + events.size()); for (Iterator i = events.iterator(); i.hasNext();) { TestDebuggerManagerListener.Event event1 = (TestDebuggerManagerListener.Event) i.next(); System.out.println("event: " + event1.getName()); if (event1.getParam() instanceof PropertyChangeEvent) { PropertyChangeEvent pce = (PropertyChangeEvent) event1.getParam(); System.out.println("PCS name: " + pce.getPropertyName()); } System.out.println(event1.getParam()); } } }
764
878
<filename>Source/gmenu.h //HEADER_GOES_HERE #ifndef __GMENU_H__ #define __GMENU_H__ extern void *optbar_cel; extern BOOLEAN mouseNavigation; // weak extern void *PentSpin_cel; extern void *BigTGold_cel; extern int dword_634474; // weak extern char byte_634478; // weak extern void(*dword_63447C)(TMenuItem *); extern TMenuItem *sgpCurrentMenu; // idb extern void *option_cel; extern int sgCurrentMenuIdx; // weak void gmenu_draw_pause(); void gmenu_print_text(int x, int y, char *pszStr); void FreeGMenu(); void gmenu_init_menu(); BOOL gmenu_exception(); void gmenu_call_proc(TMenuItem *pItem, void(*gmFunc)(TMenuItem *)); void gmenu_up_down(BOOL isDown); void gmenu_draw(); void gmenu_draw_menu_item(TMenuItem *pItem, int a2); void gmenu_clear_buffer(int x, int y, int width, int height); int gmenu_get_lfont(TMenuItem *pItem); BOOL gmenu_presskeys(int a1); void gmenu_left_right(BOOL isRight); BOOL gmenu_on_mouse_move(); BOOLEAN gmenu_valid_mouse_pos(int *plOffset); BOOL gmenu_left_mouse(BOOL isDown); void gmenu_enable(TMenuItem *pMenuItem, BOOL enable); void gmenu_slider_set(TMenuItem *pItem, int min, int max, int gamma); int gmenu_slider_get(TMenuItem *pItem, int min, int max); void gmenu_slider_steps(TMenuItem *pItem, int dwTicks); /* rdata */ extern const unsigned char lfontframe[127]; extern const unsigned char lfontkern[56]; #endif /* __GMENU_H__ */
539
15,337
<reponame>fairhopeweb/saleor # Generated by Django 3.2.6 on 2021-09-13 07:31 from django.db import migrations from ...order import FulfillmentStatus def increase_order_lines_quantity_for_waiting_fulfillments(apps, schema): """Increase order_line quantity fulfilled. Add quantity of each related fulfillment line which fulfillment is in WAITING_FOR_APPROVAL state. """ FulfillmentLine = apps.get_model("order", "FulfillmentLine") for fulfillment_line in FulfillmentLine.objects.filter( fulfillment__status=FulfillmentStatus.WAITING_FOR_APPROVAL ).iterator(): order_line = fulfillment_line.order_line order_line.quantity_fulfilled += fulfillment_line.quantity if order_line.quantity_fulfilled > order_line.quantity: order_line.quantity_fulfilled = order_line.quantity order_line.save(update_fields=["quantity_fulfilled"]) def decrease_order_lines_quantity_for_waiting_fulfillments(apps, schema): FulfillmentLine = apps.get_model("order", "FulfillmentLine") for fulfillment_line in FulfillmentLine.objects.filter( fulfillment__status=FulfillmentStatus.WAITING_FOR_APPROVAL ).iterator(): order_line = fulfillment_line.order_line order_line.quantity_fulfilled -= fulfillment_line.quantity if order_line.quantity_fulfilled < 0: order_line.quantity_fulfilled = 0 order_line.save(update_fields=["quantity_fulfilled"]) class Migration(migrations.Migration): dependencies = [ ("order", "0117_merge_20210903_1013"), ] operations = [ migrations.RunPython( increase_order_lines_quantity_for_waiting_fulfillments, reverse_code=decrease_order_lines_quantity_for_waiting_fulfillments, ), ]
693
4,071
<reponame>Ru-Xiang/x-deeplearning /* * \file in_parallel_gemm_test.cc * \brief The parallel gemm test unit, which only support Fix-sized bacthed gemm */ #include "gtest/gtest.h" #include "blaze/test/graph/pattern/pattern_test_common.h" namespace blaze { TEST(TestInOrder, All) { CheckPatternOutput( "./utest_data/graph/pattern/in_parallel/parallel_split_matmul_fusion.blaze", "./utest_data/graph/pattern/in_parallel/parallel_split_matmul_fusion_expected.blaze"); } } // namespace blaze
201
524
#!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE from ansible.module_utils.basic import * LAIN_TINYDNS_PREFIX_KEY = "/lain/config/domains" module = AnsibleModule( argument_spec=dict( domain=dict(required=True), record=dict(required=True), ), ) def main(): domain = module.params['domain'] record = module.params['record'] changed = False old_config = get_config(domain) if not old_config: if record == "": module.exit_json(changed=changed) changed = True else: if len(old_config['ips']) > 1: changed = True elif old_config['ips'][0] != record: changed = True if changed is False: module.exit_json(changed=changed) set_config(domain, record) module.exit_json(changed=changed) def get_config(domain): key = "%s/%s" % (LAIN_TINYDNS_PREFIX_KEY, domain) value = get_etcd_key(key) if value is None: return None elif value == "": return None data = json.loads(value) return data def set_config(domain, record): key = "%s/%s" % (LAIN_TINYDNS_PREFIX_KEY, domain) if record == "": rm_etcd_key(key) return data = {"ips": [record]} value = json.dumps(data) prev_value = get_etcd_key(key) set_etcd_key(key, value, prev_value) def get_etcd_key(key): p = Popen(['etcdctl', 'get', key], stdout=PIPE, stderr=PIPE) output, err = p.communicate() if p.returncode == 4: if "Key not found" in err: return None else: module.fail_json(msg=err) elif p.returncode != 0: module.fail_json(msg=err) return output.rstrip() def set_etcd_key(key, value, prev_value=None): if prev_value is not None: cmd = ['etcdctl', 'set', key, value, '--swap-with-value', prev_value] else: cmd = ['etcdctl', 'set', key, value] p = Popen(cmd, stdout=PIPE, stderr=PIPE) output, err = p.communicate() if p.returncode != 0: module.fail_json(msg=err) def rm_etcd_key(key): cmd = ['etcdctl', 'rm', key] p = Popen(cmd, stdout=PIPE, stderr=PIPE) output, err = p.communicate() if p.returncode != 0: module.fail_json(msg=err) if __name__ == '__main__': main()
1,067
3,071
/* * MIT License * * Copyright (c) 2010 - 2021 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors * * 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 oshi.hardware.platform.unix.aix; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Supplier; import oshi.annotation.concurrent.Immutable; import oshi.hardware.UsbDevice; import oshi.hardware.common.AbstractUsbDevice; import oshi.util.Constants; import oshi.util.ParseUtil; /** * AIX Usb Device */ @Immutable public class AixUsbDevice extends AbstractUsbDevice { public AixUsbDevice(String name, String vendor, String vendorId, String productId, String serialNumber, String uniqueDeviceId, List<UsbDevice> connectedDevices) { super(name, vendor, vendorId, productId, serialNumber, uniqueDeviceId, connectedDevices); } /** * Instantiates a list of {@link oshi.hardware.UsbDevice} objects, representing * devices connected via a usb port (including internal devices). * <p> * If the value of {@code tree} is true, the top level devices returned from * this method are the USB Controllers; connected hubs and devices in its device * tree share that controller's bandwidth. If the value of {@code tree} is * false, USB devices (not controllers) are listed in a single flat list. * * @param tree * If true, returns a list of controllers, which requires recursive * iteration of connected devices. If false, returns a flat list of * devices excluding controllers. * @param lscfg * A memoized lscfg list * @return a list of {@link oshi.hardware.UsbDevice} objects. */ public static List<UsbDevice> getUsbDevices(boolean tree, Supplier<List<String>> lscfg) { List<UsbDevice> deviceList = new ArrayList<>(); for (String line : lscfg.get()) { String s = line.trim(); if (s.startsWith("usb")) { String[] split = ParseUtil.whitespaces.split(s, 3); if (split.length == 3) { deviceList.add(new AixUsbDevice(split[2], Constants.UNKNOWN, Constants.UNKNOWN, Constants.UNKNOWN, Constants.UNKNOWN, split[0], Collections.emptyList())); } } } if (tree) { return Arrays.asList(new AixUsbDevice("USB Controller", "", "0000", "0000", "", "", deviceList)); } return deviceList; } }
1,277
3,227
<reponame>ffteja/cgal<filename>Surface_mesh_parameterization/examples/Surface_mesh_parameterization/iterative_authalic_parameterizer.cpp #include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Surface_mesh_parameterization/IO/File_off.h> #include <CGAL/Surface_mesh_parameterization/Square_border_parameterizer_3.h> #include <CGAL/Surface_mesh_parameterization/Circular_border_parameterizer_3.h> #include <CGAL/Surface_mesh_parameterization/Iterative_authalic_parameterizer_3.h> #include <CGAL/Polygon_mesh_processing/measure.h> #include <CGAL/Unique_hash_map.h> #include <cstdlib> #include <iostream> #include <fstream> typedef CGAL::Simple_cartesian<double> Kernel; typedef Kernel::Point_2 Point_2; typedef Kernel::Point_3 Point_3; typedef CGAL::Surface_mesh<Point_3> Surface_mesh; typedef boost::graph_traits<Surface_mesh>::vertex_descriptor vertex_descriptor; typedef boost::graph_traits<Surface_mesh>::halfedge_descriptor halfedge_descriptor; typedef CGAL::Unique_hash_map<vertex_descriptor, Point_2> UV_uhm; typedef boost::associative_property_map<UV_uhm> UV_pmap; namespace SMP = CGAL::Surface_mesh_parameterization; int main(int argc, char** argv) { std::ifstream in((argc>1) ? argv[1] : CGAL::data_file_path("meshes/nefertiti.off")); if(!in) { std::cerr << "Error: problem loading the input data" << std::endl; return EXIT_FAILURE; } Surface_mesh sm; in >> sm; halfedge_descriptor bhd = CGAL::Polygon_mesh_processing::longest_border(sm).first; // The 2D points of the uv parametrisation will be written into this map UV_uhm uv_uhm; UV_pmap uv_map(uv_uhm); typedef SMP::Circular_border_arc_length_parameterizer_3<Surface_mesh> Border_parameterizer; Border_parameterizer border_parameterizer; // the border parameterizer will automatically compute the corner vertices typedef SMP::Iterative_authalic_parameterizer_3<Surface_mesh, Border_parameterizer> Parameterizer; Parameterizer parameterizer(border_parameterizer); const unsigned int iterations = (argc > 2) ? std::atoi(argv[2]) : 15; SMP::Error_code err = parameterizer.parameterize(sm, bhd, uv_map, iterations); if(err != SMP::OK) { std::cerr << "Error: " << SMP::get_error_message(err) << std::endl; return EXIT_FAILURE; } std::ofstream out("iterative_result.off"); SMP::IO::output_uvmap_to_off(sm, bhd, uv_map, out); return EXIT_SUCCESS; }
1,103
852
<filename>L1Trigger/GlobalMuonTrigger/test/L1MuGMTDump.h //------------------------------------------------- // // \class L1MuGMTDump /** * Description: Dump GMT readout */ // // // <NAME> HEPHY Vienna // //-------------------------------------------------- #ifndef L1MU_GMT_DUMP_H #define L1MU_GMT_DUMP_H //--------------- // C++ Headers -- //--------------- #include <memory> //---------------------- // Base Class Headers -- //---------------------- #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/Event.h" #include "DataFormats/Common/interface/Handle.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ #include "DataFormats/L1GlobalMuonTrigger/interface/L1MuRegionalCand.h" #include "DataFormats/L1GlobalMuonTrigger/interface/L1MuGMTReadoutCollection.h" #include "FWCore/Utilities/interface/InputTag.h" // --------------------- // -- Class Interface -- // --------------------- const int MAXGEN = 10; const int MAXRPC = 20; const int MAXDTBX = 20; const int MAXCSC = 20; const int MAXGMT = 20; class L1MuGMTDump : public edm::EDAnalyzer { private: edm::InputTag m_inputTag; public: // constructor explicit L1MuGMTDump(const edm::ParameterSet&); // fill tree virtual void analyze(const edm::Event&, const edm::EventSetup&); virtual void endJob(); public: //GENERAL block int runn; int eventn; float weight; //generator block int ngen; float pxgen[MAXGEN]; float pygen[MAXGEN]; float pzgen[MAXGEN]; float ptgen[MAXGEN]; float etagen[MAXGEN]; float phigen[MAXGEN]; int chagen[MAXGEN]; float vxgen[MAXGEN]; float vygen[MAXGEN]; float vzgen[MAXGEN]; //DTBX Trigger block int ndt; int bxd[MAXDTBX]; float ptd[MAXDTBX]; int chad[MAXDTBX]; float etad[MAXDTBX]; int etafined[MAXDTBX]; float phid[MAXDTBX]; int quald[MAXDTBX]; int tclassd[MAXDTBX]; int ntsd[MAXDTBX]; //CSC Trigger block int ncsc; int bxc[MAXCSC]; float ptc[MAXCSC]; int chac[MAXCSC]; float etac[MAXCSC]; float phic[MAXCSC]; int qualc[MAXCSC]; int ntsc[MAXCSC]; int rankc[MAXCSC]; //RPCb Trigger int nrpcb; int bxrb[MAXRPC]; float ptrb[MAXRPC]; int charb[MAXRPC]; float etarb[MAXRPC]; float phirb[MAXRPC]; int qualrb[MAXRPC]; //RPCf Trigger int nrpcf; int bxrf[MAXRPC]; float ptrf[MAXRPC]; int charf[MAXRPC]; float etarf[MAXRPC]; float phirf[MAXRPC]; int qualrf[MAXRPC]; //Global Muon Trigger int ngmt; int bxg[MAXGMT]; float ptg[MAXGMT]; int chag[MAXGMT]; float etag[MAXGMT]; float phig[MAXGMT]; int qualg[MAXGMT]; int detg[MAXGMT]; int rankg[MAXGMT]; int isolg[MAXGMT]; int mipg[MAXGMT]; int datawordg[MAXGMT]; int idxRPCb[MAXGMT]; int idxRPCf[MAXGMT]; int idxDTBX[MAXGMT]; int idxCSC[MAXGMT]; }; #endif
1,208
473
<gh_stars>100-1000 #include "io.h" int main(void) { long long rd, rs, rt, result; rd = 0x0; rs = 0x246856789ABCDEF0; rt = 0x123456789ABCDEF0; result = 0x091A000000000000; __asm("subuh.ob %0, %1, %2\n\t" : "=r"(rd) : "r"(rs), "r"(rt) ); if (rd != result) { printf("subuh.ob error\n"); return -1; } rs = 0x246856789ABCDEF0; rt = 0x1131517191B1D1F1; result = 0x1b4f2d2d51637577; __asm("subuh.ob %0, %1, %2\n\t" : "=r"(rd) : "r"(rs), "r"(rt) ); if (rd != result) { printf("subuh.ob error\n"); return -1; } return 0; }
401
634
<reponame>vttranlina/james-project<filename>backends-common/cassandra/src/test/java/org/apache/james/backends/cassandra/CassandraClusterTest.java /**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.backends.cassandra; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; import org.apache.james.backends.cassandra.components.CassandraModule; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; class CassandraClusterTest { @RegisterExtension static DockerCassandraExtension cassandraExtension = new DockerCassandraExtension(); CassandraCluster connection; @BeforeEach void setUp() { connection = methodToDetectInStackTrace(); } CassandraCluster methodToDetectInStackTrace() { return createCluster(); } @AfterEach void tearDown() { connection.close(); } private CassandraCluster createCluster() { return CassandraCluster.create(CassandraModule.builder().build(), cassandraExtension.getDockerCassandra().getHost()); } @Test void creatingTwoClustersShouldThrow() { assertThatThrownBy(this::createCluster).isInstanceOf(IllegalStateException.class); } @Test void creatingTwoClustersSequentiallyShouldNotThrow() { connection.close(); assertThatCode(() -> { try (CassandraCluster cluster = createCluster()) { // Trigger autoclose } }).doesNotThrowAnyException(); } @Test void closingAnAlreadyClosedConnectionShouldNotCloseANewOne() { connection.close(); try (CassandraCluster cnx2 = createCluster()) { connection.close(); assertThatThrownBy(this::createCluster).isInstanceOf(IllegalStateException.class); } } @Test void creatingTwoClustersShouldProvideFirstCreationStacktrace() { assertThatThrownBy(this::createCluster).hasStackTraceContaining("methodToDetectInStackTrace"); } }
1,227
764
<reponame>641589523/token-profile<gh_stars>100-1000 {"symbol": "DEVE","address": "0xfdb615d6A15F929dDabc6b83A4f1Cf9d361b064E","overview":{"en": "Divert Finance aims to offer an efficient mining project."},"email": "<EMAIL>","website": "https://divertfinance.com/","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/divertfinance","telegram": "https://t.me/DivertCommunity","github": "https://github.com/divertfinance/DEVE"}}
164
1,746
/* * Copyright (c) 2010-2020, sik<EMAIL>, sikulix.com - MIT license */ package org.sikuli.support.animators; import java.util.Date; public class AnimatorPulse implements Animator { protected float _v1, _v2; protected long _interval, _totalMS; protected boolean _running; protected long _begin_time = -1; public AnimatorPulse(float v1, float v2, long interval, long totalMS) { _v1 = v1; _v2 = v2; _interval = interval; _totalMS = totalMS; _running = true; } @Override public float step() { if (_begin_time == -1) { _begin_time = (new Date()).getTime(); return _v1; } long now = (new Date()).getTime(); long delta = now - _begin_time; if (delta >= _totalMS) { _running = false; } if ((delta / _interval) % 2 == 0) { return _v1; } else { return _v2; } } @Override public boolean running() { return _running; } }
385
1,085
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.concurrent; import java.util.concurrent.atomic.AtomicBoolean; /** * Ensures no more than a single copy of this runnable is run at any one time. */ public class SingletonRunnable implements Runnable { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SingletonRunnable.class); private final Runnable delegate; private final AtomicBoolean running = new AtomicBoolean(false); public SingletonRunnable(Runnable runnable) { this.delegate = runnable; } @Override public void run() { if(!running.compareAndSet(false, true)) { logger.info("Task {} already running, skipping secondary execution.", delegate.toString()); return; } try { delegate.run(); } finally { running.compareAndSet(true, false); } } @Override public String toString() { return delegate.toString(); } public static Runnable of(final Runnable delegate, final String name) { return new SingletonRunnable(delegate); } }
505
348
{"nom":"Courcelles-en-Montagne","dpt":"Haute-Marne","inscrits":82,"abs":20,"votants":62,"blancs":9,"nuls":4,"exp":49,"res":[{"panneau":"1","voix":25},{"panneau":"2","voix":24}]}
76
423
import csv """ Open <path> as sites.csv file. URL = row[1] return: row[1] = {'status': '', 'quant': '', 'pixel': '', 'ganal': ''} """ def open_sites_csv(path): sites_info = dict() with open(path) as csvfile: #skip the header next(csvfile) csvreader = csv.reader(csvfile, dialect='excel') for row in csvreader: info = {'status': '', 'quant': '', 'pixel': '', 'ganal': ''} sites_info[row[1]] = info return sites_info """ Outputs <sites_info> to CSV file <outfile> row: site, status, ganal, pixel, quant """ def output_sites_information(sites_info, outfile): with open(outfile, 'w', newline='') as csvfile: output = csv.writer(csvfile, dialect='excel') output.writerow(['site', 'status-code', 'google-analytics', 'fb-pixel', 'quantserve']) for key in sites_info: output.writerow([key, sites_info[key]['status'], sites_info[key]['ganal'], sites_info[key]['pixel'], sites_info[key]['quant']]) """ Open <path> as sites-information.csv file. URL = row[1] return: row[1] = {'status': '***', 'quant': '****', 'pixel': '****', 'ganal': '****'} """ def open_sites_information(path): sites_info = dict() with open(path) as csvfile: #skip the header line in the file before reading in rows. next(csvfile) csvreader = csv.reader(csvfile, dialect='excel') for row in csvreader: info = {'status': [1], 'quant': row[4], 'pixel': row[3], 'ganal': row[2]} sites_info[row[0]] = info return sites_info """ Open publicWWW outputfile <outfile>: output csv format: site, linked linked linked site2, site2_linked site2_linked site2_linked """ def output_publicwww(sites_linked, outfile): with open(outfile, 'w', newline='') as csvfile: output = csv.writer(csvfile, dialect='excel') output.writerow(["site", "links"]) for key in sites_linked: output.writerow([key, " ".join(sites_linked[key])]) return """ Read output of output_lynx_map and parse return: site => link link link """ def open_lynx_map(path): link_map = dict() with open(path, 'r') as csvfile: #skip the 'domain' header next(csvfile) csvreader = csv.reader(csvfile, dialect='excel') for row in csvreader: site = row[0] links = row[1].split(' ') link_map[site] = links return link_map """ Output lynx site->links map to csv file. output: row: site, link link link row: site2, link link link """ def output_lynx_map(path, site_map): with open(path, 'w', newline='\n') as csvfile: output = csv.writer(csvfile, dialect='excel') output.writerow(["site", "links"]) for site in site_map: output.writerow([site, " ".join(site_map[site])])
1,345
424
package com.zzx.service; import com.zzx.config.JwtConfig; import com.zzx.dao.MessageDao; import com.zzx.dao.UserDao; import com.zzx.model.pojo.Message; import com.zzx.model.pojo.User; import com.zzx.utils.DateUtil; import com.zzx.utils.FormatUtil; import com.zzx.utils.JwtTokenUtil; import com.zzx.utils.RequestUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.List; @Service public class MessageService { @Autowired private MessageDao messageDao; @Autowired private UserDao userDao; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private RequestUtil requestUtil; @Autowired private JwtConfig jwtConfig; @Autowired private HttpServletRequest request; @Autowired private FormatUtil formatUtil; @Autowired private DateUtil dateUtil; /** * 留言 * * @param messageBody */ public void saveMessage(String messageBody) { String name = null; try { User user = userDao.findUserByName(jwtTokenUtil.getUsernameFromRequest(request));//已登录 name = user.getName(); } catch (NullPointerException e) { //token 校验失败 游客身份 name = requestUtil.getIpAddress(request); } //查询此ip/name 是否留言过 if (messageDao.findMessageByName(name) != null) { throw new RuntimeException("你已留过言"); } Message message = new Message(); message.setName(name); message.setBody(messageBody); message.setTime(dateUtil.getCurrentDate()); messageDao.saveMessage(message); } /** * 根据id删除留言 * * @param messageId */ public void deleteMessageById(Integer messageId) { messageDao.deleteMessageById(messageId); } /** * 获取留言数量 * * @return */ public Long getMessageCount() { return messageDao.getMessageCount(); } public List<Message> findMessage(Integer page, Integer showCount) { List<Message> messages = messageDao.findMessage((page - 1) * showCount, showCount); for (Message message : messages) { String ip = message.getName(); if (formatUtil.checkIP(ip)) {//该name是ip //保留ip 前16位 ( [127.0].0.1 ) [] 内为前16位 String[] subStrs = ip.split("\\."); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < subStrs.length && i < 2; i++) { buffer.append(subStrs[i]).append("."); } buffer.append("*.*"); message.setName(buffer.toString()); } } return messages; } }
1,327
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/iLifeSlideshow.framework/iLifeSlideshow */ @class NSArray, NSSet; @protocol MCFilterSupport @property(readonly, assign) NSSet *filters; @property(readonly, assign) NSArray *orderedFilters; - (void)initFiltersWithImprints:(id)imprints; - (void)demolishFilters; - (id)imprintsForFilters; - (unsigned)countOfFilters; - (id)filterAtIndex:(unsigned)index; - (id)addFilterWithFilterID:(id)filterID; - (id)insertFilterWithFilterID:(id)filterID atIndex:(unsigned)index; - (void)removeFiltersAtIndices:(id)indices; - (void)removeAllFilters; - (void)moveFiltersAtIndices:(id)indices toIndex:(unsigned)index; - (void)observeFilter:(id)filter; - (void)unobserveFilter:(id)filter; // declared property getter: - (id)orderedFilters; // declared property getter: - (id)filters; @end
308
582
/******************************************************************************* * Copyright (c) 2003, 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.draw2d.graph; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * Assigns a valid rank assignment to all nodes based on their edges. The * assignment is not optimal in that it does not provide the minimum global * length of edge lengths. * * @author <NAME> * @since 2.1.2 */ @SuppressWarnings({"rawtypes", "unchecked", "deprecation"}) class InitialRankSolver extends GraphVisitor { protected DirectedGraph graph; protected EdgeList candidates = new EdgeList(); protected NodeList members = new NodeList(); @Override public void visit(DirectedGraph graph) { this.graph = graph; graph.edges.resetFlags(false); graph.nodes.resetFlags(); solve(); } protected void solve() { if (graph.nodes.size() == 0) return; NodeList unranked = new NodeList(graph.nodes); NodeList rankMe = new NodeList(); Node node; int i; while (!unranked.isEmpty()) { rankMe.clear(); for (i = 0; i < unranked.size();) { node = unranked.getNode(i); if (node.incoming.isCompletelyFlagged()) { rankMe.add(node); unranked.remove(i); } else i++; } if (rankMe.size() == 0) throw new RuntimeException("Cycle detected in graph"); //$NON-NLS-1$ for (i = 0; i < rankMe.size(); i++) { node = rankMe.getNode(i); assignMinimumRank(node); node.outgoing.setFlags(true); } } connectForest(); } private void connectForest() { List forest = new ArrayList(); Stack stack = new Stack(); NodeList tree; graph.nodes.resetFlags(); for (int i = 0; i < graph.nodes.size(); i++) { Node neighbor, n = graph.nodes.getNode(i); if (n.flag) continue; tree = new NodeList(); stack.push(n); while (!stack.isEmpty()) { n = (Node) stack.pop(); n.flag = true; tree.add(n); for (int s = 0; s < n.incoming.size(); s++) { neighbor = n.incoming.getEdge(s).source; if (!neighbor.flag) stack.push(neighbor); } for (int s = 0; s < n.outgoing.size(); s++) { neighbor = n.outgoing.getEdge(s).target; if (!neighbor.flag) stack.push(neighbor); } } forest.add(tree); } if (forest.size() > 1) { // connect the forest graph.forestRoot = new Node("the forest root"); //$NON-NLS-1$ graph.nodes.add(graph.forestRoot); for (int i = 0; i < forest.size(); i++) { tree = (NodeList) forest.get(i); graph.edges.add(new Edge(graph.forestRoot, tree.getNode(0), 0, 0)); } } } private void assignMinimumRank(Node node) { int rank = 0; Edge e; for (int i1 = 0; i1 < node.incoming.size(); i1++) { e = node.incoming.getEdge(i1); rank = Math.max(rank, e.delta + e.source.rank); } node.rank = rank; } }
1,898
550
<gh_stars>100-1000 /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk.audiogen.voices; import com.google.android.apps.forscience.whistlepunk.audiogen.JsynUnitVoiceAdapter; import com.jsyn.Synthesizer; import com.softsynth.math.AudioMath; import com.softsynth.shared.time.TimeStamp; /** * Base class to adapt the SimpleJsynUnitVoice to the SimpleJsynAudioGenerator using a scale. * * <p>Adapt the SimpleJsynUnitVoice to the SimpleJsynAudioGenerator. This implementation does * nothing. */ public class DataToScalePitchSimpleJsynUnitVoiceAdapter extends JsynUnitVoiceAdapter { protected final int[] pitches; public DataToScalePitchSimpleJsynUnitVoiceAdapter( Synthesizer synth, int[] scale, int pitchMin, int pitchMax) { pitches = PitchGenerator.generatePitches(scale, pitchMin, pitchMax); voice = new SimpleJsynUnitVoice(); synth.add(voice); } public void noteOn(double value, double min, double max, TimeStamp timeStamp) { // Default implementation (or any implementation with no pitches) does nothing. if (pitches.length == 0) { return; } // Range checking, in case min or max is higher or lower than value (respectively). if (value < min) { value = min; } if (value > max) { value = max; } int index = (int) Math.floor((value - min) / (max - min) * (pitches.length - 1)); double freq = AudioMath.pitchToFrequency(pitches[index]); voice.noteOn(freq, AMP_VALUE, timeStamp); } }
671
572
<filename>codigo/Live143/live_143/src/live_143/app.py import toga from functools import partial from toga.style import Pack from toga.style.pack import COLUMN, ROW def volta_box(window, widget): window.content = window.content def meu_box(window, widget): box = toga.Box() box.add( toga.Button('voltar', on_press=partial(volta_box, window)) ) window.content = box class live_143(toga.App): def startup(self): self.main_window = toga.MainWindow(title=self.formal_name) main_box = toga.Box() main_box.add( toga.Label( 'Batatinha Frita', style=Pack( font_size=50, padding=50 ) ), toga.TextInput(placeholder='Sua batata preferida'), toga.Button('Click me', on_press=partial(meu_box, self.main_window)), ) main_box.style.update( direction=COLUMN ) self.main_window.content = main_box self.main_window.show() def main(): return live_143()
554
855
// Copyright 2018 Google Inc. All Rights Reserved. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #ifndef PIK_SIMD_COMPILER_SPECIFIC_H_ #define PIK_SIMD_COMPILER_SPECIFIC_H_ // Compiler-specific includes and definitions. // SIMD_COMPILER expands to one of the following: #define SIMD_COMPILER_CLANG 1 #define SIMD_COMPILER_GCC 2 #define SIMD_COMPILER_MSVC 3 #ifdef _MSC_VER #define SIMD_COMPILER SIMD_COMPILER_MSVC #elif defined(__clang__) #define SIMD_COMPILER SIMD_COMPILER_CLANG #elif defined(__GNUC__) #define SIMD_COMPILER SIMD_COMPILER_GCC #else #error "Unsupported compiler" #endif #if SIMD_COMPILER == SIMD_COMPILER_MSVC #include <intrin.h> #define SIMD_RESTRICT __restrict #define SIMD_INLINE __forceinline #define SIMD_NOINLINE __declspec(noinline) #define SIMD_LIKELY(expr) expr #define SIMD_TRAP __debugbreak #define SIMD_TARGET_ATTR(feature_str) #define SIMD_DIAGNOSTICS(tokens) __pragma(warning(tokens)) #define SIMD_DIAGNOSTICS_OFF(msc, gcc) SIMD_DIAGNOSTICS(msc) #else #define SIMD_RESTRICT __restrict__ #define SIMD_INLINE \ inline __attribute__((always_inline)) __attribute__((flatten)) #define SIMD_NOINLINE inline __attribute__((noinline)) #define SIMD_LIKELY(expr) __builtin_expect(!!(expr), 1) #define SIMD_TRAP __builtin_trap #define SIMD_TARGET_ATTR(feature_str) __attribute__((target(feature_str))) #define SIMD_PRAGMA(tokens) _Pragma(#tokens) #define SIMD_DIAGNOSTICS(tokens) SIMD_PRAGMA(GCC diagnostic tokens) #define SIMD_DIAGNOSTICS_OFF(msc, gcc) SIMD_DIAGNOSTICS(gcc) #endif #endif // PIK_SIMD_COMPILER_SPECIFIC_H_
676
2,180
<filename>modules/src/main/java/org/archive/modules/fetcher/FetchFTP.java /* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.modules.fetcher; import static org.archive.modules.CoreAttributeConstants.A_FTP_CONTROL_CONVERSATION; import static org.archive.modules.CoreAttributeConstants.A_FTP_FETCH_STATUS; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URLEncoder; import java.net.UnknownHostException; import java.security.MessageDigest; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.SocketFactory; import org.apache.commons.httpclient.URIException; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPCommand; import org.archive.io.RecordingInputStream; import org.archive.io.ReplayCharSequence; import org.archive.modules.CrawlURI; import org.archive.modules.Processor; import org.archive.modules.extractor.Hop; import org.archive.modules.extractor.LinkContext; import org.archive.net.ClientFTP; import org.archive.net.UURI; import org.archive.net.UURIFactory; import org.archive.util.Recorder; /** * Fetches documents and directory listings using FTP. This class will also * try to extract FTP "links" from directory listings. For this class to * archive a directory listing, the remote FTP server must support the NLIST * command. Most modern FTP servers should. * * @author pjack * */ public class FetchFTP extends Processor { @SuppressWarnings("unused") private static final long serialVersionUID = 1L; /** Logger for this class. */ private static Logger logger = Logger.getLogger(FetchFTP.class.getName()); /** Pattern for matching directory entries. */ private static Pattern DIR = Pattern.compile("(.+)$", Pattern.MULTILINE); { setUsername("anonymous"); } public String getUsername() { return (String) kp.get("username"); } /** * The username to send to FTP servers. By convention, the default value of * "anonymous" is used for publicly available FTP sites. */ public void setUsername(String username) { kp.put("username",username); } { setPassword("password"); } public String getPassword() { return (String) kp.get("password"); } /** * The password to send to FTP servers. By convention, anonymous users send * their email address in this field. */ public void setPassword(String pw) { kp.put("password",pw); } { setExtractFromDirs(true); } /** * Returns the <code>extract.from.dirs</code> attribute for this * <code>FetchFTP</code> and the given curi. * * @return that curi's <code>extract.from.dirs</code> */ public boolean getExtractFromDirs() { return (Boolean) kp.get("extractFromDirs"); } /** * Set to true to extract further URIs from FTP directories. Default is * true. */ public void setExtractFromDirs(boolean extractFromDirs) { kp.put("extractFromDirs",extractFromDirs); } { setExtractParent(true); } /** * Returns the <code>extract.parent</code> attribute for this * <code>FetchFTP</code> and the given curi. * * @return that curi's <code>extract-parent</code> */ public boolean getExtractParent() { return (Boolean) kp.get("extractParent"); } /** * Set to true to extract the parent URI from all FTP URIs. Default is true. */ public void setExtractParent(boolean extractParent) { kp.put("extractParent",extractParent); } { setDigestContent(true); } public boolean getDigestContent() { return (Boolean) kp.get("digestContent"); } /** * Whether or not to perform an on-the-fly digest hash of retrieved * content-bodies. */ public void setDigestContent(boolean digest) { kp.put("digestContent",digest); } /** * Which algorithm (for example MD5 or SHA-1) to use to perform an * on-the-fly digest hash of retrieved content-bodies. */ protected String digestAlgorithm = "sha1"; public String getDigestAlgorithm() { return digestAlgorithm; } public void setDigestAlgorithm(String digestAlgorithm) { this.digestAlgorithm = digestAlgorithm; } { setMaxLengthBytes(0L); // no limit } public long getMaxLengthBytes() { return (Long) kp.get("maxLengthBytes"); } /** * Maximum length in bytes to fetch. Fetch is truncated at this length. A * value of 0 means no limit. */ public void setMaxLengthBytes(long timeout) { kp.put("maxLengthBytes",timeout); } { setMaxFetchKBSec(0); // no limit } public int getMaxFetchKBSec() { return (Integer) kp.get("maxFetchKBSec"); } /** * The maximum KB/sec to use when fetching data from a server. The default * of 0 means no maximum. */ public void setMaxFetchKBSec(int rate) { kp.put("maxFetchKBSec",rate); } { setTimeoutSeconds(20*60); // 20 minutes } public int getTimeoutSeconds() { return (Integer) kp.get("timeoutSeconds"); } /** * If the fetch is not completed in this number of seconds, give up (and * retry later). */ public void setTimeoutSeconds(int timeout) { kp.put("timeoutSeconds",timeout); } { setSoTimeoutMs(20*1000); // 20 seconds } public int getSoTimeoutMs() { return (Integer) kp.get("soTimeoutMs"); } /** * If the socket is unresponsive for this number of milliseconds, give up. * Set to zero for no timeout (Not. recommended. Could hang a thread on an * unresponsive server). This timeout is used timing out socket opens and * for timing out each socket read. Make sure this value is &lt; * {@link #TIMEOUT_SECONDS} for optimal configuration: ensures at least one * retry read. */ public void setSoTimeoutMs(int timeout) { kp.put("soTimeoutMs",timeout); } /** * Constructs a new <code>FetchFTP</code>. */ public FetchFTP() { } @Override protected boolean shouldProcess(CrawlURI curi) { if (!curi.getUURI().getScheme().equals("ftp")) { return false; } return true; } /** * Processes the given URI. If the given URI is not an FTP URI, then * this method does nothing. Otherwise an attempt is made to connect * to the FTP server. * * <p>If the connection is successful, an attempt will be made to CD to * the path specified in the URI. If the remote CD command succeeds, * then it is assumed that the URI represents a directory. If the * CD command fails, then it is assumed that the URI represents * a file. * * <p>For directories, the directory listing will be fetched using * the FTP LIST command, and saved to the HttpRecorder. If the * <code>extract.from.dirs</code> attribute is set to true, then * the files in the fetched list will be added to the curi as * extracted FTP links. (It was easier to do that here, rather * than writing a separate FTPExtractor.) * * <p>For files, the file will be fetched using the FTP RETR * command, and saved to the HttpRecorder. * * <p>All file transfers (including directory listings) occur using * Binary mode transfer. Also, the local passive transfer mode * is always used, to play well with firewalls. * * @param curi the curi to process * @throws InterruptedException if the thread is interrupted during * processing */ @Override protected void innerProcess(CrawlURI curi) throws InterruptedException { curi.setFetchBeginTime(System.currentTimeMillis()); ClientFTP client = new ClientFTP(); Recorder recorder = curi.getRecorder(); try { if (logger.isLoggable(Level.FINE)) { logger.fine("attempting to fetch ftp uri: " + curi); } fetch(curi, client, recorder); } catch (IOException e) { if (logger.isLoggable(Level.INFO)) { logger.info(curi + ": " + e); } curi.getNonFatalFailures().add(e); curi.setFetchStatus(FetchStatusCodes.S_CONNECT_FAILED); } finally { disconnect(client); curi.setFetchCompletedTime(System.currentTimeMillis()); curi.getData().put(A_FTP_CONTROL_CONVERSATION, client.getControlConversation()); } } /** * A {@link SocketFactory} much like javax.net.DefaultSocketFactory, * except that the createSocket() methods that open connections support a * connect timeout. */ public class SocketFactoryWithTimeout extends SocketFactory { protected int connectTimeoutMs = 0; public int getConnectTimeoutMs() { return connectTimeoutMs; } public void setConnectTimeoutMs(int connectTimeoutMs) { this.connectTimeoutMs = connectTimeoutMs; } public Socket createSocket() { return new Socket(); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { Socket sock = createSocket(); sock.connect(new InetSocketAddress(host, port), connectTimeoutMs); return sock; } public Socket createSocket(InetAddress host, int port) throws IOException { Socket sock = createSocket(); sock.connect(new InetSocketAddress(host, port), connectTimeoutMs); return sock; } public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { Socket sock = createSocket(); sock.bind(new InetSocketAddress(localHost, localPort)); sock.connect(new InetSocketAddress(host, port), connectTimeoutMs); return sock; } public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { Socket sock = createSocket(); sock.bind(new InetSocketAddress(localAddress, localPort)); sock.connect(new InetSocketAddress(address, port), connectTimeoutMs); return sock; } } protected SocketFactoryWithTimeout socketFactory; /** * Fetches a document from an FTP server. * * @param curi the URI of the document to fetch * @param client the FTPClient to use for the fetch * @param recorder the recorder to preserve the document in * @throws IOException if a network or protocol error occurs * @throws InterruptedException if the thread is interrupted */ private void fetch(CrawlURI curi, ClientFTP client, Recorder recorder) throws IOException, InterruptedException { // Connect to the FTP server. UURI uuri = curi.getUURI(); int port = uuri.getPort(); if (port == -1) { port = 21; } if (socketFactory == null) { socketFactory = new SocketFactoryWithTimeout(); } socketFactory.setConnectTimeoutMs(getSoTimeoutMs()); client.setSocketFactory(socketFactory); client.setConnectTimeout(getSoTimeoutMs()); client.setDefaultTimeout(getSoTimeoutMs()); client.setDataTimeout(getSoTimeoutMs()); client.connect(uuri.getHost(), port); client.setSoTimeout(getSoTimeoutMs()); // must be after connect() // Authenticate. String[] auth = getAuth(curi); client.login(auth[0], auth[1]); // The given resource may or may not be a directory. // To figure out which is which, execute a CD command to // the UURI's path. If CD works, it's a directory. boolean isDirectory = client.changeWorkingDirectory(uuri.getPath()); // Get a data socket. This will either be the result of a NLST // command for a directory, or a RETR command for a file. int command; String path; if (isDirectory) { curi.getAnnotations().add("ftpDirectoryList"); command = FTPCommand.NLST; client.setFileType(FTP.ASCII_FILE_TYPE); path = "."; } else { command = FTPCommand.RETR; client.setFileType(FTP.BINARY_FILE_TYPE); path = uuri.getPath(); } client.enterLocalPassiveMode(); Socket socket = null; try { socket = client.openDataConnection(command, path); // if "227 Entering Passive Mode" these will get reset later curi.setFetchStatus(client.getReplyCode()); curi.getData().put(A_FTP_FETCH_STATUS, client.getReplyStrings()[0]); } catch (IOException e) { // try it again, see AbstractFrontier.needsRetrying() curi.setFetchStatus(FetchStatusCodes.S_CONNECT_LOST); } // Save the streams in the CURI, where downstream processors // expect to find them. if (socket != null) { if (socket.getSoTimeout() != getSoTimeoutMs()) { logger.warning("data socket timeout " + socket.getSoTimeout() + "ms is not expected value " + getSoTimeoutMs() + "ms"); } // Shall we get a digest on the content downloaded? boolean digestContent = getDigestContent(); String algorithm = null; if (digestContent) { algorithm = getDigestAlgorithm(); recorder.getRecordedInput().setDigest(algorithm); recorder.getRecordedInput().startDigest(); } else { // clear recorder.getRecordedInput().setDigest((MessageDigest)null); } curi.setServerIP(socket.getInetAddress().getHostAddress()); try { saveToRecorder(curi, socket, recorder); } finally { recorder.close(); client.closeDataConnection(); // does socket.close() curi.setContentSize(recorder.getRecordedInput().getSize()); // "226 Transfer complete." client.getReply(); curi.setFetchStatus(client.getReplyCode()); curi.getData().put(A_FTP_FETCH_STATUS, client.getReplyStrings()[0]); if (isDirectory) { curi.setContentType("text/plain"); } else { curi.setContentType("application/octet-stream"); } if (logger.isLoggable(Level.FINE)) { logger.fine("read " + recorder.getRecordedInput().getSize() + " bytes from ftp data socket"); } if (digestContent) { curi.setContentDigest(algorithm, recorder.getRecordedInput().getDigestValue()); } } if (isDirectory) { extract(curi, recorder); } } else { // no data - without this, content size is -1 curi.setContentSize(0); } addParent(curi); } /** * Saves the given socket to the given recorder. * * @param curi the curi that owns the recorder * @param socket the socket whose streams to save * @param recorder the recorder to save them to * @throws IOException if a network or file error occurs * @throws InterruptedException if the thread is interrupted */ private void saveToRecorder(CrawlURI curi, Socket socket, Recorder recorder) throws IOException, InterruptedException { recorder.inputWrap(socket.getInputStream()); recorder.outputWrap(socket.getOutputStream()); recorder.markContentBegin(); // Read the remote file/dir listing in its entirety. long softMax = 0; long hardMax = getMaxLengthBytes(); long timeout = (long)getTimeoutSeconds() * 1000L; int maxRate = getMaxFetchKBSec(); RecordingInputStream input = recorder.getRecordedInput(); input.setLimits(hardMax, timeout, maxRate); input.readFullyOrUntil(softMax); } /** * Extract FTP links in a directory listing. * The listing must already be saved to the given recorder. * * @param curi The curi to save extracted links to * @param recorder The recorder containing the directory listing */ private void extract(CrawlURI curi, Recorder recorder) { if (!getExtractFromDirs()) { return; } ReplayCharSequence seq = null; try { seq = recorder.getContentReplayCharSequence(); extract(curi, seq); } catch (IOException e) { logger.log(Level.SEVERE, "IO error during extraction.", e); } catch (RuntimeException e) { logger.log(Level.SEVERE, "IO error during extraction.", e); } finally { close(seq); } } /** * Extracts FTP links in a directory listing. * * @param curi The curi to save extracted links to * @param dir The directory listing to extract links from * @throws URIException if an extracted link is invalid */ private void extract(CrawlURI curi, ReplayCharSequence dir) { logger.log(Level.FINEST, "Extracting URIs from FTP directory."); Matcher matcher = DIR.matcher(dir); while (matcher.find()) { String file = matcher.group(1); addExtracted(curi, file); } } /** * Adds an extracted filename to the curi. A new URI will be formed * by taking the given curi (which should represent the directory the * file lives in) and appending the file. * * @param curi the curi to store the discovered link in * @param file the filename of the discovered link */ private void addExtracted(CrawlURI curi, String file) { try { file = URLEncoder.encode(file, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "Found " + file); } String base = curi.toString(); if (base.endsWith("/")) { base = base.substring(0, base.length() - 1); } try { UURI n = UURIFactory.getInstance(base + "/" + file); CrawlURI link = curi.createCrawlURI(n, LinkContext.NAVLINK_MISC, Hop.NAVLINK); curi.getOutLinks().add(link); } catch (URIException e) { logger.log(Level.WARNING, "URI error during extraction.", e); } } /** * Extracts the parent URI from the given curi, then adds that parent * URI as a discovered link to the curi. * * <p>If the <code>extract-parent</code> attribute is false, then this * method does nothing. Also, if the path of the given curi is * <code>/</code>, then this method does nothing. * * <p>Otherwise the parent is determined by eliminated the lowest part * of the URI's path. Eg, the parent of <code>ftp://foo.com/one/two</code> * is <code>ftp://foo.com/one</code>. * * @param curi the curi whose parent to add */ private void addParent(CrawlURI curi) { if (!getExtractParent()) { return; } UURI uuri = curi.getUURI(); try { if (uuri.getPath().equals("/")) { // There's no parent to add. return; } String scheme = uuri.getScheme(); String auth = uuri.getEscapedAuthority(); String path = uuri.getEscapedCurrentHierPath(); UURI parent = UURIFactory.getInstance(scheme + "://" + auth + path); CrawlURI link = curi.createCrawlURI(parent, LinkContext.NAVLINK_MISC, Hop.NAVLINK); curi.getOutLinks().add(link); } catch (URIException e) { logger.log(Level.WARNING, "URI error during extraction.", e); } } /** * Returns the username and password for the given URI. This method * always returns an array of length 2. The first element in the returned * array is the username for the URI, and the second element is the * password. * * <p>If the URI itself contains the username and password (i.e., it looks * like <code>ftp://username:password@host/path</code>) then that username * and password are returned. * * <p>Otherwise the settings system is probed for the <code>username</code> * and <code>password</code> attributes for this <code>FTPFetch</code> * and the given <code>curi</code> context. The values of those * attributes are then returned. * * @param curi the curi whose username and password to return * @return an array containing the username and password */ private String[] getAuth(CrawlURI curi) { String[] result = new String[2]; UURI uuri = curi.getUURI(); String userinfo; try { userinfo = uuri.getUserinfo(); } catch (URIException e) { assert false; logger.finest("getUserinfo raised URIException."); userinfo = null; } if (userinfo != null) { int p = userinfo.indexOf(':'); if (p > 0) { result[0] = userinfo.substring(0,p); result[1] = userinfo.substring(p + 1); return result; } } result[0] = getUsername(); result[1] = getPassword(); return result; } /** * Quietly closes the given sequence. * If an IOException is raised, this method logs it as a warning. * * @param seq the sequence to close */ private static void close(ReplayCharSequence seq) { if (seq == null) { return; } try { seq.close(); } catch (IOException e) { logger.log(Level.WARNING, "IO error closing ReplayCharSequence.", e); } } /** * Quietly disconnects from the given FTP client. * If an IOException is raised, this method logs it as a warning. * * @param client the client to disconnect */ private static void disconnect(ClientFTP client) { if (client.isConnected()) try { client.logout(); } catch (IOException e) { } if (client.isConnected()) try { client.disconnect(); } catch (IOException e) { logger.warning("Could not disconnect from FTP client: " + e); } } }
10,173
1,444
package mage.client.table; /** * @author JayDi85 */ public class ColumnInfo { private final Integer index; private final Integer width; private final String headerName; private final String headerHint; private final Class colClass; public ColumnInfo(Integer index, Integer width, Class colClass, String headerName, String headerHint) { this.index = index; this.width = width; this.colClass = colClass; this.headerName = headerName; this.headerHint = headerHint; } public Integer getIndex() { return index; } public Integer getWidth() { return width; } public String getHeaderName() { return headerName; } public String getHeaderHint() { return headerHint; } public Class getColClass() { return colClass; } }
327
1,647
<filename>pythran/tests/cases/ramsurf.py #pythran export deriv(int, float, float, complex list, complex list, complex list, float list list, float) import cmath #This subroutine finds a root of a polynomial of degree n > 2 # by Laguerre's method. def guerre(a,n,z,err,nter): az = [complex(0,0) for i in range(50)] azz = [complex(0,0) for i in range(50)] ci=complex(0.0,1.0) eps=1.0e-20 # The coefficients of p'[z] and p''[z]. for i in range(1,n+1): az[i-1]=float(i)*a[i] for i in range(1,n): azz[i-1]=float(i)*az[i] dz=err+1 itera=0 jter=0 while abs(dz)>err and itera<nter: p=a[n-1]+a[n]*z for i in range(n-1,0,-1): p=a[i-1]+z*p if abs(p)<eps: return z pz=az[n-2]+az[n-1]*z for i in range(n-2,0,-1): pz=az[i-1]+z*pz pzz=azz[n-3]+azz[n-2]*z for i in range(n-3,0,-1): pzz=azz[i-1]+z*pzz # The Laguerre perturbation. f=pz/p g=(f**2)-pzz/p h= n*g#cmath.sqrt((float(n)-1.0)*(n*g-(f**2))) amp1=abs(f+h); amp2=abs(f-h); if amp1>amp2: dz=float(-n)/(f+h) else: dz=float(-n)/(f-h) itera=itera+1 # Rotate by 90 degrees to avoid limit cycles. jter=jter+1 if jter==10: jter=1 dz=dz*ci z=z+dz if jter==100: raise RuntimeError("Laguerre method not converging") return z # The root-finding subroutine. def fndrt(a,n): z=[complex(0,0) for k in range(n) ] if n==1: z[0]=-a[0]/a[1] return z if n>2: for k in range(n,2,-1): # Obtain an approximate root. root=complex(0.0,0) err=1.0e-12 root = guerre(a,k,root,err,1000) # Refine the root by iterating five more times. err=0.0; root = guerre(a,k,root,err,5) z[k-1]=root # Divide out the factor [z-root]. for i in range(k,0,-1): a[i-1]=a[i-1]+root*a[i] for i in range(1,k+1): a[i-1]=a[i]; # Solve the quadratic equation. z[1]=0.5*(-a[1]+cmath.sqrt(a[1]*a[1]-4.0*a[0]*a[2]))/a[2] z[0]=0.5*(-a[1]-cmath.sqrt(a[1]*a[1]-4.0*a[0]*a[2]))/a[2] return z # Rows are interchanged for stability. def pivot(n,i,a,b): i0=i amp0=abs(a[i-1][i-1]) for j in range(i+1,n+1): amp=abs(a[i-1][j-1]) if amp>amp0: i0=j amp0=amp if i==i0: return temp=b[i-1] b[i-1]=b[i0-1]; b[i0-1]=temp; for j in range(i,n+1): temp=a[j-1][i-1] a[j-1][i-1]=a[j-1][i0-1] a[j-1][i0-1]=temp def gauss(n,a,b): # Downward elimination. for i in range(1,n+1): if i<n: pivot(n,i,a,b) a[i-1][i-1]=1.0/a[i-1][i-1] b[i-1]=b[i-1]*a[i-1][i-1] if i<n: for j in range(i+1,n+1): a[j-1][i-1]=a[j-1][i-1]*a[i-1][i-1] for k in range(i+1,n+1): b[k-1]=b[k-1]-a[i-1][k-1]*b[i-1] for j in range(i+1,n+1): a[j-1][k-1]=a[j-1][k-1]-a[i-1][k-1]*a[j-1][i-1] # Back substitution. for i in range(n-1,0,-1): for j in range(i,n): b[i-1]=b[i-1]-a[j][i-1]*b[j] # The derivatives of the operator function at x=0. def deriv(n,sig,alp,dg,dh1,dh3,bin,nu): dh2=[complex(0,0) for n in dh1] ci = complex(0.0,1.0) dh1[0]=complex(0.5,0)*ci*complex(sig,0) exp1 = complex(-0.5,0) dh2[0]=alp; exp2 = complex(-1.0,0) dh3[0]=-2.0*nu exp3 = complex(-1.0,0) for i in range(1,n): dh1[i]=dh1[i-1]*exp1 exp1=exp1-1.0 dh2[i]=dh2[i-1]*exp2 exp2=exp2-1.0 dh3[i]=-nu*dh3[i-1]*exp3 exp3=exp3-1.0 dg[0]=1.0 dg[1]=dh1[0]+dh2[0]+dh3[0] for i in range(2,n+1): dg[i]=dh1[i-1]+dh2[i-1]+dh3[i-1] for j in range(1,i): dg[i]=dg[i]+bin[j-1][i-1]*(dh1[j-1]+dh2[j-1]+dh3[j-1])*dg[i-j] # The coefficients of the rational approximation. def epade(np,ns,ip,k0,dr,pd1,pd2): m=40 dg = range(m) dh1 = range(m) dh3 = range(m) a = [[ 0 for i in range(m)] for j in range(m)] b = range(m); bin = [[ 0 for i in range(m)] for j in range(m)] fact = range(m) ci=complex(0.0,1.0) sig=k0*dr n=2*np if ip==1: nu=0.0 alp=0.0 else: nu=1.0 alp=-0.25 # The factorials fact[0]=1.0 for i in range(1,n): fact[i]=(i+1)*fact[i-1] # The binomial coefficients.; for i in range(0,n+1): bin[0][i]=1.0 bin[i][i]=1.0 for i in range(2,n+1): for j in range(1,i): bin[j][i]=bin[j-1][i-1]+bin[j][i-1] for i in range(0,n): for j in range(0,n): a[i][j]=0.0 # The accuracy constraints.; deriv(n, sig, alp, dg, dh1, dh3, bin, nu) for i in range(0,n): b[i]=dg[i+1] for i in range(1,n+1): if 2*i-1<=n: a[2*i-2][i-1]=fact[i-1] for j in range(1,i+1): if 2*j<=n: a[2*j-1][i-1]=-bin[j][i]*fact[j-1]*dg[i-j] # The stability constraints.; if ns>=1: z1=-3.0 b[n-1]=-1.0 for j in range(1,np+1): a[2*j-2][n-1]=z1 ** j a[2*j-1][n-1]=0.0 if ns>=2: z1=-1.5 b[n-2]=-1.0 for j in range(1,np+1): a[2*j-2][n-2]=z1 ** j a[2*j-1][n-2]=0.0 gauss(n,a,b) dh1[0]=1.0 for j in range(1,np+1): dh1[j]=b[2*j-2] dh2=fndrt(dh1,np) for j in range(0,np): pd1[j]=-1.0/dh2[j] dh1[0]=1.0 for j in range(1,np+1): dh1[j]=b[2*j-1] dh2=fndrt(dh1,np) for j in range(0,np): pd2[j]=-1.0/dh2[j] # The tridiagonal matrices. def matrc(nz,np,iz,dz,k0,rhob,alpw,alpb,ksq,ksqw,ksqb,f1,f2,f3,r1,r2,r3,s1,s2,s3,pd1,pd2,izsrf): a1=k0*k0/6.0 a2=2.0*k0*k0/3.0 a3=k0*k0/6.0 cfact=0.5/(dz*dz) dfact=1.0/12.0 for i in range(0,iz): f1[i]=1.0/alpw[i] f2[i]=1.0 f3[i]=alpw[i] ksq[i]=ksqw[i] ii=0 for i in range(iz,nz+2): f1[i]=rhob[ii]/alpb[ii] f2[i]=1.0/rhob[ii] f3[i]=alpb[ii] ksq[i]=ksqb[ii] ii+=1 for i in range(1,nz+1): # Discretization by Galerkin's method. c1=cfact*f1[i]*(f2[i-1]+f2[i])*f3[i-1] c2=-cfact*f1[i]*(f2[i-1]+2.0*f2[i]+f2[i+1])*f3[i] c3=cfact*f1[i]*(f2[i]+f2[i+1])*f3[i+1] d1=c1+dfact*(ksq[i-1]+ksq[i]) d2=c2+dfact*(ksq[i-1]+complex(6.0,0)*ksq[i]+ksq[i+1]) d3=c3+dfact*(ksq[i]+ksq[i+1]) for j in range(0,np): r1[j][i]=a1+pd2[j]*d1 r2[j][i]=a2+pd2[j]*d2 r3[j][i]=a3+pd2[j]*d3 s1[j][i]=a1+pd1[j]*d1 s2[j][i]=a2+pd1[j]*d2 s3[j][i]=a3+pd1[j]*d3 # The entries above the surface. for j in range(0,np): for i in range(0,izsrf): r1[j][i]=0.0 r2[j][i]=1.0 r3[j][i]=0.0 s1[j][i]=0.0 s2[j][i]=0.0 s3[j][i]=0.0 # The matrix decomposition. for j in range(0,np): for i in range(1,nz+1): rfact=complex(1.0,0)/(r2[j][i]-r1[j][i]*r3[j][i-1]) r1[j][i]=r1[j][i]*rfact r3[j][i]=r3[j][i]*rfact s1[j][i]=s1[j][i]*rfact s2[j][i]=s2[j][i]*rfact s3[j][i]=s3[j][i]*rfact ## Matrix updates. #def updat(fs1,nz,np,iz,ib,dr,dz,eta,omega,rmax,c0,k0,ci,r,rp,rs,rb,zb,cw,cb,rhob,attn, \ #alpw,alpb,ksq,ksqw,ksqb,f1,f2,f3,r1,r2,r3,s1,s2,s3,pd1,pd2,rsrf,zsrf,izsrf,isrf,attw): ## Varying bathymetry. # if r>=rb[ib]: # ib=ib+1 # if r>=rsrf[isrf]: # isrf=isrf+1 # jzsrf=izsrf # z=zsrf[isrf-1]+(r+0.5*dr-rsrf[isrf-1])*(zsrf[isrf]-zsrf[isrf-1])/(rsrf[isrf]-rsrf[isrf-1]) # izsrf=int(z/dz) # jz=iz # z=zb[ib-1]+(r+0.5*dr-rb[ib-1])*(zb[ib]-zb[ib-1])/(rb[ib]-rb[ib-1]) # iz=int(1.0+z/dz) # iz=max(2,iz) # iz=min(nz,iz) # if iz!=jz or izsrf != jzsrf: # matrc(nz,np,iz,dz,k0,rhob,alpw,alpb,ksq,ksqw,ksqb,f1,f2,f3,r1,r2,r3,s1,s2,s3,pd1,pd2,izsrf) ## Varying profiles. # if r>=rp: # rp = profl(fs1,nz,ci,dz,eta,omega,rmax,c0,k0,rp,cw,cb,rhob,attn,alpw,alpb,ksqw,ksqb,attw) # matrc(nz,np,iz,dz,k0,rhob,alpw,alpb,ksq,ksqw,ksqb,f1,f2,f3,r1,r2,r3,s1,s2,s3,pd1,pd2,izsrf) ## Turn off the stability constraints. # if r>=rs: # ns=0 # epade(np,ns,1,k0,dr,pd1,pd2) # matrc(nz,np,iz,dz,k0,rhob,alpw,alpb,ksq,ksqw,ksqb,f1,f2,f3,r1,r2,r3,s1,s2,s3,pd1,pd2,izsrf) # return ib,isrf,izsrf,iz,rp
5,898
380
<filename>test/pytest/test_garnet.py<gh_stars>100-1000 import numpy as np from contrib.garnet import GarNet from tensorflow.keras.layers import Input from tensorflow.keras.models import Model import hls4ml import pytest vmax = 16 feat = 3 @pytest.fixture(scope='module') def garnet_models(): x = Input(shape=(vmax, feat)) n = Input(shape=(1,), dtype='uint16') inputs = [x, n] outputs = GarNet(8, 8, 16, simplified=True, collapse='mean', input_format='xn', output_activation=None, name='gar_1', quantize_transforms=False)(inputs) model = Model(inputs=inputs, outputs=outputs) model.summary() config = hls4ml.utils.config_from_keras_model(model, granularity='name') config['Model'] = {} config['Model']['ReuseFactor'] = 1 config['Model']['Strategy'] = 'Latency' config['Model']['Precision'] = 'ap_fixed<32,6>' config['LayerName']['gar_1']['Precision'] = {'default': 'ap_fixed<32, 6, AP_RND, AP_SAT>', 'result': 'ap_fixed<32, 6>'} cfg = hls4ml.converters.create_config(output_dir='hls4mlprj_garnet', part='xc7z020clg400-1') cfg['HLSConfig'] = config cfg['KerasModel'] = model hls_model = hls4ml.converters.keras_to_hls(cfg) hls_model.compile() return model, hls_model @pytest.mark.parametrize('batch', [1, 3]) def test_accuracy(garnet_models, batch): model, hls_model = garnet_models x = [np.random.rand(batch, vmax, feat), np.random.randint(0, vmax, size=(batch, 1))] y = model.predict(x) x_hls = [x[0], x[1].astype(np.float64)] y_hls = hls_model.predict(x_hls).reshape(y.shape) np.testing.assert_allclose(y_hls, y, rtol=0, atol=0.1)
798
15,577
<reponame>pdv-ru/ClickHouse #pragma once #include <IO/ReadBuffer.h> namespace DB { /// Just a stub - reads nothing from nowhere. class EmptyReadBuffer : public ReadBuffer { public: EmptyReadBuffer() : ReadBuffer(nullptr, 0) {} private: bool nextImpl() override { return false; } }; }
105
3,084
<gh_stars>1000+ #include "Mp_Precomp.h" #include "802_11_OID.h" #include "CustomOid.h" NDIS_STATUS InterfaceSetInformationHandleCustomizedOriginalMPSetOid( IN NDIS_HANDLE MiniportAdapterContext, IN NDIS_OID Oid, IN PVOID InformationBuffer, IN ULONG InformationBufferLength, OUT PULONG BytesRead, OUT PULONG BytesNeeded ) { PADAPTER Adapter = (PADAPTER)MiniportAdapterContext; PRT_SDIO_DEVICE pDevice = GET_RT_SDIO_DEVICE(Adapter); PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); NDIS_STATUS Status = NDIS_STATUS_SUCCESS; FunctionIn(COMP_OID_SET); *BytesRead = 0; *BytesNeeded = 0; switch(Oid) { default: // Can not find the OID specified Status = NDIS_STATUS_NOT_RECOGNIZED; break; case OID_802_11_NUMBER_OF_ANTENNAS: //TODO: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("Set OID_802_11_NUMBER_OF_ANTENNAS: \n")); break; case OID_802_11_RX_ANTENNA_SELECTED: //TODO: if( (InformationBuffer == 0) || (InformationBufferLength < sizeof(ULONG)) ) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG); goto set_oid_exit; } else { *BytesRead = sizeof(ULONG); } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("Set OID_802_11_RX_ANTENNA_SELECTED: \n")); break; case OID_802_11_TX_ANTENNA_SELECTED: //TODO: if( (InformationBuffer == 0) || (InformationBufferLength < sizeof(ULONG)) ) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG); goto set_oid_exit; } else { *BytesRead = sizeof(ULONG); } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("Set OID_802_11_TX_ANTENNA_SELECTED: \n")); break; case OID_802_11_BSSID_LIST_SCAN: // // Note! this OID is also implemented in N6CSetInformation(). // Since, we had some special requirement (which may not be necessary) for 8187, // we implement it here instead of using that in N6CSetInformation(). // 2005.10.16, by rcnjko. // RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_802_11_BSSID_LIST_SCAN.\n")); // Sometimes we also need site survey when chariot running, comment out by Bruce, 2007-06-28. // 061010, by rcnjko. // if(pMgntInfo->LinkDetectInfo.bBusyTraffic && pMgntInfo->bMediaConnect) //{ // RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_802_11_BSSID_LIST_SCAN (Immediate return because traffic is busy now)\n")); // goto set_oid_exit; // } MgntActSet_802_11_BSSID_LIST_SCAN( Adapter ); RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_802_11_BSSID_LIST_SCAN.\n")); break; case OID_RT_SCAN_AVAILABLE_BSSID: // // Note! this OID is also implemented in N6CSetInformation(). // Since, we had some special requirement (which may not be necessary) for 8187, // we implement it here instead of using that in N6CSetInformation(). // 2005.10.16, by rcnjko. // RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_SCAN_AVAILABLE_BSSID.\n")); // 061010, by rcnjko. if(pMgntInfo->LinkDetectInfo.bBusyTraffic && pMgntInfo->bMediaConnect) { RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_SCAN_AVAILABLE_BSSID (Immediate return because traffic is busy now)\n")); goto set_oid_exit; } MgntActSet_802_11_BSSID_LIST_SCAN( Adapter ); RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_SCAN_AVAILABLE_BSSID.\n")); break; case OID_RT_PRO_READ_REGISTRY: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_READ_REGISTRY.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; PRT_NDIS_DBG_CONTEXT pDbgCtx = &(Adapter->ndisDbgCtx); // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*2) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*2; goto set_oid_exit; } // Get offset and data width. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); // Read MAC register asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to get result. if(!DbgReadMacReg(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_READ_REGISTRY.\n")); break; case OID_RT_PRO_WRITE_REGISTRY: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_WRITE_REGISTRY.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; ULONG ulRegValue; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*3) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*3; goto set_oid_exit; } // Get offset, data width, and value to write. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); ulRegValue = *((ULONG*)InformationBuffer+2); // Write MAC register asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to make sure IO is completed. if(!DbgWriteMacReg(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth, ulRegValue)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_WRITE_REGISTRY.\n")); break; case OID_RT_PRO_READ_BB_REG: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_READ_BB_REG.\n")); { ULONG ulRegOffset; ULONG ulBeOFDM; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*2) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*2; goto set_oid_exit; } // Get offset, and type of BB register to read. ulRegOffset = *((ULONG*)InformationBuffer); ulBeOFDM = *((ULONG*)InformationBuffer+1); // Write BB register asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to make sure IO is completed. if(!DbgReadBbReg(GetDefaultAdapter(Adapter), ulRegOffset, ulBeOFDM)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_READ_BB_REG.\n")); break; case OID_RT_PRO_WRITE_BB_REG: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_WRITE_BB_REG.\n")); { ULONG ulRegOffset; ULONG ulBeOFDM; ULONG ulRegValue; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*3) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*3; goto set_oid_exit; } // Get offset, type of BB register, and value to write. ulRegOffset = *((ULONG*)InformationBuffer); ulBeOFDM = *((ULONG*)InformationBuffer+1); ulRegValue = *((ULONG*)InformationBuffer+2); // Write BB register asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to make sure IO is completed. if(!DbgWriteBbReg(GetDefaultAdapter(Adapter), ulRegOffset, ulBeOFDM, ulRegValue)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_WRITE_BB_REG.\n")); break; case OID_RT_PRO_RF_READ_REGISTRY: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_RF_READ_REGISTRY.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*2) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*2; goto set_oid_exit; } // Get offset and data width. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); // Read RF register asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to get result. if(!DbgReadRfReg(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_RF_READ_REGISTRY.\n")); break; case OID_RT_PRO_RF_WRITE_REGISTRY: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_RF_WRITE_REGISTRY.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; ULONG ulRegValue; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*3) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*3; goto set_oid_exit; } // Get offset, data width, and value to write. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); ulRegValue = *((ULONG*)InformationBuffer+2); // Write RF register asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to make sure IO is completed. if(!DbgWriteRfReg(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth, ulRegValue)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_RF_WRITE_REGISTRY.\n")); break; case OID_RT_PRO_READ_EEPROM: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_READ_EEPROM.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*2) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*2; goto set_oid_exit; } // Get offset and data width. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); // Read EEPROM asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to get result. if(!DbgReadEeprom(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_READ_EEPROM.\n")); break; case OID_RT_PRO_WRITE_EEPROM: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_WRITE_EEPROM.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; ULONG ulRegValue; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*3) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*3; goto set_oid_exit; } // Get offset, data width, and value to write. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); ulRegValue = *((ULONG*)InformationBuffer+2); // Write EEPROM asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to make sure IO is completed. if(!DbgWriteEeprom(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth, ulRegValue)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_WRITE_EEPROM.\n")); break; case OID_RT_PRO_READ_EFUSE: RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("===> Set OID_RT_PRO_READ_EFUSE.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*2) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*2; goto set_oid_exit; } // Get offset and data width. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); // Read EFUSE asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to get result. if(!DbgReadEFuse(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("<=== Set OID_RT_PRO_READ_EFUSE.\n")); break; case OID_RT_PRO_WRITE_EFUSE: RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("===> Set OID_RT_PRO_WRITE_EFUSE.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; ULONG ulRegValue; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*3) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*3; goto set_oid_exit; } // Get offset, data width, and value to write. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); ulRegValue = *((ULONG*)InformationBuffer+2); // Write EFUSE asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to make sure IO is completed. if(!DbgWriteEFuse(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth, ulRegValue)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("<=== Set OID_RT_PRO_WRITE_EFUSE.\n")); break; case OID_RT_PRO_UPDATE_EFUSE: RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("===> Set OID_RT_PRO_UPDATE_EFUSE.\n")); if(!DbgUpdateEFuse(Adapter)) { Status = NDIS_STATUS_NOT_ACCEPTED; } break; case OID_RT_PRO_READ_EFUSE_BT: RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("===> Set OID_RT_PRO_READ_EFUSE_BT.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*2) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*2; goto set_oid_exit; } // Get offset and data width. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); // Read EFUSE asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to get result. if(!DbgReadBTEFuse(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("<=== Set OID_RT_PRO_READ_EFUSE_BT.\n")); break; case OID_RT_PRO_WRITE_EFUSE_BT: RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("===> Set OID_RT_PRO_WRITE_EFUSE_BT.\n")); { ULONG ulRegOffset; ULONG ulRegDataWidth; ULONG ulRegValue; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*3) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*3; goto set_oid_exit; } // Get offset, data width, and value to write. ulRegOffset = *((ULONG*)InformationBuffer); ulRegDataWidth = *((ULONG*)InformationBuffer+1); ulRegValue = *((ULONG*)InformationBuffer+2); // Write EFUSE asynchronously. // Caller should use OID_RT_PRO8187_WI_POLL to make sure IO is completed. if(!DbgWriteBTEFuse(GetDefaultAdapter(Adapter), ulRegOffset, ulRegDataWidth, ulRegValue)) { Status = NDIS_STATUS_NOT_ACCEPTED; } } RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("<=== Set OID_RT_PRO_WRITE_EFUSE_BT.\n")); break; case OID_RT_PRO_UPDATE_EFUSE_BT: RT_TRACE(COMP_OID_SET|COMP_EFUSE, DBG_LOUD, ("===> Set OID_RT_PRO_UPDATE_EFUSE_BT.\n")); if(!DbgUpdateBTEFuse(Adapter)) { Status = NDIS_STATUS_NOT_ACCEPTED; } break; case OID_RT_11N_USB_TX_AGGR_NUM: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_11N_USB_TX_AGGR_NUM.\n")); #if TX_AGGREGATION { HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u1Byte numValue; u4Byte value32; numValue = *((u1Byte *)InformationBuffer); if ( numValue> 0x0f){ Status = NDIS_STATUS_INVALID_DATA; goto set_oid_exit; } pHalData->UsbTxAggDescNum = numValue; value32 = PlatformEFIORead4Byte(Adapter, REG_TDECTRL); value32 = value32 & ~(BLK_DESC_NUM_MASK << BLK_DESC_NUM_SHIFT); value32 |= ((pHalData->UsbTxAggDescNum & BLK_DESC_NUM_MASK) << BLK_DESC_NUM_SHIFT); PlatformEFIOWrite4Byte(Adapter, REG_TDECTRL, value32); } #endif RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_11N_USB_TX_AGGR_NUM.\n")); break; case OID_RT_PRO_SET_ANTENNA_BB: RT_TRACE(COMP_OID_SET, DBG_LOUD, ("===> Set OID_RT_PRO_SET_ANTENNA_BB.\n")); { u1Byte antennaIndex; // Verify input paramter. if(InformationBufferLength < sizeof(ULONG)*1) { Status = NDIS_STATUS_INVALID_LENGTH; *BytesNeeded = sizeof(ULONG)*1; RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_SET_ANTENNA_BB. return!!\n")); return Status; } // Get antenna index. antennaIndex = *((UCHAR*)InformationBuffer); RT_TRACE(COMP_OID_SET, DBG_LOUD, ("Set OID_RT_PRO_SET_ANTENNA_BB, antennaIndex(%#x)\n", antennaIndex)); if(!DbgSetTxAntenna(Adapter, antennaIndex)) { Status = NDIS_STATUS_NOT_ACCEPTED; } // Initialize antenna test pMgntInfo->AntennaTest = 1; Adapter->RxStats.PWDBAllCnt = Adapter->RxStats.PWDBAllOldCnt = 0; Adapter->RxStats.RssiCalculateCnt = Adapter->RxStats.RssiOldCalculateCnt = 0; Adapter->HalFunc.SetTxAntennaHandler(Adapter, antennaIndex); } RT_TRACE(COMP_OID_SET, DBG_LOUD, ("<=== Set OID_RT_PRO_SET_ANTENNA_BB.\n")); break; case OID_RT_SDIO_REG_CTRL: { u1Byte SdioRegCtrl = *(pu1Byte)InformationBuffer; pDevice->SdioRegDbgCtrl = SdioRegCtrl & SDIO_REG_CTRL_MASK; RT_TRACE(COMP_OID_SET, DBG_LOUD, ("Set OID_RT_SDIO_REG_CTRL: SdioRegCtrl(%d)\n", pDevice->SdioRegDbgCtrl)); } break; } set_oid_exit: return Status; }
8,343
791
#pragma once #include "cereal/types/valarray.hpp"
21
318
<filename>iclick/admin.py<gh_stars>100-1000 from django.contrib import admin from iclick.models import Link @admin.register(Link) class LinkAdmin(admin.ModelAdmin): list_display = ['token', 'to_url', 'count']
75
1,682
/* Copyright (c) 2012 LinkedIn 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.linkedin.restli.server.resources; import com.linkedin.common.callback.Callback; import com.linkedin.data.template.RecordTemplate; import com.linkedin.restli.common.PatchRequest; import com.linkedin.restli.server.UpdateResponse; /** * Interface for asynchronous implementations of Rest.li Simple Resources. Most * applications should extend SimpleResourceAsyncTemplate for convenience, rather * than implementing this interface directly. */ public interface SimpleResourceAsync<V extends RecordTemplate> extends BaseResource, SingleObjectResource<V> { /** * Gets this resource * * @param callback The callback for the asynchronous get call. */ void get(Callback<V> callback); /** * Updates this resource * * @param entity the value to update the resource with. * @param callback the callback for the asynchronous update call. */ void update(V entity, Callback<UpdateResponse> callback); /** * Updates this resource * * @param patch value to update the resource with * @param callback the callback for the asynchronous update call. */ void update(PatchRequest<V> patch, Callback<UpdateResponse> callback); /** * Deletes this resource. * * @param callback the callback for the asynchronous delete call. */ void delete(Callback<UpdateResponse> callback); }
519
11,334
<reponame>MrABKhan/spring-boot-admin { "instances": { "caches": { "label": "Caches", "cache_manager": "Cache Manager", "fetch_failed": "Fetching caches failed.", "loading": "Loading Caches...", "name": "Name", "no_caches_found": "No caches found." } } }
137
1,014
<filename>Database/Equities/Countries/Mexico/Mexico Industries.json [ "Airlines", "Airports & Air Services", "Asset Management", "Auto Parts", "Banks - Regional", "Beverages - Brewers", "Beverages - Non-Alcoholic", "Beverages - Wineries & Distilleries", "Broadcasting", "Building Materials", "Building Products & Equipment", "Business Services", "Capital Markets", "Chemicals", "Conglomerates", "Credit Services", "Department Stores", "Discount Stores", "Drug Manufacturers - Specialty & Generic", "Engineering & Construction", "Entertainment", "Farm Products", "Financial Conglomerates", "Financial Data & Stock Exchanges", "Furnishings, Fixtures & Appliances", "Grocery Stores", "Household & Personal Products", "Infrastructure Operations", "Insurance - Diversified", "Insurance - Property & Casualty", "Insurance Brokers", "Investment Brokerage - National", "Leisure", "Lodging", "Lumber & Wood Production", "Marine Shipping", "Medical Care Facilities", "Oil & Gas E&P", "Other Industrial Metals & Mining", "Other Precious Metals & Mining", "Packaged Foods", "Packaging & Containers", "Paper & Paper Products", "Pharmaceutical Retailers", "Pollution & Treatment Controls", "REIT - Diversified", "REIT - Hotel & Motel", "REIT - Industrial", "REIT - Retail", "REIT - Specialty", "Railroads", "Real Estate - Development", "Real Estate - Diversified", "Real Estate Services", "Residential Construction", "Resorts & Casinos", "Restaurants", "Shell Companies", "Specialty Business Services", "Specialty Chemicals", "Specialty Retail", "Steel", "Telecom Services", "Utilities - Regulated Gas", "Waste Management" ]
750
1,007
<reponame>iamarkaj/poc ## # Exploit Title: Schneider Electric Modicon Quantum password bypass # Date: 06/11/2019 # Exploit Author: <NAME> # CVE : CVE-2018-7811 # Advisory: https://www.tenable.com/security/research/tra-2018-38 # Affected Vendors/Device/Firmware: # - Modicon M340 # - Modicon Premium # - Modicon Quantum # - Modicon BMXNOR0200 ## import urllib.request, argparse parser = argparse.ArgumentParser() parser.add_argument("target_host", help="Modicon Quantum host") parser.add_argument("target_port", help="Modicon Quantum port (ie. 80)", type=int) parser.add_argument("target_user", help="Username (ie. admin)") parser.add_argument("new_pass", help="<PASSWORD>") args = parser.parse_args() host = args.target_host port = args.target_port user = args.target_user newpass = args.new_pass with urllib.request.urlopen('http://'+host+':'+port+'/unsecure/embedded/builtin?Language=English&user='+user+'&passwd='+newpass+'&cnfpasswd='+newpass+'&subhttppwd=Save+User') as f: print(f.read(300))
367
645
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. 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 Intel Corporation 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 INTEL OR ITS 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. END_LEGAL */ // <ORIGINAL-AUTHOR>: <NAME> // <COMPONENT>: atomic // <FILE-TYPE>: component public header #ifndef ATOMIC_EXPONENTIAL_BACKOFF_HPP #define ATOMIC_EXPONENTIAL_BACKOFF_HPP #include "fund.hpp" #include "atomic/nullstats.hpp" #include "atomic/private/backoff-impl.hpp" namespace ATOMIC { /*! @brief Helper object for exponential delays. * * A helper object that implements an exponential backoff algorithm. This is most often * used inside a compare-swap loop to prevent thrashing when there is high contention. * * @param STATS Type of an object that collects statistics. See NULLSTATS for a model. * * @par Example: * \code * #include "atomic/exponential-backoff.hpp" * #include "atomic/ops.hpp" * * void Foo() * { * ATOMIC::EXPONENTIAL_BACKOFF<> backoff; * do { * backoff.Delay(); * oldVal = .... * newVal = .... * } while (!ATOMIC::OPS::CompareAndDidSwap(&val, oldVal, newVal)); * } * \endcode */ template<typename STATS=NULLSTATS> class /*<UTILITY>*/ EXPONENTIAL_BACKOFF { public: /*! * @param[in] freeIterations Number of times through loop before Delay() does anything. * @param[in] stats Object to keep track of statistics, or NULL */ EXPONENTIAL_BACKOFF(FUND::UINT32 freeIterations = 1, STATS *stats = 0) : _freeIterations(freeIterations), _iteration(0), _stats(stats) {} ~EXPONENTIAL_BACKOFF() { if (_stats && _iteration > _freeIterations) _stats->Backoff(_iteration - _freeIterations); } /*! * Reset the object to the first "iteration". */ void Reset() { if (_stats && _iteration > _freeIterations) _stats->Backoff(_iteration - _freeIterations); _iteration = 0; } /*! * Delay for a short period of time and advance to the next "iteration". The delay * time typically grows longer for each successive iteration. */ void Delay() { if (_iteration++ < _freeIterations) return; FUND::UINT32 fixed = 1 << (_iteration - 1 - _freeIterations); FUND::UINT32 mask = fixed - 1; FUND::UINT32 random = (reinterpret_cast<FUND::PTRINT>(&random) >> 4) & mask; FUND::UINT32 delay = fixed + random; ATOMIC_SpinDelay(delay); } /*! * @return The number of times Delay() has been called since the last Reset(). */ FUND::UINT32 GetIterationCount() { return _iteration; } private: const FUND::UINT32 _freeIterations; // number "free" iterations before we start to delay FUND::UINT32 _iteration; // current iteration STATS *_stats; // points to object which collects statistics, or NULL }; } // namespace #endif // file guard
1,731
2,338
<gh_stars>1000+ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <array> // const_reference operator[](size_type) const; // constexpr in C++14 // Libc++ marks it as noexcept #include <array> #include <cassert> #include "test_macros.h" TEST_CONSTEXPR_CXX14 bool tests() { { typedef double T; typedef std::array<T, 3> C; C const c = {1, 2, 3.5}; LIBCPP_ASSERT_NOEXCEPT(c[0]); ASSERT_SAME_TYPE(C::const_reference, decltype(c[0])); C::const_reference r1 = c[0]; assert(r1 == 1); C::const_reference r2 = c[2]; assert(r2 == 3.5); } // Test operator[] "works" on zero sized arrays { { typedef double T; typedef std::array<T, 0> C; C const c = {}; LIBCPP_ASSERT_NOEXCEPT(c[0]); ASSERT_SAME_TYPE(C::const_reference, decltype(c[0])); if (c.size() > (0)) { // always false C::const_reference r = c[0]; (void)r; } } { typedef double T; typedef std::array<T const, 0> C; C const c = {}; LIBCPP_ASSERT_NOEXCEPT(c[0]); ASSERT_SAME_TYPE(C::const_reference, decltype(c[0])); if (c.size() > (0)) { // always false C::const_reference r = c[0]; (void)r; } } } return true; } int main(int, char**) { tests(); #if TEST_STD_VER >= 14 static_assert(tests(), ""); #endif return 0; }
891