max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,151
<gh_stars>1000+ // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/content/service.h" #include <utility> #include "base/bind.h" #include "base/macros.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/content/public/mojom/view_factory.mojom.h" #include "services/content/service_delegate.h" #include "services/content/view_factory_impl.h" #include "services/content/view_impl.h" #include "services/service_manager/public/cpp/service_context.h" namespace content { Service::Service(ServiceDelegate* delegate) : delegate_(delegate) { binders_.AddInterface(base::BindRepeating( [](Service* service, mojom::ViewFactoryRequest request) { service->AddViewFactory( std::make_unique<ViewFactoryImpl>(service, std::move(request))); }, this)); } Service::~Service() { delegate_->WillDestroyServiceInstance(this); } void Service::ForceQuit() { // Ensure that all bound interfaces are disconnected and no further interface // requests will be handled. view_factories_.clear(); views_.clear(); binders_.RemoveInterface<mojom::ViewFactory>(); // Force-disconnect from the Service Mangager. Under normal circumstances // (i.e. in non-test code), the call below destroys |this|. context()->QuitNow(); } void Service::AddViewFactory(std::unique_ptr<ViewFactoryImpl> factory) { auto* raw_factory = factory.get(); view_factories_.emplace(raw_factory, std::move(factory)); } void Service::RemoveViewFactory(ViewFactoryImpl* factory) { view_factories_.erase(factory); } void Service::AddView(std::unique_ptr<ViewImpl> view) { auto* raw_view = view.get(); views_.emplace(raw_view, std::move(view)); } void Service::RemoveView(ViewImpl* view) { views_.erase(view); } void Service::OnBindInterface(const service_manager::BindSourceInfo& source, const std::string& interface_name, mojo::ScopedMessagePipeHandle pipe) { binders_.BindInterface(interface_name, std::move(pipe)); } } // namespace content
752
5,250
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.test.bpmn.event.variable; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; import org.flowable.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.Deployment; import org.flowable.task.api.Task; import org.junit.jupiter.api.Test; public class VariableListenerEventTest extends PluggableFlowableTestCase { @Test @Deployment public void catchVariableListener() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("catchVariableListener"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(2); runtimeService.setVariable(processInstance.getId(), "var1", "test"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(0); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } @Test @Deployment public void catchVariableListenerCreate() { Map<String, Object> variableMap = new HashMap<>(); variableMap.put("var1", "test"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("catchVariableListener", variableMap); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); // updating variable, variable listener should not fire (create only) runtimeService.setVariable(processInstance.getId(), "var1", "test update"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(2); } @Test @Deployment public void catchVariableListenerUpdate() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("catchVariableListener"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); // creating variable, variable listener should not fire (update only) runtimeService.setVariable(processInstance.getId(), "var1", "test"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); // updating variable, variable listener should fire runtimeService.setVariable(processInstance.getId(), "var1", "test update"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(0); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } @Test @Deployment public void boundaryVariableListener() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("boundaryVariableListener"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task).isNotNull(); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); runtimeService.setVariable(processInstance.getId(), "var1", "test"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(0); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("aftertask"); taskService.complete(task.getId()); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } @Test @Deployment(resources = "org/flowable/engine/test/bpmn/event/variable/VariableListenerEventTest.boundaryVariableListener.bpmn20.xml") public void boundaryVariableListenerCompleteTask() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("boundaryVariableListener"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task).isNotNull(); taskService.complete(task.getId()); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(0); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } @Test @Deployment public void boundaryVariableListenerCreate() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("boundaryVariableListener"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task).isNotNull(); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); // creating variable, variable listener should fire (create only) runtimeService.setVariable(processInstance.getId(), "var1", "test"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).count()).isZero(); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("aftertask"); taskService.complete(task.getId()); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } @Test @Deployment public void boundaryVariableListenerNonInterrupting() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("boundaryVariableListener"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task).isNotNull(); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); runtimeService.setVariable(processInstance.getId(), "var1", "test"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(2); assertThat(taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list()).hasSize(1); runtimeService.setVariable(processInstance.getId(), "var1", "test update"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(3); assertThat(taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list()).hasSize(2); task = taskService.createTaskQuery().taskDefinitionKey("task").processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(0); task = taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list().iterator().next(); taskService.complete(task.getId()); task = taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } @Test @Deployment public void boundaryVariableListenerNonInterruptingCreate() { // trigger variable listener from the start ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder() .processDefinitionKey("boundaryVariableListener") .variable("var1", "test") .start(); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(2); assertThat(taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list()).hasSize(1); // update does not trigger variable listener (only create) runtimeService.setVariable(processInstance.getId(), "var1", "test"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(2); assertThat(taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list()).hasSize(1); Task task = taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); task = taskService.createTaskQuery().taskDefinitionKey("task").processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } @Test @Deployment public void boundaryVariableListenerNonInterruptingUpdate() { ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder() .processDefinitionKey("boundaryVariableListener") .start(); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().taskDefinitionKey("task").processInstanceId(processInstance.getId()).list()).hasSize(1); // variable create does not trigger variable listener (only update) runtimeService.setVariable(processInstance.getId(), "var1", "test"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().taskDefinitionKey("task").processInstanceId(processInstance.getId()).list()).hasSize(1); // variable update, triggers variable listener runtimeService.setVariable(processInstance.getId(), "var1", "update test 1"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(2); assertThat(taskService.createTaskQuery().taskDefinitionKey("task").processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list()).hasSize(1); // another variable update, triggers variable listener runtimeService.setVariable(processInstance.getId(), "var1", "update test 2"); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().processInstanceId(processInstance.getId()).list()).hasSize(3); assertThat(taskService.createTaskQuery().taskDefinitionKey("task").processInstanceId(processInstance.getId()).list()).hasSize(1); assertThat(taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list()).hasSize(2); Task task = taskService.createTaskQuery().taskDefinitionKey("task").processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertThat(runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).list()).hasSize(0); task = taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).list().get(0); taskService.complete(task.getId()); task = taskService.createTaskQuery().taskDefinitionKey("aftertask").processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertThat(runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).count()).isEqualTo(0); } }
5,056
15,577
#pragma once #include <Processors/IProcessor.h> #include <Processors/ISimpleTransform.h> #include <Core/ColumnNumbers.h> #include <Common/WeakHash.h> namespace DB { /// Add IColumn::Selector to chunk (see SelectorInfo.h). /// Selector is filled by formula (WeakHash(key_columns) * num_outputs / MAX_INT). class AddingSelectorTransform : public ISimpleTransform { public: AddingSelectorTransform(const Block & header, size_t num_outputs_, ColumnNumbers key_columns_); String getName() const override { return "AddingSelector"; } void transform(Chunk & input_chunk, Chunk & output_chunk) override; private: size_t num_outputs; ColumnNumbers key_columns; WeakHash32 hash; }; }
240
492
<gh_stars>100-1000 from django.shortcuts import render def index(request): mydict = {'key1' : 'value1'} mylist = [1, 2, 3, 4] list_of_dictionaries = [{'user' : '832'}, {'user' : '3238'}, {'user' : '30293'}] mybool = True context = {'name' : 'Pretty Printed', 'mydict' : mydict, 'mylist' : mylist, 'mybool' : mybool, 'list_of_dictionaries' : list_of_dictionaries} return render(request, 'examples/index.html', context) def profile(request, username): context = {'username' : username} return render(request, 'examples/profile.html', context)
227
1,093
<reponame>StandCN/spring-integration /* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.gemfire.outbound; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.geode.GemFireCheckedException; import org.apache.geode.GemFireException; import org.apache.geode.cache.Region; import org.springframework.data.gemfire.GemfireCallback; import org.springframework.data.gemfire.GemfireTemplate; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.expression.ExpressionUtils; import org.springframework.integration.handler.AbstractMessageHandler; import org.springframework.messaging.Message; import org.springframework.util.Assert; /** * A {@link org.springframework.messaging.MessageHandler} implementation that writes to a * GemFire Region. The Message's payload must be an instance of {@link Map} or * {@link #cacheEntryExpressions} must be provided. * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * * @since 2.1 */ public class CacheWritingMessageHandler extends AbstractMessageHandler { private static final SpelExpressionParser PARSER = new SpelExpressionParser(); private final Map<Expression, Expression> cacheEntryExpressions = new LinkedHashMap<Expression, Expression>(); private final GemfireTemplate gemfireTemplate = new GemfireTemplate(); private volatile EvaluationContext evaluationContext; @SuppressWarnings("rawtypes") public CacheWritingMessageHandler(Region region) { Assert.notNull(region, "region must not be null"); this.gemfireTemplate.setRegion(region); } @Override public String getComponentType() { return "gemfire:outbound-channel-adapter"; } @Override protected void onInit() { super.onInit(); this.gemfireTemplate.afterPropertiesSet(); this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) protected void handleMessageInternal(Message<?> message) { Object payload = message.getPayload(); Map<?, ?> cacheValues = (this.cacheEntryExpressions.size() > 0) ? evaluateCacheEntries(message) : null; if (cacheValues == null) { Assert.state(payload instanceof Map, "If cache entry expressions are not configured, then payload must be a Map"); cacheValues = (Map) payload; } final Map<?, ?> map = cacheValues; this.gemfireTemplate.execute(new GemfireCallback<Object>() { @Override public Object doInGemfire(Region region) throws GemFireCheckedException, GemFireException { region.putAll(map); return null; } }); } private Map<Object, Object> evaluateCacheEntries(Message<?> message) { if (this.cacheEntryExpressions.size() == 0) { return null; } else { Map<Object, Object> cacheValues = new HashMap<Object, Object>(); for (Entry<Expression, Expression> expressionEntry : this.cacheEntryExpressions.entrySet()) { cacheValues.put(expressionEntry.getKey().getValue(this.evaluationContext, message), expressionEntry.getValue().getValue(this.evaluationContext, message)); } return cacheValues; } } public void setCacheEntries(Map<String, String> cacheEntries) { Assert.notNull(cacheEntries, "'cacheEntries' must not be null"); if (this.cacheEntryExpressions.size() > 0) { this.cacheEntryExpressions.clear(); } for (Entry<String, String> cacheEntry : cacheEntries.entrySet()) { this.cacheEntryExpressions.put(PARSER.parseExpression(cacheEntry.getKey()), PARSER.parseExpression(cacheEntry.getValue())); } } public void setCacheEntryExpressions(Map<Expression, Expression> cacheEntryExpressions) { Assert.notNull(cacheEntryExpressions, "'cacheEntryExpressions' must not be null"); if (this.cacheEntryExpressions.size() > 0) { this.cacheEntryExpressions.clear(); } this.cacheEntryExpressions.putAll(cacheEntryExpressions); } }
1,431
5,169
<reponame>Gantios/Specs { "name": "EasyAuth", "version": "1.0.4", "summary": "This is private auth module", "description": "This is authorization module for EasyPay UA applications", "homepage": "https://gitlab.easypay.ua:14443/astakhov/easyauth.git", "license": "LICENSE", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "10.0" }, "source": { "git": "https://gitlab.easypay.ua:14443/astakhov/easyauth.git", "tag": "1.0.4" }, "source_files": "EasyAuth/**/*", "exclude_files": "EasyAuth/Info.plist", "dependencies": { "TPKeyboardAvoiding": [ ], "Keyboard+LayoutGuide": [ ], "SwiftPhoneNumberFormatter": [ ], "lottie-ios": [ ], "MGSwipeTableCell": [ ], "RxSwift": [ ], "RxCocoa": [ ], "RxBiBinding": [ ], "ReCaptcha": [ ], "ReCaptcha/RxSwift": [ ] } }
413
2,792
<gh_stars>1000+ # -*- coding:utf-8 -*- # Author:hankcs # Date: 2018-07-04 17:34 # 《自然语言处理入门》7.3.1 基于隐马尔可夫模型的词性标注 # 配套书籍:http://nlp.hankcs.com/book.php # 讨论答疑:https://bbs.hankcs.com/ from pyhanlp import * from tests.book.ch07.pku import PKU199801_TRAIN HMMPOSTagger = JClass('com.hankcs.hanlp.model.hmm.HMMPOSTagger') AbstractLexicalAnalyzer = JClass('com.hankcs.hanlp.tokenizer.lexical.AbstractLexicalAnalyzer') PerceptronSegmenter = JClass('com.hankcs.hanlp.model.perceptron.PerceptronSegmenter') FirstOrderHiddenMarkovModel = JClass('com.hankcs.hanlp.model.hmm.FirstOrderHiddenMarkovModel') SecondOrderHiddenMarkovModel = JClass('com.hankcs.hanlp.model.hmm.SecondOrderHiddenMarkovModel') def train_hmm_pos(corpus, model): tagger = HMMPOSTagger(model) # 创建词性标注器 tagger.train(corpus) # 训练 print(', '.join(tagger.tag("他", "的", "希望", "是", "希望", "上学"))) # 预测 analyzer = AbstractLexicalAnalyzer(PerceptronSegmenter(), tagger) # 构造词法分析器 print(analyzer.analyze("他的希望是希望上学")) # 分词+词性标注 return tagger if __name__ == '__main__': tagger = train_hmm_pos(PKU199801_TRAIN, FirstOrderHiddenMarkovModel()) tagger = train_hmm_pos(PKU199801_TRAIN, SecondOrderHiddenMarkovModel()) # 或二阶隐马
644
422
#pragma once #include "TypeReader.h" #include "GenericTypeReader.h" // Keeps track of all the available TypeReader implementations. class TypeReaderManager { public: virtual ~TypeReaderManager(); void RegisterStandardTypes(); TypeReader* GetByReaderName(wstring const& readerName); TypeReader* GetByTargetType(wstring const& targetType); template<typename T> void RegisterTypeReader() { static_assert(!is_base_of<GenericTypeReader, T>::value, "Generic reader types should use RegisterGenericTypeReader."); typeReaders.push_back(new T); } template<typename T> void RegisterGenericReader() { genericReaders.push_back(new GenericTypeReaderFactoryT<T>); } private: static wstring StripAssemblyVersion(wstring typeName); static bool SplitGenericTypeName(wstring const& typeName, wstring* genericName, vector<wstring>* genericArguments); vector<TypeReader*> typeReaders; vector<GenericTypeReaderFactory*> genericReaders; };
332
750
from unittest import TestCase from piccolo.table import create_tables, drop_tables from tests.example_apps.music.tables import Band, Manager class TestDropTables(TestCase): def setUp(self): create_tables(Band, Manager) def test_drop_tables(self): """ Make sure the tables are dropped. """ self.assertEqual(Manager.table_exists().run_sync(), True) self.assertEqual(Band.table_exists().run_sync(), True) drop_tables(Manager, Band) self.assertEqual(Manager.table_exists().run_sync(), False) self.assertEqual(Band.table_exists().run_sync(), False)
251
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.apisupport.project.queries; import java.io.File; import java.util.Arrays; import java.util.SortedSet; import java.util.TreeSet; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectManager; import org.netbeans.api.project.ProjectUtils; import org.netbeans.modules.apisupport.project.NbModuleProject; import org.netbeans.modules.apisupport.project.TestBase; import org.netbeans.spi.project.SubprojectProvider; import org.netbeans.spi.project.support.ant.AntProjectHelper; import org.netbeans.spi.project.support.ant.EditableProperties; import org.netbeans.spi.project.support.ant.PropertyUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Utilities; /** * Test subprojects. * @author <NAME> */ public class SubprojectProviderImplTest extends TestBase { public SubprojectProviderImplTest(String name) { super(name); } /* XXX too brittle: public void testNetBeansOrgSubprojects() throws Exception { checkSubprojects("o.apache.tools.ant.module", new String[] { "openide.filesystems", "openide.util", "openide.modules", "openide.nodes", "openide.awt", "openide.dialogs", "openide.windows", "openide.text", "openide.actions", "openide.execution", "openide.io", "openide.loaders", "api.xml", "spi.navigator", "openide.explorer", "options.api", "o.jdesktop.layout", "api.progress", "projectapi", "projectuiapi", }); checkSubprojects("openide.util", new String[] {}); } */ public void testExternalSubprojects() throws Exception { checkSubprojects(resolveEEPPath("/suite1/action-project"), new String[] { resolveEEPPath("/suite1/support/lib-project"), file("platform/openide.dialogs").getAbsolutePath(), }); checkSubprojects(resolveEEPPath("/suite1/support/lib-project"), new String[0]); checkSubprojects(resolveEEPPath("/suite3/dummy-project"), new String[0]); } /** @see "#63824" */ /* No examples in nb.org left; should create sample projects for it: public void testAdHocSubprojects() throws Exception { assertDepends("mdr/module", "mdr"); assertDepends("applemenu", "applemenu/eawtstub"); } */ /** @see "#77533" */ /*public void testSelfRefWithClassPathExts() throws Exception { checkSubprojects("apisupport.paintapp/PaintApp-suite/ColorChooser", new String[0]); }*/ /** @see "#81878" */ public void testInclusionOfHigherBin() throws Exception { checkSubprojects("ide/servletapi", new String[0]); } public void testInclusionOfUnresolvedRef() throws Exception { clearWorkDir(); initializeBuildProperties(getWorkDir(), null); NbModuleProject p = generateStandaloneModule("prj"); EditableProperties ep = p.getHelper().getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH); ep.put("cp.extra", "${unknown.jar}"); p.getHelper().putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep); checkSubprojects(p); } @Deprecated // relies on nb_all source root private void checkSubprojects(String project, String[] subprojects) throws Exception { Project p = project(project); SubprojectProvider spp = p.getLookup().lookup(SubprojectProvider.class); assertNotNull("have SPP in " + p, spp); SortedSet<String> expected = new TreeSet<String>(); for (String sp : subprojects) { File f = new File(sp); if (!f.isAbsolute()) { f = file(sp); } expected.add(Utilities.toURI(f).toString()); } SortedSet<String> actual = new TreeSet<String>(); for (Project sp : spp.getSubprojects()) { actual.add(sp.getProjectDirectory().toURL().toExternalForm()); } assertEquals("correct subprojects for " + project, expected.toString(), actual.toString()); } private void checkSubprojects(Project project, String... subprojectNames) throws Exception { SubprojectProvider spp = project.getLookup().lookup(SubprojectProvider.class); assertNotNull("have SPP in " + project, spp); SortedSet<String> actual = new TreeSet<String>(); for (Project sp : spp.getSubprojects()) { actual.add(ProjectUtils.getInformation(sp).getName()); } assertEquals("correct subprojects for " + project, new TreeSet<String>(Arrays.asList(subprojectNames)).toString(), actual.toString()); } private Project project(String path) throws Exception { FileObject dir = FileUtil.toFileObject(PropertyUtils.resolveFile(nbRootFile(), path)); // FileObject dir = nbRoot().getFileObject(path); assertNotNull("have " + path, dir); Project p = ProjectManager.getDefault().findProject(dir); assertNotNull("have project in " + path, p); return p; } private void assertDepends(String parent, String child) throws Exception { Project p1 = project(parent); Project p2 = project(child); SubprojectProvider spp = p1.getLookup().lookup(SubprojectProvider.class); assertNotNull("have SPP in " + p1, spp); assertTrue(parent + " includes " + child, spp.getSubprojects().contains(p2)); } }
2,487
892
{ "schema_version": "1.2.0", "id": "GHSA-v6c9-fgcv-6gvg", "modified": "2022-05-13T01:39:18Z", "published": "2022-05-13T01:39:18Z", "aliases": [ "CVE-2013-2323" ], "details": "HP SQL/MX 3.0 through 3.2 on NonStop servers, when SQL/MP Objects are used, allows remote authenticated users to bypass intended access restrictions and modify data via unspecified vectors, aka the \"SQL/MP tables\" issue.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2013-2323" }, { "type": "WEB", "url": "http://h20565.www2.hp.com/portal/site/hpsc/template.PAGE/public/kb/docDisplay/?docId=emr_na-c03762155" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
373
827
<gh_stars>100-1000 """ Example of MRI response functions ================================= Within this example we are going to plot the hemodynamic response function (:term:`HRF`) model in :term:`SPM` together with the :term:`HRF` shape proposed by G.Glover, as well as their time and dispersion derivatives. We also illustrate how users can input a custom response function, which can for instance be useful when dealing with non human primate data acquired using a contrast agent. In our case, we input a custom response function for MION, a common `agent <https://en.wikipedia.org/wiki/MRI_contrast_agent>`_ used to enhance contrast on MRI images of monkeys. The :term:`HRF` is the filter which couples neural responses to the metabolic-related changes in the MRI signal. :term:`HRF` models are simply phenomenological. In current analysis frameworks, the choice of :term:`HRF` model is essentially left to the user. Fortunately, using the :term:`SPM` or Glover model does not make a huge difference. Adding derivatives should be considered whenever timing information has some degree of uncertainty, and is actually useful to detect timing issues. This example requires matplotlib and scipy. """ ######################################################################### # Define stimulus parameters and response models # ---------------------------------------------- # # To get an impulse response, we simulate a single event occurring at time t=0, # with duration 1s. import numpy as np time_length = 30.0 frame_times = np.linspace(0, time_length, 61) onset, amplitude, duration = 0.0, 1.0, 1.0 exp_condition = np.array((onset, duration, amplitude)).reshape(3, 1) ######################################################################### # Make a time array of this condition for display: stim = np.zeros_like(frame_times) stim[(frame_times > onset) * (frame_times <= onset + duration)] = amplitude ######################################################################### # Define custom response functions for MION. Custom response # functions should at least take tr and oversampling as arguments: from scipy.stats import gamma def mion_response_function(tr, oversampling=16, onset=0.0): """Implementation of the MION response function model. Parameters ---------- tr: float scan repeat time, in seconds oversampling: int, optional temporal oversampling factor onset: float, optional hrf onset time, in seconds Returns ------- response_function: array of shape(length / tr * oversampling, dtype=float) response_function sampling on the oversampled time grid """ dt = tr / oversampling time_stamps = np.linspace( 0, time_length, np.rint(float(time_length) / dt).astype(int) ) time_stamps -= onset # parameters of the gamma function delay = 1.55 dispersion = 5.5 response_function = gamma.pdf(time_stamps, delay, loc=0, scale=dispersion) response_function /= response_function.sum() response_function *= -1 return response_function def mion_time_derivative(tr, oversampling=16.0): """Implementation of the MION time derivative response function model. Parameters ---------- tr: float scan repeat time, in seconds oversampling: int, optional temporal oversampling factor, optional Returns ------- drf: array of shape(time_length / tr * oversampling, dtype=float) derived_response_function sampling on the provided grid """ do = 0.1 drf = ( mion_response_function(tr, oversampling) - mion_response_function(tr, oversampling, do) ) / do return drf ######################################################################### # Define response function models to be displayed: rf_models = [ ("spm + derivative + dispersion", "SPM HRF", None), ("glover + derivative + dispersion", "Glover HRF", None), ( [mion_response_function, mion_time_derivative], "Mion RF + derivative", ["main", "main_derivative"], ), ] ######################################################################### # Sample and plot response functions # ---------------------------------- import matplotlib.pyplot as plt from nilearn.glm.first_level import compute_regressor oversampling = 16 fig = plt.figure(figsize=(9, 4)) for i, (rf_model, model_title, labels) in enumerate(rf_models): # compute signal of interest by convolution signal, _labels = compute_regressor( exp_condition, rf_model, frame_times, con_id="main", oversampling=oversampling, ) # plot signal plt.subplot(1, len(rf_models), i + 1) plt.fill(frame_times, stim, "k", alpha=0.5, label="stimulus") for j in range(signal.shape[1]): plt.plot( frame_times, signal.T[j], label=( labels[j] if labels is not None else (_labels[j] if _labels is not None else None) ), ) plt.xlabel("time (s)") plt.legend(loc=1) plt.title(model_title) # adjust plot plt.subplots_adjust(bottom=0.12) plt.show()
1,734
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.autofill_assistant; import android.content.Context; import android.view.LayoutInflater; import org.chromium.chrome.browser.base.SplitCompatUtils; /** Utilities for dealing with layouts and inflation. */ public class LayoutUtils { private static final String ASSISTANT_SPLIT_NAME = "autofill_assistant"; /** * Creates a LayoutInflater which can be used to inflate layouts from the autofill_assistant * module. */ public static LayoutInflater createInflater(Context context) { return LayoutInflater.from( SplitCompatUtils.createContextForInflation(context, ASSISTANT_SPLIT_NAME)); } }
273
320
// // OMSDK.h // OMSDK // // Created by <NAME> on 10/16/20. // #import <Foundation/Foundation.h> //! Project version number for OMSDK. FOUNDATION_EXPORT double OMSDKVersionNumber; //! Project version string for OMSDK. FOUNDATION_EXPORT const unsigned char OMSDKVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <OMSDK/PublicHeader.h> #import <OMSDK/OMIDImports.h>
151
1,719
/* * Copyright 2006-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.retry.policy; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryPolicy; import org.springframework.retry.context.RetryContextSupport; import org.springframework.retry.support.RetryTemplate; /** * Simple retry policy that is aware only about attempt count and retries a fixed number * of times. The number of attempts includes the initial try. * <p> * It is not recommended to use it directly, because usually exception classification is * strongly recommended (to not retry on OutOfMemoryError, for example). * <p> * For daily usage see {@link RetryTemplate#builder()} * <p> * Volatility of maxAttempts allows concurrent modification and does not require safe * publication of new instance after construction. */ @SuppressWarnings("serial") public class MaxAttemptsRetryPolicy implements RetryPolicy { /** * The default limit to the number of attempts for a new policy. */ public final static int DEFAULT_MAX_ATTEMPTS = 3; private volatile int maxAttempts; /** * Create a {@link MaxAttemptsRetryPolicy} with the default number of retry attempts * (3), retrying all throwables. */ public MaxAttemptsRetryPolicy() { this.maxAttempts = DEFAULT_MAX_ATTEMPTS; } /** * Create a {@link MaxAttemptsRetryPolicy} with the specified number of retry * attempts, retrying all throwables. * @param maxAttempts the maximum number of attempts */ public MaxAttemptsRetryPolicy(int maxAttempts) { this.maxAttempts = maxAttempts; } /** * Set the number of attempts before retries are exhausted. Includes the initial * attempt before the retries begin so, generally, will be {@code >= 1}. For example * setting this property to 3 means 3 attempts total (initial + 2 retries). * @param maxAttempts the maximum number of attempts including the initial attempt. */ public void setMaxAttempts(int maxAttempts) { this.maxAttempts = maxAttempts; } /** * The maximum number of attempts before failure. * @return the maximum number of attempts */ public int getMaxAttempts() { return this.maxAttempts; } /** * Test for retryable operation based on the status. * * @see RetryPolicy#canRetry(RetryContext) * @return true if the last exception was retryable and the number of attempts so far * is less than the limit. */ @Override public boolean canRetry(RetryContext context) { return context.getRetryCount() < this.maxAttempts; } @Override public void close(RetryContext status) { } /** * Update the status with another attempted retry and the latest exception. * * @see RetryPolicy#registerThrowable(RetryContext, Throwable) */ @Override public void registerThrowable(RetryContext context, Throwable throwable) { ((RetryContextSupport) context).registerThrowable(throwable); } /** * Get a status object that can be used to track the current operation according to * this policy. Has to be aware of the latest exception and the number of attempts. * * @see RetryPolicy#open(RetryContext) */ @Override public RetryContext open(RetryContext parent) { return new RetryContextSupport(parent); } }
1,050
6,036
<reponame>dennyac/onnxruntime<filename>onnxruntime/contrib_ops/cpu/maxpool_with_mask.cc // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "maxpool_with_mask.h" namespace onnxruntime { namespace contrib { ONNX_CPU_OPERATOR_TYPED_MS_KERNEL( MaxpoolWithMask, 1, float, KernelDefBuilder() .TypeConstraint("X", DataTypeImpl::GetTensorType<float>()), MaxpoolWithMask); } // namespace contrib } // namespace onnxruntime
192
952
package com.rudecrab.rbac.mapper; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Constants; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.rudecrab.rbac.model.entity.User; import com.rudecrab.rbac.model.vo.UserPageVO; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; /** * @author RudeCrab */ @Repository public interface UserMapper extends BaseMapper<User> { /** * 查询用户分页信息 * @param page 分页条件 * @param wrapper 查询条件 * @return 分页对象 */ IPage<UserPageVO> selectPage(Page<UserPageVO> page, @Param(Constants.WRAPPER) Wrapper<UserPageVO> wrapper); }
361
574
<reponame>joeranbosma/ModelsGenesis #!/usr/bin/env python # coding: utf-8 # In[1]: from __future__ import print_function import warnings warnings.filterwarnings('ignore') import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'} import keras print("keras = {}".format(keras.__version__)) import tensorflow as tf print("tensorflow-gpu = {}".format(tf.__version__)) try: tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) except: pass import shutil import numpy as np from tqdm import tqdm from config import models_genesis_config from utils import * from unet3d import * from keras.callbacks import LambdaCallback,TensorBoard,ReduceLROnPlateau os.environ["CUDA_VISIBLE_DEVICES"] = "0" conf = models_genesis_config() conf.display() # # Load subvolumes for self-supervised learning # In[2]: x_train = [] for i,fold in enumerate(tqdm(conf.train_fold)): file_name = "bat_"+str(conf.scale)+"_s_"+str(conf.input_rows)+"x"+str(conf.input_cols)+"x"+str(conf.input_deps)+"_"+str(fold)+".npy" s = np.load(os.path.join(conf.data, file_name)) x_train.extend(s) x_train = np.expand_dims(np.array(x_train), axis=1) x_valid = [] for i,fold in enumerate(tqdm(conf.valid_fold)): file_name = "bat_"+str(conf.scale)+"_s_"+str(conf.input_rows)+"x"+str(conf.input_cols)+"x"+str(conf.input_deps)+"_"+str(fold)+".npy" s = np.load(os.path.join(conf.data, file_name)) x_valid.extend(s) x_valid = np.expand_dims(np.array(x_valid), axis=1) print("x_train: {} | {:.2f} ~ {:.2f}".format(x_train.shape, np.min(x_train), np.max(x_train))) print("x_valid: {} | {:.2f} ~ {:.2f}".format(x_valid.shape, np.min(x_valid), np.max(x_valid))) # # Setup the model # In[3]: if conf.model == "Vnet": model = unet_model_3d((1, conf.input_rows, conf.input_cols, conf.input_deps), batch_normalization=True) if conf.weights is not None: print("Load the pre-trained weights from {}".format(conf.weights)) model.load_weights(conf.weights) model.compile(optimizer=keras.optimizers.SGD(lr=conf.lr, momentum=0.9, decay=0.0, nesterov=False), loss="MSE", metrics=["MAE", "MSE"]) if os.path.exists(os.path.join(conf.model_path, conf.exp_name+".txt")): os.remove(os.path.join(conf.model_path, conf.exp_name+".txt")) with open(os.path.join(conf.model_path, conf.exp_name+".txt"),'w') as fh: model.summary(positions=[.3, .55, .67, 1.], print_fn=lambda x: fh.write(x + '\n')) shutil.rmtree(os.path.join(conf.logs_path, conf.exp_name), ignore_errors=True) if not os.path.exists(os.path.join(conf.logs_path, conf.exp_name)): os.makedirs(os.path.join(conf.logs_path, conf.exp_name)) tbCallBack = TensorBoard(log_dir=os.path.join(conf.logs_path, conf.exp_name), histogram_freq=0, write_graph=True, write_images=True, ) tbCallBack.set_model(model) early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=conf.patience, verbose=0, mode='min', ) check_point = keras.callbacks.ModelCheckpoint(os.path.join(conf.model_path, conf.exp_name+".h5"), monitor='val_loss', verbose=1, save_best_only=True, mode='min', ) lrate_scheduler = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, min_delta=0.0001, min_lr=1e-6, verbose=1) callbacks = [check_point, early_stopping, tbCallBack, lrate_scheduler] # # Train Models Genesis # In[ ]: while conf.batch_size > 1: # To find a largest batch size that can be fit into GPU try: model.fit_generator(generate_pair(x_train, conf.batch_size, config=conf, status="train"), validation_data=generate_pair(x_valid, conf.batch_size, config=conf, status="test"), validation_steps=x_valid.shape[0]//conf.batch_size, steps_per_epoch=x_train.shape[0]//conf.batch_size, epochs=conf.nb_epoch, max_queue_size=conf.max_queue_size, workers=conf.workers, use_multiprocessing=True, shuffle=True, verbose=conf.verbose, callbacks=callbacks, ) break except tf.errors.ResourceExhaustedError as e: conf.batch_size = int(conf.batch_size - 2) print("\n> Batch size = {}".format(conf.batch_size)) # In[ ]:
2,575
372
/* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * * -*- mode: c, c-basic-offset: 4 -*- */ /* * Copyright © BeyondTrust Software 2004 - 2019 * 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. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Copyright (C) BeyondTrust Software. All rights reserved. * * Module Name: * * eventdefs.h * * Abstract: * * BeyondTrust Eventlog Service (LWEVT) * * Definitions * * Authors: <NAME> (<EMAIL>) * <NAME> (<EMAIL>) */ #ifndef __EVENTDEFS_H__ #define __EVENTDEFS_H__ #define TRY DCETHREAD_TRY #define CATCH_ALL DCETHREAD_CATCH_ALL(THIS_CATCH) #define CATCH(x) DCETHREAD_CATCH(x) #define FINALLY DCETHREAD_FINALLY #define ENDTRY DCETHREAD_ENDTRY #ifdef _WIN32 void __RPC_FAR * __RPC_USER midl_user_allocate(size_t cBytes); void __RPC_USER midl_user_free(void __RPC_FAR * p); #define RPC_SS_ALLOCATE(dwSize) RpcSsAllocate(dwSize) #define RPC_SS_FREE(node) RpcSsFree(node) #else #define RPC_SS_ALLOCATE(dwSize) rpc_ss_allocate(dwSize) #define RPC_SS_FREE(node) rpc_ss_free(node) #endif #ifndef RPC_CSTR #define RPC_CSTR UCHAR* #endif #define RPC_STRING_BINDING_COMPOSE(protocol, hostname, endpoint, pBindingString, pStatus) \ *pStatus = RpcStringBindingCompose(NULL, (RPC_CSTR)(protocol), (RPC_CSTR)(hostname), (RPC_CSTR)endpoint, NULL, (RPC_CSTR*)(pBindingString)) #define RPC_BINDING_FROM_STRING_BINDING(bindingString, pBindingHandle, pStatus) \ *pStatus = RpcBindingFromStringBinding((RPC_CSTR)(bindingString), (pBindingHandle)) #define RPC_STRING_FREE(pString, pStatus) \ *pStatus = RpcStringFree((RPC_CSTR*)pString) #define RPC_BINDING_FREE(pBindingHandle, pStatus) \ *pStatus = RpcBindingFree(pBindingHandle) #define _EVT_LOG_AT(Level, ...) LW_RTL_LOG_AT_LEVEL(Level, "eventlog", __VA_ARGS__) #define EVT_LOG_ALWAYS(...) _EVT_LOG_AT(LW_RTL_LOG_LEVEL_ALWAYS, __VA_ARGS__) #define EVT_LOG_ERROR(...) _EVT_LOG_AT(LW_RTL_LOG_LEVEL_ERROR, __VA_ARGS__) #define EVT_LOG_WARNING(...) _EVT_LOG_AT(LW_RTL_LOG_LEVEL_WARNING, __VA_ARGS__) #define EVT_LOG_INFO(...) _EVT_LOG_AT(LW_RTL_LOG_LEVEL_INFO, __VA_ARGS__) #define EVT_LOG_VERBOSE(...) _EVT_LOG_AT(LW_RTL_LOG_LEVEL_VERBOSE, __VA_ARGS__) #define EVT_LOG_DEBUG(...) _EVT_LOG_AT(LW_RTL_LOG_LEVEL_DEBUG, __VA_ARGS__) #define EVT_LOG_TRACE(...) _EVT_LOG_AT(LW_RTL_LOG_LEVEL_TRACE, __VA_ARGS__) #define BAIL_ON_EVT_ERROR(dwError) \ if (dwError) { \ EVT_LOG_DEBUG("Error at %s:%d. Error [code:%d]", __FILE__, __LINE__, dwError); \ goto error; \ } #ifndef _EVENTLOG_NO_DCERPC_SUPPORT_ #define BAIL_ON_DCE_ERROR(dwError, rpcstatus) \ if ((rpcstatus) != RPC_S_OK) \ { \ dce_error_string_t errstr; \ int error_status; \ dce_error_inq_text((rpcstatus), (unsigned char*)errstr, \ &error_status); \ if (error_status == error_status_ok) \ { \ EVT_LOG_ERROR("DCE Error [0x%8x] Reason [%s]", \ (rpcstatus), errstr); \ } \ else \ { \ EVT_LOG_ERROR("DCE Error [0x%8x]", (rpcstatus)); \ } \ \ (dwError) = LwNtStatusToWin32Error( \ LwRpcStatusToNtStatus((rpcstatus))); \ \ goto error; \ } #endif #endif /* __EVENTDEFS_H__ */
2,786
11,396
<filename>awx/main/migrations/0008_v320_drop_v1_credential_fields.py # -*- coding: utf-8 -*- # Python from __future__ import unicode_literals # Django from django.db import migrations from django.db import models # AWX import awx.main.fields class Migration(migrations.Migration): dependencies = [ ('main', '0007_v320_data_migrations'), ] operations = [ migrations.RemoveField( model_name='credential', name='authorize', ), migrations.RemoveField( model_name='credential', name='authorize_password', ), migrations.RemoveField( model_name='credential', name='become_method', ), migrations.RemoveField( model_name='credential', name='become_password', ), migrations.RemoveField( model_name='credential', name='become_username', ), migrations.RemoveField( model_name='credential', name='client', ), migrations.RemoveField( model_name='credential', name='cloud', ), migrations.RemoveField( model_name='credential', name='domain', ), migrations.RemoveField( model_name='credential', name='host', ), migrations.RemoveField( model_name='credential', name='kind', ), migrations.RemoveField( model_name='credential', name='password', ), migrations.RemoveField( model_name='credential', name='project', ), migrations.RemoveField( model_name='credential', name='secret', ), migrations.RemoveField( model_name='credential', name='security_token', ), migrations.RemoveField( model_name='credential', name='ssh_key_data', ), migrations.RemoveField( model_name='credential', name='ssh_key_unlock', ), migrations.RemoveField( model_name='credential', name='subscription', ), migrations.RemoveField( model_name='credential', name='tenant', ), migrations.RemoveField( model_name='credential', name='username', ), migrations.RemoveField( model_name='credential', name='vault_password', ), migrations.AlterUniqueTogether( name='credentialtype', unique_together=set([('name', 'kind')]), ), migrations.AlterField( model_name='credential', name='credential_type', field=models.ForeignKey( related_name='credentials', to='main.CredentialType', on_delete=models.CASCADE, null=False, help_text='Specify the type of credential you want to create. Refer to the Ansible Tower documentation for details on each type.', ), ), migrations.AlterField( model_name='credential', name='inputs', field=awx.main.fields.CredentialInputField( default=dict, help_text='Enter inputs using either JSON or YAML syntax. Use the radio button to toggle between the two. Refer to the Ansible Tower documentation for example syntax.', blank=True, ), ), migrations.RemoveField( model_name='job', name='cloud_credential', ), migrations.RemoveField( model_name='job', name='network_credential', ), migrations.RemoveField( model_name='jobtemplate', name='cloud_credential', ), migrations.RemoveField( model_name='jobtemplate', name='network_credential', ), ]
2,107
1,071
/* * Copyright 2018- The Pixie 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. * * SPDX-License-Identifier: Apache-2.0 */ #include <benchmark/benchmark.h> #include "src/common/base/base.h" #include "src/common/testing/test_environment.h" #include "src/stirling/obj_tools/dwarf_reader.h" using px::stirling::obj_tools::DwarfReader; using px::testing::BazelBinTestFilePath; constexpr std::string_view kBinary = "src/stirling/testing/demo_apps/go_grpc_tls_pl/server/golang_1_16_grpc_tls_server_binary/go/" "src/grpc_tls_server/grpc_tls_server"; struct SymAddrs { // Members of net/http.http2serverConn. int32_t http2serverConn_conn_offset; int32_t http2serverConn_hpackEncoder_offset; // Members of net/http.http2HeadersFrame int32_t http2HeadersFrame_http2FrameHeader_offset; // Members of net/http.http2FrameHeader. int32_t http2FrameHeader_Flags_offset; int32_t http2FrameHeader_StreamID_offset; // Members of net/http.http2writeResHeaders. int32_t http2writeResHeaders_streamID_offset; int32_t http2writeResHeaders_endStream_offset; // Members of net/http.http2MetaHeadersFrame. int32_t http2MetaHeadersFrame_http2HeadersFrame_offset; int32_t http2MetaHeadersFrame_Fields_offset; }; void GetSymAddrs(DwarfReader* dwarf_reader, SymAddrs* symaddrs) { #define GET_SYMADDR(symaddr, type, member) \ symaddr = dwarf_reader->GetStructMemberOffset(type, member).ValueOr(-1); GET_SYMADDR(symaddrs->http2serverConn_conn_offset, "net/http.http2serverConn", "conn"); GET_SYMADDR(symaddrs->http2serverConn_hpackEncoder_offset, "net/http.http2serverConn", "hpackEncoder"); GET_SYMADDR(symaddrs->http2HeadersFrame_http2FrameHeader_offset, "net/http.http2HeadersFrame", "http2FrameHeader"); GET_SYMADDR(symaddrs->http2FrameHeader_Flags_offset, "net/http.http2FrameHeader", "Flags"); GET_SYMADDR(symaddrs->http2FrameHeader_StreamID_offset, "net/http.http2FrameHeader", "StreamID"); GET_SYMADDR(symaddrs->http2writeResHeaders_streamID_offset, "net/http.http2writeResHeaders", "streamID"); GET_SYMADDR(symaddrs->http2writeResHeaders_endStream_offset, "net/http.http2writeResHeaders", "endStream"); GET_SYMADDR(symaddrs->http2MetaHeadersFrame_http2HeadersFrame_offset, "net/http.http2MetaHeadersFrame", "http2HeadersFrame"); GET_SYMADDR(symaddrs->http2MetaHeadersFrame_Fields_offset, "net/http.http2MetaHeadersFrame", "Fields"); } // NOLINTNEXTLINE : runtime/references. static void BM_noindex(benchmark::State& state) { size_t num_lookup_iterations = state.range(0); for (auto _ : state) { SymAddrs symaddrs; PL_ASSIGN_OR_EXIT(std::unique_ptr<DwarfReader> dwarf_reader, DwarfReader::CreateWithoutIndexing(kBinary)); for (size_t i = 0; i < num_lookup_iterations; ++i) { GetSymAddrs(dwarf_reader.get(), &symaddrs); benchmark::DoNotOptimize(symaddrs); } } } // NOLINTNEXTLINE : runtime/references. static void BM_indexed(benchmark::State& state) { size_t num_lookup_iterations = state.range(0); for (auto _ : state) { SymAddrs symaddrs; PL_ASSIGN_OR_EXIT(std::unique_ptr<DwarfReader> dwarf_reader, DwarfReader::CreateIndexingAll(kBinary)); for (size_t i = 0; i < num_lookup_iterations; ++i) { GetSymAddrs(dwarf_reader.get(), &symaddrs); benchmark::DoNotOptimize(symaddrs); } } } BENCHMARK(BM_noindex)->RangeMultiplier(2)->Range(1, 16); BENCHMARK(BM_indexed)->RangeMultiplier(2)->Range(1, 16);
1,587
739
package enchcracker; public class NativeException extends RuntimeException { private static final long serialVersionUID = 1L; public NativeException(String desc) { super(desc); } }
55
421
<filename>samples/snippets/cpp/VS_Snippets_Data/Classic WebData XmlValidatingReader.GetAttribute Example/CPP/source.cpp // <Snippet1> #using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; int main() { //Create the validating reader. XmlTextReader^ txtreader = gcnew XmlTextReader( "attrs.xml" ); XmlValidatingReader^ reader = gcnew XmlValidatingReader( txtreader ); //Read the ISBN attribute. reader->MoveToContent(); String^ isbn = reader->GetAttribute( "ISBN" ); Console::WriteLine( "The ISBN value: {0}", isbn ); //Close the reader. reader->Close(); } // </Snippet1>
268
686
<filename>pentest-tool/pentest/libs/cms.py #!/usr/bin/env python #-*- coding:utf-8 -*- ''' Pentestdb, a database for penetration test. Copyright (c) 2015 alpha1e0 ======================================================== CMS 识别 ''' import os import sys import requests as http from commons import Log from commons import PenError from commons import YamlConf from commons import URL from commons import conf class CMSIdentify(object): ''' CMS识别功能 ''' _fingerprintFile = os.path.join(conf['ptdpath'],"cms_fingerprint.yaml") def __init__(self, baseURL, notFoundPattern=None): ''' @params: baseURL: 待识别的站点的URL notFoundPattern: 指定notFoundPattern,有时候website只返回301或200,这时候需要该字段来识别‘404’ ''' baseURL = URL.getURI(baseURL) self.baseURL = baseURL.rstrip("/") self.notFoundPattern = notFoundPattern self.fp = YamlConf(self._fingerprintFile) self.log = Log("cmsidentify") def _checkPath(self, path, pattern): url = self.baseURL + path try: #response = http.get(url) response = http.get(url, allow_redirects=False) except http.ConnectionError as error: self.log.debug("Checking '{0}' failed, connection failed".format(url)) return False if response.status_code == 200: if self.notFoundPattern: if self.notFoundPattern in response.content: self.log.debug("Checking '{0}' failed, notFoundPattern matchs.".format(url)) return False #if response.history: # if self.notFoundPattern in response.history[0].content: # self.log.debug("Checking '{0}' failed, notFoundPattern matchs.".format(url)) # return False if not pattern: self.log.debug("Checking '{0}' success, status code 200.".format(url)) return True else: if pattern in response.text: self.log.debug("Checking '{0}' success, status code 200, match pattern {1}.".format(url,pattern)) return True else: self.log.debug("Checking '{0}' failed, pattern not found.".format(url)) return False else: self.log.debug("Checking '{0}' failed, status code {1}".format(url, response.status_code)) return False def _checkCMS(self, cmstype, cmsfp): matchList = [] for line in cmsfp: if line['need']: if not self._checkPath(line['path'], line['pattern']): return False else: if self._checkPath(line['path'], line['pattern']): matchList.append([line['path'], line['pattern']]) return matchList if matchList else False def identify(self): ''' CMS识别 @returns: (cmstype, matchs):CMS识别结果,返回元组CMS类型,详细识别信息,如果识别失败,则matchs为空 ''' for cmstype,cmsfp in self.fp.iteritems(): self.log.debug("Verify {0}".format(cmstype)) matchs = self._checkCMS(cmstype, cmsfp) if matchs: break else: matchs = [] return (cmstype,matchs)
1,734
348
<filename>docs/data/leg-t2/065/06501253.json {"nom":"Lamarque-Rustaing","circ":"1ère circonscription","dpt":"Hautes-Pyrénées","inscrits":49,"abs":19,"votants":30,"blancs":3,"nuls":0,"exp":27,"res":[{"nuance":"REM","nom":"<NAME>","voix":21},{"nuance":"FI","nom":"<NAME>","voix":6}]}
119
401
<filename>liteflow-core/src/main/java/com/yomahub/liteflow/property/LiteflowConfigGetter.java package com.yomahub.liteflow.property; import cn.hutool.core.util.ObjectUtil; import com.yomahub.liteflow.util.SpringAware; /** * liteflow的配置获取器 */ public class LiteflowConfigGetter { public static LiteflowConfig get(){ LiteflowConfig liteflowConfig = SpringAware.getBean(LiteflowConfig.class); //这里liteflowConfig不可能为null //如果在springboot环境,由于自动装配,所以不可能为null //在spring环境,如果xml没配置,在FlowExecutor的init时候就已经报错了 //只有在非spring环境下,是为null if (ObjectUtil.isNull(liteflowConfig)){ liteflowConfig = new LiteflowConfig(); } return liteflowConfig; } }
414
805
<reponame>shuipi100/kaldi<filename>src/cudamatrix/cu-packed-matrix-test.cc // cudamatrix/cu-packed-matrix-test.cc // // Copyright 2013 <NAME> // <NAME> // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. // UnitTests for testing cu-sp-matrix.h methods. // #include <iostream> #include <vector> #include <cstdlib> #include "base/kaldi-common.h" #include "cudamatrix/cu-device.h" #include "cudamatrix/cu-sp-matrix.h" #include "cudamatrix/cu-vector.h" #include "cudamatrix/cu-math.h" using namespace kaldi; namespace kaldi { /* * INITIALIZERS */ /* * ASSERTS */ template<typename Real> static void AssertEqual(const CuPackedMatrix<Real> &A, const CuPackedMatrix<Real> &B, float tol = 0.001) { KALDI_ASSERT(A.NumRows() == B.NumRows()); for (MatrixIndexT i = 0; i < A.NumRows(); i++) for (MatrixIndexT j = 0; j <= i; j++) KALDI_ASSERT(std::abs(A(i, j) - B(i, j)) < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j))))); } template<typename Real> static void AssertEqual(const PackedMatrix<Real> &A, const PackedMatrix<Real> &B, float tol = 0.001) { KALDI_ASSERT(A.NumRows() == B.NumRows()); for (MatrixIndexT i = 0; i < A.NumRows(); i++) for (MatrixIndexT j = 0; j <= i; j++) KALDI_ASSERT(std::abs(A(i, j) - B(i, j)) < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j))))); } template<typename Real> static void AssertDiagEqual(const PackedMatrix<Real> &A, const CuPackedMatrix<Real> &B, float value, float tol = 0.001) { for (MatrixIndexT i = 0; i < A.NumRows(); i++) { KALDI_ASSERT(std::abs((A(i, i)+value) - B(i, i)) < tol * std::max(1.0, (double) (std::abs(A(i, i)) + std::abs(B(i, i) + value)))); } } template<typename Real> static void AssertDiagEqual(const PackedMatrix<Real> &A, const PackedMatrix<Real> &B, float value, float tol = 0.001) { for (MatrixIndexT i = 0; i < A.NumRows(); i++) { KALDI_ASSERT(std::abs((A(i, i)+value) - B(i, i)) < tol * std::max(1.0, (double) (std::abs(A(i, i)) + std::abs(B(i, i) + value)))); } } template<typename Real> static void AssertEqual(const PackedMatrix<Real> &A, const CuPackedMatrix<Real> &B, float tol = 0.001) { KALDI_ASSERT(A.NumRows() == B.NumRows()); for (MatrixIndexT i = 0; i < A.NumRows(); i++) for (MatrixIndexT j = 0; j <= i; j++) KALDI_ASSERT(std::abs(A(i, j) - B(i, j)) < tol * std::max(1.0, (double) (std::abs(A(i, j)) + std::abs(B(i, j))))); } template<typename Real> static bool ApproxEqual(const PackedMatrix<Real> &A, const PackedMatrix<Real> &B, Real tol = 0.001) { KALDI_ASSERT(A.NumRows() == B.NumRows()); PackedMatrix<Real> diff(A); diff.AddPacked(1.0, B); Real a = std::max(A.Max(), -A.Min()), b = std::max(B.Max(), -B.Min()), d = std::max(diff.Max(), -diff.Min()); return (d <= tol * std::max(a, b)); } /* * Unit Tests */ template<typename Real> static void UnitTestCuPackedMatrixConstructor() { for (MatrixIndexT i = 1; i < 10; i++) { MatrixIndexT dim = 10 * i; PackedMatrix<Real> A(dim); A.SetRandn(); CuPackedMatrix<Real> B(A); CuPackedMatrix<Real> C(B); AssertEqual(B, C); } } template<typename Real> static void UnitTestCuPackedMatrixCopy() { for (MatrixIndexT i = 1; i < 10; i++) { MatrixIndexT dim = 10 * i; PackedMatrix<Real> A(dim); A.SetRandn(); CuPackedMatrix<Real> B(A); CuPackedMatrix<Real> C(dim); C.CopyFromPacked(A); CuPackedMatrix<Real> D(dim); D.CopyFromPacked(B); AssertEqual(C, D); PackedMatrix<Real> E(dim); D.CopyToPacked(&E); AssertEqual(A, E); } } template<typename Real> static void UnitTestCuPackedMatrixTrace() { for (MatrixIndexT i = 1; i < 10; i++) { MatrixIndexT dim = 5 * i + Rand() % 10; PackedMatrix<Real> A(dim); A.SetRandn(); CuPackedMatrix<Real> B(A); AssertEqual(A.Trace(), B.Trace()); } } template<typename Real> static void UnitTestCuPackedMatrixScale() { for (MatrixIndexT i = 1; i < 10; i++) { MatrixIndexT dim = 5 * i + Rand() % 10; PackedMatrix<Real> A(dim); A.SetRandn(); CuPackedMatrix<Real> B(A); Real scale_factor = 23.5896223; A.Scale(scale_factor); B.Scale(scale_factor); AssertEqual(A, B); } } template<typename Real> static void UnitTestCuPackedMatrixScaleDiag() { for (MatrixIndexT i = 1; i < 10; i++) { MatrixIndexT dim = 5 * i + Rand() % 10; PackedMatrix<Real> A(dim); A.SetRandn(); CuPackedMatrix<Real> B(A); Real scale_factor = 23.5896223; A.ScaleDiag(scale_factor); B.ScaleDiag(scale_factor); AssertEqual(A, B); } } template<typename Real> static void UnitTestCuPackedMatrixAddToDiag() { for (MatrixIndexT i = 1; i < 10; i++) { MatrixIndexT dim = 5 * i + Rand() % 10; PackedMatrix<Real> A(dim); A.SetRandn(); CuPackedMatrix<Real> B(A); Real value = Rand() % 50; B.AddToDiag(value); AssertDiagEqual(A, B, value); } } template<typename Real> static void UnitTestCuPackedMatrixSetUnit() { for (MatrixIndexT i = 1; i < 10; i++) { MatrixIndexT dim = 5 * i + Rand() % 10; CuPackedMatrix<Real> A(dim); A.SetUnit(); for (MatrixIndexT i = 0; i < A.NumRows(); i++) { for (MatrixIndexT j = 0; j < A.NumRows(); j++) { if (i != j) { KALDI_ASSERT(A(i, j) == 0); } else { KALDI_ASSERT(A(i, j) == 1.0); } } } } } template<typename Real> void CudaPackedMatrixUnitTest() { UnitTestCuPackedMatrixConstructor<Real>(); //UnitTestCuPackedMatrixCopy<Real>(); UnitTestCuPackedMatrixTrace<Real>(); UnitTestCuPackedMatrixScale<Real>(); UnitTestCuPackedMatrixAddToDiag<Real>(); UnitTestCuPackedMatrixSetUnit<Real>(); } } // namespace kaldi int main() { using namespace kaldi; #if HAVE_CUDA == 1 CuDevice::Instantiate().SetDebugStrideMode(true); // Select the GPU CuDevice::Instantiate().SelectGpuId("yes"); #endif kaldi::CudaPackedMatrixUnitTest<float>(); #if HAVE_CUDA == 1 if (CuDevice::Instantiate().DoublePrecisionSupported()) { kaldi::CudaPackedMatrixUnitTest<double>(); } else { KALDI_WARN << "Double precision not supported"; } #else kaldi::CudaPackedMatrixUnitTest<double>(); #endif KALDI_LOG << "Tests succeeded"; #if HAVE_CUDA == 1 CuDevice::Instantiate().PrintProfile(); #endif return 0; }
3,379
14,668
<reponame>zealoussnow/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/app_list/app_list_model_provider.h" #include "base/check.h" #include "base/check_op.h" namespace ash { namespace { // Pointer to the global `AppListModelProvider` instance. AppListModelProvider* g_instance = nullptr; } // namespace AppListModelProvider::AppListModelProvider() { DCHECK(!g_instance); g_instance = this; } AppListModelProvider::~AppListModelProvider() { DCHECK_EQ(g_instance, this); g_instance = nullptr; } // static AppListModelProvider* AppListModelProvider::Get() { return g_instance; } void AppListModelProvider::SetActiveModel(AppListModel* model, SearchModel* search_model) { DCHECK(model); DCHECK(search_model); model_ = model; search_model_ = search_model; for (auto& observer : observers_) observer.OnActiveAppListModelsChanged(model_, search_model_); } void AppListModelProvider::ClearActiveModel() { model_ = &default_model_; search_model_ = &default_search_model_; for (auto& observer : observers_) observer.OnActiveAppListModelsChanged(model_, search_model_); } void AppListModelProvider::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void AppListModelProvider::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } } // namespace ash
524
746
# Copyright (c) OpenMMLab. All rights reserved. from typing import Dict, Optional, Sequence import numpy as np import onnx import pyppl.common as pplcommon import pyppl.nn as pplnn import torch from mmdeploy.utils import Backend, parse_device_id from mmdeploy.utils.timer import TimeCounter from ..base import BACKEND_WRAPPER, BaseWrapper from .utils import register_engines @BACKEND_WRAPPER.register_module(Backend.PPLNN.value) class PPLNNWrapper(BaseWrapper): """PPLNN wrapper for inference. Args: onnx_file (str): Path of input ONNX model file. algo_file (str): Path of PPLNN algorithm file. device_id (int): Device id to put model. Examples: >>> from mmdeploy.backend.pplnn import PPLNNWrapper >>> import torch >>> >>> onnx_file = 'model.onnx' >>> model = PPLNNWrapper(onnx_file, 'end2end.json', 0) >>> inputs = dict(input=torch.randn(1, 3, 224, 224)) >>> outputs = model(inputs) >>> print(outputs) """ def __init__(self, onnx_file: str, algo_file: str, device: str, output_names: Optional[Sequence[str]] = None, **kwargs): # enable quick select by default to speed up pipeline # TODO: open it to users after pplnn supports saving serialized models # TODO: assert device is gpu device_id = parse_device_id(device) # enable quick select by default to speed up pipeline # TODO: disable_avx512 will be removed or open to users in config engines = register_engines( device_id, disable_avx512=False, quick_select=False, import_algo_file=algo_file) runtime_builder = pplnn.OnnxRuntimeBuilderFactory.CreateFromFile( onnx_file, engines) assert runtime_builder is not None, 'Failed to create '\ 'OnnxRuntimeBuilder.' runtime = runtime_builder.CreateRuntime() assert runtime is not None, 'Failed to create the instance of Runtime.' self.runtime = runtime self.inputs = { runtime.GetInputTensor(i).GetName(): runtime.GetInputTensor(i) for i in range(runtime.GetInputCount()) } if output_names is None: model = onnx.load(onnx_file) output_names = [node.name for node in model.graph.output] super().__init__(output_names) def forward(self, inputs: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """Run forward inference. Args: inputs (Dict[str, torch.Tensor]): Input name and tensor pairs. Return: Dict[str, torch.Tensor]: The output name and tensor pairs. """ for name, input_tensor in inputs.items(): input_tensor = input_tensor.contiguous() self.inputs[name].ConvertFromHost(input_tensor.cpu().numpy()) self.__pplnn_execute() outputs = {} for i in range(self.runtime.GetOutputCount()): out_tensor = self.runtime.GetOutputTensor(i).ConvertToHost() name = self.output_names[i] if out_tensor: outputs[name] = np.array(out_tensor, copy=False) else: out_shape = self.runtime.GetOutputTensor( i).GetShape().GetDims() outputs[name] = np.random.rand(*out_shape) outputs[name] = torch.from_numpy(outputs[name]) return outputs @TimeCounter.count_time() def __pplnn_execute(self): """Run inference with PPLNN.""" status = self.runtime.Run() assert status == pplcommon.RC_SUCCESS, 'Run() failed: ' + \ pplcommon.GetRetCodeStr(status)
1,728
880
/** * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.qos.logback.core.util; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import org.junit.Test; import ch.qos.logback.core.util.LocationUtil; /** * Unit tests for {@link LocationUtil}. * * @author <NAME> */ public class LocationUtilTest { private static final String TEST_CLASSPATH_RESOURCE = "util/testResource.txt"; private static final String TEST_PATTERN = "TEST RESOURCE"; @Test public void testImplicitClasspathUrl() throws Exception { URL url = LocationUtil.urlForResource(TEST_CLASSPATH_RESOURCE); validateResource(url); } @Test public void testExplicitClasspathUrl() throws Exception { URL url = LocationUtil.urlForResource( LocationUtil.CLASSPATH_SCHEME + TEST_CLASSPATH_RESOURCE); validateResource(url); } @Test public void testExplicitClasspathUrlWithLeadingSlash() throws Exception { URL url = LocationUtil.urlForResource( LocationUtil.CLASSPATH_SCHEME + "/" + TEST_CLASSPATH_RESOURCE); validateResource(url); } @Test(expected = MalformedURLException.class) public void testExplicitClasspathUrlEmptyPath() throws Exception { LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME); } @Test(expected = MalformedURLException.class) public void testExplicitClasspathUrlWithRootPath() throws Exception { LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + "/"); } @Test public void testFileUrl() throws Exception { File file = File.createTempFile("testResource", ".txt"); file.deleteOnExit(); PrintWriter writer = new PrintWriter(file); writer.println(TEST_PATTERN); writer.close(); URL url = file.toURI().toURL(); validateResource(url); } private void validateResource(URL url) throws IOException { InputStream inputStream = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = reader.readLine(); assertEquals(TEST_PATTERN, line); } finally { try { inputStream.close(); } catch (IOException ex) { // ignore close exception ex.printStackTrace(System.err); } } } }
1,007
6,218
{ "name": "graphite-selector", "issue": "", "data": [ "graphite-selector.bar.baz 1 {TIME_S-1m}", "graphite-selector.xxx.yy 2 {TIME_S-1m}", "graphite-selector.bb.cc 3 {TIME_S-1m}", "graphite-selector.a.baz 4 {TIME_S-1m}"], "query": ["/api/v1/query?query=sort({__graphite__='graphite-selector.*.baz'})&time={TIME_S-1m}"], "result_query": { "status":"success", "data":{"resultType":"vector","result":[ {"metric":{"__name__":"graphite-selector.bar.baz"},"value":["{TIME_S-1m}","1"]}, {"metric":{"__name__":"graphite-selector.a.baz"},"value":["{TIME_S-1m}","4"]} ]} } }
289
45,293
{ "1": { "neg": { "2": [ { "specVersion": "0.1-464", "casesNumber": 1, "description": "type context for a nested type declaration of a parent type declaration does not include the type parameters of PD", "path": "compiler/tests-spec/testData/diagnostics/linked/type-system/type-contexts-and-scopes/inner-and-nested-type-contexts/p-1/neg/2.1.kt", "unexpectedBehaviour": false, "linkType": "main" }, { "specVersion": "0.1-544", "casesNumber": 1, "description": "Primary constructor for nested class with mutable property constructor parameter", "path": "compiler/tests-spec/testData/diagnostics/linked/declarations/classifier-declaration/class-declaration/constructor-declaration/p-5/neg/2.1.kt", "unexpectedBehaviour": false, "linkType": "primary" }, { "specVersion": "0.1-544", "casesNumber": 2, "description": "Primary constructor for nested class with regular constructor parameter", "path": "compiler/tests-spec/testData/diagnostics/linked/declarations/classifier-declaration/class-declaration/constructor-declaration/p-5/neg/1.2.kt", "unexpectedBehaviour": false, "linkType": "primary" }, { "specVersion": "0.1-544", "casesNumber": 1, "description": "Primary constructor for nested class with mutable property constructor parameter", "path": "compiler/tests-spec/testData/diagnostics/linked/declarations/classifier-declaration/class-declaration/constructor-declaration/p-5/neg/3.1.kt", "unexpectedBehaviour": false, "linkType": "primary" }, { "specVersion": "0.1-544", "casesNumber": 3, "description": "Primary constructor for nested class with regular constructor parameter", "path": "compiler/tests-spec/testData/diagnostics/linked/declarations/classifier-declaration/class-declaration/constructor-declaration/p-5/neg/1.1.kt", "unexpectedBehaviour": false, "linkType": "primary" } ], "1": [ { "specVersion": "0.1-464", "casesNumber": 2, "description": "type context for a nested type declaration of a parent type declaration does not include the type parameters of PD", "path": "compiler/tests-spec/testData/diagnostics/linked/type-system/type-contexts-and-scopes/inner-and-nested-type-contexts/p-1/neg/1.2.kt", "unexpectedBehaviour": false, "linkType": "main", "helpers": "checkType" }, { "specVersion": "0.1-464", "casesNumber": 1, "description": "type context for a nested type declaration of a parent type declaration does not include the type parameters of PD", "path": "compiler/tests-spec/testData/diagnostics/linked/type-system/type-contexts-and-scopes/inner-and-nested-type-contexts/p-1/neg/1.1.kt", "unexpectedBehaviour": false, "linkType": "main", "helpers": "checkType" } ] }, "pos": { "1": [ { "specVersion": "0.1-464", "casesNumber": 2, "description": "type context for a nested type declaration of a parent type declaration does not include the type parameters of PD", "path": "compiler/tests-spec/testData/diagnostics/linked/type-system/type-contexts-and-scopes/inner-and-nested-type-contexts/p-1/pos/1.2.kt", "unexpectedBehaviour": false, "linkType": "main", "helpers": "checkType" }, { "specVersion": "0.1-464", "casesNumber": 1, "description": "type context for a nested type declaration of a parent type declaration does not include the type parameters of PD", "path": "compiler/tests-spec/testData/diagnostics/linked/type-system/type-contexts-and-scopes/inner-and-nested-type-contexts/p-1/pos/1.1.kt", "unexpectedBehaviour": false, "linkType": "main", "helpers": "checkType" } ] } } }
1,825
442
from os import environ from loader import Loader import actions LOADER = Loader() def lambda_handler(event, context): status = LOADER.personalize_cli.delete_event_tracker( eventTrackerArn=event['eventTrackerArn'] )
80
692
package com.hubspot.singularity.smtp; import com.hubspot.singularity.ExtendedTaskState; import com.hubspot.singularity.SingularityDisastersData; import com.hubspot.singularity.SingularityRequest; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskHistory; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.api.SingularityPauseRequest; import com.hubspot.singularity.api.SingularityScaleRequest; import java.util.Optional; public interface SingularityMailer { void sendTaskOverdueMail( final Optional<SingularityTask> task, final SingularityTaskId taskId, final SingularityRequest request, final long runTime, final long expectedRuntime ); void queueTaskCompletedMail( final Optional<SingularityTask> task, final SingularityTaskId taskId, final SingularityRequest request, final ExtendedTaskState taskState ); void sendTaskCompletedMail( SingularityTaskHistory taskHistory, SingularityRequest request ); void sendRequestPausedMail( SingularityRequest request, Optional<SingularityPauseRequest> pauseRequest, String user ); void sendRequestUnpausedMail( SingularityRequest request, String user, Optional<String> message ); void sendRequestScaledMail( SingularityRequest request, Optional<SingularityScaleRequest> newScaleRequest, Optional<Integer> formerInstances, String user ); void sendRequestRemovedMail( SingularityRequest request, String user, Optional<String> message ); void sendRequestInCooldownMail(final SingularityRequest request); void sendDisasterMail(final SingularityDisastersData disastersData); }
507
2,151
// Copyright (c) 2010 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 JINGLE_NOTIFIER_LISTENER_XML_ELEMENT_UTIL_H_ #define JINGLE_NOTIFIER_LISTENER_XML_ELEMENT_UTIL_H_ #include <string> namespace buzz { class XmlElement; } namespace notifier { std::string XmlElementToString(const buzz::XmlElement& xml_element); // The functions below are helpful for building notifications-related // XML stanzas. buzz::XmlElement* MakeBoolXmlElement(const char* name, bool value); buzz::XmlElement* MakeIntXmlElement(const char* name, int value); buzz::XmlElement* MakeStringXmlElement(const char* name, const char* value); } // namespace notifier #endif // JINGLE_NOTIFIER_LISTENER_XML_ELEMENT_UTIL_H_
281
316
#import <Cocoa/Cocoa.h> /// Circular slider with an arrow pointing north. @interface MGLCompassCell : NSSliderCell @end
43
384
from django.core.management.base import BaseCommand from django.core.management.utils import get_random_secret_key class Command(BaseCommand): help = "Generates a new SECRET_KEY that can be used in a project settings file." requires_system_checks = False def handle(self, *args, **options): return get_random_secret_key()
107
7,940
#ifndef multi_path_sploit_h #define multi_path_sploit_h bool mptcp_go(void); #endif
39
504
<reponame>steakknife/pcgeos<filename>Tools/utils/mallint.h /* @(#)mallint.h 1.1 86/09/24 SMI*/ /* * Copyright (c) 1986 by Sun Microsystems, Inc. * * $Id: mallint.h,v 1.4 96/05/20 18:56:21 dbaumann Exp $ */ /* * file: mallint.h * description: * * Definitions for malloc.c and friends (realloc.c, memalign.c) * * The node header structure. Header info never overlaps with user * data space, in order to accommodate the following atrocity: * free(p); * realloc(p, newsize); * ... which was historically used to obtain storage compaction as * a side effect of the realloc() call, when the block referenced * by p was coalesced with another free block by the call to free(). * * To reduce storage consumption, a header block is associated with * free blocks only, not allocated blocks. * When a free block is allocated, its header block is put on * a free header block list. * * This creates a header space and a free block space. * The left pointer of a header blocks is used to chain free header * blocks together. New header blocks are allocated in chunks of * NFREE_HDRS. */ #include "malloc.h" typedef enum {false,true} bool; typedef struct freehdr *Freehdr; typedef struct dblk *Dblk; /* * Description of a header for a free block * Only free blocks have such headers. */ struct freehdr { Freehdr left; /* Left tree pointer */ Freehdr right; /* Right tree pointer */ Dblk block; /* Ptr to the data block */ unsigned long size; }; #ifdef NIL # undef NIL #endif #define NIL ((Freehdr) 0) #if defined(sparc) #define WORDSIZE sizeof(double) #else #define WORDSIZE sizeof(int) #endif #define NFREE_HDRS 512 /* Get this many headers at a time */ #define SMALLEST_BLK (sizeof(struct dblk)+WORDSIZE) /* Size of smallest block */ #ifdef NULL #undef NULL #endif #define NULL 0 /* * Description of a data block. * The size precedes the address returned to the user. */ struct dblk { #ifdef MEM_TRACE unsigned long size; /* Size of the block */ unsigned long allocator:24, /* Caller who allocated it */ tag:8; /* Type of data stored */ #else unsigned long size:24, /* Size of block (limited to 16 Mb) */ tag:8; /* Type of data stored */ #if defined(sparc) unsigned long pad; /* Ensure double-alignment */ #endif #endif /* MEM_TRACE */ char data[LABEL_IN_STRUCT]; /* Addr returned to the caller */ }; /* * weight(x) is the size of a block, in bytes; or 0 if and only if x * is a null pointer. Note that malloc() and free() should be * prepared to deal with things like zero-length blocks, which * can be introduced by errant programs. */ #define blkhdr(p) (Dblk)((p)==0?(malloc_t)0:(((malloc_t)p)-(int)&((Dblk)0)->data)) #define weight(x) ((x) == NIL? 0: (x->size)) #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) #define nextblk(p, size) ((Dblk) ((malloc_t) (p) + (size))) #ifndef max # define max(a, b) ((a) < (b)? (b): (a)) #endif #ifndef min # define min(a, b) ((a) < (b)? (a): (b)) #endif #define heapsize() (_ubound - _lbound) #if defined(sparc) #define misaligned(p) ((unsigned)(p)&7) #else #define misaligned(p) ((unsigned)(p)&3) #endif extern Freehdr _root; extern malloc_t _lbound, _ubound; extern int malloc_debug(int level); extern int malloc_verify(void); extern struct mallinfo __mallinfo;
1,398
16,461
#import <Foundation/Foundation.h> #import "ABI41_0_0REANode.h" #import <ABI41_0_0React/ABI41_0_0RCTBridgeModule.h> #import <ABI41_0_0React/ABI41_0_0RCTUIManager.h> @class ABI41_0_0REAModule; typedef void (^ABI41_0_0REAOnAnimationCallback)(CADisplayLink *displayLink); typedef void (^ABI41_0_0REANativeAnimationOp)(ABI41_0_0RCTUIManager *uiManager); typedef void (^ABI41_0_0REAEventHandler)(NSString *eventName, id<ABI41_0_0RCTEvent> event); @interface ABI41_0_0REANodesManager : NSObject @property (nonatomic, weak, nullable) ABI41_0_0RCTUIManager *uiManager; @property (nonatomic, weak, nullable) ABI41_0_0REAModule *reanimatedModule; @property (nonatomic, readonly) CFTimeInterval currentAnimationTimestamp; @property (nonatomic, nullable) NSSet<NSString *> *uiProps; @property (nonatomic, nullable) NSSet<NSString *> *nativeProps; - (nonnull instancetype)initWithModule:(ABI41_0_0REAModule *)reanimatedModule uiManager:(nonnull ABI41_0_0RCTUIManager *)uiManager; - (ABI41_0_0REANode* _Nullable)findNodeByID:(nonnull ABI41_0_0REANodeID)nodeID; - (void)invalidate; - (void)operationsBatchDidComplete; // - (void)postOnAnimation:(ABI41_0_0REAOnAnimationCallback)clb; - (void)postRunUpdatesAfterAnimation; - (void)registerEventHandler:(ABI41_0_0REAEventHandler)eventHandler; - (void)enqueueUpdateViewOnNativeThread:(nonnull NSNumber *)ABI41_0_0ReactTag viewName:(NSString *) viewName nativeProps:(NSMutableDictionary *)nativeProps trySynchronously:(BOOL)trySync; - (void)getValue:(ABI41_0_0REANodeID)nodeID callback:(ABI41_0_0RCTResponseSenderBlock)callback; // graph - (void)createNode:(nonnull ABI41_0_0REANodeID)tag config:(NSDictionary<NSString *, id> *__nonnull)config; - (void)dropNode:(nonnull ABI41_0_0REANodeID)tag; - (void)connectNodes:(nonnull ABI41_0_0REANodeID)parentID childID:(nonnull ABI41_0_0REANodeID)childID; - (void)disconnectNodes:(nonnull ABI41_0_0REANodeID)parentID childID:(nonnull ABI41_0_0REANodeID)childID; - (void)connectNodeToView:(nonnull ABI41_0_0REANodeID)nodeID viewTag:(nonnull NSNumber *)viewTag viewName:(nonnull NSString *)viewName; - (void)disconnectNodeFromView:(nonnull ABI41_0_0REANodeID)nodeID viewTag:(nonnull NSNumber *)viewTag; - (void)attachEvent:(nonnull NSNumber *)viewTag eventName:(nonnull NSString *)eventName eventNodeID:(nonnull ABI41_0_0REANodeID)eventNodeID; - (void)detachEvent:(nonnull NSNumber *)viewTag eventName:(nonnull NSString *)eventName eventNodeID:(nonnull ABI41_0_0REANodeID)eventNodeID; // configuration - (void)configureProps:(nonnull NSSet<NSString *> *)nativeProps uiProps:(nonnull NSSet<NSString *> *)uiProps; - (void)updateProps:(nonnull NSDictionary *)props ofViewWithTag:(nonnull NSNumber *)viewTag withName:(nonnull NSString *)viewName; - (NSString*)obtainProp:(nonnull NSNumber *)viewTag propName:(nonnull NSString *)propName; // events - (void)dispatchEvent:(id<ABI41_0_0RCTEvent>)event; - (void)setValueForNodeID:(nonnull NSNumber *)nodeID value:(nonnull NSNumber *)newValue; @end
1,460
619
/* * Author: <NAME> <<EMAIL>> * Copyright (c) 2014-2016 Intel Corporation. * * This program and the accompanying materials are made available under the * terms of the The MIT License which is available at * https://opensource.org/licenses/MIT. * * SPDX-License-Identifier: MIT */ #include <unistd.h> #include <iostream> #include <string> #include <stdexcept> #include "md.hpp" using namespace upm; using namespace std; MD::MD(int bus, uint8_t address) : m_md(md_init(bus, address)) { if (!m_md) throw std::runtime_error(std::string(__FUNCTION__) + ": md_init() failed"); } MD::~MD() { md_close(m_md); } bool MD::writePacket(MD_REG_T reg, uint8_t data1, uint8_t data2) { if (!md_write_packet(m_md, reg, data1, data2)) throw std::runtime_error(std::string(__FUNCTION__) + ": md_write_packet() failed"); return true; } bool MD::setMotorSpeeds(uint8_t speedA, uint8_t speedB) { if (!md_set_motor_speeds(m_md, speedA, speedB)) throw std::runtime_error(std::string(__FUNCTION__) + ": md_set_motor_speeds() failed"); return true; } bool MD::setPWMFrequencyPrescale(uint8_t freq) { if (!md_set_pwm_frequency_prescale(m_md, freq)) throw std::runtime_error(std::string(__FUNCTION__) + ": md_set_pwm_frequency_prescale() failed"); return true; } bool MD::setMotorDirections(MD_DC_DIRECTION_T dirA, MD_DC_DIRECTION_T dirB) { if (!md_set_motor_directions(m_md, dirA, dirB)) throw std::runtime_error(std::string(__FUNCTION__) + ": md_set_motor_directions() failed"); return true; } bool MD::enableStepper(MD_STEP_DIRECTION_T dir, uint8_t speed) { return md_enable_stepper(m_md, dir, speed); } bool MD::disableStepper() { return md_disable_stepper(m_md); } bool MD::setStepperSteps(unsigned int steps) { return md_set_stepper_steps(m_md, steps); } void MD::configStepper(unsigned int stepsPerRev, MD_STEP_MODE_T mode) { md_config_stepper(m_md, stepsPerRev, mode); }
983
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/bluetooth/test/bluetooth_test_win.h" #include <windows.devices.bluetooth.h> #include <wrl/client.h> #include <wrl/implements.h> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/containers/circular_deque.h" #include "base/location.h" #include "base/run_loop.h" #include "base/strings/sys_string_conversions.h" #include "base/test/test_pending_task.h" #include "base/time/time.h" #include "base/win/windows_version.h" #include "device/base/features.h" #include "device/bluetooth/bluetooth_adapter_win.h" #include "device/bluetooth/bluetooth_adapter_winrt.h" #include "device/bluetooth/bluetooth_low_energy_win.h" #include "device/bluetooth/bluetooth_remote_gatt_characteristic_win.h" #include "device/bluetooth/bluetooth_remote_gatt_descriptor_win.h" #include "device/bluetooth/bluetooth_remote_gatt_service_win.h" #include "device/bluetooth/test/fake_bluetooth_adapter_winrt.h" #include "device/bluetooth/test/fake_device_information_winrt.h" namespace { using Microsoft::WRL::Make; using Microsoft::WRL::ComPtr; using ABI::Windows::Devices::Bluetooth::IBluetoothAdapter; using ABI::Windows::Devices::Bluetooth::IBluetoothAdapterStatics; using ABI::Windows::Devices::Enumeration::IDeviceInformation; using ABI::Windows::Devices::Enumeration::IDeviceInformationStatics; class TestBluetoothAdapterWinrt : public device::BluetoothAdapterWinrt { public: TestBluetoothAdapterWinrt(ComPtr<IBluetoothAdapter> adapter, ComPtr<IDeviceInformation> device_information, InitCallback init_cb) : adapter_(std::move(adapter)), device_information_(std::move(device_information)) { Init(std::move(init_cb)); } protected: ~TestBluetoothAdapterWinrt() override = default; HRESULT GetBluetoothAdapterStaticsActivationFactory( IBluetoothAdapterStatics** statics) const override { auto adapter_statics = Make<device::FakeBluetoothAdapterStaticsWinrt>(adapter_); return adapter_statics.CopyTo(statics); }; HRESULT GetDeviceInformationStaticsActivationFactory( IDeviceInformationStatics** statics) const override { auto device_information_statics = Make<device::FakeDeviceInformationStaticsWinrt>(device_information_); return device_information_statics.CopyTo(statics); }; private: ComPtr<IBluetoothAdapter> adapter_; ComPtr<IDeviceInformation> device_information_; }; BLUETOOTH_ADDRESS CanonicalStringToBLUETOOTH_ADDRESS( std::string device_address) { BLUETOOTH_ADDRESS win_addr; unsigned int data[6]; int result = sscanf_s(device_address.c_str(), "%02X:%02X:%02X:%02X:%02X:%02X", &data[5], &data[4], &data[3], &data[2], &data[1], &data[0]); CHECK_EQ(6, result); for (int i = 0; i < 6; i++) { win_addr.rgBytes[i] = data[i]; } return win_addr; } // The canonical UUID string format is device::BluetoothUUID.value(). BTH_LE_UUID CanonicalStringToBTH_LE_UUID(std::string uuid) { BTH_LE_UUID win_uuid = {0}; if (uuid.size() == 4) { win_uuid.IsShortUuid = TRUE; unsigned int data[1]; int result = sscanf_s(uuid.c_str(), "%04x", &data[0]); CHECK_EQ(1, result); win_uuid.Value.ShortUuid = data[0]; } else if (uuid.size() == 36) { win_uuid.IsShortUuid = FALSE; unsigned int data[11]; int result = sscanf_s( uuid.c_str(), "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5], &data[6], &data[7], &data[8], &data[9], &data[10]); CHECK_EQ(11, result); win_uuid.Value.LongUuid.Data1 = data[0]; win_uuid.Value.LongUuid.Data2 = data[1]; win_uuid.Value.LongUuid.Data3 = data[2]; win_uuid.Value.LongUuid.Data4[0] = data[3]; win_uuid.Value.LongUuid.Data4[1] = data[4]; win_uuid.Value.LongUuid.Data4[2] = data[5]; win_uuid.Value.LongUuid.Data4[3] = data[6]; win_uuid.Value.LongUuid.Data4[4] = data[7]; win_uuid.Value.LongUuid.Data4[5] = data[8]; win_uuid.Value.LongUuid.Data4[6] = data[9]; win_uuid.Value.LongUuid.Data4[7] = data[10]; } else { CHECK(false); } return win_uuid; } } // namespace namespace device { BluetoothTestWin::BluetoothTestWin() : ui_task_runner_(new base::TestSimpleTaskRunner()), bluetooth_task_runner_(new base::TestSimpleTaskRunner()), fake_bt_classic_wrapper_(nullptr), fake_bt_le_wrapper_(nullptr) {} BluetoothTestWin::~BluetoothTestWin() {} bool BluetoothTestWin::PlatformSupportsLowEnergy() { if (fake_bt_le_wrapper_) return fake_bt_le_wrapper_->IsBluetoothLowEnergySupported(); return true; } void BluetoothTestWin::InitWithDefaultAdapter() { if (BluetoothAdapterWin::UseNewBLEWinImplementation()) { base::RunLoop run_loop; auto adapter = base::WrapRefCounted(new BluetoothAdapterWinrt()); adapter->Init(run_loop.QuitClosure()); adapter_ = std::move(adapter); run_loop.Run(); return; } auto adapter = base::WrapRefCounted(new BluetoothAdapterWin(base::DoNothing())); adapter->Init(); adapter_ = std::move(adapter); } void BluetoothTestWin::InitWithoutDefaultAdapter() { if (BluetoothAdapterWin::UseNewBLEWinImplementation()) { base::RunLoop run_loop; adapter_ = base::MakeRefCounted<TestBluetoothAdapterWinrt>( nullptr, nullptr, run_loop.QuitClosure()); run_loop.Run(); return; } auto adapter = base::WrapRefCounted(new BluetoothAdapterWin(base::DoNothing())); adapter->InitForTest(ui_task_runner_, bluetooth_task_runner_); adapter_ = std::move(adapter); } void BluetoothTestWin::InitWithFakeAdapter() { if (BluetoothAdapterWin::UseNewBLEWinImplementation()) { base::RunLoop run_loop; adapter_ = base::MakeRefCounted<TestBluetoothAdapterWinrt>( Make<FakeBluetoothAdapterWinrt>(kTestAdapterAddress), Make<FakeDeviceInformationWinrt>(kTestAdapterName), run_loop.QuitClosure()); run_loop.Run(); return; } fake_bt_classic_wrapper_ = new win::BluetoothClassicWrapperFake(); fake_bt_le_wrapper_ = new win::BluetoothLowEnergyWrapperFake(); fake_bt_le_wrapper_->AddObserver(this); win::BluetoothClassicWrapper::SetInstanceForTest(fake_bt_classic_wrapper_); win::BluetoothLowEnergyWrapper::SetInstanceForTest(fake_bt_le_wrapper_); fake_bt_classic_wrapper_->SimulateARadio( base::SysUTF8ToWide(kTestAdapterName), CanonicalStringToBLUETOOTH_ADDRESS(kTestAdapterAddress)); auto adapter = base::WrapRefCounted(new BluetoothAdapterWin(base::DoNothing())); adapter->InitForTest(nullptr, bluetooth_task_runner_); adapter_ = std::move(adapter); FinishPendingTasks(); } bool BluetoothTestWin::DenyPermission() { return false; } void BluetoothTestWin::StartLowEnergyDiscoverySession() { __super ::StartLowEnergyDiscoverySession(); FinishPendingTasks(); } BluetoothDevice* BluetoothTestWin::SimulateLowEnergyDevice(int device_ordinal) { if (device_ordinal > 4 || device_ordinal < 1) return nullptr; std::string device_name = kTestDeviceName; std::string device_address = kTestDeviceAddress1; std::string service_uuid_1; std::string service_uuid_2; switch (device_ordinal) { case 1: service_uuid_1 = kTestUUIDGenericAccess; service_uuid_2 = kTestUUIDGenericAttribute; break; case 2: service_uuid_1 = kTestUUIDImmediateAlert; service_uuid_2 = kTestUUIDLinkLoss; break; case 3: device_name = kTestDeviceNameEmpty; break; case 4: device_name = kTestDeviceNameEmpty; device_address = kTestDeviceAddress2; break; } win::BLEDevice* simulated_device = fake_bt_le_wrapper_->SimulateBLEDevice( device_name, CanonicalStringToBLUETOOTH_ADDRESS(device_address)); if (simulated_device != nullptr) { if (!service_uuid_1.empty()) { fake_bt_le_wrapper_->SimulateGattService( simulated_device, nullptr, CanonicalStringToBTH_LE_UUID(service_uuid_1)); } if (!service_uuid_2.empty()) { fake_bt_le_wrapper_->SimulateGattService( simulated_device, nullptr, CanonicalStringToBTH_LE_UUID(service_uuid_2)); } } FinishPendingTasks(); std::vector<BluetoothDevice*> devices = adapter_->GetDevices(); for (auto* device : devices) { if (device->GetAddress() == device_address) return device; } return nullptr; } void BluetoothTestWin::SimulateGattConnection(BluetoothDevice* device) { FinishPendingTasks(); // We don't actually attempt to discover on Windows, so fake it for testing. gatt_discovery_attempts_++; } void BluetoothTestWin::SimulateGattServicesDiscovered( BluetoothDevice* device, const std::vector<std::string>& uuids) { std::string address = device ? device->GetAddress() : remembered_device_address_; win::BLEDevice* simulated_device = fake_bt_le_wrapper_->GetSimulatedBLEDevice(address); CHECK(simulated_device); for (auto uuid : uuids) { fake_bt_le_wrapper_->SimulateGattService( simulated_device, nullptr, CanonicalStringToBTH_LE_UUID(uuid)); } FinishPendingTasks(); // We still need to discover characteristics. Wait for the appropriate method // to be posted and then finish the pending tasks. base::RunLoop().RunUntilIdle(); FinishPendingTasks(); } void BluetoothTestWin::SimulateGattServiceRemoved( BluetoothRemoteGattService* service) { std::string device_address = service->GetDevice()->GetAddress(); win::BLEDevice* target_device = fake_bt_le_wrapper_->GetSimulatedBLEDevice(device_address); CHECK(target_device); BluetoothRemoteGattServiceWin* win_service = static_cast<BluetoothRemoteGattServiceWin*>(service); std::string service_att_handle = std::to_string(win_service->GetAttributeHandle()); fake_bt_le_wrapper_->SimulateGattServiceRemoved(target_device, nullptr, service_att_handle); ForceRefreshDevice(); } void BluetoothTestWin::SimulateGattCharacteristic( BluetoothRemoteGattService* service, const std::string& uuid, int properties) { std::string device_address = service->GetDevice()->GetAddress(); win::BLEDevice* target_device = fake_bt_le_wrapper_->GetSimulatedBLEDevice(device_address); CHECK(target_device); win::GattService* target_service = GetSimulatedService(target_device, service); CHECK(target_service); BTH_LE_GATT_CHARACTERISTIC win_characteristic_info; win_characteristic_info.CharacteristicUuid = CanonicalStringToBTH_LE_UUID(uuid); win_characteristic_info.IsBroadcastable = FALSE; win_characteristic_info.IsReadable = FALSE; win_characteristic_info.IsWritableWithoutResponse = FALSE; win_characteristic_info.IsWritable = FALSE; win_characteristic_info.IsNotifiable = FALSE; win_characteristic_info.IsIndicatable = FALSE; win_characteristic_info.IsSignedWritable = FALSE; win_characteristic_info.HasExtendedProperties = FALSE; if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_BROADCAST) win_characteristic_info.IsBroadcastable = TRUE; if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_READ) win_characteristic_info.IsReadable = TRUE; if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE) win_characteristic_info.IsWritableWithoutResponse = TRUE; if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_WRITE) win_characteristic_info.IsWritable = TRUE; if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_NOTIFY) win_characteristic_info.IsNotifiable = TRUE; if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_INDICATE) win_characteristic_info.IsIndicatable = TRUE; if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_AUTHENTICATED_SIGNED_WRITES) { win_characteristic_info.IsSignedWritable = TRUE; } if (properties & BluetoothRemoteGattCharacteristic::PROPERTY_EXTENDED_PROPERTIES) win_characteristic_info.HasExtendedProperties = TRUE; fake_bt_le_wrapper_->SimulateGattCharacterisc(device_address, target_service, win_characteristic_info); ForceRefreshDevice(); } void BluetoothTestWin::SimulateGattCharacteristicRemoved( BluetoothRemoteGattService* service, BluetoothRemoteGattCharacteristic* characteristic) { CHECK(service); CHECK(characteristic); std::string device_address = service->GetDevice()->GetAddress(); win::GattService* target_service = GetSimulatedService( fake_bt_le_wrapper_->GetSimulatedBLEDevice(device_address), service); CHECK(target_service); std::string characteristic_att_handle = std::to_string( static_cast<BluetoothRemoteGattCharacteristicWin*>(characteristic) ->GetAttributeHandle()); fake_bt_le_wrapper_->SimulateGattCharacteriscRemove( target_service, characteristic_att_handle); ForceRefreshDevice(); } void BluetoothTestWin::RememberCharacteristicForSubsequentAction( BluetoothRemoteGattCharacteristic* characteristic) { CHECK(characteristic); BluetoothRemoteGattCharacteristicWin* win_characteristic = static_cast<BluetoothRemoteGattCharacteristicWin*>(characteristic); std::string device_address = win_characteristic->GetService()->GetDevice()->GetAddress(); win::BLEDevice* target_device = fake_bt_le_wrapper_->GetSimulatedBLEDevice(device_address); CHECK(target_device); win::GattService* target_service = GetSimulatedService(target_device, win_characteristic->GetService()); CHECK(target_service); fake_bt_le_wrapper_->RememberCharacteristicForSubsequentAction( target_service, std::to_string(win_characteristic->GetAttributeHandle())); } void BluetoothTestWin::SimulateGattCharacteristicRead( BluetoothRemoteGattCharacteristic* characteristic, const std::vector<uint8_t>& value) { win::GattCharacteristic* target_simulated_characteristic = nullptr; if (characteristic) { target_simulated_characteristic = GetSimulatedCharacteristic(characteristic); } fake_bt_le_wrapper_->SimulateGattCharacteristicValue( target_simulated_characteristic, value); RunPendingTasksUntilCallback(); } void BluetoothTestWin::SimulateGattCharacteristicReadError( BluetoothRemoteGattCharacteristic* characteristic, BluetoothRemoteGattService::GattErrorCode error_code) { win::GattCharacteristic* target_characteristic = GetSimulatedCharacteristic(characteristic); CHECK(target_characteristic); HRESULT hr = HRESULT_FROM_WIN32(ERROR_SEM_TIMEOUT); if (error_code == BluetoothRemoteGattService::GATT_ERROR_INVALID_LENGTH) hr = E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH; fake_bt_le_wrapper_->SimulateGattCharacteristicReadError( target_characteristic, hr); FinishPendingTasks(); } void BluetoothTestWin::SimulateGattCharacteristicWrite( BluetoothRemoteGattCharacteristic* characteristic) { RunPendingTasksUntilCallback(); } void BluetoothTestWin::SimulateGattCharacteristicWriteError( BluetoothRemoteGattCharacteristic* characteristic, BluetoothRemoteGattService::GattErrorCode error_code) { win::GattCharacteristic* target_characteristic = GetSimulatedCharacteristic(characteristic); CHECK(target_characteristic); HRESULT hr = HRESULT_FROM_WIN32(ERROR_SEM_TIMEOUT); if (error_code == BluetoothRemoteGattService::GATT_ERROR_INVALID_LENGTH) hr = E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH; fake_bt_le_wrapper_->SimulateGattCharacteristicWriteError( target_characteristic, hr); FinishPendingTasks(); } void BluetoothTestWin::RememberDeviceForSubsequentAction( BluetoothDevice* device) { remembered_device_address_ = device->GetAddress(); } void BluetoothTestWin::DeleteDevice(BluetoothDevice* device) { CHECK(device); fake_bt_le_wrapper_->RemoveSimulatedBLEDevice(device->GetAddress()); FinishPendingTasks(); } void BluetoothTestWin::SimulateGattDescriptor( BluetoothRemoteGattCharacteristic* characteristic, const std::string& uuid) { win::GattCharacteristic* target_characteristic = GetSimulatedCharacteristic(characteristic); CHECK(target_characteristic); fake_bt_le_wrapper_->SimulateGattDescriptor( characteristic->GetService()->GetDevice()->GetAddress(), target_characteristic, CanonicalStringToBTH_LE_UUID(uuid)); ForceRefreshDevice(); } void BluetoothTestWin::SimulateGattNotifySessionStarted( BluetoothRemoteGattCharacteristic* characteristic) { FinishPendingTasks(); } void BluetoothTestWin::SimulateGattNotifySessionStartError( BluetoothRemoteGattCharacteristic* characteristic, BluetoothRemoteGattService::GattErrorCode error_code) { win::GattCharacteristic* simulated_characteristic = GetSimulatedCharacteristic(characteristic); DCHECK(simulated_characteristic); DCHECK(error_code == BluetoothRemoteGattService::GATT_ERROR_UNKNOWN); fake_bt_le_wrapper_->SimulateGattCharacteristicSetNotifyError( simulated_characteristic, E_BLUETOOTH_ATT_UNKNOWN_ERROR); } void BluetoothTestWin::SimulateGattCharacteristicChanged( BluetoothRemoteGattCharacteristic* characteristic, const std::vector<uint8_t>& value) { win::GattCharacteristic* target_simulated_characteristic = nullptr; if (characteristic) { target_simulated_characteristic = GetSimulatedCharacteristic(characteristic); } fake_bt_le_wrapper_->SimulateGattCharacteristicValue( target_simulated_characteristic, value); fake_bt_le_wrapper_->SimulateCharacteristicValueChangeNotification( target_simulated_characteristic); FinishPendingTasks(); } void BluetoothTestWin::OnReadGattCharacteristicValue() { gatt_read_characteristic_attempts_++; } void BluetoothTestWin::OnWriteGattCharacteristicValue( const PBTH_LE_GATT_CHARACTERISTIC_VALUE value) { gatt_write_characteristic_attempts_++; last_write_value_.clear(); for (ULONG i = 0; i < value->DataSize; i++) last_write_value_.push_back(value->Data[i]); } void BluetoothTestWin::OnStartCharacteristicNotification() { gatt_notify_characteristic_attempts_++; } void BluetoothTestWin::OnWriteGattDescriptorValue( const std::vector<uint8_t>& value) { gatt_write_descriptor_attempts_++; last_write_value_.assign(value.begin(), value.end()); } win::GattService* BluetoothTestWin::GetSimulatedService( win::BLEDevice* device, BluetoothRemoteGattService* service) { CHECK(device); CHECK(service); std::vector<std::string> chain_of_att_handles; BluetoothRemoteGattServiceWin* win_service = static_cast<BluetoothRemoteGattServiceWin*>(service); chain_of_att_handles.insert( chain_of_att_handles.begin(), std::to_string(win_service->GetAttributeHandle())); win::GattService* simulated_service = fake_bt_le_wrapper_->GetSimulatedGattService(device, chain_of_att_handles); CHECK(simulated_service); return simulated_service; } win::GattCharacteristic* BluetoothTestWin::GetSimulatedCharacteristic( BluetoothRemoteGattCharacteristic* characteristic) { CHECK(characteristic); BluetoothRemoteGattCharacteristicWin* win_characteristic = static_cast<BluetoothRemoteGattCharacteristicWin*>(characteristic); std::string device_address = win_characteristic->GetService()->GetDevice()->GetAddress(); win::BLEDevice* target_device = fake_bt_le_wrapper_->GetSimulatedBLEDevice(device_address); if (target_device == nullptr) return nullptr; win::GattService* target_service = GetSimulatedService(target_device, win_characteristic->GetService()); if (target_service == nullptr) return nullptr; return fake_bt_le_wrapper_->GetSimulatedGattCharacteristic( target_service, std::to_string(win_characteristic->GetAttributeHandle())); } void BluetoothTestWin::RunPendingTasksUntilCallback() { base::circular_deque<base::TestPendingTask> tasks = bluetooth_task_runner_->TakePendingTasks(); int original_callback_count = callback_count_; int original_error_callback_count = error_callback_count_; do { base::TestPendingTask task = std::move(tasks.front()); tasks.pop_front(); std::move(task.task).Run(); base::RunLoop().RunUntilIdle(); } while (tasks.size() && callback_count_ == original_callback_count && error_callback_count_ == original_error_callback_count); // Put the rest of pending tasks back to Bluetooth task runner. for (auto& task : tasks) { if (task.delay.is_zero()) { bluetooth_task_runner_->PostTask(task.location, std::move(task.task)); } else { bluetooth_task_runner_->PostDelayedTask(task.location, std::move(task.task), task.delay); } } } void BluetoothTestWin::ForceRefreshDevice() { auto* adapter_win = static_cast<BluetoothAdapterWin*>(adapter_.get()); adapter_win->force_update_device_for_test_ = true; FinishPendingTasks(); adapter_win->force_update_device_for_test_ = false; // The characteristics still need to be discovered. base::RunLoop().RunUntilIdle(); FinishPendingTasks(); } void BluetoothTestWin::FinishPendingTasks() { bluetooth_task_runner_->RunPendingTasks(); base::RunLoop().RunUntilIdle(); } BluetoothTestWinrt::BluetoothTestWinrt() { if (GetParam()) { scoped_feature_list_.InitAndEnableFeature(kNewBLEWinImplementation); if (base::win::GetVersion() >= base::win::VERSION_WIN10) { scoped_winrt_initializer_.emplace(); } } else { scoped_feature_list_.InitAndDisableFeature(kNewBLEWinImplementation); } } BluetoothTestWinrt::~BluetoothTestWinrt() = default; } // namespace device
7,898
333
<gh_stars>100-1000 package com.alipay.api.response; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.CampBaseDto; import com.alipay.api.AlipayResponse; /** * ALIPAY API: koubei.marketing.campaign.activity.batchquery response. * * @author auto create * @since 1.0, 2021-02-02 14:24:03 */ public class KoubeiMarketingCampaignActivityBatchqueryResponse extends AlipayResponse { private static final long serialVersionUID = 6884256797386327694L; /** * 活动列表 */ @ApiListField("camp_sets") @ApiField("camp_base_dto") private List<CampBaseDto> campSets; /** * 总数量 */ @ApiField("total_number") private String totalNumber; public void setCampSets(List<CampBaseDto> campSets) { this.campSets = campSets; } public List<CampBaseDto> getCampSets( ) { return this.campSets; } public void setTotalNumber(String totalNumber) { this.totalNumber = totalNumber; } public String getTotalNumber( ) { return this.totalNumber; } }
463
1,816
class Cache: def __init__(self, application, store_config=None): self.application = application self.drivers = {} self.store_config = store_config or {} self.options = {} def add_driver(self, name, driver): self.drivers.update({name: driver}) def set_configuration(self, config): self.store_config = config return self def get_driver(self, name=None): if name is None: return self.drivers[self.store_config.get("default")] return self.drivers[name] def get_store_config(self, name=None): if name is None or name == "default": return self.store_config.get(self.store_config.get("default")) return self.store_config.get(name) def get_config_options(self, name=None): if name is None or name == "default": return self.store_config.get(self.store_config.get("default")) return self.store_config.get(name) def store(self, name="default"): store_config = self.get_config_options(name) driver = self.get_driver(self.get_config_options(name).get("driver")) return driver.set_options(store_config) def add(self, *args, store=None, **kwargs): return self.store(name=store).add(*args, **kwargs) def get(self, *args, store=None, **kwargs): return self.store(name=store).get(*args, **kwargs) def put(self, *args, store=None, **kwargs): return self.store(name=store).put(*args, **kwargs) def has(self, *args, store=None, **kwargs): return self.store(name=store).has(*args, **kwargs) def forget(self, *args, store=None, **kwargs): return self.store(name=store).forget(*args, **kwargs) def increment(self, *args, store=None, **kwargs): return self.store(name=store).increment(*args, **kwargs) def decrement(self, *args, store=None, **kwargs): return self.store(name=store).decrement(*args, **kwargs) def flush(self, *args, store=None, **kwargs): return self.store(name=store).flush(*args, **kwargs)
844
14,668
// Copyright 2020 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 "net/dns/https_record_rdata.h" #include <fuzzer/FuzzedDataProvider.h> #include <stdint.h> #include <memory> #include <set> #include <string> #include <vector> #include "base/check.h" #include "base/strings/string_piece.h" #include "net/base/ip_address.h" #include "net/dns/public/dns_protocol.h" namespace net { namespace { void ParseAndExercise(FuzzedDataProvider& data_provider) { std::string data1 = data_provider.ConsumeRandomLengthString(); std::unique_ptr<HttpsRecordRdata> parsed = HttpsRecordRdata::Parse(data1); std::unique_ptr<HttpsRecordRdata> parsed2 = HttpsRecordRdata::Parse(data1); std::unique_ptr<HttpsRecordRdata> parsed3 = HttpsRecordRdata::Parse(data_provider.ConsumeRemainingBytesAsString()); CHECK_EQ(!!parsed, !!parsed2); if (!parsed) return; // `parsed` and `parsed2` parsed from the same data, so they should always be // equal. CHECK(parsed->IsEqual(parsed.get())); CHECK(parsed->IsEqual(parsed2.get())); CHECK(parsed2->IsEqual(parsed.get())); // Attempt comparison with an rdata parsed from separate data. IsEqual() will // probably return false most of the time, but easily could be true if the // input data is similar enough. if (parsed3) CHECK_EQ(parsed->IsEqual(parsed3.get()), parsed3->IsEqual(parsed.get())); CHECK_EQ(parsed->Type(), dns_protocol::kTypeHttps); if (parsed->IsAlias()) { CHECK(!parsed->IsMalformed()); AliasFormHttpsRecordRdata* alias = parsed->AsAliasForm(); alias->alias_name(); } else if (!parsed->IsMalformed()) { ServiceFormHttpsRecordRdata* service = parsed->AsServiceForm(); CHECK_GT(service->priority(), 0); service->service_name(); service->alpn_ids(); service->default_alpn(); service->port(); service->ech_config(); service->unparsed_params(); service->IsCompatible(); std::set<uint16_t> mandatory_keys = service->mandatory_keys(); CHECK(mandatory_keys.find(dns_protocol::kHttpsServiceParamKeyMandatory) == mandatory_keys.end()); std::vector<IPAddress> ipv4_hint = service->ipv4_hint(); for (const IPAddress& address : ipv4_hint) { CHECK(address.IsIPv4()); } std::vector<IPAddress> ipv6_hint = service->ipv6_hint(); for (const IPAddress& address : ipv6_hint) { CHECK(address.IsIPv6()); } } } } // namespace extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { FuzzedDataProvider data_provider(data, size); ParseAndExercise(data_provider); return 0; } } // namespace net
1,053
362
<gh_stars>100-1000 // Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include "error_code.h" #include "boost/noncopyable.hpp" #include <stdio.h> namespace baidu { namespace galaxy { namespace file { class InputStreamFile : public boost::noncopyable { public: explicit InputStreamFile(const std::string& path); ~InputStreamFile(); bool IsOpen(); bool Eof(); baidu::galaxy::util::ErrorCode GetLastError(); baidu::galaxy::util::ErrorCode ReadLine(std::string& line); baidu::galaxy::util::ErrorCode Read(void* buf, size_t& size); private: std::string path_; int errno_; // last_erro FILE* file_; }; } } }
286
1,929
""" Remove ------ :mod:`textacy.preprocessing.remove`: Remove aspects of raw text that may be unwanted for certain use cases. """ from __future__ import annotations import re import unicodedata from typing import Collection, Optional from . import resources from .. import utils def accents(text: str, *, fast: bool = False) -> str: """ Remove accents from any accented unicode characters in ``text``, either by replacing them with ASCII equivalents or removing them entirely. Args: text fast: If False, accents are removed from any unicode symbol with a direct ASCII equivalent; if True, accented chars for all unicode symbols are removed, regardless. .. note:: ``fast=True`` can be significantly faster than ``fast=False``, but its transformation of ``text`` is less "safe" and more likely to result in changes of meaning, spelling errors, etc. Returns: str See Also: For a more powerful (but slower) alternative, check out ``unidecode``: https://github.com/avian2/unidecode """ if fast is False: return "".join( char for char in unicodedata.normalize("NFKD", text) if not unicodedata.combining(char) ) else: return ( unicodedata.normalize("NFKD", text) .encode("ascii", errors="ignore") .decode("ascii") ) def brackets( text: str, *, only: Optional[str | Collection[str]] = None, ) -> str: """ Remove text within curly {}, square [], and/or round () brackets, as well as the brackets themselves. Args: text only: Remove only those bracketed contents as specified here: "curly", "square", and/or "round". For example, ``"square"`` removes only those contents found between square brackets, while ``["round", "square"]`` removes those contents found between square or round brackets, but not curly. Returns: str Note: This function relies on regular expressions, applied sequentially for curly, square, then round brackets; as such, it doesn't handle nested brackets of the same type and may behave unexpectedly on text with "wild" use of brackets. It should be fine removing structured bracketed contents, as is often used, for instance, to denote in-text citations. """ only = utils.to_collection(only, val_type=str, col_type=set) if only is None or "curly" in only: text = resources.RE_BRACKETS_CURLY.sub("", text) if only is None or "square" in only: text = resources.RE_BRACKETS_SQUARE.sub("", text) if only is None or "round" in only: text = resources.RE_BRACKETS_ROUND.sub("", text) return text def html_tags(text: str) -> str: """ Remove HTML tags from ``text``, returning just the text found between tags and other non-data elements. Args: text Returns: str Note: This function relies on the stdlib :class:`html.parser.HTMLParser` and doesn't do anything fancy. For a better and potentially faster solution, consider using ``lxml`` and/or ``beautifulsoup4``. """ parser = resources.HTMLTextExtractor() parser.feed(text) return parser.get_text() def punctuation( text: str, *, only: Optional[str | Collection[str]] = None, ) -> str: """ Remove punctuation from ``text`` by replacing all instances of punctuation (or a subset thereof specified by ``only``) with whitespace. Args: text only: Remove only those punctuation marks specified here. For example, ``"."`` removes only periods, while ``[",", ";", ":"]`` removes commas, semicolons, and colons; if None, all unicode punctuation marks are removed. Returns: str Note: When ``only=None``, Python's built-in :meth:`str.translate()` is used to remove punctuation; otherwise, a regular expression is used. The former's performance can be up to an order of magnitude faster. """ if only is not None: only = utils.to_collection(only, val_type=str, col_type=set) return re.sub("[{}]+".format(re.escape("".join(only))), " ", text) else: return text.translate(resources.PUNCT_TRANSLATION_TABLE)
1,663
678
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @interface FunctionSwitchUtil : NSObject { } + (void)setVoipOnlyExtStatusSwitch:(unsigned int)arg1 statusBit:(unsigned int)arg2 setOpen:(_Bool)arg3 sync:(_Bool)arg4; + (_Bool)addVoipOnlySwitchOplog:(unsigned int)arg1 SwitchValue:(unsigned int)arg2 sync:(_Bool)arg3; + (void)setExtStatusSwitch:(unsigned int)arg1 statusBit:(unsigned int)arg2 setOpen:(_Bool)arg3 sync:(_Bool)arg4; + (void)setStatusSwitch:(unsigned int)arg1 statusBit:(unsigned int)arg2 setOpen:(_Bool)arg3 sync:(_Bool)arg4; + (void)setPluginSwitch:(unsigned int)arg1 statusBit:(unsigned int)arg2 setOpen:(_Bool)arg3 sync:(_Bool)arg4; + (_Bool)addSwitchOplog:(unsigned int)arg1 SwitchValue:(unsigned int)arg2 sync:(_Bool)arg3; + (unsigned int)convertType:(unsigned int)arg1; @end
336
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; ResourceOverridesDescription::ResourceOverridesDescription() : Endpoints() { } ResourceOverridesDescription::ResourceOverridesDescription( ResourceOverridesDescription const & other) : Endpoints(other.Endpoints) { } ResourceOverridesDescription::ResourceOverridesDescription(ResourceOverridesDescription && other) : Endpoints(move(other.Endpoints)) { } ResourceOverridesDescription & ResourceOverridesDescription::operator = (ResourceOverridesDescription const & other) { if (this != &other) { this->Endpoints = other.Endpoints; } return *this; } ResourceOverridesDescription & ResourceOverridesDescription::operator = (ResourceOverridesDescription && other) { if (this != &other) { this->Endpoints = move(other.Endpoints); } return *this; } bool ResourceOverridesDescription::operator == (ResourceOverridesDescription const & other) const { bool equals = true; equals = this->Endpoints.size() == other.Endpoints.size(); if (!equals) { return equals; } for (auto const& endpoint: Endpoints) { auto it = find(other.Endpoints.begin(), other.Endpoints.end(), endpoint); equals = it != other.Endpoints.end(); if (!equals) { return equals; } } return equals; } bool ResourceOverridesDescription::operator != (ResourceOverridesDescription const & other) const { return !(*this == other); } void ResourceOverridesDescription::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write("ResourceOverrides { "); w.Write("Endpoints = {"); for (auto const& endpoint : Endpoints) { w.Write("{0},", endpoint); } w.Write("}"); w.Write("}"); } void ResourceOverridesDescription::ReadFromXml( XmlReaderUPtr const & xmlReader) { clear(); xmlReader->StartElement( *SchemaNames::Element_ResourceOverrides, *SchemaNames::Namespace, false); if (xmlReader->IsEmptyElement()) { // <ResourceOverrides /> xmlReader->ReadElement(); return; } xmlReader->ReadStartElement(); ParseEndpoints(xmlReader); // </ResourceOverrides> xmlReader->ReadEndElement(); } ErrorCode ResourceOverridesDescription::WriteToXml(XmlWriterUPtr const & xmlWriter) { if (NoEndPoints()) { return ErrorCodeValue::Success; } ErrorCode er = xmlWriter->WriteStartElement(*SchemaNames::Element_ResourceOverrides, L"", *SchemaNames::Namespace); if (!er.IsSuccess()) { return er; } er = WriteEndpoints(xmlWriter); if (!er.IsSuccess()) { return er; } return xmlWriter->WriteEndElement(); } ErrorCode ResourceOverridesDescription::WriteEndpoints(XmlWriterUPtr const & xmlWriter) { if (NoEndPoints()) { return ErrorCodeValue::Success; } ErrorCode er = xmlWriter->WriteStartElement(*SchemaNames::Element_Endpoints, L"", *SchemaNames::Namespace); if (!er.IsSuccess()) { return er; } for (auto endpoint : Endpoints) { er = endpoint.WriteToXml(xmlWriter); if (!er.IsSuccess()) { return er; } } return xmlWriter->WriteEndElement(); } bool ResourceOverridesDescription::NoEndPoints() { return this->Endpoints.empty(); } void ResourceOverridesDescription::ParseEndpoints(XmlReaderUPtr const & xmlReader) { if (xmlReader->IsStartElement( *SchemaNames::Element_Endpoints, *SchemaNames::Namespace, false)) { xmlReader->StartElement( *SchemaNames::Element_Endpoints, *SchemaNames::Namespace); xmlReader->ReadStartElement(); bool done = false; while(!done) { done = true; if (xmlReader->IsStartElement( *SchemaNames::Element_Endpoint, *SchemaNames::Namespace, false)) { EndpointOverrideDescription endpoint; endpoint.ReadFromXml(xmlReader); this->Endpoints.push_back(move(endpoint)); done = false; } } // </Endpoints> xmlReader->ReadEndElement(); } } void ResourceOverridesDescription::clear() { this->Endpoints.clear(); }
1,811
892
{ "schema_version": "1.2.0", "id": "GHSA-9cmq-xm5p-pqc3", "modified": "2022-04-29T01:27:53Z", "published": "2022-04-29T01:27:53Z", "aliases": [ "CVE-2003-1323" ], "details": "Elm ME+ 2.4 before PL109S, when installed setgid mail and the operating system lacks POSIX saved ID support, allows local users to read and modify certain files with the privileges of the mail group via unspecified vectors.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2003-1323" }, { "type": "WEB", "url": "http://www.elmme-mailer.org/elm-2.4ME+PL109S.patch.gz" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
356
1,232
<filename>tree/Yu/236.py # Time: O(n) # Space: O(1) # # Given a binary tree, find the lowest common ancestor (LCA) # of two given nodes in the tree. # # According to the definition of LCA on Wikipedia: “The lowest # common ancestor is defined between two nodes v and w as the # lowest node in T that has both v and w as descendants (where we # allow a node to be a descendant of itself).” # # _______3______ # / \ # ___5__ ___1__ # / \ / \ # 6 _2 0 8 # / \ # 7 4 # For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. # Another example is LCA of nodes 5 and 4 is 5, since a node can be a # descendant of itself according to the LCA definition. # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ # Edge/Condition if not root: return None if root == p or root == q: return root # Divide left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) # Conquer if left and right: return root if not left: return right if not right: return left
712
1,510
<filename>exec/java-exec/src/main/java/org/apache/drill/exec/resourcemgr/config/selectionpolicy/QueueSelectionPolicyFactory.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.drill.exec.resourcemgr.config.selectionpolicy; /** * Factory to return an instance of {@link QueueSelectionPolicy} based on the configured policy name. By default if * the configured policy name doesn't matches any supported policies then it returns {@link BestFitQueueSelection} */ public class QueueSelectionPolicyFactory { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(QueueSelectionPolicyFactory.class); public static QueueSelectionPolicy createSelectionPolicy(QueueSelectionPolicy.SelectionPolicy policy) { logger.debug("Creating SelectionPolicy of type {}", policy); QueueSelectionPolicy selectionPolicy; switch (policy) { case DEFAULT: selectionPolicy = new DefaultQueueSelection(); break; case BESTFIT: selectionPolicy = new BestFitQueueSelection(); break; case RANDOM: selectionPolicy = new RandomQueueSelection(); break; default: logger.info("QueueSelectionPolicy is not configured so proceeding with the bestfit as default policy"); selectionPolicy = new BestFitQueueSelection(); break; } return selectionPolicy; } // prevents from instantiation private QueueSelectionPolicyFactory() { // no-op } }
645
1,595
<filename>graphistry/tests/test_pygraphistry.py # -*- coding: utf-8 -*- import unittest from graphistry import PyGraphistry #TODO mock requests for testing actual effectful code class TestPyGraphistry_Auth(unittest.TestCase): def test_defaults(self): assert PyGraphistry.store_token_creds_in_memory() is True def test_overrides(self): PyGraphistry.register(store_token_creds_in_memory=None) assert PyGraphistry.store_token_creds_in_memory() is True PyGraphistry.register(store_token_creds_in_memory=False) assert PyGraphistry.store_token_creds_in_memory() is False
238
853
<reponame>blin00/tinyssh #include "uint32_pack_big.h" /* The 'uint32_pack_big' function converts 32-bit unsigned integer into 4 bytes stored in big-endian format */ void uint32_pack_big(unsigned char *y, crypto_uint32 x) { long long i; for (i = 3; i >= 0; --i) { y[i] = x; x >>= 8; } }
120
4,339
/* * 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.ignite.ml.selection.scoring.evaluator.aggregator; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.ml.IgniteModel; import org.apache.ignite.ml.math.primitives.vector.Vector; import org.apache.ignite.ml.selection.scoring.evaluator.context.EmptyContext; import org.apache.ignite.ml.structures.LabeledVector; /** * Class represents statistics aggregator for regression estimation. */ public class RegressionMetricStatsAggregator implements MetricStatsAggregator<Double, EmptyContext<Double>, RegressionMetricStatsAggregator> { /** * Serial version uid. */ private static final long serialVersionUID = -2459352313996869235L; /** * Number of examples in dataset. */ private long n; /** * Absolute error. */ private double absoluteError = Double.NaN; /** * Residual sum of squares. */ private double rss = Double.NaN; /** * Sum of labels. */ private double sumOfYs = Double.NaN; /** * Sum of squared labels. */ private double sumOfSquaredYs = Double.NaN; /** * Creates an instance of RegressionMetricStatsAggregator. */ public RegressionMetricStatsAggregator() { } /** * Creates an instance of RegressionMetricStatsAggregator. * * @param n Number of examples in dataset. * @param absoluteError Absolute error. * @param rss Rss. * @param sumOfYs Sum of labels. * @param sumOfSquaredYs Sum of squared labels. */ public RegressionMetricStatsAggregator(long n, double absoluteError, double rss, double sumOfYs, double sumOfSquaredYs) { this.n = n; this.absoluteError = absoluteError; this.rss = rss; this.sumOfYs = sumOfYs; this.sumOfSquaredYs = sumOfSquaredYs; } /** * {@inheritDoc} */ @Override public void aggregate(IgniteModel<Vector, Double> model, LabeledVector<Double> vector) { n += 1; Double prediction = model.predict(vector.features()); Double truth = vector.label(); A.notNull(truth != null, "Test set mustn't contain null labels"); A.notNull(prediction != null, "Model mustn't return null answers"); double error = truth - prediction; absoluteError = sum(Math.abs(error), absoluteError); rss = sum(Math.pow(error, 2), rss); sumOfYs = sum(truth, sumOfYs); sumOfSquaredYs = sum(Math.pow(truth, 2), sumOfSquaredYs); } /** * {@inheritDoc} */ @Override public RegressionMetricStatsAggregator mergeWith(RegressionMetricStatsAggregator other) { long n = this.n + other.n; double absoluteError = sum(this.absoluteError, other.absoluteError); double squaredError = sum(this.rss, other.rss); double sumOfYs = sum(this.sumOfYs, other.sumOfYs); double sumOfSquaredYs = sum(this.sumOfSquaredYs, other.sumOfSquaredYs); return new RegressionMetricStatsAggregator(n, absoluteError, squaredError, sumOfYs, sumOfSquaredYs); } /** * {@inheritDoc} */ @Override public EmptyContext createInitializedContext() { return new EmptyContext(); } /** * {@inheritDoc} */ @Override public void initByContext(EmptyContext context) { } /** * Returns mean absolute error. * * @return Mean absolute error. */ public double getMAE() { if (Double.isNaN(absoluteError)) return Double.NaN; return absoluteError / Math.max(n, 1); } /** * Returns mean squared error. * * @return Mean squared error. */ public double getMSE() { return rss / Math.max(n, 1); } /** * Returns sum of squared errors. * * @return Sum of squared errors */ public double ysRss() { return ysVariance() * Math.max(n, 1); } /** * Returns label variance. * * @return Label variance. */ public double ysVariance() { if (Double.isNaN(sumOfSquaredYs)) return Double.NaN; return (sumOfSquaredYs / Math.max(n, 1) - Math.pow(sumOfYs / Math.max(n, 1), 2)); } /** * Returns RSS. * * @return RSS. */ public double getRss() { return rss; } /** * Returns sum of given values considering NaNs. * * @param v1 First value. * @param v2 Second value. * @return v1 + v2. */ private double sum(double v1, double v2) { if (Double.isNaN(v1)) return v2; else if (Double.isNaN(v2)) return v1; else return v1 + v2; } }
2,213
944
<gh_stars>100-1000 #include <torch/csrc/jit/passes/subgraph_rewrite.h> #include "core/util/prelude.h" namespace trtorch { namespace core { namespace lowering { namespace passes { void RemoveDropout(std::shared_ptr<torch::jit::Graph>& graph) { std::string dropout_pattern = R"IR( graph(%input, %4, %5): %6 = aten::dropout(%input, %4, %5) return (%6))IR"; std::string no_dropout_pattern = R"IR( graph(%input, %4, %5): return (%input))IR"; torch::jit::SubgraphRewriter remove_dropout; remove_dropout.RegisterRewritePattern(dropout_pattern, no_dropout_pattern); remove_dropout.runOnGraph(graph); std::string dropout_inplace_pattern = R"IR( graph(%input, %4, %5): %6 = aten::dropout_(%input, %4, %5) return (%6))IR"; std::string no_dropout_inplace_pattern = R"IR( graph(%input, %4, %5): return (%input))IR"; torch::jit::SubgraphRewriter remove_dropout_inplace_pattern; remove_dropout_inplace_pattern.RegisterRewritePattern(dropout_inplace_pattern, no_dropout_inplace_pattern); remove_dropout_inplace_pattern.runOnGraph(graph); // remove feature_dropout std::string feature_dropout_pattern = R"IR( graph(%input, %4, %5): %6 = aten::feature_dropout(%input, %4, %5) return (%6))IR"; std::string no_feature_dropout_pattern = R"IR( graph(%input, %4, %5): return (%input))IR"; torch::jit::SubgraphRewriter remove_feature_dropout_pattern; remove_feature_dropout_pattern.RegisterRewritePattern(feature_dropout_pattern, no_feature_dropout_pattern); remove_feature_dropout_pattern.runOnGraph(graph); // remove feature_dropout inplace std::string feature_dropout_inplace_pattern = R"IR( graph(%input, %4, %5): %6 = aten::feature_dropout_(%input, %4, %5) return (%6))IR"; std::string no_feature_dropout_inplace_pattern = R"IR( graph(%input, %4, %5): return (%input))IR"; torch::jit::SubgraphRewriter remove_feature_dropout_inplace_pattern; remove_feature_dropout_inplace_pattern.RegisterRewritePattern( feature_dropout_inplace_pattern, no_feature_dropout_inplace_pattern); remove_feature_dropout_inplace_pattern.runOnGraph(graph); // remove feature_alpha_dropout std::string feature_alpha_dropout_pattern = R"IR( graph(%input, %4, %5): %6 = aten::feature_alpha_dropout(%input, %4, %5) return (%6))IR"; std::string no_feature_alpha_dropout_pattern = R"IR( graph(%input, %4, %5): return (%input))IR"; torch::jit::SubgraphRewriter remove_feature_alpha_dropout_pattern; remove_feature_alpha_dropout_pattern.RegisterRewritePattern( feature_alpha_dropout_pattern, no_feature_alpha_dropout_pattern); remove_feature_alpha_dropout_pattern.runOnGraph(graph); // remove feature_alpha_dropout inplace std::string feature_alpha_dropout_inplace_pattern = R"IR( graph(%input, %4, %5): %6 = aten::feature_alpha_dropout_(%input, %4, %5) return (%6))IR"; std::string no_feature_alpha_dropout_inplace_pattern = R"IR( graph(%input, %4, %5): return (%input))IR"; torch::jit::SubgraphRewriter remove_feature_alpha_dropout_inplace_pattern; remove_feature_alpha_dropout_inplace_pattern.RegisterRewritePattern( feature_alpha_dropout_inplace_pattern, no_feature_alpha_dropout_inplace_pattern); remove_feature_alpha_dropout_inplace_pattern.runOnGraph(graph); LOG_GRAPH("Post remove dropout: " << *graph); } } // namespace passes } // namespace lowering } // namespace core } // namespace trtorch
1,499
436
<gh_stars>100-1000 package com.jdon.jivejdon.presentation.action.query; import com.jdon.controller.WebAppUtil; import com.jdon.controller.model.PageIterator; import com.jdon.jivejdon.spi.component.mapreduce.ThreadApprovedNewList; import com.jdon.jivejdon.spi.component.mapreduce.ThreadDigList; import com.jdon.jivejdon.domain.model.Forum; import com.jdon.jivejdon.domain.model.ForumThread; import com.jdon.jivejdon.api.query.ForumMessageQueryService; import com.jdon.jivejdon.api.ForumService; import com.jdon.strutsutil.ModelListAction; import com.jdon.strutsutil.ModelListForm; import com.jdon.util.UtilValidate; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import javax.servlet.http.HttpServletRequest; public class ThreadDigSortedListAction extends ModelListAction { private ForumMessageQueryService forumMessageQueryService; private ThreadApprovedNewList threadApprovedNewList; public ForumMessageQueryService getForumMessageQueryService() { if (forumMessageQueryService == null) forumMessageQueryService = (ForumMessageQueryService) WebAppUtil.getService ("forumMessageQueryService", this.servlet.getServletContext()); return forumMessageQueryService; } public ThreadApprovedNewList getThreadApprovedNewList() { if (threadApprovedNewList == null) threadApprovedNewList = (ThreadApprovedNewList) WebAppUtil .getComponentInstance("threadApprovedNewList", this.servlet.getServletContext ()); return threadApprovedNewList; } @Override public PageIterator getPageIterator(HttpServletRequest httpServletRequest, int start, int count) { ThreadDigList messageDigList = getThreadApprovedNewList().getThreadDigList(); return messageDigList.getPageIterator(start, count); } public Object findModelIFByKey(HttpServletRequest request, Object key) { ForumThread thread = null; try { thread = getForumMessageQueryService().getThread((Long) key); } catch (Exception e) { } return thread; } public void customizeListForm(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, ModelListForm modelListForm) throws Exception { ForumService forumService = (ForumService) WebAppUtil.getService ("forumService", this.servlet.getServletContext()); String forumId = request.getParameter("forum"); if (forumId == null) forumId = request.getParameter("forumId"); Forum forum = null; if ((forumId == null) || !UtilValidate.isInteger(forumId) || forumId.length() > 10) { forum = new Forum(); forum.setName("主题总表"); } else { forum = forumService.getForum(new Long(forumId)); } if (forum == null) throw new Exception("forum is null forumid=" + forumId); modelListForm.setOneModel(forum); } }
939
1,056
<filename>ide/editor.macros/src/org/netbeans/modules/editor/macros/MacroDialogSupport.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.modules.editor.macros; import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Map; import java.util.MissingResourceException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.KeyStroke; import javax.swing.border.EmptyBorder; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.AbstractDocument; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.undo.UndoableEdit; import org.netbeans.api.editor.mimelookup.MimePath; import org.netbeans.api.editor.settings.MultiKeyBinding; import org.netbeans.core.options.keymap.api.KeyStrokeUtils; import org.netbeans.editor.BaseAction; import org.netbeans.editor.BaseDocument; import org.netbeans.editor.BaseKit; import org.netbeans.editor.Utilities; import org.netbeans.modules.editor.NbEditorUtilities; import org.netbeans.modules.editor.macros.storage.MacroDescription; import org.netbeans.modules.editor.macros.storage.MacrosStorage; import org.netbeans.modules.editor.macros.storage.ui.MacrosPanel; import org.netbeans.modules.editor.settings.storage.api.EditorSettingsStorage; import org.netbeans.spi.options.OptionsPanelController; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.text.CloneableEditorSupport; import org.openide.util.Lookup; import org.openide.util.NbBundle; /** * * @author <NAME> */ public final class MacroDialogSupport { private static final Logger LOG = Logger.getLogger(MacroDialogSupport.class.getName()); private MacroDialogSupport() { // no-op } public static MacroDescription findMacro(MimePath mimeType, KeyStroke... shortcut) { EditorSettingsStorage<String, MacroDescription> ess = EditorSettingsStorage.<String, MacroDescription>get(MacrosStorage.ID); MacroDescription macro = null; // try 'mimeType' specific macros try { Map<String, MacroDescription> macros = ess.load(mimeType, null, false); macro = findByShortcut(macros, shortcut); } catch (IOException ioe) { LOG.log(Level.WARNING, null, ioe); } if (macro == null) { // try 'all languages' macros try { Map<String, MacroDescription> macros = ess.load(MimePath.EMPTY, null, false); macro = findByShortcut(macros, shortcut); } catch (IOException ioe) { LOG.log(Level.WARNING, null, ioe); } } return macro; } private static final MacroDescription findByShortcut(Map<String, MacroDescription> macros, KeyStroke... shortcut) { for(MacroDescription m : macros.values()) { outer: for(MultiKeyBinding mkb : m.getShortcuts()) { if (mkb == null) { // erroneous shortcut LOG.warning("Null shortcut in macro definition: " + m); continue; } if (mkb.getKeyStrokeCount() == shortcut.length) { for(int i = 0; i < shortcut.length; i++) { if (!mkb.getKeyStroke(i).equals(shortcut[i])) { continue outer; } } return m; } } } return null; } public static class StartMacroRecordingAction extends BaseAction { static final long serialVersionUID = 1L; public StartMacroRecordingAction() { super(BaseKit.startMacroRecordingAction, NO_RECORDING); putValue(BaseAction.ICON_RESOURCE_PROPERTY, "org/netbeans/modules/editor/macros/start_macro_recording.png"); // NOI18N } public void actionPerformed(ActionEvent evt, JTextComponent target) { if (target != null) { if (!startRecording(target)) { target.getToolkit().beep(); } } } private boolean startRecording(JTextComponent c) { try { Method m = BaseAction.class.getDeclaredMethod("startRecording", JTextComponent.class); //NOI18N m.setAccessible(true); return (Boolean) m.invoke(this, c); } catch (Exception e) { LOG.log(Level.WARNING, "Can't call BaseAction.startRecording", e); //NOI18N return false; } } } // End of StartMacroRecordingAction class public static final class StopMacroRecordingAction extends BaseAction { static final long serialVersionUID = 1L; public StopMacroRecordingAction() { super(BaseKit.stopMacroRecordingAction, NO_RECORDING); putValue(BaseAction.ICON_RESOURCE_PROPERTY, "org/netbeans/modules/editor/macros/stop_macro_recording.png"); // NOI18N } public void actionPerformed(ActionEvent evt, JTextComponent target) { if (target != null) { final String macro = stopRecording(target); if (macro == null) { // not recording target.getToolkit().beep(); } else { // popup a macro dialog final MacrosPanel panel = new MacrosPanel(Lookup.getDefault()); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.addAncestorListener(new AncestorListener() { public void ancestorAdded(AncestorEvent event) { panel.forceAddMacro(macro); } public void ancestorRemoved(AncestorEvent event) { } public void ancestorMoved(AncestorEvent event) { } }); panel.getModel().load(); final DialogDescriptor descriptor = new DialogDescriptor( panel, NbBundle.getMessage(MacroDialogSupport.class, "Macros_Dialog_title"), //NOI18N true, new Object[] { DialogDescriptor.OK_OPTION, DialogDescriptor.CANCEL_OPTION }, DialogDescriptor.OK_OPTION, DialogDescriptor.DEFAULT_ALIGN, null, null ); descriptor.setClosingOptions (new Object[] { DialogDescriptor.OK_OPTION, DialogDescriptor.CANCEL_OPTION }); descriptor.setValid(false); panel.getModel().addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName() == null || OptionsPanelController.PROP_CHANGED.equals(evt.getPropertyName())) { descriptor.setValid(panel.getModel().isChanged()); } } }); DialogDisplayer.getDefault ().notify (descriptor); if (descriptor.getValue () == DialogDescriptor.OK_OPTION) { panel.save(); } } } } private String stopRecording(JTextComponent c) { try { Method m = BaseAction.class.getDeclaredMethod("stopRecording", JTextComponent.class); //NOI18N m.setAccessible(true); return (String) m.invoke(this, c); } catch (Exception e) { LOG.log(Level.WARNING, "Can't call BaseAction.stopRecording", e); //NOI18N return null; } } } // End of StopMacroRecordingAction class public static class RunMacroAction extends BaseAction { static final long serialVersionUID = 1L; static HashSet<String> runningActions = new HashSet<String>(); public static final String runMacroAction = "run-macro"; //NOI18N public RunMacroAction() { super(runMacroAction, NO_RECORDING); //NOI18N } protected void error(JTextComponent target, String messageKey, Object... params) { String message; try { message = NbBundle.getMessage(RunMacroAction.class, messageKey, params); } catch (MissingResourceException e) { message = "Error in macro: " + messageKey; //NOI18N } NotifyDescriptor descriptor = new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE); // NOI18N Toolkit.getDefaultToolkit().beep(); DialogDisplayer.getDefault().notify(descriptor); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, null, new Throwable(message)); } } public void actionPerformed(ActionEvent evt, JTextComponent target) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("actionCommand='" + evt.getActionCommand() //NOI18N + "', modifiers=" + evt.getModifiers() //NOI18N + ", when=" + evt.getWhen() //NOI18N + ", paramString='" + evt.paramString() + "'"); //NOI18N } if (target == null) { return; } BaseKit kit = Utilities.getKit(target); if (kit == null) { return; } BaseDocument doc = Utilities.getDocument(target); if (doc == null) { return; } // changed as reponse to #250157: other events may get fired during // the course of key binding processing and if an event is processed // as nested (i.e. hierarchy change resulting from a component retracting from the screen), // thie following test would fail. AWTEvent maybeKeyEvent = EventQueue.getCurrentEvent(); KeyStroke keyStroke = null; if (maybeKeyEvent instanceof KeyEvent) { keyStroke = KeyStroke.getKeyStrokeForEvent((KeyEvent) maybeKeyEvent); } // try simple keystorkes first MimePath mimeType = MimePath.parse(NbEditorUtilities.getMimeType(target)); MacroDescription macro = null; if (keyStroke != null) { macro = findMacro(mimeType, keyStroke); } else { LOG.warning("KeyStroke could not be created for event " + maybeKeyEvent); } if (macro == null) { // if not found, try action command, which should contain complete multi keystroke KeyStroke[] shortcut = KeyStrokeUtils.getKeyStrokes(evt.getActionCommand()); if (shortcut != null) { macro = findMacro(mimeType, shortcut); } else { LOG.warning("KeyStroke could not be created for action command " + evt.getActionCommand()); } } if (macro == null) { error(target, "macro-not-found", KeyStrokeUtils.getKeyStrokeAsText(keyStroke)); // NOI18N return; } if (!runningActions.add(macro.getName())) { // this macro is already running, beware of loops error(target, "macro-loop", macro.getName()); // NOI18N return; } try { runMacro(target, doc, kit, macro); } finally { runningActions.remove(macro.getName()); } } private void runMacro(JTextComponent component, BaseDocument doc, BaseKit kit, MacroDescription macro) { StringBuilder actionName = new StringBuilder(); char[] command = macro.getCode().toCharArray(); int len = command.length; sendUndoableEdit(doc, CloneableEditorSupport.BEGIN_COMMIT_GROUP); try { for (int i = 0; i < len; i++) { if (Character.isWhitespace(command[i])) { continue; } if (command[i] == '"') { //NOI18N while (++i < len && command[i] != '"') { //NOI18N char ch = command[i]; if (ch == '\\') { //NOI18N if (++i >= len) { // '\' at the end error(component, "macro-malformed", macro.getName()); // NOI18N return; } ch = command[i]; if (ch != '"' && ch != '\\') { // neither \\ nor \" // NOI18N error(component, "macro-malformed", macro.getName()); // NOI18N return; } // else fall through } Action a = component.getKeymap().getDefaultAction(); if (a != null) { ActionEvent newEvt = new ActionEvent(component, 0, new String(new char[]{ch})); if (a instanceof BaseAction) { ((BaseAction) a).updateComponent(component); ((BaseAction) a).actionPerformed(newEvt, component); } else { a.actionPerformed(newEvt); } } } } else { // parse the action name actionName.setLength(0); while (i < len && !Character.isWhitespace(command[i])) { char ch = command[i++]; if (ch == '\\') { //NOI18N if (i >= len) { // macro ending with single '\' error(component, "macro-malformed", macro.getName()); // NOI18N return; } ch = command[i++]; if (ch != '\\' && !Character.isWhitespace(ch)) { //NOI18N error(component, "macro-malformed", macro.getName()); // neither "\\" nor "\ " // NOI18N return; } // else fall through } actionName.append(ch); } // execute the action Action a = kit.getActionByName(actionName.toString()); if (a != null) { ActionEvent fakeEvt = new ActionEvent(component, 0, ""); //NOI18N if (a instanceof BaseAction) { ((BaseAction) a).updateComponent(component); ((BaseAction) a).actionPerformed(fakeEvt, component); } else { a.actionPerformed(fakeEvt); } if (DefaultEditorKit.insertBreakAction.equals(actionName.toString())) { Action def = component.getKeymap().getDefaultAction(); ActionEvent fakeEvt10 = new ActionEvent(component, 0, new String(new byte[]{10})); if (def instanceof BaseAction) { ((BaseAction) def).updateComponent(component); ((BaseAction) def).actionPerformed(fakeEvt10, component); } else { def.actionPerformed(fakeEvt10); } } } else { error(component, "macro-unknown-action", macro.getName(), actionName.toString()); // NOI18N return; } } } } finally { sendUndoableEdit(doc, CloneableEditorSupport.END_COMMIT_GROUP); } } } // End of RunMacroAction class private static void sendUndoableEdit(Document d, UndoableEdit ue) { if(d instanceof AbstractDocument) { UndoableEditListener[] uels = ((AbstractDocument)d).getUndoableEditListeners(); UndoableEditEvent ev = new UndoableEditEvent(d, ue); for(UndoableEditListener uel : uels) { uel.undoableEditHappened(ev); } } } }
9,574
15,577
<filename>src/Dictionaries/DictionarySourceHelpers.cpp #include "DictionarySourceHelpers.h" #include <Columns/ColumnsNumber.h> #include <Core/ColumnWithTypeAndName.h> #include <DataTypes/DataTypesNumber.h> #include <IO/WriteHelpers.h> #include "DictionaryStructure.h" #include <Interpreters/Context.h> #include <Core/Settings.h> #include <Poco/Util/AbstractConfiguration.h> #include <Common/SettingsChanges.h> namespace DB { namespace ErrorCodes { extern const int SIZES_OF_COLUMNS_DOESNT_MATCH; } /// For simple key Block blockForIds( const DictionaryStructure & dict_struct, const std::vector<UInt64> & ids) { auto column = ColumnUInt64::create(ids.size()); memcpy(column->getData().data(), ids.data(), ids.size() * sizeof(ids.front())); Block block{{std::move(column), std::make_shared<DataTypeUInt64>(), (*dict_struct.id).name}}; return block; } /// For composite key Block blockForKeys( const DictionaryStructure & dict_struct, const Columns & key_columns, const std::vector<size_t> & requested_rows) { Block block; for (size_t i = 0, size = key_columns.size(); i < size; ++i) { const ColumnPtr & source_column = key_columns[i]; size_t column_rows_size = source_column->size(); PaddedPODArray<UInt8> filter(column_rows_size, false); for (size_t idx : requested_rows) filter[idx] = true; auto filtered_column = source_column->filter(filter, requested_rows.size()); block.insert({std::move(filtered_column), (*dict_struct.key)[i].type, (*dict_struct.key)[i].name}); } return block; } SettingsChanges readSettingsFromDictionaryConfig(const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix) { if (!config.has(config_prefix + ".settings")) return {}; const auto prefix = config_prefix + ".settings"; Poco::Util::AbstractConfiguration::Keys config_keys; config.keys(prefix, config_keys); SettingsChanges changes; for (const std::string & key : config_keys) { const auto value = config.getString(prefix + "." + key); changes.emplace_back(key, value); } return changes; } ContextMutablePtr copyContextAndApplySettingsFromDictionaryConfig( const ContextPtr & context, const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix) { auto context_copy = Context::createCopy(context); auto changes = readSettingsFromDictionaryConfig(config, config_prefix); context_copy->applySettingsChanges(changes); return context_copy; } static Block transformHeader(Block header, Block block_to_add) { for (Int64 i = static_cast<Int64>(block_to_add.columns() - 1); i >= 0; --i) header.insert(0, block_to_add.getByPosition(i).cloneEmpty()); return header; } TransformWithAdditionalColumns::TransformWithAdditionalColumns( Block block_to_add_, const Block & header) : ISimpleTransform(header, transformHeader(header, block_to_add_), true) , block_to_add(std::move(block_to_add_)) { } void TransformWithAdditionalColumns::transform(Chunk & chunk) { if (chunk) { auto num_rows = chunk.getNumRows(); auto columns = chunk.detachColumns(); auto cut_block = block_to_add.cloneWithCutColumns(current_range_index, num_rows); if (cut_block.rows() != num_rows) throw Exception(ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH, "Number of rows in block to add after cut must equal to number of rows in block from inner stream"); for (Int64 i = static_cast<Int64>(cut_block.columns() - 1); i >= 0; --i) columns.insert(columns.begin(), cut_block.getByPosition(i).column); current_range_index += num_rows; chunk.setColumns(std::move(columns), num_rows); } } String TransformWithAdditionalColumns::getName() const { return "TransformWithAdditionalColumns"; } }
1,457
563
<filename>mdm/orientdb-api/src/main/java/com/gentics/mesh/core/data/dao/PermissionRoots.java<gh_stars>100-1000 package com.gentics.mesh.core.data.dao; import com.gentics.mesh.core.data.HibBaseElement; /** * Contains global roots of every element type where permissions can be assigned to. */ public interface PermissionRoots { /** * Return the root for projects. * * @return */ HibBaseElement project(); /** * Return the root for users. * * @return */ HibBaseElement user(); /** * Return the root for groups. * * @return */ HibBaseElement group(); /** * Return the root for roles. * * @return */ HibBaseElement role(); /** * Return the root for microschemas. * * @return */ HibBaseElement microschema(); /** * Return the root for schemas. * * @return */ HibBaseElement schema(); }
312
7,892
/********************************************************************** Audacity: A Digital Audio Editor EBUR128.h <NAME> ***********************************************************************/ #ifndef __EBUR128_H__ #define __EBUR128_H__ #include "Biquad.h" #include <memory> #include "SampleFormat.h" #include <cmath> /// \brief Implements EBU-R128 loudness measurement. class EBUR128 { public: EBUR128(double rate, size_t channels); EBUR128(const EBUR128&) = delete; EBUR128(EBUR128&&) = delete; ~EBUR128() = default; static ArrayOf<Biquad> CalcWeightingFilter(double fs); void Initialize(); void ProcessSampleFromChannel(float x_in, size_t channel); void NextSample(); double IntegrativeLoudness(); inline double IntegrativeLoudnessToLUFS(double loudness) { return 10 * log10(loudness); } private: void HistogramSums(size_t start_idx, double& sum_v, long int& sum_c); void AddBlockToHistogram(size_t validLen); static const size_t HIST_BIN_COUNT = 65536; /// EBU R128 absolute threshold static constexpr double GAMMA_A = (-70.0 + 0.691) / 10.0; ArrayOf<long int> mLoudnessHist; Doubles mBlockRingBuffer; size_t mSampleCount; size_t mBlockRingPos; size_t mBlockRingSize; size_t mBlockSize; size_t mBlockOverlap; size_t mChannelCount; double mRate; /// This is be an array of arrays of the type /// mWeightingFilter[CHANNEL][FILTER] with /// CHANNEL = LEFT/RIGHT (0/1) and /// FILTER = HSF/HPF (0/1) ArrayOf<ArrayOf<Biquad>> mWeightingFilter; }; #endif
570
14,668
// Copyright (c) 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Helper for tests that want to fill in a NetworkServiceConfig #include "jingle/glue/network_service_config_test_util.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/synchronization/waitable_event.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "mojo/public/cpp/bindings/pending_receiver.h" namespace jingle_glue { NetworkServiceConfigTestUtil::NetworkServiceConfigTestUtil( scoped_refptr<net::URLRequestContextGetter> url_request_context_getter) : url_request_context_getter_(std::move(url_request_context_getter)) { net_runner_ = url_request_context_getter_->GetNetworkTaskRunner(); mojo_runner_ = base::SequencedTaskRunnerHandle::Get(); if (net_runner_->BelongsToCurrentThread()) { CreateNetworkContextOnNetworkRunner( network_context_remote_.BindNewPipeAndPassReceiver(), nullptr); } else { base::ScopedAllowBaseSyncPrimitivesForTesting permission; base::WaitableEvent wait_for_create; net_runner_->PostTask( FROM_HERE, base::BindOnce( &NetworkServiceConfigTestUtil::CreateNetworkContextOnNetworkRunner, base::Unretained(this), network_context_remote_.BindNewPipeAndPassReceiver(), &wait_for_create)); // Block for creation to avoid needing to worry about // CreateNetworkContextOnNetworkRunner // potentially happening after ~NetworkServiceConfigTestUtil. wait_for_create.Wait(); } } NetworkServiceConfigTestUtil::NetworkServiceConfigTestUtil( NetworkContextGetter network_context_getter) : net_runner_(base::ThreadPool::CreateSingleThreadTaskRunner({})), mojo_runner_(base::SequencedTaskRunnerHandle::Get()), network_context_getter_(network_context_getter) {} NetworkServiceConfigTestUtil::~NetworkServiceConfigTestUtil() { if (!net_runner_->BelongsToCurrentThread()) { base::ScopedAllowBaseSyncPrimitivesForTesting permission; base::WaitableEvent wait_for_delete; net_runner_->PostTask( FROM_HERE, base::BindOnce( &NetworkServiceConfigTestUtil::DeleteNetworkContextOnNetworkRunner, base::Unretained(this), &wait_for_delete)); wait_for_delete.Wait(); } } void NetworkServiceConfigTestUtil::FillInNetworkConfig( NetworkServiceConfig* config) { config->task_runner = net_runner_; config->get_proxy_resolving_socket_factory_callback = MakeSocketFactoryCallback(); } GetProxyResolvingSocketFactoryCallback NetworkServiceConfigTestUtil::MakeSocketFactoryCallback() { DCHECK(mojo_runner_->RunsTasksInCurrentSequence()); return base::BindRepeating(&NetworkServiceConfigTestUtil::RequestSocket, weak_ptr_factory_.GetWeakPtr(), mojo_runner_, net_runner_); } void NetworkServiceConfigTestUtil::RequestSocket( base::WeakPtr<NetworkServiceConfigTestUtil> instance, scoped_refptr<base::SequencedTaskRunner> mojo_runner, scoped_refptr<base::SequencedTaskRunner> net_runner, mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory> receiver) { DCHECK(net_runner->RunsTasksInCurrentSequence()); mojo_runner->PostTask( FROM_HERE, base::BindOnce(&NetworkServiceConfigTestUtil::RequestSocketOnMojoRunner, std::move(instance), std::move(receiver))); } void NetworkServiceConfigTestUtil::RequestSocketOnMojoRunner( base::WeakPtr<NetworkServiceConfigTestUtil> instance, mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory> receiver) { if (!instance) return; if (instance->network_context_getter_) { instance->network_context_getter_.Run()->CreateProxyResolvingSocketFactory( std::move(receiver)); } else { instance->network_context_remote_->CreateProxyResolvingSocketFactory( std::move(receiver)); } } void NetworkServiceConfigTestUtil::CreateNetworkContextOnNetworkRunner( mojo::PendingReceiver<network::mojom::NetworkContext> network_context_receiver, base::WaitableEvent* notify) { DCHECK(net_runner_->RunsTasksInCurrentSequence()); network_context_ = std::make_unique<network::NetworkContext>( nullptr, std::move(network_context_receiver), url_request_context_getter_->GetURLRequestContext(), /*cors_exempt_header_list=*/std::vector<std::string>()); if (notify) notify->Signal(); } void NetworkServiceConfigTestUtil::DeleteNetworkContextOnNetworkRunner( base::WaitableEvent* notify) { DCHECK(net_runner_->RunsTasksInCurrentSequence()); network_context_ = nullptr; notify->Signal(); } } // namespace jingle_glue
1,755
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE2D_POLYPOLYGONPRIMITIVE2D_HXX #define INCLUDED_DRAWINGLAYER_PRIMITIVE2D_POLYPOLYGONPRIMITIVE2D_HXX #include <drawinglayer/drawinglayerdllapi.h> #include <drawinglayer/primitive2d/baseprimitive2d.hxx> #include <drawinglayer/attribute/fillgraphicattribute.hxx> #include <basegfx/polygon/b2dpolypolygon.hxx> #include <drawinglayer/attribute/lineattribute.hxx> #include <drawinglayer/attribute/strokeattribute.hxx> #include <drawinglayer/attribute/linestartendattribute.hxx> #include <drawinglayer/attribute/fillgradientattribute.hxx> #include <drawinglayer/attribute/fillhatchattribute.hxx> #include <drawinglayer/primitive2d/primitivetools2d.hxx> #include <basegfx/color/bcolor.hxx> ////////////////////////////////////////////////////////////////////////////// // PolyPolygonHairlinePrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonHairlinePrimitive2D class This primitive defines a multi-PolygonHairlinePrimitive2D and is just for convenience. The definition is not different from the single defined PolygonHairlinePrimitive2Ds. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonHairlinePrimitive2D : public BufferedDecompositionPrimitive2D { private: /// the hairline geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the hairline color basegfx::BColor maBColor; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructor PolyPolygonHairlinePrimitive2D(const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::BColor& rBColor); /// data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const basegfx::BColor& getBColor() const { return maBColor; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// get range virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonMarkerPrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonMarkerPrimitive2D class This primitive defines a multi-PolygonMarkerPrimitive2D and is just for convenience. The definition is not different from the single defined PolygonMarkerPrimitive2Ds. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonMarkerPrimitive2D : public BufferedDecompositionPrimitive2D { private: /// the marker hairline geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the two colors basegfx::BColor maRGBColorA; basegfx::BColor maRGBColorB; /// the dash distance in 'pixels' double mfDiscreteDashLength; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructor PolyPolygonMarkerPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::BColor& rRGBColorA, const basegfx::BColor& rRGBColorB, double fDiscreteDashLength); // data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const basegfx::BColor& getRGBColorA() const { return maRGBColorA; } const basegfx::BColor& getRGBColorB() const { return maRGBColorB; } double getDiscreteDashLength() const { return mfDiscreteDashLength; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// get range virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonStrokePrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonStrokePrimitive2D class This primitive defines a multi-PolygonStrokePrimitive2D and is just for convenience. The definition is not different from the single defined PolygonStrokePrimitive2Ds. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonStrokePrimitive2D : public BufferedDecompositionPrimitive2D { private: /// the line geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the line attributes like width, join and color attribute::LineAttribute maLineAttribute; /// the line stroking (if used) attribute::StrokeAttribute maStrokeAttribute; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructor PolyPolygonStrokePrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const attribute::LineAttribute& rLineAttribute, const attribute::StrokeAttribute& rStrokeAttribute); /// constructor without stroking PolyPolygonStrokePrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const attribute::LineAttribute& rLineAttribute); /// data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const attribute::LineAttribute& getLineAttribute() const { return maLineAttribute; } const attribute::StrokeAttribute& getStrokeAttribute() const { return maStrokeAttribute; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// get range virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonStrokeArrowPrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonStrokePrimitive2D class This primitive defines a multi-PolygonStrokeArrowPrimitive2D and is just for convenience. The definition is not different from the single defined PolygonStrokeArrowPrimitive2Ds. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonStrokeArrowPrimitive2D : public PolyPolygonStrokePrimitive2D { private: /// geometric definitions for line start and end attribute::LineStartEndAttribute maStart; attribute::LineStartEndAttribute maEnd; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructor PolyPolygonStrokeArrowPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const attribute::LineAttribute& rLineAttribute, const attribute::StrokeAttribute& rStrokeAttribute, const attribute::LineStartEndAttribute& rStart, const attribute::LineStartEndAttribute& rEnd); /// constructor without stroking PolyPolygonStrokeArrowPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const attribute::LineAttribute& rLineAttribute, const attribute::LineStartEndAttribute& rStart, const attribute::LineStartEndAttribute& rEnd); /// data read access const attribute::LineStartEndAttribute& getStart() const { return maStart; } const attribute::LineStartEndAttribute& getEnd() const { return maEnd; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// get range virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonColorPrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonColorPrimitive2D class This primitive defines a PolyPolygon filled with a single color. This is one of the non-decomposable primitives, so a renderer should process it. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonColorPrimitive2D : public BasePrimitive2D { private: /// the PolyPolygon geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the polygon fill color basegfx::BColor maBColor; public: /// constructor PolyPolygonColorPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::BColor& rBColor); /// data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const basegfx::BColor& getBColor() const { return maBColor; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// get range virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonGradientPrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonColorPrimitive2D class This primitive defines a PolyPolygon filled with a gradient. The decomosition will create a MaskPrimitive2D containing a FillGradientPrimitive2D. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonGradientPrimitive2D : public BufferedDecompositionPrimitive2D { private: /// the PolyPolygon geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the definition range basegfx::B2DRange maDefinitionRange; /// the gradient definition attribute::FillGradientAttribute maFillGradient; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructors. The one without definition range will use output range as definition range PolyPolygonGradientPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const attribute::FillGradientAttribute& rFillGradient); PolyPolygonGradientPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::B2DRange& rDefinitionRange, const attribute::FillGradientAttribute& rFillGradient); /// data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } const attribute::FillGradientAttribute& getFillGradient() const { return maFillGradient; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonHatchPrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonHatchPrimitive2D class This primitive defines a PolyPolygon filled with a hatch. The decomosition will create a MaskPrimitive2D containing a FillHatchPrimitive2D. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonHatchPrimitive2D : public BufferedDecompositionPrimitive2D { private: /// the PolyPolygon geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the definition range basegfx::B2DRange maDefinitionRange; /// the hatch background color (if used) basegfx::BColor maBackgroundColor; /// the hatch definition attribute::FillHatchAttribute maFillHatch; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructors. The one without definition range will use output range as definition range PolyPolygonHatchPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::BColor& rBackgroundColor, const attribute::FillHatchAttribute& rFillHatch); PolyPolygonHatchPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::B2DRange& rDefinitionRange, const basegfx::BColor& rBackgroundColor, const attribute::FillHatchAttribute& rFillHatch); /// data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } const basegfx::BColor& getBackgroundColor() const { return maBackgroundColor; } const attribute::FillHatchAttribute& getFillHatch() const { return maFillHatch; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonGraphicPrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonGraphicPrimitive2D class This primitive defines a PolyPolygon filled with bitmap data (including transparence). The decomosition will create a MaskPrimitive2D containing a FillGraphicPrimitive2D. */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonGraphicPrimitive2D : public BufferedDecompositionPrimitive2D { private: /// the PolyPolygon geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the definition range basegfx::B2DRange maDefinitionRange; /// the bitmap fill definition (may include tiling) attribute::FillGraphicAttribute maFillGraphic; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructors. The one without definition range will use output range as definition range PolyPolygonGraphicPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const attribute::FillGraphicAttribute& rFillGraphic); PolyPolygonGraphicPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::B2DRange& rDefinitionRange, const attribute::FillGraphicAttribute& rFillGraphic); /// data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const basegfx::B2DRange& getDefinitionRange() const { return maDefinitionRange; } const attribute::FillGraphicAttribute& getFillGraphic() const { return maFillGraphic; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // PolyPolygonSelectionPrimitive2D class namespace drawinglayer { namespace primitive2d { /** PolyPolygonSelectionPrimitive2D class This primitive defines a PolyPolygon which gets filled with a defined color and a defined transparence, but also gets extended ('grown') by the given discrete size (thus being a view-dependent primitive) */ class DRAWINGLAYER_DLLPUBLIC PolyPolygonSelectionPrimitive2D : public DiscreteMetricDependentPrimitive2D { private: /// the PolyPolygon geometry basegfx::B2DPolyPolygon maPolyPolygon; /// the color basegfx::BColor maColor; /// the transparence [0.0 .. 1.0] double mfTransparence; /// the discrete grow size ('pixels'), only posivive values allowed double mfDiscreteGrow; /// bitfield /// draw polygons filled when fill is set bool mbFill : 1; protected: /// local decomposition. virtual Primitive2DSequence create2DDecomposition(const geometry::ViewInformation2D& rViewInformation) const; public: /// constructor PolyPolygonSelectionPrimitive2D( const basegfx::B2DPolyPolygon& rPolyPolygon, const basegfx::BColor& rColor, double fTransparence, double fDiscreteGrow, bool bFill); /// data read access const basegfx::B2DPolyPolygon& getB2DPolyPolygon() const { return maPolyPolygon; } const basegfx::BColor& getColor() const { return maColor; } double getTransparence() const { return mfTransparence; } double getDiscreteGrow() const { return mfDiscreteGrow; } bool getFill() const { return mbFill; } /// compare operator virtual bool operator==(const BasePrimitive2D& rPrimitive) const; /// get range virtual basegfx::B2DRange getB2DRange(const geometry::ViewInformation2D& rViewInformation) const; /// provide unique ID DeclPrimitrive2DIDBlock() }; } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// #endif //INCLUDED_DRAWINGLAYER_PRIMITIVE2D_POLYPOLYGONPRIMITIVE2D_HXX ////////////////////////////////////////////////////////////////////////////// // eof
9,039
1,738
<gh_stars>1000+ # # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or the license accompanying this file. Do not # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # from __future__ import print_function import boto3 import CloudCanvas import json from botocore.exceptions import ClientError from botocore.client import Config def __get_bucket(): if not hasattr(__get_bucket,'client_configuration'): __get_bucket.client_configuration = boto3.resource('s3', config=Config(signature_version='s3v4')).Bucket(CloudCanvas.get_setting("ClientConfiguration")) return __get_bucket.client_configuration def update_client_configuration(client_configuration): __get_bucket().put_object(Key="client_configuration.json", Body=json.dumps(client_configuration)) return 'SUCCEED' def get_client_configuration(): client = boto3.client('s3', config=Config(signature_version='s3v4')) client_configuration = [] try: response = client.get_object(Bucket=CloudCanvas.get_setting("ClientConfiguration"), Key="client_configuration.json") client_configuration = json.loads(response["Body"].read()) except ClientError as e: if e.response['Error']['Code'] == 'AccessDenied': client_configuration = [] else: raise e return client_configuration
556
780
<filename>src/main/java/com/codeborne/selenide/conditions/Hidden.java package com.codeborne.selenide.conditions; import com.codeborne.selenide.CheckResult; import com.codeborne.selenide.Condition; import com.codeborne.selenide.Driver; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebElement; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import static com.codeborne.selenide.CheckResult.Verdict.ACCEPT; @ParametersAreNonnullByDefault public class Hidden extends Condition { public Hidden() { super("hidden", true); } @Nonnull @Override public CheckResult check(Driver driver, WebElement element) { try { boolean hidden = !element.isDisplayed(); return new CheckResult(hidden, String.format("hidden:%s", hidden)); } catch (StaleElementReferenceException elementHasDisappeared) { return new CheckResult(ACCEPT, "hidden:true"); } } @Nonnull @Override public Condition negate() { return new Not(this, false); } }
348
317
/* $Id$ *====================================================================== * * DISCLAIMER * * This material was prepared as an account of work sponsored by an * agency of the United States Government. Neither the United States * Government nor the United States Department of Energy, nor Battelle, * nor any of their employees, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, * COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, APPARATUS, PRODUCT, * SOFTWARE, OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT * INFRINGE PRIVATELY OWNED RIGHTS. * * ACKNOWLEDGMENT * * This software and its documentation were produced with Government * support under Contract Number DE-AC06-76RLO-1830 awarded by the United * States Department of Energy. The Government retains a paid-up * non-exclusive, irrevocable worldwide license to reproduce, prepare * derivative works, perform publicly and display publicly by or for the * Government, including the right to distribute to other Government * contractors. * *====================================================================== * * -- PEIGS routine (version 2.1) -- * Pacific Northwest Laboratory * July 28, 1995 * *====================================================================== */ #include <stdio.h> #include <math.h> #include "globalp.c.h" /* PeIGS internal routine. This is used in the one processor case. The user should be warned of possible communication hang in the multiprocessor case if there's not enough buffer space. Let U be any upper triangular matrix. Let L be a lower triangular matrix. This subroutine solves the upper-triangular part of Y for the matrix problem L Y = U The resulting upper-triangular part of matrix Y overwrites U. The matrix U is row wrapped. The resulting matrix Y overwrites the matrix U. The matrix L is column wrapped. */ void forwardLU_ ( n, mapL, mapvecL, colL, mapU, mapvecU, rowU, buffer, nprocs, proclist, ibuffer, buff, buff_ptr) Integer *n, *mapL, *mapvecL, *mapU, *mapvecU, *nprocs, *proclist, *ibuffer; DoublePrecision **colL, **rowU, *buffer, *buff, **buff_ptr; { /* n = dimension of the matrix mapL = index array holding the proces mapvecL = index array holding the i-th column this processor owns colL = DoublePrecision pointer to the array location of the i-th column ditto for mapvecU, rowU, mapU buffer = (DoublePrecision ) of size 2n, buffer for message passing ibuffer = integer buffer space of size p remark: one can improve the x-fer by taking advantage size of the vector */ static Integer ONE = 1, MINUSONE = 99999; Integer i, k, me, isize, indxx; Integer i_L, i_U, nvecsU; DoublePrecision t, *d_ptr; extern Integer count_list(); extern void pipe_bcst_fut_col(); /* mxsubs calls */ extern Integer mxmynd_ (); /* blas calls */ extern void dcopy_ (); /* mxsubs calls */ extern Integer mxwrit_ (), mxread_ (); extern void dscal_(); extern void daxpy_(); me = mxmynd_ (); nvecsU = count_list ( me, mapU, n); i_L=0; i_U=0; for ( i = 0; i < *n; i++ ) { /* indexing on L[i] */ if ( mapL[i]== me ) { if ( mapU[i] != me ) { isize = *n - i; isize = isize*sizeof(DoublePrecision); isize = mxwrit_ ( colL[i_L], &isize, &mapU[i], &MINUSONE); isize = 2 * ( *n -i ) *sizeof(DoublePrecision); pipe_bcst_fut_col( *n , (char *) buffer, isize, i, mapU[i], i, mapU, ibuffer); } if ( mapU[i] == me ){ /* i own both U[i] and L[i]; copy them into one vector buffer buffer owns L[i:n-1] U[n-1:i] this is a trick to minimize data movement but only pass the necessary vectors */ t = (DoublePrecision) 1.0e0 / (DoublePrecision) *colL[i_L] ; isize = *n - i; d_ptr = rowU[i_U]; dscal_(&isize, &t, d_ptr, &ONE); d_ptr = colL[i_L]; dcopy_( &isize, d_ptr, &ONE, buffer, &ONE ); d_ptr = rowU[i_U]; dcopy_( &isize, d_ptr, &ONE, &buffer[isize] , &ONE ); /* broadcasting l[i,i]... l[n-1, i] y[i,i] ... y[n-1 , i ] ; just a choice since a better way is to map it via l[i,i], ... l[n-1, i], y[n-1, i], ... y[i,i] it removes the problems of shifting later */ isize = 2*(*n - i)*sizeof(DoublePrecision); pipe_bcst_fut_col( *n , (char *) buffer, isize, i, mapU[i], i, mapU, ibuffer); i_U++; } i_L++; } if ( mapL[i] != me ) { if ( mapU[i] == me ){ isize = (*n - i)*sizeof(DoublePrecision); isize = mxread_ ( buffer, &isize, &mapL[i], &MINUSONE); t = *buffer; /* this is L[i,i] */ t = (DoublePrecision) 1.0e0 / t; isize = *n - i; d_ptr = rowU[i_U]; dscal_(&isize, &t, d_ptr, &ONE); dcopy_( &isize, d_ptr, &ONE, &buffer[isize], &ONE ); isize = 2*(*n - i)*sizeof(DoublePrecision); pipe_bcst_fut_col( *n , (char *) buffer, isize, i, mapU[i], i, mapU, ibuffer); i_U++; } else if ( mapU[i] != me ) { /* receive the Ls and the Us */ /* if ( i != 0 ){ */ isize = 2*(*n-i)*sizeof(DoublePrecision); pipe_bcst_fut_col( *n , (char *) buffer, isize, i, mapU[i], i, mapU, ibuffer ); } } /* buffer now contains the ( L[i:n-1], Y[i:n-1] ); this is the vectors that is coming in */ for ( k = i_U; k < nvecsU; k++ ){ indxx = mapvecU[k]; t = (DoublePrecision) -1.0e0 * buffer[indxx - i]; /* this is u(i, indx) */ isize = *n - indxx ; d_ptr = rowU[k]; daxpy_ ( &isize, &t, &buffer[*n - i + indxx - i] , &ONE, d_ptr, &ONE); } } return; }
2,340
828
<reponame>Mrliu8023/mongo-tools {"indexes":[{"v":{"$numberInt":"2"},"key":{"_id":{"$numberInt":"1"}},"name":"_id_"},{"v":{"$numberInt":"2"},"key":{"expireAt":{"$numberInt":"1"}},"name":"TenantMigrationDonorTTLIndex","expireAfterSeconds":{"$numberInt":"0"}}],"uuid":"75a80fb546f8489e907e935188d3053c","collectionName":"tenantMigrationDonors","type":"collection"}
130
605
<gh_stars>100-1000 //===--- RenamingOperation.cpp - ------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #include "clang/Tooling/Refactor/RenamingOperation.h" #include "clang/AST/DeclObjC.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Refactor/SymbolOperation.h" using namespace clang; /// \brief Lexes the given name string. /// /// \return False if the name was consumed fully, true otherwise. static bool lexNameString(StringRef Name, Token &Result, const LangOptions &LangOpts) { Lexer Lex(SourceLocation(), LangOpts, Name.data(), Name.data(), Name.data() + Name.size()); return !Lex.LexFromRawLexer(Result); } namespace clang { namespace tooling { namespace rename { bool isNewNameValid(const OldSymbolName &NewName, bool IsSymbolObjCSelector, IdentifierTable &IDs, const LangOptions &LangOpts) { Token Tok; if (IsSymbolObjCSelector) { // Check if the name is a valid selector. for (const auto &Name : NewName.strings()) { // Lex the name and verify that it was fully consumed. Then make sure that // it's a valid identifier. if (lexNameString(Name, Tok, LangOpts) || !Tok.isAnyIdentifier()) return false; } return true; } for (const auto &Name : NewName.strings()) { // Lex the name and verify that it was fully consumed. Then make sure that // it's a valid identifier that's also not a language keyword. if (lexNameString(Name, Tok, LangOpts) || !Tok.isAnyIdentifier() || !tok::isAnyIdentifier(IDs.get(Name).getTokenID())) return false; } return true; } bool isNewNameValid(const OldSymbolName &NewName, const SymbolOperation &Operation, IdentifierTable &IDs, const LangOptions &LangOpts) { assert(!Operation.symbols().empty()); return isNewNameValid(NewName, Operation.symbols().front().ObjCSelector.hasValue(), IDs, LangOpts); } void determineNewNames(OldSymbolName NewName, const SymbolOperation &Operation, SmallVectorImpl<OldSymbolName> &NewNames, const LangOptions &LangOpts) { auto Symbols = Operation.symbols(); assert(!Symbols.empty()); NewNames.push_back(std::move(NewName)); if (const auto *PropertyDecl = dyn_cast<ObjCPropertyDecl>(Symbols.front().FoundDecl)) { assert(NewNames.front().size() == 1 && "Property's name should have one string only"); StringRef PropertyName = NewNames.front()[0]; Symbols = Symbols.drop_front(); auto AddName = [&](const NamedDecl *D, StringRef Name) { assert(Symbols.front().FoundDecl == D && "decl is missing"); NewNames.push_back(OldSymbolName(Name, LangOpts)); Symbols = Symbols.drop_front(); }; if (!PropertyDecl->hasExplicitGetterName()) { if (const auto *Getter = PropertyDecl->getGetterMethodDecl()) AddName(Getter, PropertyName); } if (!PropertyDecl->hasExplicitSetterName()) { if (const auto *Setter = PropertyDecl->getSetterMethodDecl()) { auto SetterName = SelectorTable::constructSetterName(PropertyName); AddName(Setter, SetterName); } } } } } // end namespace rename } // end namespace tooling } // end namespace clang
1,357
6,433
<filename>buildTools/win32-x64/gbdk/libc/_modslong.c<gh_stars>1000+ /*------------------------------------------------------------------------- _modslong.c - routine for modulus of 32 bit signed long Written By - <NAME> . <EMAIL> (1999) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2, 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In other words, you are welcome to use, share and improve this program. You are forbidden to forbid anyone else to use, share and improve what you give them. Help stamp out software-hoarding! -------------------------------------------------------------------------*/ #ifndef GBDK #include <sdcc-lib.h> #endif #if _SDCC_MANGLES_SUPPORT_FUNS || GBDK unsigned long _modulong (unsigned long a, unsigned long b); #endif /* Assembler-functions are provided for: mcs51 small mcs51 small stack-auto */ #if !defined(SDCC_USE_XSTACK) && !defined(_SDCC_NO_ASM_LIB_FUNCS) # if defined(SDCC_mcs51) # if defined(SDCC_MODEL_SMALL) # if defined(SDCC_STACK_AUTO) # define _MODSLONG_ASM_SMALL_AUTO # else # define _MODSLONG_ASM_SMALL # endif # endif # endif #endif #if defined _MODSLONG_ASM_SMALL static void _modslong_dummy (void) _naked { _asm #define a0 dpl #define a1 dph #define a2 b #define a3 r1 .globl __modslong // _modslong_PARM_2 shares the same memory with _modulong_PARM_2 // and is defined in _modulong.c #define b0 (__modslong_PARM_2) #define b1 (__modslong_PARM_2 + 1) #define b2 (__modslong_PARM_2 + 2) #define b3 (__modslong_PARM_2 + 3) __modslong: ; a3 in acc ; b3 in (__modslong_PARM_2 + 3) mov a3,a ; save a3 clr F0 ; Flag 0 in PSW ; available to user for general purpose jnb acc.7,a_not_negative setb F0 clr a ; a = -a; clr c subb a,a0 mov a0,a clr a subb a,a1 mov a1,a clr a subb a,a2 mov a2,a clr a subb a,a3 mov a3,a a_not_negative: mov a,b3 jnb acc.7,b_not_negative cpl F0 clr a ; b = -b; clr c subb a,b0 mov b0,a clr a subb a,b1 mov b1,a clr a subb a,b2 mov b2,a clr a subb a,b3 mov b3,a b_not_negative: mov a,a3 ; restore a3 in acc lcall __modulong jnb F0,not_negative ; result in (a == r1), b, dph, dpl clr a clr c subb a,a0 mov a0,a clr a subb a,a1 mov a1,a clr a subb a,a2 mov a2,a clr a subb a,a3 ; result in a, b, dph, dpl not_negative: ret _endasm ; } #elif defined _MODSLONG_ASM_SMALL_AUTO static void _modslong_dummy (void) _naked { _asm #define a0 dpl #define a1 dph #define a2 b #define a3 r1 #define b0 r2 #define b1 r3 #define b2 r4 #define b3 r5 ar2 = 2 ; BUG register set is not considered ar3 = 3 ar4 = 4 ar5 = 5 .globl __modslong __modslong: ; a3 in acc mov a3,a ; save a3 clr F0 ; F0 (Flag 0) ; available to user for general purpose jnb acc.7,a_not_negative setb F0 clr a ; a = -a; clr c subb a,a0 mov a0,a clr a subb a,a1 mov a1,a clr a subb a,a2 mov a2,a clr a subb a,a3 mov a3,a a_not_negative: mov a,sp add a,#-2-3 ; 2 bytes return address, 3 bytes param b mov r0,a ; r1 points to b0 mov ar2,@r0 ; load b0 inc r0 ; r0 points to b1 mov ar3,@r0 ; b1 inc r0 mov ar4,@r0 ; b2 inc r0 mov a,@r0 ; b3 mov b3,a jnb acc.7,b_not_negative cpl F0 clr a ; b = -b; clr c subb a,b0 mov b0,a clr a subb a,b1 mov b1,a clr a subb a,b2 mov b2,a clr a subb a,b3 mov b3,a b_not_negative: lcall __modlong jnb F0,not_negative ; result in (a == r1), b, dph, dpl clr a clr c subb a,a0 mov a0,a clr a subb a,a1 mov a1,a clr a subb a,a2 mov a2,a clr a subb a,a3 ; result in a, b, dph, dpl not_negative: ret _endasm ; } #else // _MODSLONG_ASM long _modslong (long a, long b) { long r; r = _modulong((a < 0 ? -a : a), (b < 0 ? -b : b)); if ( (a < 0) ^ (b < 0)) return -r; else return r; } #endif // _MODSLONG_ASM
2,398
441
// Copyright 2009-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once namespace embree { /* 4-wide SSE float type */ template<> struct vfloat<4> { ALIGNED_STRUCT_(16); typedef vboolf4 Bool; typedef vint4 Int; typedef vfloat4 Float; enum { size = 4 }; // number of SIMD elements union { __m128 v; float f[4]; int i[4]; }; // data //////////////////////////////////////////////////////////////////////////////// /// Constructors, Assignment & Cast Operators //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat() {} __forceinline vfloat(const vfloat4& other) { v = other.v; } __forceinline vfloat4& operator =(const vfloat4& other) { v = other.v; return *this; } __forceinline vfloat(__m128 a) : v(a) {} __forceinline operator const __m128&() const { return v; } __forceinline operator __m128&() { return v; } __forceinline vfloat(float a) : v(_mm_set1_ps(a)) {} __forceinline vfloat(float a, float b, float c, float d) : v(_mm_set_ps(d, c, b, a)) {} __forceinline explicit vfloat(const vint4& a) : v(_mm_cvtepi32_ps(a)) {} __forceinline explicit vfloat(const vuint4& x) { const __m128i a = _mm_and_si128(x,_mm_set1_epi32(0x7FFFFFFF)); const __m128i b = _mm_and_si128(_mm_srai_epi32(x,31),_mm_set1_epi32(0x4F000000)); //0x4F000000 = 2^31 const __m128 af = _mm_cvtepi32_ps(a); const __m128 bf = _mm_castsi128_ps(b); v = _mm_add_ps(af,bf); } //////////////////////////////////////////////////////////////////////////////// /// Constants //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat(ZeroTy) : v(_mm_setzero_ps()) {} __forceinline vfloat(OneTy) : v(_mm_set1_ps(1.0f)) {} __forceinline vfloat(PosInfTy) : v(_mm_set1_ps(pos_inf)) {} __forceinline vfloat(NegInfTy) : v(_mm_set1_ps(neg_inf)) {} __forceinline vfloat(StepTy) : v(_mm_set_ps(3.0f, 2.0f, 1.0f, 0.0f)) {} __forceinline vfloat(NaNTy) : v(_mm_set1_ps(nan)) {} __forceinline vfloat(UndefinedTy) : v(_mm_undefined_ps()) {} //////////////////////////////////////////////////////////////////////////////// /// Loads and Stores //////////////////////////////////////////////////////////////////////////////// static __forceinline vfloat4 load (const void* a) { return _mm_load_ps((float*)a); } static __forceinline vfloat4 loadu(const void* a) { return _mm_loadu_ps((float*)a); } static __forceinline void store (void* ptr, const vfloat4& v) { _mm_store_ps((float*)ptr,v); } static __forceinline void storeu(void* ptr, const vfloat4& v) { _mm_storeu_ps((float*)ptr,v); } #if defined(__AVX512VL__) static __forceinline vfloat4 compact(const vboolf4& mask, vfloat4 &v) { return _mm_mask_compress_ps(v, mask, v); } static __forceinline vfloat4 compact(const vboolf4& mask, vfloat4 &a, const vfloat4& b) { return _mm_mask_compress_ps(a, mask, b); } static __forceinline vfloat4 load (const vboolf4& mask, const void* ptr) { return _mm_mask_load_ps (_mm_setzero_ps(),mask,(float*)ptr); } static __forceinline vfloat4 loadu(const vboolf4& mask, const void* ptr) { return _mm_mask_loadu_ps(_mm_setzero_ps(),mask,(float*)ptr); } static __forceinline void store (const vboolf4& mask, void* ptr, const vfloat4& v) { _mm_mask_store_ps ((float*)ptr,mask,v); } static __forceinline void storeu(const vboolf4& mask, void* ptr, const vfloat4& v) { _mm_mask_storeu_ps((float*)ptr,mask,v); } #elif defined(__AVX__) static __forceinline vfloat4 load (const vboolf4& mask, const void* ptr) { return _mm_maskload_ps((float*)ptr,mask); } static __forceinline vfloat4 loadu(const vboolf4& mask, const void* ptr) { return _mm_maskload_ps((float*)ptr,mask); } static __forceinline void store (const vboolf4& mask, void* ptr, const vfloat4& v) { _mm_maskstore_ps((float*)ptr,(__m128i)mask,v); } static __forceinline void storeu(const vboolf4& mask, void* ptr, const vfloat4& v) { _mm_maskstore_ps((float*)ptr,(__m128i)mask,v); } #else static __forceinline vfloat4 load (const vboolf4& mask, const void* ptr) { return _mm_and_ps(_mm_load_ps ((float*)ptr),mask); } static __forceinline vfloat4 loadu(const vboolf4& mask, const void* ptr) { return _mm_and_ps(_mm_loadu_ps((float*)ptr),mask); } static __forceinline void store (const vboolf4& mask, void* ptr, const vfloat4& v) { store (ptr,select(mask,v,load (ptr))); } static __forceinline void storeu(const vboolf4& mask, void* ptr, const vfloat4& v) { storeu(ptr,select(mask,v,loadu(ptr))); } #endif #if defined(__AVX__) static __forceinline vfloat4 broadcast(const void* a) { return _mm_broadcast_ss((float*)a); } #else static __forceinline vfloat4 broadcast(const void* a) { return _mm_set1_ps(*(float*)a); } #endif static __forceinline vfloat4 load_nt (const float* ptr) { #if defined (__SSE4_1__) return _mm_castsi128_ps(_mm_stream_load_si128((__m128i*)ptr)); #else return _mm_load_ps(ptr); #endif } #if defined(__SSE4_1__) static __forceinline vfloat4 load(const char* ptr) { return _mm_cvtepi32_ps(_mm_cvtepi8_epi32(_mm_loadu_si128((__m128i*)ptr))); } #else static __forceinline vfloat4 load(const char* ptr) { return vfloat4(ptr[0],ptr[1],ptr[2],ptr[3]); } #endif #if defined(__SSE4_1__) static __forceinline vfloat4 load(const unsigned char* ptr) { return _mm_cvtepi32_ps(_mm_cvtepu8_epi32(_mm_loadu_si128((__m128i*)ptr))); } #else static __forceinline vfloat4 load(const unsigned char* ptr) { //return _mm_cvtpu8_ps(*(__m64*)ptr); // don't enable, will use MMX instructions return vfloat4(ptr[0],ptr[1],ptr[2],ptr[3]); } #endif #if defined(__SSE4_1__) static __forceinline vfloat4 load(const short* ptr) { return _mm_cvtepi32_ps(_mm_cvtepi16_epi32(_mm_loadu_si128((__m128i*)ptr))); } #else static __forceinline vfloat4 load(const short* ptr) { return vfloat4(ptr[0],ptr[1],ptr[2],ptr[3]); } #endif static __forceinline vfloat4 load(const unsigned short* ptr) { return _mm_mul_ps(vfloat4(vint4::load(ptr)),vfloat4(1.0f/65535.0f)); } static __forceinline void store_nt(void* ptr, const vfloat4& v) { #if defined (__SSE4_1__) _mm_stream_ps((float*)ptr,v); #else _mm_store_ps((float*)ptr,v); #endif } template<int scale = 4> static __forceinline vfloat4 gather(const float* ptr, const vint4& index) { #if defined(__AVX2__) return _mm_i32gather_ps(ptr, index, scale); #else return vfloat4( *(float*)(((char*)ptr)+scale*index[0]), *(float*)(((char*)ptr)+scale*index[1]), *(float*)(((char*)ptr)+scale*index[2]), *(float*)(((char*)ptr)+scale*index[3])); #endif } template<int scale = 4> static __forceinline vfloat4 gather(const vboolf4& mask, const float* ptr, const vint4& index) { vfloat4 r = zero; #if defined(__AVX512VL__) return _mm_mmask_i32gather_ps(r, mask, index, ptr, scale); #elif defined(__AVX2__) return _mm_mask_i32gather_ps(r, ptr, index, mask, scale); #else if (likely(mask[0])) r[0] = *(float*)(((char*)ptr)+scale*index[0]); if (likely(mask[1])) r[1] = *(float*)(((char*)ptr)+scale*index[1]); if (likely(mask[2])) r[2] = *(float*)(((char*)ptr)+scale*index[2]); if (likely(mask[3])) r[3] = *(float*)(((char*)ptr)+scale*index[3]); return r; #endif } template<int scale = 4> static __forceinline void scatter(void* ptr, const vint4& index, const vfloat4& v) { #if defined(__AVX512VL__) _mm_i32scatter_ps((float*)ptr, index, v, scale); #else *(float*)(((char*)ptr)+scale*index[0]) = v[0]; *(float*)(((char*)ptr)+scale*index[1]) = v[1]; *(float*)(((char*)ptr)+scale*index[2]) = v[2]; *(float*)(((char*)ptr)+scale*index[3]) = v[3]; #endif } template<int scale = 4> static __forceinline void scatter(const vboolf4& mask, void* ptr, const vint4& index, const vfloat4& v) { #if defined(__AVX512VL__) _mm_mask_i32scatter_ps((float*)ptr ,mask, index, v, scale); #else if (likely(mask[0])) *(float*)(((char*)ptr)+scale*index[0]) = v[0]; if (likely(mask[1])) *(float*)(((char*)ptr)+scale*index[1]) = v[1]; if (likely(mask[2])) *(float*)(((char*)ptr)+scale*index[2]) = v[2]; if (likely(mask[3])) *(float*)(((char*)ptr)+scale*index[3]) = v[3]; #endif } static __forceinline void store(const vboolf4& mask, char* ptr, const vint4& ofs, const vfloat4& v) { scatter<1>(mask,ptr,ofs,v); } static __forceinline void store(const vboolf4& mask, float* ptr, const vint4& ofs, const vfloat4& v) { scatter<4>(mask,ptr,ofs,v); } //////////////////////////////////////////////////////////////////////////////// /// Array Access //////////////////////////////////////////////////////////////////////////////// __forceinline const float& operator [](size_t index) const { assert(index < 4); return f[index]; } __forceinline float& operator [](size_t index) { assert(index < 4); return f[index]; } friend __forceinline vfloat4 select(const vboolf4& m, const vfloat4& t, const vfloat4& f) { #if defined(__AVX512VL__) return _mm_mask_blend_ps(m, f, t); #elif defined(__SSE4_1__) return _mm_blendv_ps(f, t, m); #else return _mm_or_ps(_mm_and_ps(m, t), _mm_andnot_ps(m, f)); #endif } }; //////////////////////////////////////////////////////////////////////////////// /// Unary Operators //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat4 asFloat(const vint4& a) { return _mm_castsi128_ps(a); } __forceinline vint4 asInt (const vfloat4& a) { return _mm_castps_si128(a); } __forceinline vuint4 asUInt (const vfloat4& a) { return _mm_castps_si128(a); } __forceinline vint4 toInt (const vfloat4& a) { return vint4(a); } __forceinline vfloat4 toFloat(const vint4& a) { return vfloat4(a); } __forceinline vfloat4 operator +(const vfloat4& a) { return a; } __forceinline vfloat4 operator -(const vfloat4& a) { return _mm_xor_ps(a, _mm_castsi128_ps(_mm_set1_epi32(0x80000000))); } __forceinline vfloat4 abs(const vfloat4& a) { return _mm_and_ps(a, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff))); } #if defined(__AVX512VL__) __forceinline vfloat4 sign(const vfloat4& a) { return _mm_mask_blend_ps(_mm_cmp_ps_mask(a, vfloat4(zero), _CMP_LT_OQ), vfloat4(one), -vfloat4(one)); } #else __forceinline vfloat4 sign(const vfloat4& a) { return blendv_ps(vfloat4(one), -vfloat4(one), _mm_cmplt_ps(a, vfloat4(zero))); } #endif __forceinline vfloat4 signmsk(const vfloat4& a) { return _mm_and_ps(a,_mm_castsi128_ps(_mm_set1_epi32(0x80000000))); } __forceinline vfloat4 rcp(const vfloat4& a) { #if defined(__AVX512VL__) const vfloat4 r = _mm_rcp14_ps(a); #else const vfloat4 r = _mm_rcp_ps(a); #endif #if defined(__AVX2__) return _mm_mul_ps(r,_mm_fnmadd_ps(r, a, vfloat4(2.0f))); #else return _mm_mul_ps(r,_mm_sub_ps(vfloat4(2.0f), _mm_mul_ps(r, a))); #endif } __forceinline vfloat4 sqr (const vfloat4& a) { return _mm_mul_ps(a,a); } __forceinline vfloat4 sqrt(const vfloat4& a) { return _mm_sqrt_ps(a); } __forceinline vfloat4 rsqrt(const vfloat4& a) { #if defined(__AVX512VL__) const vfloat4 r = _mm_rsqrt14_ps(a); #else const vfloat4 r = _mm_rsqrt_ps(a); #endif #if defined(__AVX2__) return _mm_fmadd_ps(_mm_set1_ps(1.5f), r, _mm_mul_ps(_mm_mul_ps(_mm_mul_ps(a, _mm_set1_ps(-0.5f)), r), _mm_mul_ps(r, r))); #else return _mm_add_ps(_mm_mul_ps(_mm_set1_ps(1.5f), r), _mm_mul_ps(_mm_mul_ps(_mm_mul_ps(a, _mm_set1_ps(-0.5f)), r), _mm_mul_ps(r, r))); #endif } __forceinline vboolf4 isnan(const vfloat4& a) { const vfloat4 b = _mm_and_ps(a, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff))); #if defined(__AVX512VL__) return _mm_cmp_epi32_mask(_mm_castps_si128(b), _mm_set1_epi32(0x7f800000), _MM_CMPINT_GT); #else return _mm_castsi128_ps(_mm_cmpgt_epi32(_mm_castps_si128(b), _mm_set1_epi32(0x7f800000))); #endif } //////////////////////////////////////////////////////////////////////////////// /// Binary Operators //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat4 operator +(const vfloat4& a, const vfloat4& b) { return _mm_add_ps(a, b); } __forceinline vfloat4 operator +(const vfloat4& a, float b) { return a + vfloat4(b); } __forceinline vfloat4 operator +(float a, const vfloat4& b) { return vfloat4(a) + b; } __forceinline vfloat4 operator -(const vfloat4& a, const vfloat4& b) { return _mm_sub_ps(a, b); } __forceinline vfloat4 operator -(const vfloat4& a, float b) { return a - vfloat4(b); } __forceinline vfloat4 operator -(float a, const vfloat4& b) { return vfloat4(a) - b; } __forceinline vfloat4 operator *(const vfloat4& a, const vfloat4& b) { return _mm_mul_ps(a, b); } __forceinline vfloat4 operator *(const vfloat4& a, float b) { return a * vfloat4(b); } __forceinline vfloat4 operator *(float a, const vfloat4& b) { return vfloat4(a) * b; } __forceinline vfloat4 operator /(const vfloat4& a, const vfloat4& b) { return _mm_div_ps(a,b); } __forceinline vfloat4 operator /(const vfloat4& a, float b) { return a/vfloat4(b); } __forceinline vfloat4 operator /(float a, const vfloat4& b) { return vfloat4(a)/b; } __forceinline vfloat4 operator &(const vfloat4& a, const vfloat4& b) { return _mm_and_ps(a,b); } __forceinline vfloat4 operator |(const vfloat4& a, const vfloat4& b) { return _mm_or_ps(a,b); } __forceinline vfloat4 operator ^(const vfloat4& a, const vfloat4& b) { return _mm_xor_ps(a,b); } __forceinline vfloat4 operator ^(const vfloat4& a, const vint4& b) { return _mm_xor_ps(a,_mm_castsi128_ps(b)); } __forceinline vfloat4 min(const vfloat4& a, const vfloat4& b) { return _mm_min_ps(a,b); } __forceinline vfloat4 min(const vfloat4& a, float b) { return _mm_min_ps(a,vfloat4(b)); } __forceinline vfloat4 min(float a, const vfloat4& b) { return _mm_min_ps(vfloat4(a),b); } __forceinline vfloat4 max(const vfloat4& a, const vfloat4& b) { return _mm_max_ps(a,b); } __forceinline vfloat4 max(const vfloat4& a, float b) { return _mm_max_ps(a,vfloat4(b)); } __forceinline vfloat4 max(float a, const vfloat4& b) { return _mm_max_ps(vfloat4(a),b); } #if defined(__SSE4_1__) __forceinline vfloat4 mini(const vfloat4& a, const vfloat4& b) { const vint4 ai = _mm_castps_si128(a); const vint4 bi = _mm_castps_si128(b); const vint4 ci = _mm_min_epi32(ai,bi); return _mm_castsi128_ps(ci); } __forceinline vfloat4 maxi(const vfloat4& a, const vfloat4& b) { const vint4 ai = _mm_castps_si128(a); const vint4 bi = _mm_castps_si128(b); const vint4 ci = _mm_max_epi32(ai,bi); return _mm_castsi128_ps(ci); } __forceinline vfloat4 minui(const vfloat4& a, const vfloat4& b) { const vint4 ai = _mm_castps_si128(a); const vint4 bi = _mm_castps_si128(b); const vint4 ci = _mm_min_epu32(ai,bi); return _mm_castsi128_ps(ci); } __forceinline vfloat4 maxui(const vfloat4& a, const vfloat4& b) { const vint4 ai = _mm_castps_si128(a); const vint4 bi = _mm_castps_si128(b); const vint4 ci = _mm_max_epu32(ai,bi); return _mm_castsi128_ps(ci); } #else __forceinline vfloat4 mini(const vfloat4& a, const vfloat4& b) { return min(a,b); } __forceinline vfloat4 maxi(const vfloat4& a, const vfloat4& b) { return max(a,b); } #endif //////////////////////////////////////////////////////////////////////////////// /// Ternary Operators //////////////////////////////////////////////////////////////////////////////// #if defined(__AVX2__) __forceinline vfloat4 madd (const vfloat4& a, const vfloat4& b, const vfloat4& c) { return _mm_fmadd_ps(a,b,c); } __forceinline vfloat4 msub (const vfloat4& a, const vfloat4& b, const vfloat4& c) { return _mm_fmsub_ps(a,b,c); } __forceinline vfloat4 nmadd(const vfloat4& a, const vfloat4& b, const vfloat4& c) { return _mm_fnmadd_ps(a,b,c); } __forceinline vfloat4 nmsub(const vfloat4& a, const vfloat4& b, const vfloat4& c) { return _mm_fnmsub_ps(a,b,c); } #else __forceinline vfloat4 madd (const vfloat4& a, const vfloat4& b, const vfloat4& c) { return a*b+c; } __forceinline vfloat4 msub (const vfloat4& a, const vfloat4& b, const vfloat4& c) { return a*b-c; } __forceinline vfloat4 nmadd(const vfloat4& a, const vfloat4& b, const vfloat4& c) { return -a*b+c;} __forceinline vfloat4 nmsub(const vfloat4& a, const vfloat4& b, const vfloat4& c) { return -a*b-c; } #endif //////////////////////////////////////////////////////////////////////////////// /// Assignment Operators //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat4& operator +=(vfloat4& a, const vfloat4& b) { return a = a + b; } __forceinline vfloat4& operator +=(vfloat4& a, float b) { return a = a + b; } __forceinline vfloat4& operator -=(vfloat4& a, const vfloat4& b) { return a = a - b; } __forceinline vfloat4& operator -=(vfloat4& a, float b) { return a = a - b; } __forceinline vfloat4& operator *=(vfloat4& a, const vfloat4& b) { return a = a * b; } __forceinline vfloat4& operator *=(vfloat4& a, float b) { return a = a * b; } __forceinline vfloat4& operator /=(vfloat4& a, const vfloat4& b) { return a = a / b; } __forceinline vfloat4& operator /=(vfloat4& a, float b) { return a = a / b; } //////////////////////////////////////////////////////////////////////////////// /// Comparison Operators + Select //////////////////////////////////////////////////////////////////////////////// #if defined(__AVX512VL__) __forceinline vboolf4 operator ==(const vfloat4& a, const vfloat4& b) { return _mm_cmp_ps_mask(a, b, _MM_CMPINT_EQ); } __forceinline vboolf4 operator !=(const vfloat4& a, const vfloat4& b) { return _mm_cmp_ps_mask(a, b, _MM_CMPINT_NE); } __forceinline vboolf4 operator < (const vfloat4& a, const vfloat4& b) { return _mm_cmp_ps_mask(a, b, _MM_CMPINT_LT); } __forceinline vboolf4 operator >=(const vfloat4& a, const vfloat4& b) { return _mm_cmp_ps_mask(a, b, _MM_CMPINT_GE); } __forceinline vboolf4 operator > (const vfloat4& a, const vfloat4& b) { return _mm_cmp_ps_mask(a, b, _MM_CMPINT_GT); } __forceinline vboolf4 operator <=(const vfloat4& a, const vfloat4& b) { return _mm_cmp_ps_mask(a, b, _MM_CMPINT_LE); } #else __forceinline vboolf4 operator ==(const vfloat4& a, const vfloat4& b) { return _mm_cmpeq_ps (a, b); } __forceinline vboolf4 operator !=(const vfloat4& a, const vfloat4& b) { return _mm_cmpneq_ps(a, b); } __forceinline vboolf4 operator < (const vfloat4& a, const vfloat4& b) { return _mm_cmplt_ps (a, b); } __forceinline vboolf4 operator >=(const vfloat4& a, const vfloat4& b) { return _mm_cmpnlt_ps(a, b); } __forceinline vboolf4 operator > (const vfloat4& a, const vfloat4& b) { return _mm_cmpnle_ps(a, b); } __forceinline vboolf4 operator <=(const vfloat4& a, const vfloat4& b) { return _mm_cmple_ps (a, b); } #endif __forceinline vboolf4 operator ==(const vfloat4& a, float b) { return a == vfloat4(b); } __forceinline vboolf4 operator ==(float a, const vfloat4& b) { return vfloat4(a) == b; } __forceinline vboolf4 operator !=(const vfloat4& a, float b) { return a != vfloat4(b); } __forceinline vboolf4 operator !=(float a, const vfloat4& b) { return vfloat4(a) != b; } __forceinline vboolf4 operator < (const vfloat4& a, float b) { return a < vfloat4(b); } __forceinline vboolf4 operator < (float a, const vfloat4& b) { return vfloat4(a) < b; } __forceinline vboolf4 operator >=(const vfloat4& a, float b) { return a >= vfloat4(b); } __forceinline vboolf4 operator >=(float a, const vfloat4& b) { return vfloat4(a) >= b; } __forceinline vboolf4 operator > (const vfloat4& a, float b) { return a > vfloat4(b); } __forceinline vboolf4 operator > (float a, const vfloat4& b) { return vfloat4(a) > b; } __forceinline vboolf4 operator <=(const vfloat4& a, float b) { return a <= vfloat4(b); } __forceinline vboolf4 operator <=(float a, const vfloat4& b) { return vfloat4(a) <= b; } __forceinline vboolf4 eq(const vfloat4& a, const vfloat4& b) { return a == b; } __forceinline vboolf4 ne(const vfloat4& a, const vfloat4& b) { return a != b; } __forceinline vboolf4 lt(const vfloat4& a, const vfloat4& b) { return a < b; } __forceinline vboolf4 ge(const vfloat4& a, const vfloat4& b) { return a >= b; } __forceinline vboolf4 gt(const vfloat4& a, const vfloat4& b) { return a > b; } __forceinline vboolf4 le(const vfloat4& a, const vfloat4& b) { return a <= b; } #if defined(__AVX512VL__) __forceinline vboolf4 eq(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return _mm_mask_cmp_ps_mask(mask, a, b, _MM_CMPINT_EQ); } __forceinline vboolf4 ne(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return _mm_mask_cmp_ps_mask(mask, a, b, _MM_CMPINT_NE); } __forceinline vboolf4 lt(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return _mm_mask_cmp_ps_mask(mask, a, b, _MM_CMPINT_LT); } __forceinline vboolf4 ge(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return _mm_mask_cmp_ps_mask(mask, a, b, _MM_CMPINT_GE); } __forceinline vboolf4 gt(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return _mm_mask_cmp_ps_mask(mask, a, b, _MM_CMPINT_GT); } __forceinline vboolf4 le(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return _mm_mask_cmp_ps_mask(mask, a, b, _MM_CMPINT_LE); } #else __forceinline vboolf4 eq(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return mask & (a == b); } __forceinline vboolf4 ne(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return mask & (a != b); } __forceinline vboolf4 lt(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return mask & (a < b); } __forceinline vboolf4 ge(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return mask & (a >= b); } __forceinline vboolf4 gt(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return mask & (a > b); } __forceinline vboolf4 le(const vboolf4& mask, const vfloat4& a, const vfloat4& b) { return mask & (a <= b); } #endif template<int mask> __forceinline vfloat4 select(const vfloat4& t, const vfloat4& f) { #if defined(__SSE4_1__) return _mm_blend_ps(f, t, mask); #else return select(vboolf4(mask), t, f); #endif } __forceinline vfloat4 lerp(const vfloat4& a, const vfloat4& b, const vfloat4& t) { return madd(t,b-a,a); } __forceinline bool isvalid(const vfloat4& v) { return all((v > vfloat4(-FLT_LARGE)) & (v < vfloat4(+FLT_LARGE))); } __forceinline bool is_finite(const vfloat4& a) { return all((a >= vfloat4(-FLT_MAX)) & (a <= vfloat4(+FLT_MAX))); } __forceinline bool is_finite(const vboolf4& valid, const vfloat4& a) { return all(valid, (a >= vfloat4(-FLT_MAX)) & (a <= vfloat4(+FLT_MAX))); } //////////////////////////////////////////////////////////////////////////////// /// Rounding Functions //////////////////////////////////////////////////////////////////////////////// #if defined (__SSE4_1__) __forceinline vfloat4 floor(const vfloat4& a) { return _mm_round_ps(a, _MM_FROUND_TO_NEG_INF ); } __forceinline vfloat4 ceil (const vfloat4& a) { return _mm_round_ps(a, _MM_FROUND_TO_POS_INF ); } __forceinline vfloat4 trunc(const vfloat4& a) { return _mm_round_ps(a, _MM_FROUND_TO_ZERO ); } __forceinline vfloat4 round(const vfloat4& a) { return _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT); } #else __forceinline vfloat4 floor(const vfloat4& a) { return vfloat4(floorf(a[0]),floorf(a[1]),floorf(a[2]),floorf(a[3])); } __forceinline vfloat4 ceil (const vfloat4& a) { return vfloat4(ceilf (a[0]),ceilf (a[1]),ceilf (a[2]),ceilf (a[3])); } __forceinline vfloat4 trunc(const vfloat4& a) { return vfloat4(truncf(a[0]),truncf(a[1]),truncf(a[2]),truncf(a[3])); } __forceinline vfloat4 round(const vfloat4& a) { return vfloat4(roundf(a[0]),roundf(a[1]),roundf(a[2]),roundf(a[3])); } #endif __forceinline vfloat4 frac(const vfloat4& a) { return a-floor(a); } __forceinline vint4 floori(const vfloat4& a) { #if defined(__SSE4_1__) return vint4(floor(a)); #else return vint4(a-vfloat4(0.5f)); #endif } //////////////////////////////////////////////////////////////////////////////// /// Movement/Shifting/Shuffling Functions //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat4 unpacklo(const vfloat4& a, const vfloat4& b) { return _mm_unpacklo_ps(a, b); } __forceinline vfloat4 unpackhi(const vfloat4& a, const vfloat4& b) { return _mm_unpackhi_ps(a, b); } template<int i0, int i1, int i2, int i3> __forceinline vfloat4 shuffle(const vfloat4& v) { return _mm_castsi128_ps(_mm_shuffle_epi32(_mm_castps_si128(v), _MM_SHUFFLE(i3, i2, i1, i0))); } template<int i0, int i1, int i2, int i3> __forceinline vfloat4 shuffle(const vfloat4& a, const vfloat4& b) { return _mm_shuffle_ps(a, b, _MM_SHUFFLE(i3, i2, i1, i0)); } #if defined (__SSSE3__) __forceinline vfloat4 shuffle8(const vfloat4& a, const vint4& shuf) { return _mm_castsi128_ps(_mm_shuffle_epi8(_mm_castps_si128(a), shuf)); } #endif #if defined(__SSE3__) template<> __forceinline vfloat4 shuffle<0, 0, 2, 2>(const vfloat4& v) { return _mm_moveldup_ps(v); } template<> __forceinline vfloat4 shuffle<1, 1, 3, 3>(const vfloat4& v) { return _mm_movehdup_ps(v); } template<> __forceinline vfloat4 shuffle<0, 1, 0, 1>(const vfloat4& v) { return _mm_castpd_ps(_mm_movedup_pd(_mm_castps_pd(v))); } #endif template<int i> __forceinline vfloat4 shuffle(const vfloat4& v) { return shuffle<i,i,i,i>(v); } #if defined (__SSE4_1__) && !defined(__GNUC__) template<int i> __forceinline float extract(const vfloat4& a) { return _mm_cvtss_f32(_mm_extract_ps(a,i)); } #else template<int i> __forceinline float extract(const vfloat4& a) { return _mm_cvtss_f32(shuffle<i,i,i,i>(a)); } #endif template<> __forceinline float extract<0>(const vfloat4& a) { return _mm_cvtss_f32(a); } #if defined (__SSE4_1__) template<int dst, int src, int clr> __forceinline vfloat4 insert(const vfloat4& a, const vfloat4& b) { return _mm_insert_ps(a, b, (dst << 4) | (src << 6) | clr); } template<int dst, int src> __forceinline vfloat4 insert(const vfloat4& a, const vfloat4& b) { return insert<dst, src, 0>(a, b); } template<int dst> __forceinline vfloat4 insert(const vfloat4& a, const float b) { return insert<dst, 0>(a, _mm_set_ss(b)); } #else template<int dst, int src> __forceinline vfloat4 insert(const vfloat4& a, const vfloat4& b) { vfloat4 c = a; c[dst&3] = b[src&3]; return c; } template<int dst> __forceinline vfloat4 insert(const vfloat4& a, float b) { vfloat4 c = a; c[dst&3] = b; return c; } #endif __forceinline float toScalar(const vfloat4& v) { return _mm_cvtss_f32(v); } __forceinline vfloat4 broadcast4f(const vfloat4& a, size_t k) { return vfloat4::broadcast(&a[k]); } __forceinline vfloat4 shift_right_1(const vfloat4& x) { return _mm_castsi128_ps(_mm_srli_si128(_mm_castps_si128(x), 4)); } #if defined (__AVX2__) __forceinline vfloat4 permute(const vfloat4 &a, const __m128i &index) { return _mm_permutevar_ps(a,index); } __forceinline vfloat4 broadcast1f(const void* a) { return _mm_broadcast_ss((float*)a); } #endif #if defined(__AVX512VL__) template<int i> __forceinline vfloat4 align_shift_right(const vfloat4& a, const vfloat4& b) { return _mm_castsi128_ps(_mm_alignr_epi32(_mm_castps_si128(a), _mm_castps_si128(b), i)); } #endif //////////////////////////////////////////////////////////////////////////////// /// Sorting Network //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat4 sort_ascending(const vfloat4& v) { const vfloat4 a0 = v; const vfloat4 b0 = shuffle<1,0,3,2>(a0); const vfloat4 c0 = min(a0,b0); const vfloat4 d0 = max(a0,b0); const vfloat4 a1 = select<0x5 /* 0b0101 */>(c0,d0); const vfloat4 b1 = shuffle<2,3,0,1>(a1); const vfloat4 c1 = min(a1,b1); const vfloat4 d1 = max(a1,b1); const vfloat4 a2 = select<0x3 /* 0b0011 */>(c1,d1); const vfloat4 b2 = shuffle<0,2,1,3>(a2); const vfloat4 c2 = min(a2,b2); const vfloat4 d2 = max(a2,b2); const vfloat4 a3 = select<0x2 /* 0b0010 */>(c2,d2); return a3; } __forceinline vfloat4 sort_descending(const vfloat4& v) { const vfloat4 a0 = v; const vfloat4 b0 = shuffle<1,0,3,2>(a0); const vfloat4 c0 = max(a0,b0); const vfloat4 d0 = min(a0,b0); const vfloat4 a1 = select<0x5 /* 0b0101 */>(c0,d0); const vfloat4 b1 = shuffle<2,3,0,1>(a1); const vfloat4 c1 = max(a1,b1); const vfloat4 d1 = min(a1,b1); const vfloat4 a2 = select<0x3 /* 0b0011 */>(c1,d1); const vfloat4 b2 = shuffle<0,2,1,3>(a2); const vfloat4 c2 = max(a2,b2); const vfloat4 d2 = min(a2,b2); const vfloat4 a3 = select<0x2 /* 0b0010 */>(c2,d2); return a3; } //////////////////////////////////////////////////////////////////////////////// /// Transpose //////////////////////////////////////////////////////////////////////////////// __forceinline void transpose(const vfloat4& r0, const vfloat4& r1, const vfloat4& r2, const vfloat4& r3, vfloat4& c0, vfloat4& c1, vfloat4& c2, vfloat4& c3) { vfloat4 l02 = unpacklo(r0,r2); vfloat4 h02 = unpackhi(r0,r2); vfloat4 l13 = unpacklo(r1,r3); vfloat4 h13 = unpackhi(r1,r3); c0 = unpacklo(l02,l13); c1 = unpackhi(l02,l13); c2 = unpacklo(h02,h13); c3 = unpackhi(h02,h13); } __forceinline void transpose(const vfloat4& r0, const vfloat4& r1, const vfloat4& r2, const vfloat4& r3, vfloat4& c0, vfloat4& c1, vfloat4& c2) { vfloat4 l02 = unpacklo(r0,r2); vfloat4 h02 = unpackhi(r0,r2); vfloat4 l13 = unpacklo(r1,r3); vfloat4 h13 = unpackhi(r1,r3); c0 = unpacklo(l02,l13); c1 = unpackhi(l02,l13); c2 = unpacklo(h02,h13); } //////////////////////////////////////////////////////////////////////////////// /// Reductions //////////////////////////////////////////////////////////////////////////////// __forceinline vfloat4 vreduce_min(const vfloat4& v) { vfloat4 h = min(shuffle<1,0,3,2>(v),v); return min(shuffle<2,3,0,1>(h),h); } __forceinline vfloat4 vreduce_max(const vfloat4& v) { vfloat4 h = max(shuffle<1,0,3,2>(v),v); return max(shuffle<2,3,0,1>(h),h); } __forceinline vfloat4 vreduce_add(const vfloat4& v) { vfloat4 h = shuffle<1,0,3,2>(v) + v ; return shuffle<2,3,0,1>(h) + h ; } __forceinline float reduce_min(const vfloat4& v) { return _mm_cvtss_f32(vreduce_min(v)); } __forceinline float reduce_max(const vfloat4& v) { return _mm_cvtss_f32(vreduce_max(v)); } __forceinline float reduce_add(const vfloat4& v) { return _mm_cvtss_f32(vreduce_add(v)); } __forceinline size_t select_min(const vboolf4& valid, const vfloat4& v) { const vfloat4 a = select(valid,v,vfloat4(pos_inf)); const vbool4 valid_min = valid & (a == vreduce_min(a)); return bsf(movemask(any(valid_min) ? valid_min : valid)); } __forceinline size_t select_max(const vboolf4& valid, const vfloat4& v) { const vfloat4 a = select(valid,v,vfloat4(neg_inf)); const vbool4 valid_max = valid & (a == vreduce_max(a)); return bsf(movemask(any(valid_max) ? valid_max : valid)); } //////////////////////////////////////////////////////////////////////////////// /// Euclidian Space Operators //////////////////////////////////////////////////////////////////////////////// __forceinline float dot(const vfloat4& a, const vfloat4& b) { return reduce_add(a*b); } __forceinline vfloat4 cross(const vfloat4& a, const vfloat4& b) { const vfloat4 a0 = a; const vfloat4 b0 = shuffle<1,2,0,3>(b); const vfloat4 a1 = shuffle<1,2,0,3>(a); const vfloat4 b1 = b; return shuffle<1,2,0,3>(msub(a0,b0,a1*b1)); } //////////////////////////////////////////////////////////////////////////////// /// Output Operators //////////////////////////////////////////////////////////////////////////////// __forceinline embree_ostream operator <<(embree_ostream cout, const vfloat4& a) { return cout << "<" << a[0] << ", " << a[1] << ", " << a[2] << ", " << a[3] << ">"; } }
13,648
14,668
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PPAPI_PROXY_AUDIO_INPUT_RESOURCE_H_ #define PPAPI_PROXY_AUDIO_INPUT_RESOURCE_H_ #include <stddef.h> #include <stdint.h> #include <memory> #include "base/compiler_specific.h" #include "base/memory/read_only_shared_memory_region.h" #include "base/memory/ref_counted.h" #include "base/sync_socket.h" #include "base/threading/simple_thread.h" #include "ppapi/proxy/device_enumeration_resource_helper.h" #include "ppapi/proxy/plugin_resource.h" #include "ppapi/shared_impl/scoped_pp_resource.h" #include "ppapi/thunk/ppb_audio_input_api.h" namespace media { class AudioBus; } namespace ppapi { namespace proxy { class ResourceMessageReplyParams; class AudioInputResource : public PluginResource, public thunk::PPB_AudioInput_API, public base::DelegateSimpleThread::Delegate { public: AudioInputResource(Connection connection, PP_Instance instance); AudioInputResource(const AudioInputResource&) = delete; AudioInputResource& operator=(const AudioInputResource&) = delete; ~AudioInputResource() override; // Resource overrides. thunk::PPB_AudioInput_API* AsPPB_AudioInput_API() override; void OnReplyReceived(const ResourceMessageReplyParams& params, const IPC::Message& msg) override; // PPB_AudioInput_API implementation. int32_t EnumerateDevices(const PP_ArrayOutput& output, scoped_refptr<TrackedCallback> callback) override; int32_t MonitorDeviceChange(PP_MonitorDeviceChangeCallback callback, void* user_data) override; int32_t Open0_3(PP_Resource device_ref, PP_Resource config, PPB_AudioInput_Callback_0_3 audio_input_callback_0_3, void* user_data, scoped_refptr<TrackedCallback> callback) override; int32_t Open(PP_Resource device_ref, PP_Resource config, PPB_AudioInput_Callback audio_input_callback, void* user_data, scoped_refptr<TrackedCallback> callback) override; PP_Resource GetCurrentConfig() override; PP_Bool StartCapture() override; PP_Bool StopCapture() override; void Close() override; protected: // Resource override. void LastPluginRefWasDeleted() override; private: enum OpenState { BEFORE_OPEN, OPENED, CLOSED }; void OnPluginMsgOpenReply(const ResourceMessageReplyParams& params); // Sets the shared memory and socket handles. This will automatically start // capture if we're currently set to capture. void SetStreamInfo(base::ReadOnlySharedMemoryRegion shared_memory_region, base::SyncSocket::Handle socket_handle); // Starts execution of the audio input thread. void StartThread(); // Stops execution of the audio input thread. void StopThread(); // DelegateSimpleThread::Delegate implementation. // Run on the audio input thread. void Run() override; int32_t CommonOpen(PP_Resource device_ref, PP_Resource config, PPB_AudioInput_Callback_0_3 audio_input_callback_0_3, PPB_AudioInput_Callback audio_input_callback, void* user_data, scoped_refptr<TrackedCallback> callback); OpenState open_state_; // True if capturing the stream. bool capturing_; // Socket used to notify us when new samples are available. This pointer is // created in SetStreamInfo(). std::unique_ptr<base::CancelableSyncSocket> socket_; // Sample buffer in shared memory. This pointer is created in // SetStreamInfo(). The memory is only mapped when the audio thread is // created. base::ReadOnlySharedMemoryMapping shared_memory_mapping_; // The size of the sample buffer in bytes. size_t shared_memory_size_; // When the callback is set, this thread is spawned for calling it. std::unique_ptr<base::DelegateSimpleThread> audio_input_thread_; // Callback to call when new samples are available. PPB_AudioInput_Callback_0_3 audio_input_callback_0_3_; PPB_AudioInput_Callback audio_input_callback_; // User data pointer passed verbatim to the callback function. void* user_data_; // The callback is not directly passed to OnPluginMsgOpenReply() because we // would like to be able to cancel it early in Close(). scoped_refptr<TrackedCallback> open_callback_; // Owning reference to the current config object. This isn't actually used, // we just dish it out as requested by the plugin. ScopedPPResource config_; DeviceEnumerationResourceHelper enumeration_helper_; // The data size (in bytes) of one second of audio input. Used to calculate // latency. size_t bytes_per_second_; // AudioBus for shuttling data across the shared memory. std::unique_ptr<const media::AudioBus> audio_bus_; int sample_frame_count_; // Internal buffer for client's integer audio data. int client_buffer_size_bytes_; std::unique_ptr<uint8_t[]> client_buffer_; }; } // namespace proxy } // namespace ppapi #endif // PPAPI_PROXY_AUDIO_INPUT_RESOURCE_H_
1,876
1,521
<filename>interactive_engine/gaia-adaptor/src/main/java/com/alibaba/graphscope/gaia/vineyard/store/VineyardConfig.java<gh_stars>1000+ package com.alibaba.graphscope.gaia.vineyard.store; import com.alibaba.graphscope.gaia.config.GaiaConfig; import com.alibaba.graphscope.gaia.store.GraphType; import com.alibaba.maxgraph.common.cluster.InstanceConfig; public class VineyardConfig implements GaiaConfig { private InstanceConfig instanceConfig; public VineyardConfig(InstanceConfig instanceConfig) { this.instanceConfig = instanceConfig; } @Override public int getPegasusWorkerNum() { return instanceConfig.getPegasusWorkerNum(); } @Override public int getPegasusServerNum() { return instanceConfig.getResourceExecutorCount(); } @Override public long getPegasusTimeout() { return instanceConfig.getPegasusTimeoutMS(); } @Override public int getPegasusBatchSize() { return instanceConfig.getPegasusBatchSize(); } @Override public int getPegasusOutputCapacity() { return instanceConfig.getPegasusOutputCapacity(); } @Override public int getPegasusMemoryLimit() { return instanceConfig.getPegasusMemoryLimit(); } @Override public String getSchemaFilePath() { throw new UnsupportedOperationException(); } @Override public GraphType getGraphType() { return GraphType.MAXGRAPH; } @Override public boolean getOptimizationStrategyFlag(String strategyFlagName) { if (strategyFlagName.equals(GaiaConfig.REMOVE_TAG)) { return false; } return true; } }
625
1,293
package manifold.templates.misc; import manifold.rt.api.DisableStringLiteralTemplates; import org.junit.Test; import static org.junit.Assert.assertEquals; public class WhitespaceTest { @Test public void testForNewLines() { assertEquals( "This is a ManTL (Manifold Template Language) file.\n" + "\n" + "You can render this template type-safely from Java like this:\n" + "\n" + "TemplateName.render(\"Hello World!\");\n" + "\n" + "You can declare any number of parameters in the 'params' directive, import\n" + "types and packages using the 'import' directive, extend a special template\n" + "class using the 'extends' directive, include content from other templates,\n" + "define sections, and many other useful features.\n" + "\n" + "You can use Java statements:\n" + "\n" + "The value of 'param1' is: Hello World!!!\n" + "\n" + "And you can use Java expressions:\n" + "\n" + "H\n" + "H\n" + "\n" + "Learn more: http://manifold.systems/manifold-templates.html", misc.TestNewLines.render( "Hello World!!!" ) ); } @Test @DisableStringLiteralTemplates public void testWhitespace() { assertEquals( "<html>\n" + " hello bye\n" + " hello true asfds\n" + " hello\n" + " hello\n" + "\n" + " hello } bye\n" + " hello\n" + " hello\n" + " hello\n" + " hello\n" + " The date is JUNE/15/1984\n" + " hello hullohullo bye\n" + " hello\n" + "\n" + "<%= expression syntax %>high\n" + "\n" + " bye\n" + "</html>", misc.whitespace.WhitespaceTemplate1.render( "hullo" ) ); } @Test public void testWhitespace2() { assertEquals( " hi\n" + " bye\n" + " sigh", misc.whitespace.WhitespaceTemplate2.render() ); } @Test public void testWhitespace3() { assertEquals( " hi\n" + " bye\n" + " sigh", misc.whitespace.WhitespaceTemplate3.render() ); } }
1,204
17,337
<gh_stars>1000+ #include <stdlib.h> #include <string.h> #include "vrclient_private.h" #include "vrclient_defs.h" #include "openvr_v0.9.4/openvr.h" using namespace vr; extern "C" { #include "struct_converters.h" #pragma pack(push, 8) struct winRenderModel_TextureMap_t_094 { uint16_t unWidth; uint16_t unHeight; const uint8_t * rubTextureMapData; RenderModel_TextureMap_t *linux_side; } __attribute__ ((ms_struct)); #pragma pack(pop) void struct_RenderModel_TextureMap_t_094_lin_to_win(void *l, void *w) { struct winRenderModel_TextureMap_t_094 *win = (struct winRenderModel_TextureMap_t_094 *)w; RenderModel_TextureMap_t *lin = (RenderModel_TextureMap_t *)l; win->unWidth = lin->unWidth; win->unHeight = lin->unHeight; win->rubTextureMapData = lin->rubTextureMapData; } void struct_RenderModel_TextureMap_t_094_win_to_lin(void *w, void *l) { struct winRenderModel_TextureMap_t_094 *win = (struct winRenderModel_TextureMap_t_094 *)w; RenderModel_TextureMap_t *lin = (RenderModel_TextureMap_t *)l; lin->unWidth = win->unWidth; lin->unHeight = win->unHeight; lin->rubTextureMapData = win->rubTextureMapData; } struct winRenderModel_TextureMap_t_094 *struct_RenderModel_TextureMap_t_094_wrap(void *l) { struct winRenderModel_TextureMap_t_094 *win = (struct winRenderModel_TextureMap_t_094 *)malloc(sizeof(*win)); RenderModel_TextureMap_t *lin = (RenderModel_TextureMap_t *)l; win->unWidth = lin->unWidth; win->unHeight = lin->unHeight; win->rubTextureMapData = lin->rubTextureMapData; win->linux_side = lin; return win; } struct RenderModel_TextureMap_t *struct_RenderModel_TextureMap_t_094_unwrap(winRenderModel_TextureMap_t_094 *w) { RenderModel_TextureMap_t *ret = w->linux_side; free(w); return ret; } #pragma pack(push, 8) struct winRenderModel_t_094 { uint64_t ulInternalHandle; const vr::RenderModel_Vertex_t * rVertexData; uint32_t unVertexCount; const uint16_t * rIndexData; uint32_t unTriangleCount; winRenderModel_TextureMap_t_094 diffuseTexture __attribute__((aligned(4))); RenderModel_t *linux_side; } __attribute__ ((ms_struct)); #pragma pack(pop) void struct_RenderModel_t_094_lin_to_win(void *l, void *w) { struct winRenderModel_t_094 *win = (struct winRenderModel_t_094 *)w; RenderModel_t *lin = (RenderModel_t *)l; win->ulInternalHandle = lin->ulInternalHandle; win->rVertexData = lin->rVertexData; win->unVertexCount = lin->unVertexCount; win->rIndexData = lin->rIndexData; win->unTriangleCount = lin->unTriangleCount; struct_RenderModel_TextureMap_t_094_lin_to_win(&lin->diffuseTexture, &win->diffuseTexture); } void struct_RenderModel_t_094_win_to_lin(void *w, void *l) { struct winRenderModel_t_094 *win = (struct winRenderModel_t_094 *)w; RenderModel_t *lin = (RenderModel_t *)l; lin->ulInternalHandle = win->ulInternalHandle; lin->rVertexData = win->rVertexData; lin->unVertexCount = win->unVertexCount; lin->rIndexData = win->rIndexData; lin->unTriangleCount = win->unTriangleCount; struct_RenderModel_TextureMap_t_094_win_to_lin(&win->diffuseTexture, &lin->diffuseTexture); } struct winRenderModel_t_094 *struct_RenderModel_t_094_wrap(void *l) { struct winRenderModel_t_094 *win = (struct winRenderModel_t_094 *)malloc(sizeof(*win)); RenderModel_t *lin = (RenderModel_t *)l; win->ulInternalHandle = lin->ulInternalHandle; win->rVertexData = lin->rVertexData; win->unVertexCount = lin->unVertexCount; win->rIndexData = lin->rIndexData; win->unTriangleCount = lin->unTriangleCount; struct_RenderModel_TextureMap_t_094_lin_to_win(&lin->diffuseTexture, &win->diffuseTexture); win->linux_side = lin; return win; } struct RenderModel_t *struct_RenderModel_t_094_unwrap(winRenderModel_t_094 *w) { RenderModel_t *ret = w->linux_side; free(w); return ret; } #pragma pack(push, 8) struct winVRControllerState001_t_094 { uint32_t unPacketNum; uint64_t ulButtonPressed; uint64_t ulButtonTouched; vr::VRControllerAxis_t rAxis[5]; } __attribute__ ((ms_struct)); #pragma pack(pop) void struct_VRControllerState001_t_094_lin_to_win(void *l, void *w, uint32_t sz) { struct winVRControllerState001_t_094 *win = (struct winVRControllerState001_t_094 *)w; VRControllerState001_t *lin = (VRControllerState001_t *)l; win->unPacketNum = lin->unPacketNum; win->ulButtonPressed = lin->ulButtonPressed; win->ulButtonTouched = lin->ulButtonTouched; memcpy(win->rAxis, lin->rAxis, sizeof(win->rAxis)); } void struct_VRControllerState001_t_094_win_to_lin(void *w, void *l) { struct winVRControllerState001_t_094 *win = (struct winVRControllerState001_t_094 *)w; VRControllerState001_t *lin = (VRControllerState001_t *)l; lin->unPacketNum = win->unPacketNum; lin->ulButtonPressed = win->ulButtonPressed; lin->ulButtonTouched = win->ulButtonTouched; memcpy(lin->rAxis, win->rAxis, sizeof(lin->rAxis)); } #pragma pack(push, 8) struct winCompositor_FrameTiming_094 { uint32_t size; double frameStart; float frameVSync; uint32_t droppedFrames; uint32_t frameIndex; vr::TrackedDevicePose_t pose __attribute__((aligned(4))); float prediction; float m_flFrameIntervalMs; float m_flSceneRenderCpuMs; float m_flSceneRenderGpuMs; float m_flCompositorRenderCpuMs; float m_flCompositorRenderGpuMs; float m_flPresentCallCpuMs; float m_flRunningStartMs; } __attribute__ ((ms_struct)); #pragma pack(pop) void struct_Compositor_FrameTiming_094_lin_to_win(void *l, void *w) { struct winCompositor_FrameTiming_094 *win = (struct winCompositor_FrameTiming_094 *)w; Compositor_FrameTiming *lin = (Compositor_FrameTiming *)l; win->size = sizeof(*win); win->frameStart = lin->frameStart; win->frameVSync = lin->frameVSync; win->droppedFrames = lin->droppedFrames; win->frameIndex = lin->frameIndex; win->pose = lin->pose; win->prediction = lin->prediction; win->m_flFrameIntervalMs = lin->m_flFrameIntervalMs; win->m_flSceneRenderCpuMs = lin->m_flSceneRenderCpuMs; win->m_flSceneRenderGpuMs = lin->m_flSceneRenderGpuMs; win->m_flCompositorRenderCpuMs = lin->m_flCompositorRenderCpuMs; win->m_flCompositorRenderGpuMs = lin->m_flCompositorRenderGpuMs; win->m_flPresentCallCpuMs = lin->m_flPresentCallCpuMs; win->m_flRunningStartMs = lin->m_flRunningStartMs; } void struct_Compositor_FrameTiming_094_win_to_lin(void *w, void *l) { struct winCompositor_FrameTiming_094 *win = (struct winCompositor_FrameTiming_094 *)w; Compositor_FrameTiming *lin = (Compositor_FrameTiming *)l; lin->size = sizeof(*lin); lin->frameStart = win->frameStart; lin->frameVSync = win->frameVSync; lin->droppedFrames = win->droppedFrames; lin->frameIndex = win->frameIndex; lin->pose = win->pose; lin->prediction = win->prediction; lin->m_flFrameIntervalMs = win->m_flFrameIntervalMs; lin->m_flSceneRenderCpuMs = win->m_flSceneRenderCpuMs; lin->m_flSceneRenderGpuMs = win->m_flSceneRenderGpuMs; lin->m_flCompositorRenderCpuMs = win->m_flCompositorRenderCpuMs; lin->m_flCompositorRenderGpuMs = win->m_flCompositorRenderGpuMs; lin->m_flPresentCallCpuMs = win->m_flPresentCallCpuMs; lin->m_flRunningStartMs = win->m_flRunningStartMs; } }
3,001
3,651
<filename>core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLimit.java /* Generated By:JJTree: Do not edit this line. OLimit.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package com.orientechnologies.orient.core.sql.parser; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.exception.OCommandExecutionException; import com.orientechnologies.orient.core.sql.executor.OResult; import com.orientechnologies.orient.core.sql.executor.OResultInternal; import java.util.Map; public class OLimit extends SimpleNode { protected OInteger num; protected OInputParameter inputParam; public OLimit(int id) { super(id); } public OLimit(OrientSql p, int id) { super(p, id); } public void toString(Map<Object, Object> params, StringBuilder builder) { if (num == null && inputParam == null) { return; } builder.append(" LIMIT "); if (num != null) { num.toString(params, builder); } else { inputParam.toString(params, builder); } } public int getValue(OCommandContext ctx) { if (num != null) { return num.getValue().intValue(); } if (inputParam != null) { Object paramValue = inputParam.getValue(ctx.getInputParameters()); if (paramValue instanceof Number) { return ((Number) paramValue).intValue(); } else { throw new OCommandExecutionException("Invalid value for LIMIT: " + paramValue); } } throw new OCommandExecutionException("No value for LIMIT"); } public OLimit copy() { OLimit result = new OLimit(-1); result.num = num == null ? null : num.copy(); result.inputParam = inputParam == null ? null : inputParam.copy(); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OLimit oLimit = (OLimit) o; if (num != null ? !num.equals(oLimit.num) : oLimit.num != null) return false; if (inputParam != null ? !inputParam.equals(oLimit.inputParam) : oLimit.inputParam != null) return false; return true; } @Override public int hashCode() { int result = num != null ? num.hashCode() : 0; result = 31 * result + (inputParam != null ? inputParam.hashCode() : 0); return result; } public OResult serialize() { OResultInternal result = new OResultInternal(); if (num != null) { result.setProperty("num", num.serialize()); } if (inputParam != null) { result.setProperty("inputParam", inputParam.serialize()); } return result; } public void deserialize(OResult fromResult) { if (fromResult.getProperty("num") != null) { num = new OInteger(-1); num.deserialize(fromResult.getProperty("num")); } if (fromResult.getProperty("inputParam") != null) { inputParam = OInputParameter.deserializeFromOResult(fromResult.getProperty("inputParam")); } } } /* JavaCC - OriginalChecksum=1063b9489290bb08de6048ba55013171 (do not edit this line) */
1,179
2,372
// // 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 NVIDIA 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 ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScIterators.h" #include "ScBodySim.h" #include "ScShapeSim.h" #include "ScShapeInteraction.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////// Sc::ContactIterator::Pair::Pair(const void*& contactPatches, const void*& contactPoints, PxU32 /*contactDataSize*/, const PxReal*& forces, PxU32 numContacts, PxU32 numPatches, ShapeSim& shape0, ShapeSim& shape1) : mIndex(0) , mNumContacts(numContacts) , mIter(reinterpret_cast<const PxU8*>(contactPatches), reinterpret_cast<const PxU8*>(contactPoints), reinterpret_cast<const PxU32*>(forces + numContacts), numPatches, numContacts) , mForces(forces) { mCurrentContact.shape0 = shape0.getPxShape(); mCurrentContact.shape1 = shape1.getPxShape(); mCurrentContact.normalForceAvailable = (forces != NULL); } Sc::ContactIterator::Pair* Sc::ContactIterator::getNextPair() { if(mCurrent < mLast) { ShapeInteraction* si = static_cast<ShapeInteraction*>(*mCurrent); const void* contactPatches = NULL; const void* contactPoints = NULL; PxU32 contactDataSize = 0; const PxReal* forces = NULL; PxU32 numContacts = 0; PxU32 numPatches = 0; PxU32 nextOffset = si->getContactPointData(contactPatches, contactPoints, contactDataSize, numContacts, numPatches, forces, mOffset, *mOutputs); if (nextOffset == mOffset) ++mCurrent; else mOffset = nextOffset; mCurrentPair = Pair(contactPatches, contactPoints, contactDataSize, forces, numContacts, numPatches, si->getShape0(), si->getShape1()); return &mCurrentPair; } else return NULL; } Sc::Contact* Sc::ContactIterator::Pair::getNextContact() { if(mIndex < mNumContacts) { if(!mIter.hasNextContact()) { if(!mIter.hasNextPatch()) return NULL; mIter.nextPatch(); } PX_ASSERT(mIter.hasNextContact()); mIter.nextContact(); mCurrentContact.normal = mIter.getContactNormal(); mCurrentContact.point = mIter.getContactPoint(); mCurrentContact.separation = mIter.getSeparation(); mCurrentContact.normalForce = mForces ? mForces[mIndex] : 0; mCurrentContact.faceIndex0 = mIter.getFaceIndex0(); mCurrentContact.faceIndex1 = mIter.getFaceIndex1(); mIndex++; return &mCurrentContact; } return NULL; } ///////////////////////////////////////////////////////////////////////////////
1,288
782
<gh_stars>100-1000 // Copyright (c) 2018 Intel Corporation // // 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. /* // // Function(s) to deinterlace video image(s) // // */ #include "precomp.h" #include "pvcown.h" #include "ownvc.h" #include "pvcmacro.h" #include "pvccommonfunctions.h" #if (_IPP >= _IPP_A6) #ifndef imp_mfxiDeinterlaceFilterTriangle_8u_C1R #define imp_mfxiDeinterlaceFilterTriangle_8u_C1R IPPFUN(IppStatus, mfxiDeinterlaceFilterTriangle_8u_C1R, (const Ipp8u *pSrc, Ipp32s srcStep, Ipp8u *pDst, Ipp32s dstStep, IppiSize roiSize, Ipp32u centerWeight, Ipp32u layout)) { Ipp32u edgeWeight; /* check error(s) */ IPP_BAD_PTR2_RET(pSrc, pDst); if ((3 > roiSize.height) || (1 > roiSize.width)) return ippStsSizeErr; /* create pixel's weight(s) */ if (256 < centerWeight) centerWeight = 256; edgeWeight = (256 - centerWeight) / 2; switch (layout) { /* process upper slice */ case IPP_UPPER: if (16 > roiSize.width) { IppiSize size; Ipp32s x, y; /* skip upper row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); /* set new source line */ pSrc += srcStep; pDst += dstStep; /* process all lines except last one */ for (y = 1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); }; pSrc += srcStep; pDst += dstStep; }; } else deinterlace_filter_triangle_upper_slice(pSrc, srcStep, pDst, dstStep, roiSize.width, roiSize.height, centerWeight); break; /* process center slice */ case IPP_CENTER: if (16 > roiSize.width) { Ipp32s x, y; /* we need to process last line from previos slice */ pSrc -= srcStep; pDst -= dstStep; /* process all lines except last one */ for (y = -1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); } pSrc += srcStep; pDst += dstStep; } } else deinterlace_filter_triangle_middle_slice(pSrc, srcStep, pDst, dstStep, roiSize.width, roiSize.height, centerWeight); break; /* process lower slice */ case IPP_LOWER: if (16 > roiSize.width) { IppiSize size; Ipp32s x, y; /* we need to process last line from previos slice */ pSrc -= srcStep; pDst -= dstStep; /* process all lines except last one */ for (y = -1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); }; pSrc += srcStep; pDst += dstStep; } /* skip lower row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); } else deinterlace_filter_triangle_lower_slice(pSrc, srcStep, pDst, dstStep, roiSize.width, roiSize.height, centerWeight); break; /* image is not sliced */ default: if (16 > roiSize.width) { IppiSize size; Ipp32s x, y; /* skip upper row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); /* set new source line */ pSrc += srcStep; pDst += dstStep; /* process all lines except last one */ for (y = 1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); }; pSrc += srcStep; pDst += dstStep; }; /* skip lower row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); } else deinterlace_filter_triangle(pSrc, srcStep, pDst, dstStep, roiSize.width, roiSize.height, centerWeight); break; }; return ippStsOk; } /* IPPFUN(IppStatus, mfxiDeinterlaceFilterTriangle_8u_C1R, (const Ipp8u *pSrc, */ #endif /* imp_mfxiDeinterlaceFilterTriangle_8u_C1R */ #endif /* (_IPP >= _IPP_A6) */ #ifndef imp_mfxiDeinterlaceFilterTriangle_8u_C1R #define imp_mfxiDeinterlaceFilterTriangle_8u_C1R IPPFUN(IppStatus, mfxiDeinterlaceFilterTriangle_8u_C1R, (const Ipp8u *pSrc, Ipp32s srcStep, Ipp8u *pDst, Ipp32s dstStep, IppiSize roiSize, Ipp32u centerWeight, Ipp32u layout)) { Ipp32u edgeWeight; /* check error(s) */ IPP_BAD_PTR2_RET(pSrc, pDst); if ((3 > roiSize.height) || (1 > roiSize.width)) return ippStsSizeErr; /* create pixel's weight(s) */ if (256 < centerWeight) centerWeight = 256; edgeWeight = (256 - centerWeight) / 2; switch (layout) { /* process upper slice */ case IPP_UPPER: { IppiSize size; Ipp32s x, y; /* skip upper row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); /* set new source line */ pSrc += srcStep; pDst += dstStep; /* process all lines except last one */ for (y = 1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); }; pSrc += srcStep; pDst += dstStep; }; }; break; /* process center slice */ case IPP_CENTER: { Ipp32s x, y; /* we need to process last line from previos slice */ pSrc -= srcStep; pDst -= dstStep; /* process all lines except last one */ for (y = -1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); }; pSrc += srcStep; pDst += dstStep; }; }; break; /* process lower slice */ case IPP_LOWER: { IppiSize size; Ipp32s x, y; /* we need to process last line from previos slice */ pSrc -= srcStep; pDst -= dstStep; /* process all lines except last one */ for (y = -1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); }; pSrc += srcStep; pDst += dstStep; }; /* skip lower row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); }; break; /* image is not sliced */ default: { IppiSize size; Ipp32s x, y; /* skip upper row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); /* set new source line */ pSrc += srcStep; pDst += dstStep; /* process all lines except last one */ for (y = 1;y < (signed) (roiSize.height - 1);y += 1) { for (x = 0;x < (signed) roiSize.width;x += 1) { pDst[x] = (Ipp8u) (((pSrc[x - srcStep] + pSrc[x + srcStep]) * edgeWeight + pSrc[x] * centerWeight) / 256); }; pSrc += srcStep; pDst += dstStep; }; /* skip lower row */ size.width = roiSize.width; size.height = 1; mfxiCopy_8u_C1R(pSrc, srcStep, pDst, dstStep, size); }; break; }; return ippStsOk; } /* IPPFUN(IppStatus, mfxiDeinterlaceFilterTriangle_8u_C1R, (const Ipp8u *pSrc, */ #endif /* imp_mfxiDeinterlaceFilterTriangle_8u_C1R */
8,165
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"<NAME>","circ":"5ème circonscription","dpt":"Isère","inscrits":2454,"abs":1577,"votants":877,"blancs":91,"nuls":16,"exp":770,"res":[{"nuance":"REM","nom":"<NAME>","voix":502},{"nuance":"LR","nom":"<NAME>","voix":268}]}
109
2,648
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file accompanying this file. This file is distributed # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language governing # permissions and limitations under the License. from collections import Counter from typing import Iterator, List, Optional import numpy as np from numpy.lib.stride_tricks import as_strided from gluonts.core.component import validated from gluonts.dataset.common import DataEntry from gluonts.dataset.field_names import FieldName from gluonts.transform import FlatMapTransformation, shift_timestamp class ForkingSequenceSplitter(FlatMapTransformation): """Forking sequence splitter.""" @validated() def __init__( self, instance_sampler, enc_len: int, dec_len: int, num_forking: Optional[int] = None, target_field: str = FieldName.TARGET, encoder_series_fields: Optional[List[str]] = None, decoder_series_fields: Optional[List[str]] = None, encoder_disabled_fields: Optional[List[str]] = None, decoder_disabled_fields: Optional[List[str]] = None, prediction_time_decoder_exclude: Optional[List[str]] = None, is_pad_out: str = "is_pad", start_input_field: str = "start", ) -> None: super().__init__() assert enc_len > 0, "The value of `enc_len` should be > 0" assert dec_len > 0, "The value of `dec_len` should be > 0" self.instance_sampler = instance_sampler self.enc_len = enc_len self.dec_len = dec_len self.num_forking = ( num_forking if num_forking is not None else self.enc_len ) self.target_field = target_field self.encoder_series_fields = ( encoder_series_fields + [self.target_field] if encoder_series_fields is not None else [self.target_field] ) self.decoder_series_fields = ( decoder_series_fields + [self.target_field] if decoder_series_fields is not None else [self.target_field] ) self.encoder_disabled_fields = ( encoder_disabled_fields if encoder_disabled_fields is not None else [] ) self.decoder_disabled_fields = ( decoder_disabled_fields if decoder_disabled_fields is not None else [] ) # Fields that are not used at prediction time for the decoder self.prediction_time_decoder_exclude = ( prediction_time_decoder_exclude + [self.target_field] if prediction_time_decoder_exclude is not None else [self.target_field] ) self.is_pad_out = is_pad_out self.start_in = start_input_field def _past(self, col_name): return f"past_{col_name}" def _future(self, col_name): return f"future_{col_name}" def flatmap_transform( self, data: DataEntry, is_train: bool ) -> Iterator[DataEntry]: target = data[self.target_field] if is_train: # We currently cannot handle time series that are shorter than the # prediction length during training, so we just skip these. # If we want to include them we would need to pad and to mask # the loss. if len(target) < self.dec_len: return sampling_indices = self.instance_sampler(target) else: sampling_indices = [len(target)] # Loops over all encoder and decoder fields even those that are disabled to # set to dummy zero fields in those cases ts_fields_counter = Counter( set(self.encoder_series_fields + self.decoder_series_fields) ) for sampling_idx in sampling_indices: # irrelevant data should have been removed by now in the # transformation chain, so copying everything is ok out = data.copy() enc_len_diff = sampling_idx - self.enc_len dec_len_diff = sampling_idx - self.num_forking # ensure start indices are not negative start_idx_enc = max(0, enc_len_diff) start_idx_dec = max(0, dec_len_diff) # Define pad length indices for shorter time series of variable length being updated in place pad_length_enc = max(0, -enc_len_diff) pad_length_dec = max(0, -dec_len_diff) for ts_field in ts_fields_counter.keys(): # target is 1d, this ensures ts is always 2d ts = np.atleast_2d(out[ts_field]).T ts_len = ts.shape[1] if ts_fields_counter[ts_field] == 1: del out[ts_field] else: ts_fields_counter[ts_field] -= 1 out[self._past(ts_field)] = np.zeros( shape=(self.enc_len, ts_len), dtype=ts.dtype ) if ts_field not in self.encoder_disabled_fields: out[self._past(ts_field)][pad_length_enc:] = ts[ start_idx_enc:sampling_idx, : ] # exclude some fields at prediction time if ( not is_train and ts_field in self.prediction_time_decoder_exclude ): continue if ts_field in self.decoder_series_fields: out[self._future(ts_field)] = np.zeros( shape=(self.num_forking, self.dec_len, ts_len), dtype=ts.dtype, ) if ts_field not in self.decoder_disabled_fields: # This is where some of the forking magic happens: # For each of the num_forking time-steps at which the decoder is applied we slice the # corresponding inputs called decoder_fields to the appropriate dec_len decoder_fields = ts[ start_idx_dec + 1 : sampling_idx + 1, : ] # For default row-major arrays, strides = (dtype*n_cols, dtype). Since this array is transposed, # it is stored in column-major (Fortran) ordering with strides = (dtype, dtype*n_rows) stride = decoder_fields.strides out[self._future(ts_field)][ pad_length_dec: ] = as_strided( decoder_fields, shape=( self.num_forking - pad_length_dec, self.dec_len, ts_len, ), # strides for 2D array expanded to 3D array of shape (dim1, dim2, dim3) = # (1, n_rows, n_cols). For transposed data, strides = # (dtype, dtype * dim1, dtype*dim1*dim2) = (dtype, dtype, dtype*n_rows). strides=stride[0:1] + stride, ) # edge case for prediction_length = 1 if out[self._future(ts_field)].shape[-1] == 1: out[self._future(ts_field)] = np.squeeze( out[self._future(ts_field)], axis=-1 ) # So far encoder pad indicator not in use - # Marks that left padding for the encoder will occur on shorter time series pad_indicator = np.zeros(self.enc_len) pad_indicator[:pad_length_enc] = True out[self._past(self.is_pad_out)] = pad_indicator # So far pad forecast_start not in use out[FieldName.FORECAST_START] = shift_timestamp( out[self.start_in], sampling_idx ) yield out
4,098
56,632
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // AdvancedCapture.xaml.cpp // Implementation of the AdvancedCapture class // #include "pch.h" #include "AdvancedCapture.xaml.h" using namespace SDKSample::MediaCapture; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::Xaml::Data; using namespace Windows::System; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Platform; using namespace Windows::UI; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Media; using namespace Windows::Storage; using namespace Windows::Media::MediaProperties; using namespace Windows::Storage::Streams; using namespace Windows::System; using namespace Windows::UI::Xaml::Media::Imaging; using namespace Windows::Devices::Enumeration; ref class ReencodeState sealed { public: ReencodeState() { } virtual ~ReencodeState() { if (InputStream != nullptr) { delete InputStream; } if (OutputStream != nullptr) { delete OutputStream; } } internal: Windows::Storage::Streams::IRandomAccessStream ^InputStream; Windows::Storage::Streams::IRandomAccessStream ^OutputStream; Windows::Storage::StorageFile ^PhotoStorage; Windows::Graphics::Imaging::BitmapDecoder ^Decoder; Windows::Graphics::Imaging::BitmapEncoder ^Encoder; }; AdvancedCapture::AdvancedCapture() { InitializeComponent(); ScenarioInit(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void AdvancedCapture::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() rootPage = MainPage::Current; m_orientationChangedEventToken = Windows::Graphics::Display::DisplayProperties::OrientationChanged += ref new Windows::Graphics::Display::DisplayPropertiesEventHandler(this, &AdvancedCapture::DisplayProperties_OrientationChanged); } void AdvancedCapture::OnNavigatedFrom(NavigationEventArgs^ e) { Windows::Media::MediaControl::SoundLevelChanged -= m_eventRegistrationToken; Windows::Graphics::Display::DisplayProperties::OrientationChanged -= m_orientationChangedEventToken; } void AdvancedCapture::ScenarioInit() { rootPage = MainPage::Current; btnStartDevice2->IsEnabled = true; btnStartPreview2->IsEnabled = false; m_bRecording = false; m_bPreviewing = false; m_bEffectAdded = false; previewElement2->Source = nullptr; ShowStatusMessage(""); EffectTypeCombo->IsEnabled = false; previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Collapsed; EnumerateWebcamsAsync(); m_bSuspended = false; } void AdvancedCapture::ScenarioReset() { previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Collapsed; ScenarioInit(); } void AdvancedCapture::Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ currentFailure) { String ^message = "Fatal error" + currentFailure->Message; create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this, message]() { ShowStatusMessage(message); }))); } void AdvancedCapture::btnStartDevice_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { try { EnableButton(false, "StartDevice"); ShowStatusMessage("Starting device"); auto mediaCapture = ref new Windows::Media::Capture::MediaCapture(); m_mediaCaptureMgr = mediaCapture; auto settings = ref new Windows::Media::Capture::MediaCaptureInitializationSettings(); auto chosenDevInfo = m_devInfoCollection->GetAt(EnumedDeviceList2->SelectedIndex); settings->VideoDeviceId = chosenDevInfo->Id; if (chosenDevInfo->EnclosureLocation != nullptr && chosenDevInfo->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Back) { m_bRotateVideoOnOrientationChange = true; m_bReversePreviewRotation = false; } else if (chosenDevInfo->EnclosureLocation != nullptr && chosenDevInfo->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front) { m_bRotateVideoOnOrientationChange = true; m_bReversePreviewRotation = true; } else { m_bRotateVideoOnOrientationChange = false; } create_task(mediaCapture->InitializeAsync(settings)).then([this](task<void> initTask) { try { initTask.get(); auto mediaCapture = m_mediaCaptureMgr.Get(); DisplayProperties_OrientationChanged(nullptr); EnableButton(true, "StartPreview"); EnableButton(true, "StartStopRecord"); EnableButton(true, "TakePhoto"); ShowStatusMessage("Device initialized successful"); EffectTypeCombo->IsEnabled = true; mediaCapture->Failed += ref new Windows::Media::Capture::MediaCaptureFailedEventHandler(this, &AdvancedCapture::Failed); } catch (Exception ^ e) { ShowExceptionMessage(e); } }); } catch (Platform::Exception^ e) { ShowExceptionMessage(e); } } void AdvancedCapture::btnStartPreview_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { m_bPreviewing = false; try { ShowStatusMessage("Starting preview"); EnableButton(false, "StartPreview"); auto mediaCapture = m_mediaCaptureMgr.Get(); previewCanvas2->Visibility = Windows::UI::Xaml::Visibility::Visible; previewElement2->Source = mediaCapture; create_task(mediaCapture->StartPreviewAsync()).then([this](task<void> previewTask) { try { previewTask.get(); m_bPreviewing = true; ShowStatusMessage("Start preview successful"); } catch (Exception ^e) { ShowExceptionMessage(e); } }); } catch (Platform::Exception^ e) { m_bPreviewing = false; previewElement2->Source = nullptr; EnableButton(true, "StartPreview"); ShowExceptionMessage(e); } } void AdvancedCapture::lstEnumedDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e) { if ( m_bPreviewing ) { create_task(m_mediaCaptureMgr->StopPreviewAsync()).then([this](task<void> previewTask) { try { previewTask.get(); m_bPreviewing = false; } catch (Exception ^e) { ShowExceptionMessage(e); } }); } btnStartDevice2->IsEnabled = true; btnStartPreview2->IsEnabled = false; m_bRecording = false; previewElement2->Source = nullptr; EffectTypeCombo->IsEnabled = false; m_bEffectAdded = false; m_bEffectAddedToRecord = false; m_bEffectAddedToPhoto = false; ShowStatusMessage(""); } void AdvancedCapture::EnumerateWebcamsAsync() { try { ShowStatusMessage("Enumerating Webcams..."); m_devInfoCollection = nullptr; EnumedDeviceList2->Items->Clear(); task<DeviceInformationCollection^>(DeviceInformation::FindAllAsync(DeviceClass::VideoCapture)).then([this](task<DeviceInformationCollection^> findTask) { try { m_devInfoCollection = findTask.get(); if (m_devInfoCollection == nullptr || m_devInfoCollection->Size == 0) { ShowStatusMessage("No WebCams found."); } else { for(unsigned int i = 0; i < m_devInfoCollection->Size; i++) { auto devInfo = m_devInfoCollection->GetAt(i); EnumedDeviceList2->Items->Append(devInfo->Name); } EnumedDeviceList2->SelectedIndex = 0; ShowStatusMessage("Enumerating Webcams completed successfully."); btnStartDevice2->IsEnabled = true; } } catch (Exception ^e) { ShowExceptionMessage(e); } }); } catch (Platform::Exception^ e) { ShowExceptionMessage(e); } } void AdvancedCapture::AddEffectToImageStream() { auto mediaCapture = m_mediaCaptureMgr.Get(); Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic; if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) && (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewPhotoStreamsIdentical) && (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::RecordPhotoStreamsIdentical)) { Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo); if(props->Type->Equals("Image")) { //Switch to a video media type instead since we can't add an effect to an image media type Windows::Foundation::Collections::IVectorView<Windows::Media::MediaProperties::IMediaEncodingProperties^>^ supportedPropsList = mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(Windows::Media::Capture::MediaStreamType::Photo); { unsigned int i = 0; while (i < supportedPropsList->Size) { Windows::Media::MediaProperties::IMediaEncodingProperties^ props = supportedPropsList->GetAt(i); String^ s = props->Type; if(props->Type->Equals("Video")) { task<void>(mediaCapture->VideoDeviceController->SetMediaStreamPropertiesAsync(Windows::Media::Capture::MediaStreamType::Photo,props)).then([this](task<void> changeTypeTask) { try { changeTypeTask.get(); ShowStatusMessage("Change type on photo stream successful"); //Now add the effect on the image pin task<void>(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"OcvTransform.OcvImageManipulations", nullptr)).then([this](task<void> effectTask3) { try { effectTask3.get(); m_bEffectAddedToPhoto = true; ShowStatusMessage("Adding effect to photo stream successful"); EffectTypeCombo->IsEnabled = true; } catch(Exception ^e) { ShowExceptionMessage(e); EffectTypeCombo->IsEnabled = true; } }); } catch(Exception ^e) { ShowExceptionMessage(e); EffectTypeCombo->IsEnabled = true; } }); break; } i++; } } } else { //Add the effect to the image pin if the type is already "Video" task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::Photo,"OcvTransform.OcvImageManipulations", nullptr)).then([this](task<void> effectTask3) { try { effectTask3.get(); m_bEffectAddedToPhoto = true; ShowStatusMessage("Adding effect to photo stream successful"); EffectTypeCombo->IsEnabled = true; } catch(Exception ^e) { ShowExceptionMessage(e); EffectTypeCombo->IsEnabled = true; } }); } } } void AdvancedCapture::ShowStatusMessage(Platform::String^ text) { rootPage->NotifyUser(text, NotifyType::StatusMessage); } void AdvancedCapture::ShowExceptionMessage(Platform::Exception^ ex) { rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage); } void AdvancedCapture::EnableButton(bool enabled, String^ name) { if (name->Equals("StartDevice")) { btnStartDevice2->IsEnabled = enabled; } else if (name->Equals("StartPreview")) { btnStartPreview2->IsEnabled = enabled; } } task<Windows::Storage::StorageFile^> AdvancedCapture::ReencodePhotoAsync( Windows::Storage::StorageFile ^tempStorageFile, Windows::Storage::FileProperties::PhotoOrientation photoRotation) { ReencodeState ^state = ref new ReencodeState(); return create_task(tempStorageFile->OpenAsync(Windows::Storage::FileAccessMode::Read)).then([state](Windows::Storage::Streams::IRandomAccessStream ^stream) { state->InputStream = stream; return Windows::Graphics::Imaging::BitmapDecoder::CreateAsync(state->InputStream); }).then([state](Windows::Graphics::Imaging::BitmapDecoder ^decoder) { state->Decoder = decoder; return Windows::Storage::KnownFolders::PicturesLibrary->CreateFileAsync(PHOTO_FILE_NAME, Windows::Storage::CreationCollisionOption::GenerateUniqueName); }).then([state](Windows::Storage::StorageFile ^storageFile) { state->PhotoStorage = storageFile; return state->PhotoStorage->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite); }).then([state](Windows::Storage::Streams::IRandomAccessStream ^stream) { state->OutputStream = stream; state->OutputStream->Size = 0; return Windows::Graphics::Imaging::BitmapEncoder::CreateForTranscodingAsync(state->OutputStream, state->Decoder); }).then([state, photoRotation](Windows::Graphics::Imaging::BitmapEncoder ^encoder) { state->Encoder = encoder; auto properties = ref new Windows::Graphics::Imaging::BitmapPropertySet(); properties->Insert("System.Photo.Orientation", ref new Windows::Graphics::Imaging::BitmapTypedValue((unsigned short)photoRotation, Windows::Foundation::PropertyType::UInt16)); return create_task(state->Encoder->BitmapProperties->SetPropertiesAsync(properties)); }).then([state]() { return state->Encoder->FlushAsync(); }).then([tempStorageFile, state](task<void> previousTask) { auto result = state->PhotoStorage; delete state; tempStorageFile->DeleteAsync(Windows::Storage::StorageDeleteOption::PermanentDelete); previousTask.get(); return result; }); } Windows::Storage::FileProperties::PhotoOrientation AdvancedCapture::GetCurrentPhotoRotation() { bool counterclockwiseRotation = m_bReversePreviewRotation; if (m_bRotateVideoOnOrientationChange) { return PhotoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation); } else { return Windows::Storage::FileProperties::PhotoOrientation::Normal; } } void AdvancedCapture::PrepareForVideoRecording() { Windows::Media::Capture::MediaCapture ^mediaCapture = m_mediaCaptureMgr.Get(); if (mediaCapture == nullptr) { return; } bool counterclockwiseRotation = m_bReversePreviewRotation; if (m_bRotateVideoOnOrientationChange) { mediaCapture->SetRecordRotation(VideoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation)); } else { mediaCapture->SetRecordRotation(Windows::Media::Capture::VideoRotation::None); } } void AdvancedCapture::DisplayProperties_OrientationChanged(Platform::Object^ sender) { Windows::Media::Capture::MediaCapture ^mediaCapture = m_mediaCaptureMgr.Get(); if (mediaCapture == nullptr) { return; } bool previewMirroring = mediaCapture->GetPreviewMirroring(); bool counterclockwiseRotation = (previewMirroring && !m_bReversePreviewRotation) || (!previewMirroring && m_bReversePreviewRotation); if (m_bRotateVideoOnOrientationChange) { mediaCapture->SetPreviewRotation(VideoRotationLookup(Windows::Graphics::Display::DisplayProperties::CurrentOrientation, counterclockwiseRotation)); } else { mediaCapture->SetPreviewRotation(Windows::Media::Capture::VideoRotation::None); } } Windows::Storage::FileProperties::PhotoOrientation AdvancedCapture::PhotoRotationLookup( Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise) { switch (displayOrientation) { case Windows::Graphics::Display::DisplayOrientations::Landscape: return Windows::Storage::FileProperties::PhotoOrientation::Normal; case Windows::Graphics::Display::DisplayOrientations::Portrait: return (counterclockwise) ? Windows::Storage::FileProperties::PhotoOrientation::Rotate270: Windows::Storage::FileProperties::PhotoOrientation::Rotate90; case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped: return Windows::Storage::FileProperties::PhotoOrientation::Rotate180; case Windows::Graphics::Display::DisplayOrientations::PortraitFlipped: return (counterclockwise) ? Windows::Storage::FileProperties::PhotoOrientation::Rotate90 : Windows::Storage::FileProperties::PhotoOrientation::Rotate270; default: return Windows::Storage::FileProperties::PhotoOrientation::Unspecified; } } Windows::Media::Capture::VideoRotation AdvancedCapture::VideoRotationLookup( Windows::Graphics::Display::DisplayOrientations displayOrientation, bool counterclockwise) { switch (displayOrientation) { case Windows::Graphics::Display::DisplayOrientations::Landscape: return Windows::Media::Capture::VideoRotation::None; case Windows::Graphics::Display::DisplayOrientations::Portrait: return (counterclockwise) ? Windows::Media::Capture::VideoRotation::Clockwise270Degrees : Windows::Media::Capture::VideoRotation::Clockwise90Degrees; case Windows::Graphics::Display::DisplayOrientations::LandscapeFlipped: return Windows::Media::Capture::VideoRotation::Clockwise180Degrees; case Windows::Graphics::Display::DisplayOrientations::PortraitFlipped: return (counterclockwise) ? Windows::Media::Capture::VideoRotation::Clockwise90Degrees: Windows::Media::Capture::VideoRotation::Clockwise270Degrees ; default: return Windows::Media::Capture::VideoRotation::None; } } void SDKSample::MediaCapture::AdvancedCapture::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { try { create_task(m_mediaCaptureMgr->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoPreview)).then([this](task<void> cleanTask) { m_bEffectAdded = true; int index = EffectTypeCombo->SelectedIndex; PropertySet^ props = ref new PropertySet(); props->Insert(L"{698649BE-8EAE-4551-A4CB-3EC98FBD3D86}", index); create_task(m_mediaCaptureMgr->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoPreview,"OcvTransform.OcvImageManipulations", props)).then([this](task<void> effectTask) { try { effectTask.get(); auto mediaCapture = m_mediaCaptureMgr.Get(); Windows::Media::Capture::VideoDeviceCharacteristic charecteristic = mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic; ShowStatusMessage("Add effect successful to preview stream successful"); if((charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::AllStreamsIdentical) && (charecteristic != Windows::Media::Capture::VideoDeviceCharacteristic::PreviewRecordStreamsIdentical)) { Windows::Media::MediaProperties::IMediaEncodingProperties ^props = mediaCapture->VideoDeviceController->GetMediaStreamProperties(Windows::Media::Capture::MediaStreamType::VideoRecord); Windows::Media::MediaProperties::VideoEncodingProperties ^videoEncodingProperties = static_cast<Windows::Media::MediaProperties::VideoEncodingProperties ^>(props); if(!videoEncodingProperties->Subtype->Equals("H264")) //Can't add an effect to an H264 stream { task<void>(mediaCapture->AddEffectAsync(Windows::Media::Capture::MediaStreamType::VideoRecord,"OcvTransform.OcvImageManipulations", nullptr)).then([this](task<void> effectTask2) { try { effectTask2.get(); ShowStatusMessage("Add effect successful to record stream successful"); m_bEffectAddedToRecord = true; AddEffectToImageStream(); EffectTypeCombo->IsEnabled = true; } catch(Exception ^e) { ShowExceptionMessage(e); EffectTypeCombo->IsEnabled = true; } }); } else { AddEffectToImageStream(); EffectTypeCombo->IsEnabled = true; } } else { AddEffectToImageStream(); EffectTypeCombo->IsEnabled = true; } } catch (Exception ^e) { ShowExceptionMessage(e); EffectTypeCombo->IsEnabled = true; } }); }); } catch (Platform::Exception ^e) { ShowExceptionMessage(e); EffectTypeCombo->IsEnabled = true; } }
10,280
5,169
{ "name": "MGRenterActionCenter", "version": "0.0.2", "license": "MIT License", "summary": "MGRenterActionCenter", "description": "MGRenterActionCenterMGRenterActionCenter", "homepage": "https://github.com/mgzf/MGRenterActionCenter", "authors": { "Harly": "<EMAIL>" }, "source": { "git": "https://github.com/mgzf/MGRenterActionCenter.git", "tag": "0.0.2" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "MGRenterActionCenter/CenterSources/**/*.swift", "dependencies": { "DeeplinkNavigator": [ ] }, "pushed_with_swift_version": "3.0" }
258
1,347
<reponame>fserracant/mmskeleton<filename>mmskeleton/models/skeleton_head/__init__.py from .simplehead import SimpleSkeletonHead
42
5,912
<gh_stars>1000+ # Intentionally empty
14
3,427
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.gtfs.fare; import com.conveyal.gtfs.GTFSFeed; import com.conveyal.gtfs.model.Fare; import com.conveyal.gtfs.model.FareAttribute; import com.conveyal.gtfs.model.FareRule; import com.csvreader.CsvReader; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.io.IOException; import java.io.StringReader; import java.math.BigDecimal; import java.util.*; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; public class FareTest { // See https://code.google.com/archive/p/googletransitdatafeed/wikis/FareExamples.wiki private static final List<Map<String, Map<String, Fare>>> fares = Arrays.asList( // 0: 1$, unlimited transfers map( "only_feed_id", parseFares("only_feed_id", "only_fare,1.00,USD,0\n", ""), "feed_id_2", parseFares("feed_id_2", "", "") ), // 1: 1$, no transfers map( "only_feed_id", parseFares("only_feed_id", "only_fare,1.00,USD,0,0\n", ""), "feed_id_2", parseFares("feed_id_2", "", "") ), // 2: 1$, time limited transfers map( "only_feed_id", parseFares("only_feed_id", "only_fare,1.00,USD,0,,5400\n", ""), "feed_id_2", parseFares("feed_id_2", "", "") ), // 3: regular and express map( "only_feed_id", parseFares("only_feed_id", "local_fare,1.75,USD,0,0\n" + "express_fare,5.00,USD,0,0\n", "local_fare,Route_1\nexpress_fare,Route_2\nexpress_fare,Route3\n"), "feed_id_2", parseFares("feed_id_2", "", "") ), // 4: with transfers or without map( "only_feed_id", parseFares("only_feed_id", "simple_fare,2.00,USD,0,0\n" + "plustransfer_fare,2.50,USD,0,,5400", ""), "feed_id_2", parseFares("feed_id_2", "", "") ), // 5: station pairs map( "only_feed_id", parseFares("only_feed_id", "!S1_to_S2,1.75,USD,0\n!S1_to_S3,3.25,USD,0\n!S1_to_S4,4.55,USD,0\n!S4_to_S1,5.65,USD,0\n", "!S1_to_S2,,S1,S2\n!S1_to_S3,,S1,S3\n!S1_to_S4,,S1,S4\n!S4_to_S1,,S4,S1\n"), "feed_id_2", parseFares("feed_id_2", "", "") ), // 6: zones map( "only_feed_id", parseFares("only_feed_id", "F1,4.15,USD,0\nF2,2.20,USD,0\nF3,2.20,USD,0\nF4,2.95,USD,0\nF5,1.25,USD,0\nF6,1.95,USD,0\nF7,1.95,USD,0\n", "F1,,,,1\nF1,,,,2\nF1,,,,3\nF2,,,,1\nF2,,,,2\nF3,,,,1\nF3,,,,3\nF4,,,,2\nF4,,,,3\nF5,,,,1\nF6,,,,2\nF7,,,,3\n"), "feed_id_2", parseFares("feed_id_2", "", "") ), // 7: two feeds map( "only_feed_id", parseFares("only_feed_id", "only_fare,1.00,USD,0,0\n", ""), "feed_id_2", parseFares("feed_id_2", "only_fare,2.00,USD,0,0\n", "") ) ); private static final List<Trip> trips = new ArrayList<>(); static { Trip trip; trips.add(trip = new Trip()); trip.segments.add(new Trip.Segment("only_feed_id", "Route_1", 0, "S1", "S2", new HashSet<>(Arrays.asList("1", "2", "3")))); trips.add(trip = new Trip()); trip.segments.add(new Trip.Segment("only_feed_id", "Route_1", 0, "S1", "S4", new HashSet<>(Arrays.asList("1")))); trip.segments.add(new Trip.Segment("only_feed_id", "Route_2", 6000, "S4", "S1", new HashSet<>(Arrays.asList("1")))); trips.add(trip = new Trip()); trip.segments.add(new Trip.Segment("only_feed_id", "Route_1", 0, "S1", "S4", new HashSet<>(Arrays.asList("2", "3")))); trip.segments.add(new Trip.Segment("only_feed_id", "Route_2", 5000, "S4", "S1", new HashSet<>(Arrays.asList("2", "3")))); trips.add(trip = new Trip()); trip.segments.add(new Trip.Segment("only_feed_id", "Route_1", 0, "S1", "S4", new HashSet<>(Arrays.asList("1")))); trip.segments.add(new Trip.Segment("only_feed_id", "Route_2", 5000, "S4", "S1", new HashSet<>(Arrays.asList("2")))); trip.segments.add(new Trip.Segment("only_feed_id", "Route_1", 6000, "S1", "S4", new HashSet<>(Arrays.asList("3")))); trips.add(trip = new Trip()); trip.segments.add(new Trip.Segment("only_feed_id", "Route_1", 0, "S1", "S4", new HashSet<>())); trip.segments.add(new Trip.Segment("feed_id_2", "Route_2", 5000, "T", "T", new HashSet<>())); } private static class DataPointProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Object[]> dataPoints = new ArrayList<>(); for (int i = 0; i < fares.size(); i++) { Map<String, Map<String, Fare>> fare = fares.get(i); for (int j = 0; j < trips.size(); j++) { Trip trip = trips.get(j); dataPoints.add(new Object[]{fare, trip, "fare " + i + ", trip: " + j}); } } return dataPoints.stream().map(Arguments::of); } } @ParameterizedTest(name = "{2}") @ArgumentsSource(DataPointProvider.class) public void irrelevantAlternatives(Map<String, Map<String, Fare>> fares, Trip trip, String displayName) { assumeTrue(fares.get("only_feed_id").entrySet().size() >= 2, "There are at least two fares."); // If we only use one fare, say, the most expensive one... Fare mostExpensiveFare = fares.get("only_feed_id").values().stream().max(Comparator.comparingDouble(f -> f.fare_attribute.price)).get(); Map<String, Map<String, Fare>> singleFare = map( "only_feed_id", map(mostExpensiveFare.fare_id, mostExpensiveFare), "feed_id_2", parseFares("feed_id_2", "", "") ); // ..and that still works for our trip.. assumeTrue( trip.segments.stream() .map(segment -> Fares.possibleFares(singleFare.get(segment.feed_id), segment)) .noneMatch(Collection::isEmpty), "There is at least one fare for each segment"); double priceWithOneOption = Fares.cheapestFare(singleFare, trip).get().getAmount().doubleValue(); double priceWithAllOptions = Fares.cheapestFare(fares, trip).get().getAmount().doubleValue(); assertTrue(priceWithAllOptions <= priceWithOneOption, "...it shouldn't get more expensive when we put the cheaper options back."); } @ParameterizedTest(name = "{2}") @ArgumentsSource(DataPointProvider.class) public void everySegmentHasAFare(Map<String, Map<String, Fare>> fares, Trip trip, String displayName) { assumeEachFeedHasAFare(fares); assertTrue(trip.segments.stream() .map(segment -> Fares.possibleFares(fares.get(segment.feed_id), segment)) .noneMatch(Collection::isEmpty), "There is at least one fare for each segment."); } @ParameterizedTest(name = "{2}") @ArgumentsSource(DataPointProvider.class) public void withNoTransfersAndNoAlternativesBuyOneTicketForEachSegment(Map<String, Map<String, Fare>> fares, Trip trip, String displayName) { assumeEachFeedHasAFare(fares); fares.values().stream().flatMap(fs -> fs.values().stream()).forEach(fare -> assumeTrue(0 == fare.fare_attribute.transfers, "No Transfers allowed.")); trip.segments.stream() .map(segment -> Fares.possibleFares(fares.get(segment.feed_id), segment)) .forEach(candidateFares -> assertEquals(1, candidateFares.size(), "Only one fare candidate per segment.")); double totalFare = Fares.cheapestFare(fares, trip).get().getAmount().doubleValue(); double sumOfIndividualFares = trip.segments.stream().flatMap(segment -> Fares.possibleFares(fares.get(segment.feed_id), segment).stream()).mapToDouble(fare -> fare.fare_attribute.price).sum(); assertEquals(sumOfIndividualFares, totalFare, "Total fare is the sum of all individual fares."); } @ParameterizedTest(name = "{2}") @ArgumentsSource(DataPointProvider.class) public void canGoAllTheWayOnOneTicket(Map<String, Map<String, Fare>> fares, Trip trip, String displayName) { assumeTrue(1L == trip.segments.stream().map(s -> s.feed_id).distinct().count()); Optional<Fare> obviouslyCheapestFare = fares.values().stream().flatMap(fs -> fs.values().stream()) .filter(fare -> fare.fare_rules.isEmpty()) // Fare has no restrictions except transfer count/duration .filter(fare -> fare.fare_attribute.transfers >= trip.segments.size() - 1) // Fare allows the number of transfers we need for our trip .filter(fare -> fare.fare_attribute.transfer_duration >= trip.segments.get(trip.segments.size() - 1).getStartTime() - trip.segments.get(0).getStartTime()) .min(Comparator.comparingDouble(fare -> fare.fare_attribute.price)); assumeTrue(obviouslyCheapestFare.isPresent(), "There is an obviously cheapest fare."); Amount amount = Fares.cheapestFare(fares, trip).get(); assertEquals(BigDecimal.valueOf(obviouslyCheapestFare.get().fare_attribute.price), amount.getAmount(), "The fare calculator agrees"); } @ParameterizedTest(name = "{2}") @ArgumentsSource(DataPointProvider.class) public void buyMoreThanOneTicketIfTripIsLongerThanAllowedOnOne(Map<String, Map<String, Fare>> fares, Trip trip, String displayName) { assumeTrue(1L == fares.values().stream().flatMap(fs -> fs.values().stream()).count(), "Only one fare."); Fare onlyFare = fares.values().stream().flatMap(fs -> fs.values().stream()).findFirst().get(); assumeTrue(trip.segments.size() > 1, "We have a transfer"); assumeTrue(onlyFare.fare_attribute.transfers >= trip.segments.size(), "Fare allows the number of transfers we need for our trip."); assumeTrue((long) onlyFare.fare_attribute.transfer_duration <= trip.segments.get(trip.segments.size() - 1).getStartTime() - trip.segments.get(0).getStartTime(), "Fare does not allow the time we need for our trip."); Amount amount = Fares.cheapestFare(fares, trip).get(); assertTrue(amount.getAmount().doubleValue() > onlyFare.fare_attribute.price); } @ParameterizedTest(name = "{2}") @ArgumentsSource(DataPointProvider.class) public void ifAllLegsPassThroughAllZonesOfTheTripItCantGetCheaper(Map<String, Map<String, Fare>> fares, Trip trip, String displayName) { assumeEachFeedHasAFare(fares); double cheapestFare = Fares.cheapestFare(fares, trip).get().getAmount().doubleValue(); Set<String> allZones = trip.segments.stream().flatMap(seg -> seg.getZones().stream()).collect(Collectors.toSet()); Trip otherTrip = new Trip(); for (Trip.Segment segment : trip.segments) { otherTrip.segments.add(new Trip.Segment(segment.feed_id, segment.getRoute(), segment.getStartTime(), segment.getOriginId(), segment.getDestinationId(), allZones)); } double cheapestFareWhereEveryLegGoesThroughAllZones = Fares.cheapestFare(fares, otherTrip).get().getAmount().doubleValue(); assertTrue(cheapestFareWhereEveryLegGoesThroughAllZones >= cheapestFare); } @ParameterizedTest(name = "{2}") @ArgumentsSource(DataPointProvider.class) public void ifIOnlyHaveOneTicketAndItIsZoneBasedItMustBeGoodForAllZonesOnMyTrip(Map<String, Map<String, Fare>> fares, Trip trip, String displayName) { Fares.allShoppingCarts(fares, trip) .filter(purchase -> purchase.getTickets().size() == 1) .filter(purchase -> purchase.getTickets().get(0).getFare().fare_rules.stream().anyMatch(rule -> rule.contains_id != null)) .forEach(purchase -> { Set<String> zonesICanUse = purchase.getTickets().get(0).getFare().fare_rules.stream().filter(rule -> rule.contains_id != null).map(rule -> rule.contains_id).collect(Collectors.toSet()); Set<String> zonesINeed = trip.segments.stream().flatMap(segment -> segment.getZones().stream()).collect(Collectors.toSet()); assertTrue(zonesICanUse.containsAll(zonesINeed)); }); } public static Map<String, Fare> parseFares(String feedId, String fareAttributes, String fareRules) { GTFSFeed feed = new GTFSFeed(); feed.feedId = feedId; HashMap<String, Fare> fares = new HashMap<>(); new FareAttribute.Loader(feed, fares) { void load(String input) { reader = new CsvReader(new StringReader(input)); reader.setHeaders(new String[]{"fare_id", "price", "currency_type", "payment_method", "transfers", "transfer_duration"}); try { while (reader.readRecord()) { loadOneRow(); } } catch (IOException e) { e.printStackTrace(); } } }.load(fareAttributes); new FareRule.Loader(feed, fares) { void load(String input) { reader = new CsvReader(new StringReader(input)); reader.setHeaders(new String[]{"fare_id", "route_id", "origin_id", "destination_id", "contains_id"}); try { while (reader.readRecord()) { loadOneRow(); } } catch (IOException e) { e.printStackTrace(); } } }.load(fareRules); return fares; } private void assumeEachFeedHasAFare(Map<String, Map<String, Fare>> fares) { fares.values().forEach(faresForOneFeed -> assumeFalse(faresForOneFeed.entrySet().isEmpty(), "There are fares.")); } // https://bitbucket.org/assylias/bigblue-utils/src/master/src/main/java/com/assylias/bigblue/utils/Maps.java?at=master public static <K, V> Map<K, V> map(K key, V value, Object... kvs) { return map(HashMap::new, key, value, kvs); } public static <K, V, T extends Map<K, V>> T map(BiFunction<Integer, Float, T> mapFactory, K key, V value, Object... kvs) { T m = mapFactory.apply(kvs.length / 2 + 1, 1f); m.put(key, value); for (int i = 0; i < kvs.length; ) { K k = (K) kvs[i++]; V v = (V) kvs[i++]; if (k != null && v != null) { m.put(k, v); } } return m; } }
6,992
1,470
<reponame>oberblastmeister/comby int depth_0() {}
20
766
import itertools import numpy as np from . import common class Interpolator: def __init__(self, resolution=1024, width=128): self.width = width self.resolution = resolution N = resolution * width u = np.arange(-N, N, dtype=float) window = np.cos(0.5 * np.pi * u / N) ** 2.0 # raised cosine h = np.sinc(u / resolution) * window self.filt = [] for index in range(resolution): # split into multiphase filters filt = h[index::resolution] filt = filt[::-1] # flip (due to convolution) self.filt.append(filt) lengths = [len(f) for f in self.filt] self.coeff_len = 2 * width assert set(lengths) == set([self.coeff_len]) # verify same lengths assert len(self.filt) == resolution defaultInterpolator = Interpolator() class Sampler: def __init__(self, src, interp=None, freq=1.0): self.freq = freq self.equalizer = lambda x: x # LTI equalization filter if interp is not None: self.interp = interp self.resolution = self.interp.resolution self.filt = self.interp.filt self.width = self.interp.width # polyphase filters are centered at (width + 1) index padding = [0.0] * self.interp.width # pad with zeroes to "simulate" regular sampling self.src = itertools.chain(padding, src) self.offset = self.interp.width + 1 # samples' buffer to be used by interpolation self.buff = np.zeros(self.interp.coeff_len) self.index = 0 self.take = self._take else: # skip interpolation (for testing) src = iter(src) self.take = lambda size: common.take(src, size) def _take(self, size): frame = np.zeros(size) count = 0 for frame_index in range(size): offset = self.offset # offset = k + (j / self.resolution) k = int(offset) # integer part j = int((offset - k) * self.resolution) # fractional part coeffs = self.filt[j] # choose correct filter phase end = k + self.width # process input until all buffer is full with samples try: while self.index < end: self.buff[:-1] = self.buff[1:] self.buff[-1] = next(self.src) # throws StopIteration self.index += 1 except StopIteration: break self.offset += self.freq # apply interpolation filter frame[frame_index] = np.dot(coeffs, self.buff) count = frame_index + 1 return self.equalizer(frame[:count]) def resample(src, dst, df=0.0): x = common.load(src) sampler = Sampler(x, Interpolator()) sampler.freq += df y = sampler.take(len(x)) dst.write(common.dumps(y))
1,416
433
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.redkale.convert.bson; import java.io.Serializable; import java.lang.reflect.Type; import java.util.*; import java.util.stream.Stream; import org.redkale.convert.*; import org.redkale.convert.ext.*; import org.redkale.util.*; /** * BSON的ConvertFactory * * <p> * 详情见: https://redkale.org * * @author zhangjx */ @SuppressWarnings("unchecked") public final class BsonFactory extends ConvertFactory<BsonReader, BsonWriter> { private static final BsonFactory instance = new BsonFactory(null, getSystemPropertyBoolean("redkale.convert.bson.tiny", "redkale.convert.tiny", true)); static final Decodeable objectDecoder = instance.loadDecoder(Object.class); static final Encodeable objectEncoder = instance.loadEncoder(Object.class); static final Decodeable skipArrayDecoder = new SkipArrayDecoder(instance, Object[].class); static final Decodeable skipCollectionDecoder = new SkipCollectionDecoder(instance, new TypeToken<Collection<Object>>() { }.getType()); static final Decodeable skipStreamDecoder = new SkipStreamDecoder(instance, new TypeToken<Stream<Object>>() { }.getType()); static final Decodeable skipMapDecoder = new SkipMapDecoder(instance, Map.class); static { instance.register(Serializable.class, objectDecoder); instance.register(Serializable.class, objectEncoder); //instance.register(AnyValue.class, instance.loadDecoder(AnyValue.DefaultAnyValue.class)); //instance.register(AnyValue.class, instance.loadEncoder(AnyValue.DefaultAnyValue.class)); } private BsonFactory(BsonFactory parent, boolean tiny) { super(parent, tiny); } @Override public BsonFactory tiny(boolean tiny) { this.tiny = tiny; return this; } @Override public BsonFactory skipAllIgnore(final boolean skipIgnore) { this.registerSkipAllIgnore(skipIgnore); return this; } public static BsonFactory root() { return instance; } public static BsonFactory create() { return new BsonFactory(null, getSystemPropertyBoolean("redkale.convert.bson.tiny", "redkale.convert.tiny", true)); } @Override public final BsonConvert getConvert() { if (convert == null) convert = new BsonConvert(this, tiny); return (BsonConvert) convert; } @Override public BsonFactory createChild() { return new BsonFactory(this, this.tiny); } @Override public BsonFactory createChild(boolean tiny) { return new BsonFactory(this, tiny); } @Override public ConvertType getConvertType() { return ConvertType.BSON; } @Override public boolean isReversible() { return true; } @Override public boolean isFieldSort() { return true; } protected static byte typeEnum(final Type type) { return typeEnum(TypeToken.typeToClass(type)); } protected static byte typeEnum(final Class type) { Objects.requireNonNull(type); byte typeval = 127; //字段的类型值 if (type == boolean.class || type == Boolean.class) { typeval = 11; } else if (type == byte.class || type == Byte.class) { typeval = 12; } else if (type == short.class || type == Short.class) { typeval = 13; } else if (type == char.class || type == Character.class) { typeval = 14; } else if (type == int.class || type == Integer.class) { typeval = 15; } else if (type == long.class || type == Long.class) { typeval = 16; } else if (type == float.class || type == Float.class) { typeval = 17; } else if (type == double.class || type == Double.class) { typeval = 18; } else if (type == String.class) { typeval = 19; } else if (type == boolean[].class || type == Boolean[].class) { typeval = 21; } else if (type == byte[].class || type == Byte[].class) { typeval = 22; } else if (type == short[].class || type == Short[].class) { typeval = 23; } else if (type == char[].class || type == Character[].class) { typeval = 24; } else if (type == int[].class || type == Integer[].class) { typeval = 25; } else if (type == long[].class || type == Long[].class) { typeval = 26; } else if (type == float[].class || type == Float[].class) { typeval = 27; } else if (type == double[].class || type == Double[].class) { typeval = 28; } else if (type == String[].class) { typeval = 29; } else if (type.isArray()) { typeval = 81; } else if (Collection.class.isAssignableFrom(type)) { typeval = 82; } else if (Stream.class.isAssignableFrom(type)) { typeval = 83; } else if (Map.class.isAssignableFrom(type)) { typeval = 84; } return typeval; } protected static Decodeable typeEnum(final byte typeval) { switch (typeval) { case 11: return BoolSimpledCoder.instance; case 12: return ByteSimpledCoder.instance; case 13: return ShortSimpledCoder.instance; case 14: return CharSimpledCoder.instance; case 15: return IntSimpledCoder.instance; case 16: return LongSimpledCoder.instance; case 17: return FloatSimpledCoder.instance; case 18: return DoubleSimpledCoder.instance; case 19: return StringSimpledCoder.instance; case 21: return BoolArraySimpledCoder.instance; case 22: return ByteArraySimpledCoder.instance; case 23: return ShortArraySimpledCoder.instance; case 24: return CharArraySimpledCoder.instance; case 25: return IntArraySimpledCoder.instance; case 26: return LongArraySimpledCoder.instance; case 27: return FloatArraySimpledCoder.instance; case 28: return DoubleArraySimpledCoder.instance; case 29: return StringArraySimpledCoder.instance; case 81: return skipArrayDecoder; case 82: return skipCollectionDecoder; case 83: return skipStreamDecoder; case 84: return skipMapDecoder; case 127: return BsonFactory.objectDecoder; } return null; } }
3,329
303
<gh_stars>100-1000 {"id":78885,"line-1":"Dobrich","line-2":"Bulgaria","attribution":"©2016 CNES / Astrium, DigitalGlobe","url":"https://www.google.com/maps/@43.574564,28.154902,17z/data=!3m1!1e3"}
86
816
<gh_stars>100-1000 package com.jxtech.jbo.virtual; import java.io.OutputStream; import java.sql.Connection; import java.util.List; import java.util.Map; import com.jxtech.jbo.BaseJboSet; import com.jxtech.jbo.JboIFace; import com.jxtech.jbo.base.JxUserInfo; import com.jxtech.jbo.util.JxException; /** * 虚拟JboSet,不会进行持久化 * * @author <EMAIL> * @date 2014.11 * */ public class VirtualJboSet extends BaseJboSet { private static final long serialVersionUID = -8890814440371572093L; @Override protected JboIFace getJboInstance() throws JxException { currentJbo = new VirtualJbo(this); return currentJbo; // 创建自己的JBO } @Override public List<JboIFace> query(String shipname) throws JxException { // TODO Auto-generated method stub return null; } @Override public boolean save(Connection conn) throws JxException { return true; } @Override public void setFlag() { } @Override public boolean rollback() throws JxException { return true; } @Override public boolean commit() throws JxException { return true; } @Override public boolean delete(String[] ids) throws JxException { return false; } @Override public boolean delete(Connection conn, JboIFace jbi, boolean isSave) throws JxException { return true; } @Override public JboIFace queryJbo(String uid) throws JxException { return null; } @Override public JboIFace getJboOfIndex(int index, boolean reload) throws JxException { return null; } @Override public int count() throws JxException { List<JboIFace> list = this.getJbolist(); if (list != null) { return list.size(); } return 0; } @Override public void getBlob(String blobColumnName, String uid, OutputStream os) throws JxException { } @Override public String getWorkflowId() { return null; } @Override public void setWorkflowId(String wfId) { } @Override public int route() throws JxException { // TODO Auto-generated method stub return 0; } @Override public void afterLoad() throws JxException { // TODO Auto-generated method stub } @Override public String loadImportFile(List<Map<Object, String>> importFileResult, JxUserInfo userInfo) throws JxException { // TODO Auto-generated method stub return null; } @Override public JboIFace queryJbo(String jboKey, String uid) throws JxException { // TODO Auto-generated method stub return null; } @Override public JboIFace queryJbo(String where, String jboKey, String uid) throws JxException { // TODO Auto-generated method stub return null; } @Override public void lookup(List<JboIFace> lookupList) throws JxException { // TODO Auto-generated method stub } @Override public List<JboIFace> queryJbo(String[] ids) throws JxException { // TODO Auto-generated method stub return null; } @Override public String getSecurityrestrict(boolean elValue) throws JxException { // TODO Auto-generated method stub return null; } @Override public boolean commit(long flag) throws JxException { // TODO Auto-generated method stub return false; } @Override public boolean delete(Connection conn, String whereCause, Object[] params) throws JxException { // TODO Auto-generated method stub return false; } @Override public boolean delete(String whereCause, Object[] params) throws JxException { // TODO Auto-generated method stub return false; } @Override public List<JboIFace> getTree(String parentName, String parentValue, String idName, boolean includeSelf) throws JxException { // TODO Auto-generated method stub return null; } @Override public String getWorkflowEngine() throws JxException { // TODO Auto-generated method stub return null; } @Override public void setWorkflowEngine(String workflowEngine) { // TODO Auto-generated method stub } @Override public int getCount(boolean flag) { return super.getCount(false); } @Override public int route(String action) throws JxException { // TODO Auto-generated method stub return 0; } @Override public int route(String[] ids, String action, String memo) throws JxException { // TODO Auto-generated method stub return 0; } }
1,840
1,880
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package sample; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import dagger.Lazy; import dagger.MembersInjector; import javax.inject.Inject; import sample.child.Shboom; public class PseudoActivity { @Inject @BarAnnotation Bar bar; @Inject @BarAnnotation Bar bar2; @Inject Baz baz; @Inject Shboom shboom; @Inject Alien alien; @Inject FooByStatic fooByStatic; @Inject Optional<OptYes> optYes; @Inject Optional<Lazy<OptYes>> lazyOptYes; @Inject Optional<OptNo> optNo; @Inject MembersInjector<Buggie> buggieInjector; Buggie buggie = new Buggie(); void onCreate(DaggerApplicationComponent applicationComponent) { DaggerActivityComponent activityComponent = (DaggerActivityComponent) DaggerActivityComponent.builder() .s1(applicationComponent) .setAlienSource(new AlienSource("Martian")) .b(); activityComponent.injectPseudoActivity(this); buggieInjector.injectMembers(buggie); } @Override public String toString() { return MoreObjects.toStringHelper("PseudoActivity[bar: ") .add("bar", bar) .add(" bar2: ", bar2) .add(", baz: ", baz) .add(" shboom: ", shboom) .add(" FooByStatic: ", fooByStatic) .add(" alien: ", alien) .add(" optYes: ", optYes.isPresent()) .add(" lazyoptYes: ", lazyOptYes.isPresent() + "/" + lazyOptYes.get().get()) .add(" optNo: ", optNo.isPresent()) .add("buggie", buggie) .toString(); } }
792
4,071
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #undef CHECK #undef CHECK_LT #undef CHECK_GT #undef CHECK_LE #undef CHECK_GE #undef CHECK_EQ #undef CHECK_NE #undef CHECK_NOTNULL #undef DCHECK #undef DCHECK_LT #undef DCHECK_GT #undef DCHECK_LE #undef DCHECK_GE #undef DCHECK_EQ #undef DCHECK_NE #undef VLOG #undef LOG #undef LOG_IF #undef LOG_EVERY_N #undef VLOG_IS_ON #undef CHECK_OP_LOG #undef CHECK_OP
1,006
675
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************/ #pragma once #include "calc.h" #include "device.h" #include "intersector.h" #include <memory> /** \file intersector_bittrail.h \author <NAME> \version 1.0 \brief Intersector implementation based on BVH stackless traversal using bit trail and perfect hashing. Intersector is using binary BVH with two bounding boxes per node. Traversal is using bit trail and perfect hashing for backtracing and based on the following paper: "Efficient stackless hierarchy traversal on GPUs with backtracking in constant time"" <NAME>, <NAME> http://dl.acm.org/citation.cfm?id=2977343 Traversal pseudocode: while(addr is valid) { node <- fetch next node at addr index <- 1 trail <- 0 if (node is leaf) intersect leaf else { intersect ray vs left child intersect ray vs right child if (intersect any of children) { index <- index << 1 trail <- trail << 1 determine closer child if intersect both { trail <- trail ^ 1 addr = closer child } else { addr = intersected child } if addr is right index <- index ^ 1 continue } } if (trail == 0) { break } num_levels = count trailing zeroes in trail trail <- (trail << num_levels) & 1 index <- (index << num_levels) & 1 addr = hash[index] } Pros: -Very fast traversal. -Benefits from BVH quality optimization. -Low VGPR pressure Cons: -Depth is limited. -Generates global memory traffic. */ namespace RadeonRays { class Bvh; class IntersectorBitTrail : public Intersector { public: IntersectorBitTrail(Calc::Device* device); private: void Process(World const& world) override; void Intersect(std::uint32_t queue_idx, Calc::Buffer const *rays, Calc::Buffer const *num_rays, std::uint32_t max_rays, Calc::Buffer *hits, Calc::Event const *wait_event, Calc::Event **event) const override; void Occluded(std::uint32_t queue_idx, Calc::Buffer const *rays, Calc::Buffer const *num_rays, std::uint32_t max_rays, Calc::Buffer *hits, Calc::Event const *wait_event, Calc::Event **event) const override; private: struct GpuData; struct ShapeData; // Implementation data std::unique_ptr<GpuData> m_gpudata; // Bvh data structure std::unique_ptr<Bvh> m_bvh; }; }
1,761
1,144
<reponame>dram/metasfresh package de.metas.ui.web.process.view; import java.lang.reflect.Method; import org.adempiere.exceptions.AdempiereException; import com.google.common.collect.ImmutableList; import de.metas.i18n.ITranslatableString; import de.metas.process.ProcessPreconditionsResolution; import de.metas.process.RelatedProcessDescriptor.DisplayPlace; import de.metas.ui.web.process.ProcessId; import de.metas.ui.web.process.ProcessInstanceResult; import de.metas.ui.web.process.ViewAsPreconditionsContext; import de.metas.ui.web.process.descriptor.InternalName; import de.metas.ui.web.process.descriptor.ProcessDescriptor; import de.metas.ui.web.process.descriptor.ProcessDescriptor.ProcessDescriptorType; import de.metas.ui.web.process.descriptor.ProcessLayout; import de.metas.ui.web.process.descriptor.WebuiRelatedProcessDescriptor; import de.metas.ui.web.process.view.ViewAction.Precondition; import de.metas.ui.web.view.IView; import de.metas.ui.web.window.datatypes.DocumentIdsSelection; import de.metas.ui.web.window.datatypes.DocumentType; import de.metas.ui.web.window.datatypes.PanelLayoutType; import de.metas.ui.web.window.descriptor.DocumentEntityDescriptor; import de.metas.ui.web.window.model.Document; import lombok.Builder; import lombok.NonNull; import lombok.Singular; import lombok.ToString; import javax.annotation.Nullable; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2017 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /** * Descriptor of a method annotated with {@link ViewAction}. * * @author metas-dev <<EMAIL>> * */ @ToString @Builder public final class ViewActionDescriptor { private final @NonNull String actionId; private final @NonNull Method viewActionMethod; // hard reference, because else it would be too sensible on things like cache reset private final @NonNull ITranslatableString caption; private final @NonNull ITranslatableString description; private final boolean defaultAction; private final Class<? extends Precondition> preconditionClass; private final Precondition preconditionSharedInstance; private final @NonNull PanelLayoutType layoutType; @Singular private final ImmutableList<ViewActionParamDescriptor> viewActionParamDescriptors; private final @NonNull ViewActionMethodReturnTypeConverter viewActionReturnTypeConverter; public String getActionId() { return actionId; } @Nullable public DocumentEntityDescriptor createParametersEntityDescriptor(@NonNull final ProcessId processId) { final DocumentEntityDescriptor.Builder parametersDescriptor = DocumentEntityDescriptor.builder() .setDocumentType(DocumentType.Process, processId.toDocumentId()) .disableDefaultTableCallouts(); viewActionParamDescriptors.stream() .filter(ViewActionParamDescriptor::isUserParameter) .map(ViewActionParamDescriptor::createParameterFieldDescriptor) .forEach(parametersDescriptor::addField); if (parametersDescriptor.getFieldsCount() == 0) { return null; } return parametersDescriptor.build(); } public ProcessDescriptor getProcessDescriptor(@NonNull final ProcessId processId) { final DocumentEntityDescriptor parametersDescriptor = createParametersEntityDescriptor(processId); final ProcessLayout processLayout = ProcessLayout.builder() .setProcessId(processId) .setLayoutType(layoutType) .setCaption(caption) .setDescription(description) .addElements(parametersDescriptor) .build(); return ProcessDescriptor.builder() .setProcessId(processId) .setInternalName(InternalName.ofString(actionId)) .setType(ProcessDescriptorType.Process) // .setLayout(processLayout) // .build(); } public WebuiRelatedProcessDescriptor toWebuiRelatedProcessDescriptor(final ViewAsPreconditionsContext viewContext) { final IView view = viewContext.getView(); final DocumentIdsSelection selectedDocumentIds = viewContext.getSelectedRowIds(); return WebuiRelatedProcessDescriptor.builder() .processId(ViewProcessInstancesRepository.buildProcessId(view.getViewId(), actionId)) .processCaption(caption) .processDescription(description) // .displayPlace(DisplayPlace.ViewQuickActions) .defaultQuickAction(defaultAction) // .preconditionsResolutionSupplier(() -> checkPreconditions(view, selectedDocumentIds)) // .build(); } private ProcessPreconditionsResolution checkPreconditions(final IView view, final DocumentIdsSelection selectedDocumentIds) { try { return getPreconditionsInstance().matches(view, selectedDocumentIds); } catch (final InstantiationException | IllegalAccessException ex) { throw AdempiereException.wrapIfNeeded(ex); } } private Precondition getPreconditionsInstance() throws InstantiationException, IllegalAccessException { if (preconditionSharedInstance != null) { return preconditionSharedInstance; } return preconditionClass.newInstance(); } @NonNull public Method getViewActionMethod() { return viewActionMethod; } public ProcessInstanceResult.ResultAction convertReturnType(final Object returnValue) { return viewActionReturnTypeConverter.convert(returnValue); } @NonNull public Object[] extractMethodArguments(final IView view, final Document processParameters, final DocumentIdsSelection selectedDocumentIds) { return viewActionParamDescriptors.stream() .map(paramDesc -> paramDesc.extractArgument(view, processParameters, selectedDocumentIds)) .toArray(); } @FunctionalInterface public interface ViewActionMethodReturnTypeConverter { ProcessInstanceResult.ResultAction convert(Object returnValue); } @FunctionalInterface public interface ViewActionMethodArgumentExtractor { Object extractArgument(IView view, Document processParameters, DocumentIdsSelection selectedDocumentIds); } }
2,022
1,538
// 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.kudu.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import org.junit.Rule; import org.junit.Test; import org.apache.kudu.test.junit.RetryRule; public class TestByteVec { private static final Random RAND = new Random(); @Rule public RetryRule retryRule = new RetryRule(); private void assertBytesEqual(byte a, byte b) { if (a != b) { throw new AssertionError(String.format("%s != %s", a, b)); } } private List<Byte> random() { return random(RAND.nextInt(1024)); } private List<Byte> random(int len) { List<Byte> list = new ArrayList<>(); for (int i = 0; i < len; i++) { list.add((byte) RAND.nextInt(i + 1)); } return Collections.unmodifiableList(list); } private void checkByteVec(List<Byte> vals) { ByteVec vec = ByteVec.create(); assertEquals(0, vec.len()); // push for (byte i : vals) { vec.push(i); } assertEquals(vals, vec.asList()); // withCapacity assertEquals(0, ByteVec.withCapacity(0).capacity()); assertEquals(13, ByteVec.withCapacity(13).capacity()); // wrap assertEquals(vec, ByteVec.wrap(vec.toArray())); // clone, equals ByteVec copy = vec.clone(); assertEquals(copy, vec); // truncate copy.truncate(vec.len() + 1); assertEquals(vals, copy.asList()); vec.truncate(copy.len()); assertEquals(vals, copy.asList()); copy.truncate(vals.size() / 2); assertEquals(vals.subList(0, vals.size() / 2), copy.asList()); if (vals.size() > 0) { assertNotEquals(vals, copy.asList()); } // reserveAdditional int unused = copy.capacity() - copy.len(); copy.reserveAdditional(unused); assertEquals(vec.capacity(), copy.capacity()); copy.reserveAdditional(unused + 1); assertTrue(copy.capacity() > vec.capacity()); // reserveExact unused = copy.capacity() - copy.len(); copy.reserveExact(unused + 3); assertEquals(copy.capacity() - copy.len(), unused + 3); copy.truncate(0); assertEquals(0, copy.len()); // shrinkToFit copy.shrinkToFit(); assertEquals(0, copy.capacity()); vec.shrinkToFit(); assertEquals(vec.len(), vec.capacity()); // get for (int i = 0; i < vals.size(); i++) { assertBytesEqual(vals.get(i), vec.get(i)); } // set if (vec.len() > 0) { copy = vec.clone(); int index = RAND.nextInt(vec.len()); copy.set(index, (byte) index); List<Byte> intsCopy = new ArrayList<>(vals); intsCopy.set(index, (byte) index); assertEquals(intsCopy, copy.asList()); } } @Test public void testByteVec() throws Exception { checkByteVec(random(0)); checkByteVec(random(1)); checkByteVec(random(2)); checkByteVec(random(3)); checkByteVec(random(ByteVec.DEFAULT_CAPACITY - 2)); checkByteVec(random(ByteVec.DEFAULT_CAPACITY - 1)); checkByteVec(random(ByteVec.DEFAULT_CAPACITY)); checkByteVec(random(ByteVec.DEFAULT_CAPACITY + 1)); checkByteVec(random(ByteVec.DEFAULT_CAPACITY + 2)); for (int i = 0; i < 100; i++) { checkByteVec(random()); } } }
1,548
1,013
"""! @brief Pyclustering package that is used to exchange between python core and 'ccore'. @authors <NAME> (<EMAIL>) @date 2014-2020 @copyright BSD-3-Clause """ from ctypes import * import collections.abc import numpy class pyclustering_package(Structure): """! @brief pyclustering_package description in memory. @details Represents following C++ structure: typedef struct pyclustering_package { std::size_t size; unsigned int type; void * data; } """ _fields_ = [("size", c_size_t), ("type", c_uint), ("data", POINTER(c_void_p))] class pyclustering_type_data: """! @brief Contains constants that defines type of package. """ PYCLUSTERING_TYPE_INT = 0 PYCLUSTERING_TYPE_UNSIGNED_INT = 1 PYCLUSTERING_TYPE_FLOAT = 2 PYCLUSTERING_TYPE_DOUBLE = 3 PYCLUSTERING_TYPE_LONG = 4 PYCLUSTERING_TYPE_CHAR = 5 PYCLUSTERING_TYPE_LIST = 6 PYCLUSTERING_TYPE_SIZE_T = 7 PYCLUSTERING_TYPE_WCHAR_T = 8 PYCLUSTERING_TYPE_UNDEFINED = 9 __CTYPE_PYCLUSTERING_MAP = { c_int: PYCLUSTERING_TYPE_INT, c_uint: PYCLUSTERING_TYPE_UNSIGNED_INT, c_float: PYCLUSTERING_TYPE_FLOAT, c_double: PYCLUSTERING_TYPE_DOUBLE, c_long: PYCLUSTERING_TYPE_LONG, c_char: PYCLUSTERING_TYPE_CHAR, POINTER(pyclustering_package): PYCLUSTERING_TYPE_LIST, c_size_t: PYCLUSTERING_TYPE_SIZE_T, c_wchar: PYCLUSTERING_TYPE_WCHAR_T, None: PYCLUSTERING_TYPE_UNDEFINED } __PYCLUSTERING_CTYPE_MAP = { PYCLUSTERING_TYPE_INT: c_int, PYCLUSTERING_TYPE_UNSIGNED_INT: c_uint, PYCLUSTERING_TYPE_FLOAT: c_float, PYCLUSTERING_TYPE_DOUBLE: c_double, PYCLUSTERING_TYPE_LONG: c_long, PYCLUSTERING_TYPE_CHAR: c_char, PYCLUSTERING_TYPE_LIST: POINTER(pyclustering_package), PYCLUSTERING_TYPE_SIZE_T: c_size_t, PYCLUSTERING_TYPE_WCHAR_T: c_wchar, PYCLUSTERING_TYPE_UNDEFINED: None } @staticmethod def get_ctype(pyclustering_package_type): """! @return (ctype) Return ctype that corresponds to pyclustering type data. """ return pyclustering_type_data.__PYCLUSTERING_CTYPE_MAP[pyclustering_package_type] @staticmethod def get_pyclustering_type(data_ctype): """! @return (unit) Return pyclustering data type that corresponds to ctype. """ return pyclustering_type_data.__CTYPE_PYCLUSTERING_MAP[data_ctype] class package_builder: """! @brief Package builder provides service to create 'pyclustering_package' from data that is stored in 'list' container. """ def __init__(self, dataset, c_data_type=None): """! @brief Initialize package builder object by dataset. @details String data is packed as it is without encoding. If string encoding is required then it should be provided already encoded, for example in case of `utf-8`: @code encoded_string = "String to pack".encode('utf-8') pyclustering_package = package_builder(encoded_string) @endcode @param[in] dataset (list): Data that should be packed in 'pyclustering_package'. @param[in] c_data_type (ctype.type): C-type data that is used to store data in the package. """ self.__dataset = dataset self.__c_data_type = c_data_type def create(self): """! @brief Performs packing procedure of the data to the package. @return (pointer) ctype-pointer to pyclustering package. """ return self.__create_package(self.__dataset) def __is_container_type(self, value): return isinstance(value, collections.abc.Iterable) def __get_type(self, pyclustering_data_type): if self.__c_data_type is None: return pyclustering_data_type return self.__c_data_type def __create_package(self, dataset): dataset_package = pyclustering_package() if isinstance(dataset, str): return self.__create_package_string(dataset_package, dataset) if isinstance(dataset, numpy.matrix): return self.__create_package_numpy_matrix(dataset_package, dataset) dataset_package.size = len(dataset) if len(dataset) == 0: dataset_package.type = pyclustering_type_data.PYCLUSTERING_TYPE_UNDEFINED dataset_package.data = None return pointer(dataset_package) c_data_type = self.__fill_type(dataset_package, dataset) self.__fill_data(dataset_package, c_data_type, dataset) return pointer(dataset_package) def __fill_dataset_type(self, dataset_package, dataset): if self.__is_container_type(dataset[0]): dataset_package.type = pyclustering_type_data.PYCLUSTERING_TYPE_LIST elif isinstance(dataset[0], int): dataset_package.type = pyclustering_type_data.PYCLUSTERING_TYPE_LONG elif isinstance(dataset[0], float): dataset_package.type = pyclustering_type_data.PYCLUSTERING_TYPE_DOUBLE else: raise NameError("Not supported type of pyclustering package.") return pyclustering_type_data.get_ctype(dataset_package.type) def __fill_specify_type(self, dataset_package): dataset_package.type = pyclustering_type_data.get_pyclustering_type(self.__c_data_type) return self.__c_data_type def __fill_type(self, dataset_package, dataset): if self.__is_container_type(dataset[0]): dataset_package.type = pyclustering_type_data.PYCLUSTERING_TYPE_LIST return None if self.__c_data_type is None: return self.__fill_dataset_type(dataset_package, dataset) return self.__fill_specify_type(dataset_package) def __fill_data(self, dataset_package, c_data_type, dataset): if dataset_package.type == pyclustering_type_data.PYCLUSTERING_TYPE_LIST: package_data = (POINTER(pyclustering_package) * len(dataset))() for index in range(len(dataset)): package_data[index] = self.__create_package(dataset[index]) dataset_package.data = cast(package_data, POINTER(c_void_p)) else: array_object = (c_data_type * len(dataset))(*dataset) dataset_package.data = cast(array_object, POINTER(c_void_p)) def __create_package_numpy_matrix(self, dataset_package, dataset): (rows, cols) = dataset.shape dataset_package.size = rows dataset_package.type = pyclustering_type_data.PYCLUSTERING_TYPE_LIST package_data = (POINTER(pyclustering_package) * rows)() for row_index in range(rows): array_package = pyclustering_package() array_package.size = cols array_package.type = pyclustering_type_data.get_pyclustering_type(self.__c_data_type) array_object = (self.__c_data_type * cols)() for col_index in range(cols): array_object[col_index] = self.__c_data_type(dataset[row_index, col_index]) array_package.data = cast(array_object, POINTER(c_void_p)) package_data[row_index] = pointer(array_package) dataset_package.data = cast(package_data, POINTER(c_void_p)) return pointer(dataset_package) def __create_package_string(self, dataset_package, string_value): dataset_package.size = len(string_value) dataset_package.type = pyclustering_type_data.PYCLUSTERING_TYPE_CHAR dataset_package.data = cast(string_value, POINTER(c_void_p)) return pointer(dataset_package) class package_extractor: """! @brief Package extractor provides servies to unpack pyclustering package. """ def __init__(self, package_pointer): """! @brief Initialize package extractor object by ctype-pointer to 'pyclustering_package'. @param[in] package_pointer (pointer): ctype-pointer to 'pyclustering_package' that should be used for unpacking. """ self.__package_pointer = package_pointer def extract(self): """! @brief Performs unpacking procedure of the pyclustering package to the data. @return (list) Extracted data from the pyclustering package. """ return self.__extract_data(self.__package_pointer) def __extract_data(self, ccore_package_pointer): if ccore_package_pointer == 0: return [] pointer_package = cast(ccore_package_pointer, POINTER(pyclustering_package)) return self.__unpack_pointer_data(pointer_package) def __unpack_data(self, pointer_package, pointer_data, type_package): if type_package == pyclustering_type_data.PYCLUSTERING_TYPE_CHAR: pointer_string = cast(pointer_data, c_char_p) return pointer_string.value elif type_package == pyclustering_type_data.PYCLUSTERING_TYPE_WCHAR_T: raise NotImplementedError("Data type 'wchar_t' is not supported.") result = [] append_element = lambda container, item: container.append(item) for index in range(0, pointer_package[0].size): if type_package == pyclustering_type_data.PYCLUSTERING_TYPE_LIST: pointer_package = cast(pointer_data[index], (POINTER(pyclustering_package))) append_element(result, self.__extract_data(pointer_package)) else: append_element(result, pointer_data[index]) return result def __unpack_pointer_data(self, pointer_package): current_package = pointer_package[0] type_package = current_package.type if current_package.size == 0: return [] pointer_data = cast(current_package.data, POINTER(pyclustering_type_data.get_ctype(type_package))) return self.__unpack_data(pointer_package, pointer_data, type_package)
5,124
14,668
<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/headless/headless_window_manager.h" namespace ui { HeadlessWindowManager::HeadlessWindowManager() = default; HeadlessWindowManager::~HeadlessWindowManager() { DCHECK(thread_checker_.CalledOnValidThread()); } int32_t HeadlessWindowManager::AddWindow(HeadlessWindow* window) { return windows_.Add(window); } void HeadlessWindowManager::RemoveWindow(int32_t window_id, HeadlessWindow* window) { DCHECK_EQ(window, windows_.Lookup(window_id)); windows_.Remove(window_id); } HeadlessWindow* HeadlessWindowManager::GetWindow(int32_t window_id) { return windows_.Lookup(window_id); } } // namespace ui
302
780
<gh_stars>100-1000 from r2.lib import amqp, baseplate_integration, websockets from reddit_place.controllers import get_activity_count, ActivityError @baseplate_integration.with_root_span("job.place_activity") def broadcast_activity(): try: activity = get_activity_count() websockets.send_broadcast( namespace="/place", type="activity", payload={ "count": activity, }, ) except ActivityError: print "failed to fetch activity" # ensure the message we put on the amqp worker queue is flushed before we # exit. amqp.worker.join()
263
1,006
/**************************************************************************** * sched/init/init.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ #ifndef __SCHED_INIT_INIT_H #define __SCHED_INIT_INIT_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: nx_start * * Description: * This function is called to initialize the operating system and to spawn * the user initialization thread of execution. This is the initial entry * point into NuttX * * Input Parameters: * None * * Returned Value: * Does not return. * ****************************************************************************/ void nx_start(void); /**************************************************************************** * Name: nx_smp_start * * Description: * In an SMP configution, only one CPU is initially active (CPU 0). System * initialization occurs on that single thread. At the completion of the * initialization of the OS, just before beginning normal multitasking, * the additional CPUs would be started by calling this function. * * Input Parameters: * None * * Returned Value: * Zero on success; a negated errno value on failure. * ****************************************************************************/ #ifdef CONFIG_SMP int nx_smp_start(void); #endif /**************************************************************************** * Name: nx_idle_trampoline * * Description: * This is the common IDLE task for CPUs 1 through (CONFIG_SMP_NCPUS-1). * It is equivalent to the CPU 0 IDLE logic in nx_start.c * * Input Parameters: * Standard task arguments. * * Returned Value: * This function does not return. * ****************************************************************************/ #ifdef CONFIG_SMP void nx_idle_trampoline(void); #endif /**************************************************************************** * Name: nx_bringup * * Description: * Start all initial system tasks. This does the "system bring-up" after * the conclusion of basic OS initialization. These initial system tasks * may include: * * - pg_worker: The page-fault worker thread (only if CONFIG_PAGING is * defined. * - work_thread: The work thread. This general thread can be used to * perform most any kind of queued work. Its primary * function is to serve as the "bottom half" of device * drivers. * * And the main application entry point: * symbols: * * - INIT_ENTRYPOINT: This is the default user application entry point. * * Input Parameters: * None * * Returned Value: * None * ****************************************************************************/ int nx_bringup(void); #endif /* __SCHED_INIT_INIT_H */
1,018
544
import numpy as np import cv2 import matplotlib.pyplot as plt import torch from tqdm import tqdm from pathlib import Path import os import warnings warnings.filterwarnings('ignore') os.environ['CUDA_VISIBLE_DEVICES'] = "0" openpose_dir = Path('./src/PoseEstimation/') save_dir = Path('./data/target/') save_dir.mkdir(exist_ok=True) img_dir = save_dir.joinpath('images') img_dir.mkdir(exist_ok=True) if len(os.listdir('./data/target/images'))<100: cap = cv2.VideoCapture(str(save_dir.joinpath('mv.mp4'))) i = 0 while (cap.isOpened()): flag, frame = cap.read() if flag == False : break cv2.imwrite(str(img_dir.joinpath('{:05}.png'.format(i))), frame) if i%100 == 0: print('Has generated %d picetures'%i) i += 1 import sys sys.path.append(str(openpose_dir)) sys.path.append('./src/utils') # openpose from network.rtpose_vgg import get_model from evaluate.coco_eval import get_multiplier, get_outputs # utils from openpose_utils import remove_noise, get_pose weight_name = './src/PoseEstimation/network/weight/pose_model.pth' print('load model...') model = get_model('vgg19') model.load_state_dict(torch.load(weight_name)) model = torch.nn.DataParallel(model).cuda() model.float() model.eval() pass save_dir = Path('./data/target/') save_dir.mkdir(exist_ok=True) img_dir = save_dir.joinpath('images') img_dir.mkdir(exist_ok=True) '''make label images for pix2pix''' train_dir = save_dir.joinpath('train') train_dir.mkdir(exist_ok=True) train_img_dir = train_dir.joinpath('train_img') train_img_dir.mkdir(exist_ok=True) train_label_dir = train_dir.joinpath('train_label') train_label_dir.mkdir(exist_ok=True) train_head_dir = train_dir.joinpath('head_img') train_head_dir.mkdir(exist_ok=True) pose_cords = [] for idx in tqdm(range(len(os.listdir(str(img_dir))))): img_path = img_dir.joinpath('{:05}.png'.format(idx)) img = cv2.imread(str(img_path)) shape_dst = np.min(img.shape[:2]) oh = (img.shape[0] - shape_dst) // 2 ow = (img.shape[1] - shape_dst) // 2 img = img[oh:oh + shape_dst, ow:ow + shape_dst] img = cv2.resize(img, (512, 512)) multiplier = get_multiplier(img) with torch.no_grad(): paf, heatmap = get_outputs(multiplier, img, model, 'rtpose') r_heatmap = np.array([remove_noise(ht) for ht in heatmap.transpose(2, 0, 1)[:-1]]).transpose(1, 2, 0) heatmap[:, :, :-1] = r_heatmap param = {'thre1': 0.1, 'thre2': 0.05, 'thre3': 0.5} #TODO get_pose label, cord = get_pose(param, heatmap, paf) index = 13 crop_size = 25 try: head_cord = cord[index] except: head_cord = pose_cords[-1] # if there is not head point in picture, use last frame pose_cords.append(head_cord) head = img[int(head_cord[1] - crop_size): int(head_cord[1] + crop_size), int(head_cord[0] - crop_size): int(head_cord[0] + crop_size), :] plt.imshow(head) plt.savefig(str(train_head_dir.joinpath('pose_{}.jpg'.format(idx)))) plt.clf() cv2.imwrite(str(train_img_dir.joinpath('{:05}.png'.format(idx))), img) cv2.imwrite(str(train_label_dir.joinpath('{:05}.png'.format(idx))), label) pose_cords = np.array(pose_cords, dtype=np.int) np.save(str((save_dir.joinpath('pose.npy'))), pose_cords) torch.cuda.empty_cache()
1,489
758
<reponame>benjo456/django-admin-honeypot #!/usr/bin/env python import sys from admin_honeypot import __version__, __description__, __license__ try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages setup( name='django-admin-honeypot', version=__version__, description=__description__, long_description=open('./README.rst', 'r').read(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Framework :: Django :: 2.2', 'Framework :: Django :: 3.0', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], keywords='django admin honeypot trap', maintainer='<NAME>', maintainer_email='<EMAIL>', url='https://github.com/dmpayton/django-admin-honeypot', download_url='https://github.com/dmpayton/django-admin-honeypot/tarball/v%s' % __version__, license=__license__, include_package_data=True, packages=find_packages(), zip_safe=False, )
579