max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
841
<filename>jbpm-services/jbpm-kie-services/src/test/java/org/jbpm/kie/services/test/ProcessServiceWithEntitiesTest.java /* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.kie.services.test; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.core.util.IoUtils; import org.drools.persistence.jpa.marshaller.MappedVariable; import org.drools.persistence.jpa.marshaller.VariableEntity; import org.hibernate.LazyInitializationException; import org.jbpm.kie.services.impl.KModuleDeploymentUnit; import org.jbpm.kie.test.util.AbstractKieServicesBaseTest; import org.jbpm.services.api.model.DeploymentUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.ReleaseId; import org.kie.api.runtime.process.ProcessInstance; import org.kie.internal.runtime.conf.DeploymentDescriptor; import org.kie.internal.runtime.conf.ObjectModel; import org.kie.internal.runtime.manager.deploy.DeploymentDescriptorImpl; import org.kie.scanner.KieMavenRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.kie.scanner.KieMavenRepository.getKieMavenRepository; public class ProcessServiceWithEntitiesTest extends AbstractKieServicesBaseTest { private static final Logger logger = LoggerFactory.getLogger(ProcessServiceWithEntitiesTest.class); private static final String CASEDETAIL_JAVA = "src/main/java/example/CaseDetail.java"; private List<DeploymentUnit> units = new ArrayList<DeploymentUnit>(); @Before public void prepare() { configureServices(); logger.debug("Preparing kjar"); KieServices ks = KieServices.Factory.get(); ReleaseId releaseId = ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION); List<String> processes = new ArrayList<String>(); processes.add("repo/processes/general/entityprocessvar-process.bpmn2"); DeploymentDescriptorImpl customDescriptor = new DeploymentDescriptorImpl("org.jbpm.domain"); List<String> remotableClasses = java.util.Arrays.asList("example.CaseDetail", "org.drools.persistence.jpa.marshaller.MappedVariable"); customDescriptor.setClasses(remotableClasses); List<ObjectModel> marshallingStrategies = new ArrayList<ObjectModel>(); marshallingStrategies.add(new ObjectModel("mvel", "new org.drools.persistence.jpa.marshaller.JPAPlaceholderResolverStrategy(\"org.jbpm.test:test-module:1.0.0\", classLoader)")); customDescriptor.setMarshallingStrategies(marshallingStrategies); Map<String, String> extraResources = new HashMap<>(); extraResources.put(CASEDETAIL_JAVA, getCaseDetailEntitySource()); extraResources.put("src/main/resources/" + DeploymentDescriptor.META_INF_LOCATION, customDescriptor.toXml()); extraResources.put("src/main/resources/META-INF/persistence.xml", getPersistenceXml()); InternalKieModule kJar1 = createKieJar(ks, releaseId, processes, extraResources); File pom = new File("target/kmodule", "pom.xml"); pom.getParentFile().mkdir(); try { FileOutputStream fs = new FileOutputStream(pom); fs.write(getPom(releaseId).getBytes()); fs.close(); } catch (Exception e) { } KieMavenRepository repository = getKieMavenRepository(); repository.deployArtifact(releaseId, kJar1, pom); } @Test public void testStartProcessAndGetVariables() { assertNotNull(deploymentService); KModuleDeploymentUnit deploymentUnit = new KModuleDeploymentUnit(GROUP_ID, ARTIFACT_ID, VERSION); deploymentService.deploy(deploymentUnit); units.add(deploymentUnit); boolean isDeployed = deploymentService.isDeployed(deploymentUnit.getIdentifier()); assertTrue(isDeployed); assertNotNull(processService); Map<String, Object> params = new HashMap<String, Object>(); long processInstanceId = processService.startProcess(deploymentUnit.getIdentifier(), "processvarentity", params); assertNotNull(processInstanceId); ProcessInstance pi = processService.getProcessInstance(processInstanceId); assertNotNull(pi); Map<String, Object> variables = processService.getProcessInstanceVariables(processInstanceId); assertNotNull(variables); assertEquals(1, variables.size()); assertTrue(variables.containsKey("caseDetails")); VariableEntity varEntity = (VariableEntity) variables.get("caseDetails"); // make sure getting mapped variables does NOT throw LazyInitializationException Set<MappedVariable> mappedVariables = varEntity.getMappedVariables(); try { assertEquals(1, mappedVariables.size()); MappedVariable mappedVariable = mappedVariables.iterator().next(); assertEquals("example.CaseDetail", mappedVariable.getVariableType()); } catch(LazyInitializationException e ) { fail("Unable to retrieve mapped variables : " + e.getMessage()); } } @After public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { // do nothing in case of some failed tests to avoid next test to fail as well } } units.clear(); } close(); } private static String getPersistenceXml() { File entityTestPersistence = new File("src/test/resources/entity/entity-test-persistence.xml"); assertTrue(entityTestPersistence.exists()); return IoUtils.readFileAsString(entityTestPersistence); } private static String getCaseDetailEntitySource() { File entitySource = new File("src/test/resources/entity/entity-casedetail-source.txt"); assertTrue(entitySource.exists()); return IoUtils.readFileAsString(entitySource); } }
2,564
669
<reponame>mszhanyi/onnxruntime<filename>tools/ci_build/github/apple/package_assembly_utils.py # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import enum import json import os import pathlib import re import shutil from typing import Dict, List _script_dir = pathlib.Path(__file__).parent.resolve(strict=True) repo_root = _script_dir.parents[3] class PackageVariant(enum.Enum): Full = 0 # full ORT build with all opsets, ops, and types Mobile = 1 # minimal ORT build with reduced ops Test = -1 # for testing purposes only @classmethod def release_variant_names(cls): return [v.name for v in cls if v.value >= 0] @classmethod def all_variant_names(cls): return [v.name for v in cls] _template_variable_pattern = re.compile(r"@(\w+)@") # match "@var@" def gen_file_from_template( template_file: pathlib.Path, output_file: pathlib.Path, variable_substitutions: Dict[str, str], strict: bool = True ): """ Generates a file from a template file. The template file may contain template variables that will be substituted with the provided values in the generated output file. In the template file, template variable names are delimited by "@"'s, e.g., "@var@". :param template_file The template file path. :param output_file The generated output file path. :param variable_substitutions The mapping from template variable name to value. :param strict Whether to require the set of template variable names in the file and the keys of `variable_substitutions` to be equal. """ with open(template_file, mode="r") as template: content = template.read() variables_in_file = set() def replace_template_variable(match): variable_name = match.group(1) variables_in_file.add(variable_name) return variable_substitutions.get(variable_name, match.group(0)) content = _template_variable_pattern.sub(replace_template_variable, content) if strict and variables_in_file != variable_substitutions.keys(): variables_in_substitutions = set(variable_substitutions.keys()) raise ValueError( f"Template file variables and substitution variables do not match. " f"Only in template file: {sorted(variables_in_file - variables_in_substitutions)}. " f"Only in substitutions: {sorted(variables_in_substitutions - variables_in_file)}." ) with open(output_file, mode="w") as output: output.write(content) def copy_repo_relative_to_dir(patterns: List[str], dest_dir: pathlib.Path): """ Copies file paths relative to the repo root to a directory. The given paths or path patterns are relative to the repo root, and the repo root-relative intermediate directory structure is maintained. :param patterns The paths or path patterns relative to the repo root. :param dest_dir The destination directory. """ paths = [path for pattern in patterns for path in repo_root.glob(pattern)] for path in paths: repo_relative_path = path.relative_to(repo_root) dst_path = dest_dir / repo_relative_path os.makedirs(dst_path.parent, exist_ok=True) shutil.copy(path, dst_path) def load_json_config(json_config_file: pathlib.Path): """ Loads configuration info from a JSON file. :param json_config_file The JSON configuration file path. :return The configuration info values. """ with open(json_config_file, mode="r") as config: return json.load(config) def get_ort_version(): """ Gets the ONNX Runtime version string from the repo. :return The ONNX Runtime version string. """ with open(repo_root / "VERSION_NUMBER", mode="r") as version_file: return version_file.read().strip()
1,348
1,253
#include<bits/stdc++.h> using namespace std; vector<int> adj[100000]; stack<int> st; bool vis[1000000]; void dfs(int a) { vis[a]=1; for (int i = 0; i < adj[a].size(); i++) { int v=adj[a][i]; if(vis[v]) continue; vis[v]=1; dfs(v); } st.push(a); } int main() { int n; cin>>n; for(int i=0;i<n-1;i++) { int a,b;cin>>a>>b; adj[a].push_back(b); } dfs(1); int len=st.size(); // cout<<len<<endl; for(int i=0;i<len;i++) { cout<<st.top()<<"-->"; st.pop(); } return 0; }
282
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.css.editor.module.main; /** * * @author <EMAIL> */ public class ImageValuesModuleTest extends CssModuleTestBase { public ImageValuesModuleTest(String testName) { super(testName); } public void testProperties() { assertPropertyDeclaration("image-orientation: 90deg"); assertPropertyDeclaration("image-resolution: 300dpi"); assertPropertyDeclaration("image-resolution: from-image"); assertPropertyDeclaration("image-resolution: 300dpi from-image"); assertPropertyDeclaration("image-resolution: from-image 300dpi"); assertPropertyDeclaration("background-image:url(picture.png)"); assertPropertyDeclaration("background: linear-gradient(white, gray);"); assertPropertyDeclaration("@radial-gradient: radial-gradient(circle, #006, #00a 90%, #0000af 100%, white 100%)"); assertPropertyDeclaration("@image: linear-gradient(yellow, blue);"); assertPropertyDeclaration("@image: linear-gradient(top, yellow 0%, blue 100%);"); assertPropertyDeclaration("@image: linear-gradient(-45deg, blue, yellow);"); assertPropertyDeclaration("@image: radial-gradient(50% 50%, farthest-corner, yellow, green);"); assertPropertyDeclaration("@radial-gradient: radial-gradient(yellow, green);"); assertPropertyDeclaration("@radial-gradient: radial-gradient(center, ellipse cover, yellow 0%, green 100%);"); assertPropertyDeclaration("@radial-gradient: radial-gradient(50% 50%, farthest-corner, yellow, green);"); // assertPropertyDeclaration("@radial-gradient: radial-gradient(bottom left, farthest-side, red, yellow 50px, green);"); assertPropertyDeclaration("@radial-gradient: radial-gradient(20px 30px, 20px 20px, red, yellow, green);"); assertPropertyDeclaration("@repeating-radial-gradient:repeating-radial-gradient(20px 30px, circle contain, red, yellow, green 100%, yellow 150%, red 200%)"); assertPropertyDeclaration("@repeating-radial-gradient:repeating-radial-gradient(red, blue 20px, red 40px)"); } }
967
572
<reponame>BrendaH/django-machina """ Forum tracking models ===================== This module defines models provided by the ``forum_tracking`` application. """ from machina.apps.forum_tracking.abstract_models import ( AbstractForumReadTrack, AbstractTopicReadTrack ) from machina.core.db.models import model_factory ForumReadTrack = model_factory(AbstractForumReadTrack) TopicReadTrack = model_factory(AbstractTopicReadTrack)
134
677
<filename>introcore/include/lixfastread.h<gh_stars>100-1000 /* * Copyright (c) 2020 Bitdefender * SPDX-License-Identifier: Apache-2.0 */ #ifndef _LIXFASTREAD_H_ #define _LIXFASTREAD_H_ #include "introcore.h" INTSTATUS IntLixFsrInitMap( _In_ QWORD Gva ); void IntLixFsrUninitMap( void ); INTSTATUS IntLixFsrRead( _In_ QWORD Gva, _In_ DWORD Offset, _In_ DWORD Size, _Out_ void *Buffer ); #endif
212
5,305
<reponame>tanishiking/dotty public class Test { public static void main(String[] args) { C<String> c = new C<String>(); scala.collection.Iterable<String> ls = c.tail(); } }
68
32,544
package com.baeldung.reactive.functional; import com.baeldung.webflux.Employee; import com.baeldung.webflux.EmployeeRepository; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.List; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class EmployeeSpringFunctionalIntegrationTest { @Autowired private EmployeeFunctionalConfig config; @MockBean private EmployeeRepository employeeRepository; @Test public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { WebTestClient client = WebTestClient .bindToRouterFunction(config.getEmployeeByIdRoute()) .build(); Employee employee = new Employee("1", "Employee 1"); given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); client.get() .uri("/employees/1") .exchange() .expectStatus() .isOk() .expectBody(Employee.class) .isEqualTo(employee); } @Test public void whenGetAllEmployees_thenCorrectEmployees() { WebTestClient client = WebTestClient .bindToRouterFunction(config.getAllEmployeesRoute()) .build(); List<Employee> employees = Arrays.asList( new Employee("1", "Employee 1"), new Employee("2", "Employee 2")); Flux<Employee> employeeFlux = Flux.fromIterable(employees); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); client.get() .uri("/employees") .exchange() .expectStatus() .isOk() .expectBodyList(Employee.class) .isEqualTo(employees); } @Test public void whenUpdateEmployee_thenEmployeeUpdated() { WebTestClient client = WebTestClient .bindToRouterFunction(config.updateEmployeeRoute()) .build(); Employee employee = new Employee("1", "Employee 1 Updated"); client.post() .uri("/employees/update") .body(Mono.just(employee), Employee.class) .exchange() .expectStatus() .isOk(); verify(employeeRepository).updateEmployee(employee); } }
1,222
351
package me.ele.dna.finder; import android.text.TextUtils; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import me.ele.dna.model.MethodInfo; import me.ele.dna.util.DnaUtils; public abstract class BaseDnaFinder { protected static final int BRIDGE = 0x40; protected static final int SYNTHETIC = 0x1000; protected static final int MODIFIERS_UN = Modifier.ABSTRACT | BRIDGE | SYNTHETIC; protected Class<?> invokeClass; protected String methodName; protected List<String> paramType; protected boolean isConstruct; public BaseDnaFinder(Class<?> invokeClass, String methodName, List<String> paramType, boolean isConstruct) { this.invokeClass = invokeClass; this.methodName = methodName; this.paramType = paramType; this.isConstruct = isConstruct; } protected abstract MethodInfo getExactMethod(List<Method> methods); public MethodInfo getReflectMethodFromClazz() { List<Method> tempMethodList = new ArrayList<>(); Method[] methods = invokeClass.getMethods(); if (methods == null) { return null; } for (Method method : methods) { int modifier = method.getModifiers(); if ((modifier & Modifier.PUBLIC) != 0 && (modifier & MODIFIERS_UN) == 0) { if (methodName.equals(method.getName())) { tempMethodList.add(method); } } } return getExactMethod(tempMethodList); } protected MethodInfo createMethod(Method method, String returnType) { MethodInfo methodInfo = null; if (method != null) { Class<?>[] parameterTypes = method.getParameterTypes(); methodInfo = new MethodInfo(method, Arrays.asList(parameterTypes), returnType, this instanceof ProxyFinder, isConstruct); } return methodInfo; } /** * java.lang.Boolean#TYPE * java.lang.Character#TYPE * java.lang.Byte#TYPE * java.lang.Short#TYPE * java.lang.Integer#TYPE * java.lang.Long#TYPE * java.lang.Float#TYPE * java.lang.Double#TYPE * java.lang.Void#TYPE * * @param name * @return */ protected String wrapper(String name) { switch (name) { case "boolean": return Boolean.class.getName(); case "char": return Character.class.getName(); case "byte": return Byte.class.getName(); case "short": return Short.class.getName(); case "int": return Integer.class.getName(); case "long": return Long.class.getName(); case "float": return Float.class.getName(); case "double": return Double.class.getName(); case "void": return Void.class.getName(); default: return null; } } protected boolean isEqualType(String dartType, String javaType) { if (TextUtils.isEmpty(dartType) && TextUtils.isEmpty(javaType)) { return true; } if (TextUtils.isEmpty(dartType) || TextUtils.isEmpty(javaType)) { return false; } if (javaType.equals(Float.class.getName()) && dartType.equals(Double.class.getName())) { return true; } if (javaType.equals(Long.class.getName()) && dartType.equals(Integer.class.getName())) { return true; } if (javaType.equals(Short.class.getName()) && dartType.equals(Integer.class.getName())) { return true; } return javaType.equals(dartType); } }
1,714
1,179
<filename>src/wnetcaps.c /******************************************************************** WNetCaps.c Returns net status Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ********************************************************************/ #include "winfile.h" #include "wnetcaps.h" ///////////////////////////////////////////////////////////////////// // // Name: WNetStat // // Synopsis: Caches and returns requested network status information // // IN nIndex NS_* request // NS_REFRESH refreshes cached info // // Return: BOOL on NS_* => answer // on NS_REFRESH => unstable (FALSE) // // Assumes: nIndex < 1 << 31 and nIndex an even power of 2 // // Effects: // // // Notes: // ///////////////////////////////////////////////////////////////////// BOOL WNetStat(INT nIndex) { static DWORD fdwRet = (DWORD)-1; DWORD dwError; BOOL bNetwork = FALSE; BOOL bConnect = FALSE; HKEY hKey; DWORD dwcbBuffer = 0; if ( // // Disable NS_REFRESH since we test for network installed on disk, // not network services started. // #if NSREFRESH NS_REFRESH == nIndex || #endif (DWORD) -1 == fdwRet) { fdwRet = 0; // // Check for connection dialog // dwError = RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("System\\CurrentControlSet\\Control\\NetworkProvider\\Order"), &hKey); if (!dwError) { dwError = RegQueryValueEx(hKey, TEXT("ProviderOrder"), NULL, NULL, NULL, &dwcbBuffer); if (ERROR_SUCCESS == dwError && dwcbBuffer > 1) { bNetwork = TRUE; } RegCloseKey(hKey); } if (bNetwork) { #if 0 // // Check the registry to see if the user can make connections // dwError = RegOpenKey(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\File Manager\\Settings"), &hKey); if (dwError != ERROR_SUCCESS) { bConnect = TRUE; } else { cb = sizeof(dwTemp); dwTemp = 0; dwError = RegQueryValueEx(hKey, TEXT("Network"), NULL, NULL, (LPBYTE)&dwTemp, &cb); if (dwError != ERROR_SUCCESS || dwTemp) bConnect = TRUE; RegCloseKey(hKey); } if (bConnect) { fdwRet |= NS_CONNECTDLG|NS_CONNECT; } #else fdwRet |= NS_CONNECTDLG|NS_CONNECT; #endif } // // Check for share-ability // dwError = RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("System\\CurrentControlSet\\Services\\LanmanServer"), &hKey); if (!dwError) { fdwRet |= NS_SHAREDLG|NS_PROPERTYDLG; RegCloseKey(hKey); } } return fdwRet & nIndex ? TRUE : FALSE; }
1,483
613
<filename>Code-Code/Clone-detection-BigCloneBench/evaluator/evaluator.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import logging import sys from sklearn.metrics import recall_score,precision_score,f1_score def read_answers(filename): answers={} with open(filename) as f: for line in f: line=line.strip() idx1,idx2,label=line.split() answers[(idx1,idx2)]=int(label) return answers def read_predictions(filename): predictions={} with open(filename) as f: for line in f: line=line.strip() idx1,idx2,label=line.split() predictions[(idx1,idx2)]=int(label) return predictions def calculate_scores(answers,predictions): y_trues,y_preds=[],[] for key in answers: if key not in predictions: logging.error("Missing prediction for ({},{}) pair.".format(key[0],key[1])) sys.exit() y_trues.append(answers[key]) y_preds.append(predictions[key]) scores={} scores['Recall']=recall_score(y_trues, y_preds) scores['Prediction']=precision_score(y_trues, y_preds) scores['F1']=f1_score(y_trues, y_preds) return scores def main(): import argparse parser = argparse.ArgumentParser(description='Evaluate leaderboard predictions for BigCloneBench dataset.') parser.add_argument('--answers', '-a',help="filename of the labels, in txt format.") parser.add_argument('--predictions', '-p',help="filename of the leaderboard predictions, in txt format.") args = parser.parse_args() answers=read_answers(args.answers) predictions=read_predictions(args.predictions) scores=calculate_scores(answers,predictions) print(scores) if __name__ == '__main__': main()
757
667
<filename>api/cplus/src/lb.cpp /** * Tencent is pleased to support the open source community by making Tseer available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ #include "lb.h" #include "global.h" #include <sstream> namespace Tseerapi { int LoadBalance::getRouters(std::vector<Tseer::RouterNodeInfo> &nodeInfoVec, std::string &errMsg) { std::ostringstream os; os << FILE_FUN << "Unsupported method invocation."; errMsg = os.str(); return -1; } int LoadBalance::getRouter(Tseer::RouterNodeInfo& nodeInfo, std::string &errMsg) { std::ostringstream os; os << FILE_FUN << "Unsupported method invocation."; errMsg = os.str(); return -1; } int LoadBalance::getRouter(unsigned long long key, Tseer::RouterNodeInfo& nodeInfo, std::string &errMsg) { std::ostringstream os; os << FILE_FUN << "Unsupported method invocation."; errMsg = os.str(); return -1; } }
518
14,668
<reponame>zealoussnow/chromium // 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 "chrome/browser/media/router/mojo/media_route_provider_util_win.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/location.h" #include "base/logging.h" #include "base/path_service.h" #include "base/task/post_task.h" #include "base/task/task_runner_util.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/installer/util/firewall_manager_win.h" namespace media_router { namespace { bool DoCanFirewallUseLocalPorts() { base::FilePath exe_path; if (!base::PathService::Get(base::FILE_EXE, &exe_path)) { LOG(WARNING) << "Couldn't get path of current executable."; return false; } auto firewall_manager = installer::FirewallManager::Create(exe_path); if (!firewall_manager) { LOG(WARNING) << "Couldn't get FirewallManager instance."; return false; } return firewall_manager->CanUseLocalPorts(); } } // namespace void CanFirewallUseLocalPorts(base::OnceCallback<void(bool)> callback) { auto task_runner = base::ThreadPool::CreateCOMSTATaskRunner( {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); base::PostTaskAndReplyWithResult(task_runner.get(), FROM_HERE, base::BindOnce(&DoCanFirewallUseLocalPorts), std::move(callback)); } } // namespace media_router
589
45,293
package verification.kt33972japi; public class InheritTheJApi33972 { public void overrideMe(String s, int i, Double aDouble) { } }
49
637
<reponame>Nekoer/uncle-novel<filename>app/src/main/java/com/unclezs/novel/app/main/views/components/cell/TagsTableCell.java package com.unclezs.novel.app.main.views.components.cell; import cn.hutool.core.util.StrUtil; import com.unclezs.novel.app.framework.components.Tag; import javafx.scene.control.TableCell; import javafx.scene.layout.HBox; import java.util.ArrayList; import java.util.List; /** * 表格标签列 * * @author <EMAIL> * @date 2021/5/2 17:00 */ public class TagsTableCell<S> extends TableCell<S, String> { private final List<Tag> tags = new ArrayList<>(); private final HBox box = new HBox(); public TagsTableCell() { box.setSpacing(3); } @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); setText(null); } else { String[] tagsText = item.split(StrUtil.COMMA); box.getChildren().clear(); for (int i = 0; i < tagsText.length; i++) { if (tags.size() < i + 1) { tags.add(new Tag(tagsText[i])); } else { tags.get(i).setText(tagsText[i]); } box.getChildren().add(tags.get(i)); } setGraphic(box); } } }
536
526
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * ClassificationDef stores the properties for the definition of a type of classification. Many of the properties * are inherited from TypeDef. ClassificationDef adds a list of Entity Types that this Classification can be * connected to and a boolean to indicate if this classification is propagatable. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class ClassificationDef extends TypeDef { private static final long serialVersionUID = 1L; private List<TypeDefLink> validEntityDefs = null; private boolean propagatable = false; /** * Minimal constructor sets up an empty ClassificationDef. */ public ClassificationDef() { super(TypeDefCategory.CLASSIFICATION_DEF); } /** * Typical constructor is passed the properties of the typedef's super class being constructed. * * @param category category of this TypeDef * @param guid unique id for the TypeDef * @param name unique name for the TypeDef * @param version active version number for the TypeDef * @param versionName name for active version of the TypeDef */ public ClassificationDef(TypeDefCategory category, String guid, String name, long version, String versionName) { super(category, guid, name, version, versionName); } /** * Copy/clone constructor copies values from the supplied template. * * @param template template to copy */ public ClassificationDef(ClassificationDef template) { super(template); if (template != null) { this.setValidEntityDefs(template.getValidEntityDefs()); propagatable = template.isPropagatable(); } } /** * Delegate the process of cloning to the subclass. * * @return subclass of TypeDef */ public TypeDef cloneFromSubclass() { return new ClassificationDef(this); } /** * Return the list of identifiers for the types of entities that this type of Classification can be connected to. * * @return List of entity type identifiers */ public List<TypeDefLink> getValidEntityDefs() { if (validEntityDefs == null) { return null; } else if (validEntityDefs.isEmpty()) { return null; } else { List<TypeDefLink> resultList = new ArrayList<>(); for (TypeDefLink typeDefLink : validEntityDefs) { if (typeDefLink != null) { resultList.add(new TypeDefLink(typeDefLink)); } } return resultList; } } /** * Set up the list of identifiers for the types of entities that this type of Classification can be connected to. * * @param validEntityDefs List of entity type identifiers */ public void setValidEntityDefs(List<TypeDefLink> validEntityDefs) { if (validEntityDefs == null) { this.validEntityDefs = null; } else if (validEntityDefs.isEmpty()) { this.validEntityDefs = null; } else { List<TypeDefLink> resultList = new ArrayList<>(); for (TypeDefLink typeDefLink : validEntityDefs) { if (typeDefLink != null) { resultList.add(new TypeDefLink(typeDefLink)); } } this.validEntityDefs = resultList; } } /** * Return whether this classification should propagate to other entities if the relationship linking them * allows classification propagation. * * @return boolean flag */ public boolean isPropagatable() { return propagatable; } /** * Sets up whether this classification should propagate to other entities if the relationship linking them * allows classification propagation. * * @param propagatable boolean flag */ public void setPropagatable(boolean propagatable) { this.propagatable = propagatable; } /** * Standard toString method. * * @return JSON style description of variables. */ @Override public String toString() { return "ClassificationDef{" + "name='" + name + '\'' + ", validEntityDefs=" + validEntityDefs + ", propagatable=" + propagatable + ", superType=" + superType + ", description='" + description + '\'' + ", descriptionGUID='" + descriptionGUID + '\'' + ", origin='" + origin + '\'' + ", createdBy='" + createdBy + '\'' + ", updatedBy='" + updatedBy + '\'' + ", createTime=" + createTime + ", updateTime=" + updateTime + ", options=" + options + ", externalStandardMappings=" + externalStandardMappings + ", validInstanceStatusList=" + validInstanceStatusList + ", initialStatus=" + initialStatus + ", propertiesDefinition=" + propertiesDefinition + ", version=" + version + ", versionName='" + versionName + '\'' + ", category=" + category + ", guid='" + guid + '\'' + '}'; } /** * Validate that an object is equal depending on their stored values. * * @param objectToCompare object * @return boolean result */ @Override public boolean equals(Object objectToCompare) { if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } if (!super.equals(objectToCompare)) { return false; } ClassificationDef that = (ClassificationDef) objectToCompare; return propagatable == that.propagatable && Objects.equals(validEntityDefs, that.validEntityDefs); } /** * Return a hash code based on the values of this object. * * @return in hash code */ @Override public int hashCode() { return Objects.hash(super.hashCode(), validEntityDefs, propagatable); } }
3,164
1,040
<reponame>Ybalrid/orbiter<filename>Src/Celbody/Vsop87/Uranus/Uranus.cpp // Copyright (c) <NAME> // Licensed under the MIT License #define ORBITER_MODULE #include "Uranus.h" // ====================================================================== // class Uranus: implementation // ====================================================================== Uranus::Uranus (OBJHANDLE hCBody): VSOPOBJ (hCBody) { a0 = 19.2; // semi-major axis [AU] } void Uranus::clbkInit (FILEHANDLE cfg) { VSOPOBJ::clbkInit (cfg); ReadData ("Uranus"); } int Uranus::clbkEphemeris (double mjd, int req, double *ret) { VsopEphem (mjd, ret+6); return fmtflag | EPHEM_BARYPOS | EPHEM_BARYVEL; } int Uranus::clbkFastEphemeris (double simt, int req, double *ret) { VsopFastEphem (simt, ret+6); return fmtflag | EPHEM_BARYPOS | EPHEM_BARYVEL; } // ====================================================================== // API interface // ====================================================================== DLLCLBK void InitModule (HINSTANCE hModule) {} DLLCLBK void ExitModule (HINSTANCE hModule) {} DLLCLBK CELBODY *InitInstance (OBJHANDLE hBody) { return new Uranus (hBody); } DLLCLBK void ExitInstance (CELBODY *body) { delete (Uranus*)body; }
442
372
<gh_stars>100-1000 package org.sunger.net.app; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; import com.squareup.okhttp.OkHttpClient; import org.sunger.net.config.ImagePipelineConfigFactory; import org.sunger.net.entity.OauthUserEntity; import org.sunger.net.support.okhttp.OkHttpClientManager; import org.sunger.net.utils.DeviceUtils; import java.util.concurrent.TimeUnit; /** * Created by sunger on 2015/10/27. */ public class App extends Application { private static final int CONNECT_TIMEOUT_MILLIS = 10 * 1000; // 15s private static final int READ_TIMEOUT_MILLIS = 15 * 1000; // 20s private static App instance; private OkHttpClient okHttpClient; private OauthUserEntity entity; @Override public void onCreate() { super.onCreate(); instance = this; initOkHttp(); initFresco(); DeviceUtils.init(this); } private void initFresco() { Fresco.initialize(this, ImagePipelineConfigFactory.getOkHttpImagePipelineConfig(this,okHttpClient)); } private void initOkHttp() { okHttpClient = OkHttpClientManager.getInstance().getOkHttpClient(); okHttpClient = new OkHttpClient(); okHttpClient.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); okHttpClient.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } public void setOauth(OauthUserEntity entity) { this.entity = entity; } public OauthUserEntity getOauthUserEntity() { return entity; } public static App getInstance() { return instance; } }
638
543
<gh_stars>100-1000 /* * 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 de.mirkosertic.bytecoder.core; import de.mirkosertic.bytecoder.unittest.BytecoderUnitTestRunner; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(BytecoderUnitTestRunner.class) public class NaNTest { @Test public void testIsNaNDouble() { Assert.assertTrue(Double.isNaN(Double.NaN)); Assert.assertFalse(Double.isNaN(10d)); } @Test public void testIsNaNFloat() { Assert.assertTrue(Float.isNaN(Float.NaN)); Assert.assertFalse(Float.isNaN(10f)); } @Test public void testCastDouble() { final double d = Double.NaN; final int x = (int) d; Assert.assertEquals(0, x, 0); } @Test public void testCastFloat() { final float f = Float.NaN; final int x = (int) f; Assert.assertEquals(0, x, 0); } }
558
348
{"nom":"Dannemarie-sur-Crète","circ":"1ère circonscription","dpt":"Doubs","inscrits":876,"abs":333,"votants":543,"blancs":9,"nuls":1,"exp":533,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":156},{"nuance":"SOC","nom":"Mme <NAME>","voix":110},{"nuance":"DVD","nom":"M. <NAME>","voix":65},{"nuance":"FN","nom":"Mme <NAME>","voix":57},{"nuance":"LR","nom":"Mme <NAME>","voix":55},{"nuance":"FI","nom":"Mme <NAME>","voix":39},{"nuance":"DIV","nom":"<NAME>","voix":30},{"nuance":"ECO","nom":"M. <NAME>","voix":8},{"nuance":"DIV","nom":"M. <NAME>","voix":5},{"nuance":"ECO","nom":"Mme <NAME>","voix":4},{"nuance":"EXG","nom":"Mme <NAME>","voix":2},{"nuance":"DIV","nom":"M. <NAME>","voix":2}]}
282
3,102
<reponame>medismailben/llvm-project // RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s void *test1() { // CHECK: call i8* @llvm.returnaddress return __builtin_return_address(1); } void *test2() { // CHECK: call i8* @llvm.frameaddress return __builtin_frame_address(0); }
119
2,133
<reponame>uavosky/uavosky-qgroundcontrol<filename>src/QtLocationPlugin/qtlocation/include/QtLocation/5.5.1/QtLocation/private/qgeomaptype_p.h #include "../../../../../src/location/maps/qgeomaptype_p.h"
84
1,144
<reponame>dram/metasfresh package org.adempiere.mm.attributes.api; /* * #%L * de.metas.handlingunits.base * %% * Copyright (C) 2015 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% */ import java.util.Properties; import de.metas.util.ISingletonService; public interface ISubProducerAttributeBL extends ISingletonService { /** * Change values of the ADR attribute that is related with the sub-producer (if and when there will be more than 1 implementation, pls move this specific information to other places so that the javadoc is correct while also being informative). * <p> * If the given attribute set has no ADR attribute, then do nothing. * <p> * Retrieve the partner (i.e. the actual sup-producer) from the attribute set's subProducer attribute, falling back to HU's bpartner. If there is none, set the ADR attribute to <code>null</code> * <p> * If called with <code>subProducerInitialized==true</code>, then don't overwrite pre-existing ADR attribute values, but only set them if there aren't values set yet. This behavior is supposed to * prevent us from loosing attribute values that were explicitly set while the sub-producer was not yet set or propagated. See task <a * href="http://dewiki908/mediawiki/index.php/08782_ADR_not_correct_in_MRP_Product_Info%2C_Passende_Best%C3%A4nde">08782 ADR not correct in MRP Product Info, Passende Bestände</a> for a * bug that happens if we <i>always</i> reset/recalculate the attributes. On the other hand, if the subproducer changes, from one not-empty value to another one, then we reset the ADR attribute to * the new partner's value. * * @param ctx * @param attributeSet * @param subProducerJustInitialized <code>true</code> if the subProducer was changed from 0/null to an actual value. */ void updateAttributesOnSubProducerChanged(Properties ctx, IAttributeSet attributeSet, boolean subProducerJustInitialized); }
741
1,405
package com.network.android.roomTap; import android.content.Context; import com.network.android.c.a.a; /* access modifiers changed from: package-private */ public final class e implements Runnable { /* renamed from: a reason: collision with root package name */ final /* synthetic */ Context f118a; e(Context context) { this.f118a = context; } public final void run() { if (AutoAnswerReceiver.c) { a.a("Disconnect calling disconnectWithAireplaneMode"); AutoAnswerReceiver.h(); return; } a.a("Disconnect phone is not ofhook, calling roleBack..."); AutoAnswerReceiver.e(this.f118a); } }
267
738
<reponame>zhquake/hudi<filename>hudi-flink-datasource/hudi-flink1.14.x/src/main/java/org/apache/hudi/adapter/Utils.java<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hudi.adapter; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.streaming.api.operators.Output; import org.apache.flink.streaming.api.operators.StreamSourceContexts; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService; import org.apache.flink.streaming.runtime.tasks.StreamTask; /** * Adapter utils. */ public class Utils { public static <O> SourceFunction.SourceContext<O> getSourceContext( TimeCharacteristic timeCharacteristic, ProcessingTimeService processingTimeService, StreamTask<?, ?> streamTask, Output<StreamRecord<O>> output, long watermarkInterval) { return StreamSourceContexts.getSourceContext( timeCharacteristic, processingTimeService, new Object(), // no actual locking needed output, watermarkInterval, -1, true); } }
620
461
<filename>03-Basic-Sorting/Insertion-Sort/src/ShellSort1.java import java.util.Arrays; public class ShellSort1 { /** * 希尔排序(shell sort)1:增量每次除以 2 递减 * @param arr */ public void sort(int[] arr) { int len = arr.length; int delta = len / 2; while (delta >= 1) { // 特别注意边界的选取,可以代入具体的值验证,要有耐心 debug for (int i = len - 1; i >= len - delta; i--) { for (int j = i; j >= delta; j -= delta) { if (arr[j - delta] > arr[j]) { swap(arr, j - delta, j); } } } // System.out.println("排序过程:" + Arrays.toString(arr)); delta /= 2; } } private void swap(int[] arr, int index1, int index2) { int temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp; } public static void main(String[] args) { // write your code here int[] nums = {8, 4, 3, 6, 5, 1, 9, 7}; ShellSort1 shellSort1 = new ShellSort1(); shellSort1.sort(nums); System.out.println(Arrays.toString(nums)); } }
692
562
import os import subprocess try: VERSION = __import__("pkg_resources").get_distribution("freight").version except Exception: VERSION = "unknown" def _get_git_revision(path): try: r = subprocess.check_output("git rev-parse HEAD", cwd=path, shell=True) except Exception: return None return r.strip() def get_revision(): """ :returns: Revision number of this branch/checkout, if available. None if no revision number can be determined. """ package_dir = os.path.dirname(__file__) checkout_dir = os.path.normpath(os.path.join(package_dir, os.pardir)) path = os.path.join(checkout_dir, ".git") if os.path.exists(path): return _get_git_revision(path) return None def get_version(): base = VERSION if __build__: base = f"{base} ({__build__})" return base __build__ = get_revision() __docformat__ = "restructuredtext en"
364
2,542
<reponame>vishnuk007/service-fabric //------------------------------------------------------------ // Copyright (c) 2012 Microsoft Corporation. All rights reserved. //------------------------------------------------------------ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE KtlLoggerTest #include <boost/test/unit_test.hpp> #include "boost-taef.h" #include <ktl.h> #include <ktrace.h> #include "RvdLoggerTests.h" //#include "KtlLoggerTests.h" #define ALLOCATION_TAG 'LLT' KAllocator* g_Allocator; VOID SetupRawKtlLoggerTests( KGuid& DiskId, UCHAR& DriveLetter, ULONGLONG& StartingAllocs, KtlSystem*& System ) { NTSTATUS status; status = KtlSystem::Initialize(FALSE, // Do not enable VNetwork, we don't need it &System); VERIFY_IS_TRUE(NT_SUCCESS(status)); g_Allocator = &KtlSystem::GlobalNonPagedAllocator(); System->SetStrictAllocationChecks(TRUE); StartingAllocs = KAllocatorSupport::gs_AllocsRemaining; KDbgMirrorToDebugger = TRUE; KDbgMirrorToDebugger = 1; EventRegisterMicrosoft_Windows_KTL(); #if !defined(PLATFORM_UNIX) DriveLetter = 0; status = FindDiskIdForDriveLetter(DriveLetter, DiskId); VERIFY_IS_TRUE(NT_SUCCESS(status)); #else // {204F01E4-6DEC-48fe-8483-B2C6B79ABECB} GUID randomGuid = { 0x204f01e4, 0x6dec, 0x48fe, { 0x84, 0x83, 0xb2, 0xc6, 0xb7, 0x9a, 0xbe, 0xcb } }; DiskId = randomGuid; #endif } VOID CleanupRawKtlLoggerTests( KGuid& DiskId, ULONGLONG& StartingAllocs, KtlSystem*& System ) { UNREFERENCED_PARAMETER(DiskId); UNREFERENCED_PARAMETER(System); UNREFERENCED_PARAMETER(StartingAllocs); EventUnregisterMicrosoft_Windows_KTL(); KtlSystem::Shutdown(); } namespace KtlPhysicalLogTest { class KtlPhysicalLogTest { public: WCHAR _driveLetter[2]; public: KtlPhysicalLogTest() { Setup(); } ~KtlPhysicalLogTest() { Cleanup(); } bool Setup() { WCHAR systemDrive[32]; ULONG result = ExpandEnvironmentStringsW(L"%SYSTEMDRIVE%", (LPWSTR)systemDrive, 32); VERIFY_ARE_NOT_EQUAL((ULONG)0, result, L"Failed to get systemdrive"); VERIFY_IS_TRUE(result <= 32, L"Failed to get systemdrive"); _driveLetter[0] = systemDrive[0]; _driveLetter[1] = 0; return true; } bool Cleanup() { return true; } }; BOOST_FIXTURE_TEST_SUITE(KtlPhysicalLogTestSuite, KtlPhysicalLogTest) BOOST_AUTO_TEST_CASE(BasicDiskLoggerTest) { NTSTATUS status; PWCHAR driveLetter = _driveLetter; status = ::BasicDiskLoggerTest(1, &driveLetter); VERIFY_IS_TRUE(NT_SUCCESS(status), L"KTL Logger Testing must be run at elevated privs"); } BOOST_AUTO_TEST_CASE(AliasTest) { NTSTATUS status; PWCHAR driveLetter = _driveLetter; status = ::RvdLoggerAliasTests(1, &driveLetter); VERIFY_IS_TRUE(NT_SUCCESS(status), L"KTL Logger Testing must be run at elevated privs"); } BOOST_AUTO_TEST_CASE(StreamTest) { NTSTATUS status; PWCHAR driveLetter = _driveLetter; status = ::LogStreamAsyncIoTests(1, &driveLetter); VERIFY_IS_TRUE(NT_SUCCESS(status)); KGuid diskId; ULONGLONG startingAllocs; KtlSystem* system; UCHAR dl; SetupRawKtlLoggerTests(diskId, dl, startingAllocs, system); CleanupRawKtlLoggerTests(diskId, startingAllocs, system); // Side effect is to delete all log files } BOOST_AUTO_TEST_CASE(RecoveryTest) { NTSTATUS status; PWCHAR driveLetter = _driveLetter; status = ::RvdLoggerRecoveryTests(1, &driveLetter); VERIFY_IS_TRUE(NT_SUCCESS(status)); } BOOST_AUTO_TEST_CASE(StructVerify) { NTSTATUS status; PWCHAR driveLetter = _driveLetter; status = ::DiskLoggerStructureVerifyTests(1, &driveLetter); VERIFY_IS_TRUE(NT_SUCCESS(status)); KGuid diskId; ULONGLONG startingAllocs; KtlSystem* system; UCHAR dl; SetupRawKtlLoggerTests(diskId, dl, startingAllocs, system); CleanupRawKtlLoggerTests(diskId, startingAllocs, system); // Side effect is to delete all log files } BOOST_AUTO_TEST_CASE(ReservationsTest) { NTSTATUS status; PWCHAR driveLetter = _driveLetter; status = ::RvdLoggerReservationTests(1, &driveLetter); VERIFY_IS_TRUE(NT_SUCCESS(status)); KGuid diskId; ULONGLONG startingAllocs; KtlSystem* system; UCHAR dl; SetupRawKtlLoggerTests(diskId, dl, startingAllocs, system); CleanupRawKtlLoggerTests(diskId, startingAllocs, system); // Side effect is to delete all log files } BOOST_AUTO_TEST_SUITE_END() }
2,356
605
// RUN: rm -rf %t.idx // RUN: %clang_cc1 %s -index-store-path %t.idx // RUN: c-index-test core -print-record %t.idx | FileCheck %s // RUN: rm -rf %t.idx.ignore // RUN: %clang_cc1 %s -index-store-path %t.idx.ignore -index-ignore-macros // RUN: c-index-test core -print-record %t.idx.ignore | FileCheck %s -check-prefix DISABLED // DISABLED-NOT: macro/C // DISABLED-NOT: X1 // CHECK: macro/C | X1 | [[X1_USR:.*@macro@X1]] | <no-cgname> | Def,Ref,Undef - // CHECK: macro/C | DEF | [[DEF_USR:.*@macro@DEF]] | <no-cgname> | Def,Ref - // CHECK: macro/C | REDEF | [[REDEF_USR1:.*@macro@REDEF]] | <no-cgname> | Def,Undef - // CHECK: macro/C | REDEF | [[REDEF_USR2:.*@macro@REDEF]] | <no-cgname> | Def - // CHECK: [[@LINE+1]]:9 | macro/C | [[X1_USR]] | Def | #define X1 1 // CHECK: [[@LINE+1]]:9 | macro/C | [[DEF_USR]] | Def | #define DEF(x) int x // CHECK: [[@LINE+1]]:8 | macro/C | [[X1_USR]] | Ref #ifdef X1 #endif // CHECK: [[@LINE+1]]:8 | macro/C | [[X1_USR]] | Undef | #undef X1 // CHECK: [[@LINE+1]]:9 | macro/C | [[REDEF_USR1]] | Def | #define REDEF // CHECK: [[@LINE+1]]:8 | macro/C | [[REDEF_USR1]] | Undef | #undef REDEF // CHECK: [[@LINE+1]]:9 | macro/C | [[REDEF_USR2]] | Def | #define REDEF // FIXME: index references to builtin macros. Adding a test since this was // crashing at one point. // CHECK-NOT: [[@LINE+1]]:5 | macro/C | __LINE__ #if __LINE__ == 41 #endif // Macro references currently not supported. // CHECK: [[@LINE+2]]:1 | macro/C | [[DEF_USR]] | Ref | rel: 0 // CHECK: [[@LINE+1]]:5 | variable/C | c:@i | Def | DEF(i);
700
385
import numpy as np from vectorhub.encoders.text.tfhub import USETransformer2Vec from ....test_utils import assert_encoder_works def test_labse_encode(): """ Testing for USE encode """ import tensorflow as tf encoder = USETransformer2Vec() assert_encoder_works(encoder, vector_length=1024, data_type='text') def test_access_urls(): """Test Access to the URLS. """ urls = USETransformer2Vec.urls assert isinstance(urls, dict)
177
411
<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.giraph.utils; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.concurrent.ThreadLocalRandom; import org.junit.Assert; import org.junit.Test; public class TestVarint { private long[] genLongs(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = ThreadLocalRandom.current().nextLong(); } return res; } private int[] genInts(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = ThreadLocalRandom.current().nextInt(); } return res; } private void writeLongs(DataOutput out, long[] array) throws IOException { for (int i = 0; i < array.length; i++) { Varint.writeSignedVarLong(array[i], out); } } private void writeInts(DataOutput out, int[] array) throws IOException { for (int i = 0; i < array.length; i++) { Varint.writeSignedVarInt(array[i], out); } } private void readLongs(DataInput in, long[] array) throws IOException { for (int i = 0; i < array.length; i++) { array[i] = Varint.readSignedVarLong(in); } } private void readInts(DataInput in, int[] array) throws IOException { for (int i = 0; i < array.length; i++) { array[i] = Varint.readSignedVarInt(in); } } private void testVarLong(long value) throws IOException { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(); Varint.writeSignedVarLong(value, os); UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray()); long newValue = Varint.readSignedVarLong(is); Assert.assertEquals(Varint.sizeOfSignedVarLong(value), os.getPos()); Assert.assertEquals(value, newValue); if (value >= 0) { os = new UnsafeByteArrayOutputStream(); Varint.writeUnsignedVarLong(value, os); is = new UnsafeByteArrayInputStream(os.getByteArray()); newValue = Varint.readUnsignedVarLong(is); Assert.assertEquals(Varint.sizeOfUnsignedVarLong(value), os.getPos()); Assert.assertEquals(value, newValue); } } private void testVarInt(int value) throws IOException { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(); Varint.writeSignedVarInt(value, os); UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray()); int newValue = Varint.readSignedVarInt(is); Assert.assertEquals(Varint.sizeOfSignedVarLong(value), os.getPos()); Assert.assertEquals(value, newValue); if (value >= 0) { os = new UnsafeByteArrayOutputStream(); Varint.writeUnsignedVarInt(value, os); is = new UnsafeByteArrayInputStream(os.getByteArray()); newValue = Varint.readUnsignedVarInt(is); Assert.assertEquals(Varint.sizeOfUnsignedVarInt(value), os.getPos()); Assert.assertEquals(value, newValue); } } @Test public void testVars() throws IOException { testVarLong(0); testVarLong(Long.MIN_VALUE); testVarLong(Long.MAX_VALUE); testVarLong(-123456789999l); testVarLong(12342356789999l); testVarInt(0); testVarInt(4); testVarInt(-1); testVarInt(1); testVarInt(Integer.MIN_VALUE); testVarInt(Integer.MAX_VALUE); testVarInt(Integer.MAX_VALUE - 1); } @Test public void testVarLongSmall() throws IOException { long[] array = new long[] {1, 2, 3, -5, 0, 12345678987l, Long.MIN_VALUE}; UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(); writeLongs(os, array); long[] resArray = new long[array.length]; UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray()); readLongs(is, resArray); Assert.assertArrayEquals(array, resArray); } @Test public void testVarIntSmall() throws IOException { int[] array = new int[] {13, -2, 3, 0, 123456789, Integer.MIN_VALUE, Integer.MAX_VALUE}; UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(); writeInts(os, array); int[] resArray = new int[array.length]; UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray()); readInts(is, resArray); Assert.assertArrayEquals(array, resArray); } @Test public void testVarLongLarge() throws IOException { int n = 1000000; long[] array = genLongs(n); UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(); long startTime = System.currentTimeMillis(); writeLongs(os, array); long endTime = System.currentTimeMillis(); System.out.println("Write time: " + (endTime - startTime) / 1000.0); long[] resArray = new long[array.length]; UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray()); startTime = System.currentTimeMillis(); readLongs(is, resArray); endTime = System.currentTimeMillis(); System.out.println("Read time: " + (endTime - startTime) / 1000.0); Assert.assertArrayEquals(array, resArray); } @Test public void testVarIntLarge() throws IOException { int n = 1000000; int[] array = genInts(n); UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(); long startTime = System.currentTimeMillis(); writeInts(os, array); long endTime = System.currentTimeMillis(); System.out.println("Write time: " + (endTime - startTime) / 1000.0); int[] resArray = new int[array.length]; UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray()); startTime = System.currentTimeMillis(); readInts(is, resArray); endTime = System.currentTimeMillis(); System.out.println("Read time: " + (endTime - startTime) / 1000.0); Assert.assertArrayEquals(array, resArray); } @Test public void testSmall() throws IOException { for (int i = -100000; i <= 100000; i++) { testVarInt(i); testVarLong(i); } } }
2,373
778
<filename>modAionImpl/test/org/aion/zero/impl/vm/TransactionExecutorTest.java /* * Copyright (c) 2017-2018 Aion foundation. * * This file is part of the aion network project. * * The aion network project is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of * the License, or any later version. * * The aion network project 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 the aion network project source files. * If not, see <https://www.gnu.org/licenses/>. * * Contributors: * Aion foundation. */ package org.aion.zero.impl.vm; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import org.aion.zero.impl.types.MiningBlock; import org.aion.zero.impl.vm.common.VmFatalException; import org.aion.base.AionTransaction; import org.aion.base.TransactionTypes; import org.aion.base.TxUtil; import org.aion.crypto.ECKey; import org.aion.log.AionLoggerFactory; import org.aion.log.LogEnum; import org.aion.zero.impl.core.ImportResult; import org.aion.base.db.RepositoryCache; import org.aion.util.types.DataWord; import org.aion.types.AionAddress; import org.aion.util.conversions.Hex; import org.aion.zero.impl.vm.common.BlockCachingContext; import org.aion.zero.impl.vm.common.BulkExecutor; import org.aion.zero.impl.types.BlockContext; import org.aion.zero.impl.blockchain.StandaloneBlockchain; import org.aion.zero.impl.blockchain.StandaloneBlockchain.Builder; import org.aion.zero.impl.types.AionBlockSummary; import org.aion.zero.impl.vm.contracts.ContractUtils; import org.aion.base.AionTxExecSummary; import org.apache.commons.lang3.tuple.Pair; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; /** Tests TransactionExecutor in more of an integration style testing. */ public class TransactionExecutorTest { private static final Logger LOGGER_VM = AionLoggerFactory.getLogger(LogEnum.VM.toString()); private static final String f_func = "26121ff0"; private static final String g_func = "e2179b8e"; private StandaloneBlockchain blockchain; private ECKey deployerKey; private AionAddress deployer; private long energyPrice = 10_000_000_000L; @Before public void setup() { StandaloneBlockchain.Bundle bundle = (new StandaloneBlockchain.Builder()) .withValidatorConfiguration("simple") .withDefaultAccounts() .build(); blockchain = bundle.bc; deployerKey = bundle.privateKeys.get(0); deployer = new AionAddress(deployerKey.getAddress()); AvmTestConfig.supportOnlyAvmVersion1(); } @After public void tearDown() { blockchain = null; deployerKey = null; deployer = null; AvmTestConfig.clearConfigurations(); } @Test public void testExecutor() throws Exception { byte[] deployCode = ContractUtils.getContractDeployer("ByteArrayMap.sol", "ByteArrayMap"); long nrg = 1_000_000; long nrgPrice = energyPrice; BigInteger value = BigInteger.ZERO; BigInteger nonce = BigInteger.ZERO; AionTransaction tx = AionTransaction.create( deployerKey, nonce.toByteArray(), null, value.toByteArray(), deployCode, nrg, nrgPrice, TransactionTypes.DEFAULT, null); assertTrue(tx.isContractCreationTransaction()); assertEquals(Builder.DEFAULT_BALANCE, blockchain.getRepository().getBalance(deployer)); assertEquals(BigInteger.ZERO, blockchain.getRepository().getNonce(deployer)); BlockContext context = blockchain.createNewMiningBlockContext( blockchain.getBestBlock(), Collections.singletonList(tx), false); RepositoryCache repo = blockchain.getRepository().startTracking(); AionTxExecSummary summary = executeTransaction(repo, context, tx); BigInteger refund = summary.getRefund(); // We expect that there is a new account created, the contract, with 0 balance and 0 nonce // and that its code is the contract body. We also expect that the deployer (sender) has // its nonce incremented and its balance is now equal to its old balance minus the // transaction // fee plus the refund byte[] body = ContractUtils.getContractBody("ByteArrayMap.sol", "ByteArrayMap"); assertEquals("", summary.getReceipt().getError()); assertArrayEquals(body, summary.getResult()); AionAddress contract = TxUtil.calculateContractAddress(summary.getTransaction()); assertArrayEquals(body, repo.getCode(contract)); assertEquals(BigInteger.ZERO, repo.getBalance(contract)); assertEquals(BigInteger.ZERO, repo.getNonce(contract)); BigInteger txFee = BigInteger.valueOf(nrg).multiply(BigInteger.valueOf(nrgPrice)); assertEquals( Builder.DEFAULT_BALANCE.subtract(txFee).add(refund), repo.getBalance(deployer)); assertEquals(BigInteger.ONE, repo.getNonce(deployer)); } @Test public void testExecutorBlind() throws IOException { byte[] deployCode = ContractUtils.getContractDeployer("ByteArrayMap.sol", "ByteArrayMap"); long nrg = 1_000_000; long nrgPrice = energyPrice; BigInteger value = BigInteger.ZERO; BigInteger nonce = BigInteger.ZERO; AionTransaction tx = AionTransaction.create( deployerKey, nonce.toByteArray(), null, value.toByteArray(), deployCode, nrg, nrgPrice, TransactionTypes.DEFAULT, null); assertTrue(tx.isContractCreationTransaction()); assertEquals(Builder.DEFAULT_BALANCE, blockchain.getRepository().getBalance(deployer)); assertEquals(BigInteger.ZERO, blockchain.getRepository().getNonce(deployer)); BlockContext context = blockchain.createNewMiningBlockContext( blockchain.getBestBlock(), Collections.singletonList(tx), false); Pair<ImportResult, AionBlockSummary> result = blockchain.tryToConnectAndFetchSummary(context.block); AionBlockSummary summary = result.getRight(); assertEquals(ImportResult.IMPORTED_BEST, result.getLeft()); // We expect that there is a new account created, the contract, with 0 balance and 0 nonce // and that its code is the contract body. We also expect that the deployer (sender) has // its nonce incremented and its balance is now equal to its old balance minus the // transaction // fee plus the refund byte[] body = ContractUtils.getContractBody("ByteArrayMap.sol", "ByteArrayMap"); AionAddress contract = TxUtil.calculateContractAddress(tx); assertArrayEquals(body, blockchain.getRepository().getCode(contract)); assertEquals(BigInteger.ZERO, blockchain.getRepository().getBalance(contract)); assertEquals(BigInteger.ZERO, blockchain.getRepository().getNonce(contract)); assertEquals(BigInteger.ONE, blockchain.getRepository().getNonce(deployer)); assertEquals( Builder.DEFAULT_BALANCE.subtract( BigInteger.valueOf( summary.getReceipts().get(0).getEnergyUsed()) .multiply(BigInteger.valueOf(nrgPrice))), blockchain.getRepository().getBalance(deployer)); } @Test public void testDeployedCodeFunctionality() throws Exception { AionAddress contract = deployByteArrayContract(); byte[] callingCode = Hex.decode(f_func); BigInteger nonce = blockchain.getRepository().getNonce(deployer); AionTransaction tx = AionTransaction.create( deployerKey, nonce.toByteArray(), contract, BigInteger.ZERO.toByteArray(), callingCode, 1_000_000, energyPrice, TransactionTypes.DEFAULT, null); assertFalse(tx.isContractCreationTransaction()); BlockContext context = blockchain.createNewMiningBlockContext( blockchain.getBestBlock(), Collections.singletonList(tx), false); RepositoryCache repo = blockchain.getRepository().startTracking(); AionTxExecSummary summary = executeTransaction(repo, context, tx); assertEquals("", summary.getReceipt().getError()); System.out.println(Hex.toHexString(summary.getResult())); // We called the function f() which returns nothing. assertEquals(0, summary.getReceipt().getTransactionOutput().length); byte[] body = ContractUtils.getContractBody("ByteArrayMap.sol", "ByteArrayMap"); assertArrayEquals(body, blockchain.getRepository().getCode(contract)); // Now we call the g() function, which returns a byte array of 1024 bytes that starts with // 'a' and ends with 'b' callingCode = Hex.decode(g_func); nonce = repo.getNonce(deployer); tx = AionTransaction.create( deployerKey, nonce.toByteArray(), contract, BigInteger.ZERO.toByteArray(), callingCode, 1_000_000, energyPrice, TransactionTypes.DEFAULT, null); assertFalse(tx.isContractCreationTransaction()); context = blockchain.createNewMiningBlockContext( blockchain.getBestBlock(), Collections.singletonList(tx), false); summary = executeTransaction(repo, context, tx); System.out.println(Hex.toHexString(summary.getResult())); System.out.println(summary.getResult().length); // // I'm guessing: first data word is the number of bytes that follows. Then those // following // // bytes denote the size of the output, which follows these last bytes. // int len = new DataWordImpl(Arrays.copyOfRange(output, 0, // DataWordImpl.BYTES)).intValue(); // byte[] outputLen = new byte[len]; // System.arraycopy(output, DataWordImpl.BYTES, outputLen, 0, len); // int outputSize = new BigInteger(outputLen).intValue(); // // byte[] expected = new byte[1024]; // expected[0] = 'a'; // expected[1023] = 'b'; // // byte[] out = new byte[outputSize]; // System.arraycopy(output, DataWordImpl.BYTES + len, out, 0, outputSize); byte[] expected = new byte[1024]; expected[0] = 'a'; expected[1023] = 'b'; byte[] out = extractActualOutput(summary.getResult()); assertArrayEquals(expected, out); } @Test public void testGfunction() throws Exception { AionAddress contract = deployByteArrayContract(); byte[] callingCode = Hex.decode(g_func); BigInteger nonce = blockchain.getRepository().getNonce(deployer); AionTransaction tx = AionTransaction.create( deployerKey, nonce.toByteArray(), contract, BigInteger.ZERO.toByteArray(), callingCode, 1_000_000, energyPrice, TransactionTypes.DEFAULT, null); assertFalse(tx.isContractCreationTransaction()); BlockContext context = blockchain.createNewMiningBlockContext( blockchain.getBestBlock(), Collections.singletonList(tx), false); RepositoryCache repo = blockchain.getRepository().startTracking(); AionTxExecSummary summary = executeTransaction(repo, context, tx); System.out.println(summary.getReceipt()); // System.out.println(Hex.toHexString(res.getOutput())); // System.out.println(res.getOutput().length); byte[] out = extractActualOutput(summary.getResult()); assertEquals(0, out.length); } // <-----------------------------------------HELPERS-------------------------------------------> private AionAddress deployByteArrayContract() throws IOException { byte[] deployCode = ContractUtils.getContractDeployer("ByteArrayMap.sol", "ByteArrayMap"); long nrg = 1_000_000; long nrgPrice = energyPrice; BigInteger value = BigInteger.ZERO; BigInteger nonce = BigInteger.ZERO; AionTransaction tx = AionTransaction.create( deployerKey, nonce.toByteArray(), null, value.toByteArray(), deployCode, nrg, nrgPrice, TransactionTypes.DEFAULT, null); assertTrue(tx.isContractCreationTransaction()); assertEquals(Builder.DEFAULT_BALANCE, blockchain.getRepository().getBalance(deployer)); assertEquals(BigInteger.ZERO, blockchain.getRepository().getNonce(deployer)); BlockContext context = blockchain.createNewMiningBlockContext( blockchain.getBestBlock(), Collections.singletonList(tx), false); blockchain.tryToConnect(context.block); return TxUtil.calculateContractAddress(tx); } private byte[] extractActualOutput(byte[] rawOutput) { // I'm guessing: first data word is the number of bytes that follows. Then those following // bytes denote the size of the output, which follows these last bytes. int len = new DataWord(Arrays.copyOfRange(rawOutput, 0, DataWord.BYTES)).intValue(); byte[] outputLen = new byte[len]; System.arraycopy(rawOutput, DataWord.BYTES, outputLen, 0, len); int outputSize = new BigInteger(outputLen).intValue(); byte[] out = new byte[outputSize]; System.arraycopy(rawOutput, DataWord.BYTES + len, out, 0, outputSize); return out; } private AionTxExecSummary executeTransaction( RepositoryCache repo, BlockContext context, AionTransaction transaction) throws VmFatalException { MiningBlock block = context.block; return BulkExecutor.executeTransactionWithNoPostExecutionWork( block.getDifficulty(), block.getNumber(), block.getTimestamp(), block.getNrgLimit(), block.getCoinbase(), transaction, repo, false, true, false, false, LOGGER_VM, BlockCachingContext.PENDING, block.getNumber() - 1, false, false); } }
6,948
852
<filename>DQM/HLTEvF/python/HLTObjectsMonitor_EGM_cfi.py import FWCore.ParameterSet.Config as cms egmObjects = cms.VPSet( cms.PSet( pathNAME = cms.string("HLT_DoubleEle33_CaloIdL_MW"), moduleNAME = cms.string("hltDiEle33CaloIdLMWPMS2UnseededFilter"), label = cms.string("unseeded electron"), xTITLE = cms.string("unseeded electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_DoubleEle33_CaloIdL_MW"), moduleNAME = cms.string("hltEle33CaloIdLMWPMS2Filter"), label = cms.string("L1 seeded electron"), xTITLE = cms.string("L1 seeded electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_DoublePhoton33_CaloIdL"), moduleNAME = cms.string("hltDiEG33CaloIdLClusterShapeUnseededFilter"), label = cms.string("unseeded caloIdL photon"), xTITLE = cms.string("unseeded caloIdL photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_DoublePhoton33_CaloIdL"), moduleNAME = cms.string("hltEG33CaloIdLClusterShapeFilter"), label = cms.string("L1 seeded photon"), xTITLE = cms.string("L1 seeded photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,50.,100.,150.,200.,250.,300.,350.,400.,450.,470.,480.,490.,500.,510.,520.,530.,540.,550.,560.,570.,580.,590.,600.,610.,620.,650.,1000.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_CaloJet500_NoJetID"), moduleNAME = cms.string("hltSingleCaloJet500"), label = cms.string("calo jet 500"), xTITLE = cms.string("calo jet"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.5,-1.0,-0.5,0.,0.5,1.0,1.5,2.0,2.5,3.), ptBINNING = cms.vdouble(0.,50.,100.,150.,200.,250.,300.,350.,400.,450.,470.,480.,490.,500.,510.,520.,530.,550.,600.,650.,1000.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(0.,20.,40.,60.,80.,100.,120.,140.,160.,180.,200.), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(True), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_CaloJet550_NoJetID"), moduleNAME = cms.string("hltSingleCaloJet550"), label = cms.string("calo jet 550"), xTITLE = cms.string("calo jet"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.5,-1.0,-0.5,0.,0.5,1.0,1.5,2.0,2.5,3.), ptBINNING = cms.vdouble(0.,50.,100.,150.,200.,250.,300.,350.,400.,450.,470.,480.,490.,500.,510.,520.,530.,540.,550.,560.,570.,580.,590.,600.,610.,620.,650.,1000.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(0.,20.,40.,60.,80.,100.,120.,140.,160.,180.,200.), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(True), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Photon300_NoHE"), moduleNAME = cms.string("hltEG300erEtFilter"), label = cms.string("high-pT photon"), xTITLE = cms.string("high-pT photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_DoublePhoton70"), moduleNAME = cms.string("hltDiEG70HEUnseededFilter"), label = cms.string("unseeded photon70"), xTITLE = cms.string("unseeded photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_DoublePhoton70"), moduleNAME = cms.string("hltEG70HEFilter"), label = cms.string("L1 seeded photon70"), xTITLE = cms.string("L1 seeded photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(False), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_DoublePhoton85"), moduleNAME = cms.string("hltDiEG85HEUnseededFilter"), label = cms.string("unseeded photon85"), xTITLE = cms.string("unseeded photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(False), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_DoublePhoton85"), moduleNAME = cms.string("hltEG85HEFilter"), label = cms.string("L1 seeded photon85"), xTITLE = cms.string("L1 seeded photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(False), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_DiSC30_18_EIso_AND_HE_Mass70"), moduleNAME = cms.string("hltEG30EIso15HE30EcalIsoLastFilter"), label = cms.string("unseeded super cluster"), xTITLE = cms.string("unseeded super cluster"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(False), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_DiSC30_18_EIso_AND_HE_Mass70"), moduleNAME = cms.string("hltEG18EIso15HE30EcalIsoUnseededFilter"), label = cms.string("seeded super cluster"), xTITLE = cms.string("seeded super cluster"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(False), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_Ele23_Ele12_CaloIdL_TrackIdL_IsoVL_DZ"), moduleNAME = cms.string("hltEle23Ele12CaloIdLTrackIdLIsoVLDZFilter"), label = cms.string("double electron dz"), xTITLE = cms.string("electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(True), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(True), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_Ele23_Ele12_CaloIdL_TrackIdL_IsoVL"), moduleNAME = cms.string("hltEle23Ele12CaloIdLTrackIdLIsoVLTrackIsoLeg2Filter"), label = cms.string("iso electron2"), xTITLE = cms.string("iso electron_{2}"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(False), displayInPrimary_dz = cms.bool(True), displayInPrimary_dimass = cms.bool(True), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(True), doPlotDiMass = cms.untracked.bool(True), ), cms.PSet( pathNAME = cms.string("HLT_Ele23_Ele12_CaloIdL_TrackIdL_IsoVL"), moduleNAME = cms.string("hltEle23Ele12CaloIdLTrackIdLIsoVLTrackIsoLeg1Filter"), label = cms.string("iso electron1"), xTITLE = cms.string("iso electron_{1}"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Ele27_WPTight_Gsf"), moduleNAME = cms.string("hltEle27WPTightGsfTrackIsoFilter"), label = cms.string("iso GSF electron27"), xTITLE = cms.string("iso GSF electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Ele32_WPTight_Gsf"), moduleNAME = cms.string("hltEle32noerWPTightGsfTrackIsoFilter"), label = cms.string("iso GSF electron32"), xTITLE = cms.string("iso GSF electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Ele38_WPTight_Gsf"), moduleNAME = cms.string("hltEle38noerWPTightGsfTrackIsoFilter"), label = cms.string("iso GSF electron38"), xTITLE = cms.string("iso GSF electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Ele40_WPTight_Gsf"), moduleNAME = cms.string("hltEle40noerWPTightGsfTrackIsoFilter"), label = cms.string("iso GSF electron40"), xTITLE = cms.string("iso GSF electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Photon200"), moduleNAME = cms.string("hltEG200HEFilter"), label = cms.string("photon200HE"), xTITLE = cms.string("photon"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,50.,100.,150.,160.,170.,180.,190.,200.,210.,220.,230.,240.,250.,300.,350.,400.,1000.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_ECALHT800"), moduleNAME = cms.string("hltHtEcal800"), label = cms.string("ECAL HT"), xTITLE = cms.string("HT"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.5,-1.0,-0.5,0.,0.5,1.0,1.5,2.0,2.5,3.), ptBINNING = cms.vdouble(0.,100.,200.,300.,400.,500.,600.,650.,700.,750.,800.,850.,900.,950.,1000.,1100.,1200.,1300.,), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Ele32_WPTight_Gsf_L1DoubleEG"), moduleNAME = cms.string("hltEle32L1DoubleEGWPTightGsfTrackIsoFilter"), label = cms.string("iso GSF electron32 L1 doubleEG"), xTITLE = cms.string("iso GSF electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), cms.PSet( pathNAME = cms.string("HLT_Ele35_WPTight_Gsf_L1DoubleEG"), moduleNAME = cms.string("hltEle35L1DoubleEGWPTightGsfTrackIsoFilter"), label = cms.string("iso GSF electron35 L1 doubleEG"), xTITLE = cms.string("iso GSF electron"), etaBINNING = cms.vdouble(-3.,-2.5,-2.0,-1.7,-1.566,-1.4442,-1.3,-1.0,-0.5,0,0.5,1.,1.3,1.4442,1.566,1.7,2.0,2.5,3.0), ptBINNING = cms.vdouble(0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,110.,120.,130.,140.,150.,160.,170.,180.,190.,200.), phiBINNING = cms.vdouble(-3.2,-3.,-2.8,-2.6,-2.4,-2.2,-2.0,-1.8,-1.6,-1.4,-1.2,-1.0,-0.8,-0.6,-0.4,-0.2,0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0,3.2), massBINNING = cms.vdouble(), dxyBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dzBINNING = cms.vdouble(-2.0,-1.5,-1.0,-0.8,-0.6,-0.4,-0.2,-0.1,-0.05,-0.025,0.0,0.025,0.05,0.1,0.2,0.4,0.6,0.8,1.0,1.5,2.0), dimassBINNING = cms.vdouble(0.,2.0,4.0,6.0,8.0,10.,12.,14.,20.,40.,60.,70.,80.,84.,86.,88.,90.,92.,94.,96.,100.,120.,140.,160.,200.), displayInPrimary_eta = cms.bool(True), displayInPrimary_phi = cms.bool(True), displayInPrimary_pt = cms.bool(True), displayInPrimary_mass = cms.bool(False), displayInPrimary_energy = cms.bool(False), displayInPrimary_csv = cms.bool(False), displayInPrimary_etaVSphi = cms.bool(True), displayInPrimary_pt_HEP17 = cms.bool(True), displayInPrimary_pt_HEM17 = cms.bool(True), displayInPrimary_MR = cms.bool(False), displayInPrimary_RSQ = cms.bool(False), displayInPrimary_dxy = cms.bool(True), displayInPrimary_dz = cms.bool(False), displayInPrimary_dimass = cms.bool(False), doPlot2D = cms.untracked.bool(True), doPlotETA = cms.untracked.bool(True), doPlotMASS = cms.untracked.bool(False), doPlotENERGY = cms.untracked.bool(False), doPlotHEP17 = cms.untracked.bool(True), doPlotCSV = cms.untracked.bool(False), doCALO = cms.untracked.bool(False), doPF = cms.untracked.bool(False), doPlotRazor = cms.untracked.bool(False), doPlotDXY = cms.untracked.bool(False), # missing electron collection doPlotDZ = cms.untracked.bool(False), doPlotDiMass = cms.untracked.bool(False), ), )
36,889
30,023
"""Constants for the elmax-cloud integration.""" from homeassistant.const import Platform DOMAIN = "elmax" CONF_ELMAX_USERNAME = "username" CONF_ELMAX_PASSWORD = "password" CONF_ELMAX_PANEL_ID = "panel_id" CONF_ELMAX_PANEL_PIN = "panel_pin" CONF_ELMAX_PANEL_NAME = "panel_name" CONF_CONFIG_ENTRY_ID = "config_entry_id" CONF_ENDPOINT_ID = "endpoint_id" ELMAX_PLATFORMS = [Platform.SWITCH] POLLING_SECONDS = 30 DEFAULT_TIMEOUT = 10.0
186
30,023
"""Support for DSMR Reader through MQTT.""" from __future__ import annotations from homeassistant.components import mqtt from homeassistant.components.sensor import SensorEntity from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.util import slugify from .definitions import SENSORS, DSMRReaderSensorEntityDescription DOMAIN = "dsmr_reader" async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up DSMR Reader sensors.""" async_add_entities(DSMRSensor(description) for description in SENSORS) class DSMRSensor(SensorEntity): """Representation of a DSMR sensor that is updated via MQTT.""" entity_description: DSMRReaderSensorEntityDescription def __init__(self, description: DSMRReaderSensorEntityDescription) -> None: """Initialize the sensor.""" self.entity_description = description slug = slugify(description.key.replace("/", "_")) self.entity_id = f"sensor.{slug}" async def async_added_to_hass(self): """Subscribe to MQTT events.""" @callback def message_received(message): """Handle new MQTT messages.""" if self.entity_description.state is not None: self._attr_native_value = self.entity_description.state(message.payload) else: self._attr_native_value = message.payload self.async_write_ha_state() await mqtt.async_subscribe( self.hass, self.entity_description.key, message_received, 1 )
646
731
<gh_stars>100-1000 #ifndef _GUID_DEFINITION_HPP #define _GUID_DEFINITION_HPP #include <initguid.h> // Actually, we should link uuid library, but we define only the necessary GUID here // to avoid causing the multiple definition with the explicit GUID of wxWidgets. // You can refer the well-known GUID. // https://www.magnumdb.com/search?q=IID_IUIAutomation+CLSID_CUIAutomation DEFINE_GUID(IID_IUIAutomation, 0x30cbe57d, 0xd9d0, 0x452a, 0xab, 0x13, 0x7a, 0xc5, 0xac, 0x48, 0x25, 0xee) ; DEFINE_GUID(CLSID_CUIAutomation, 0xff48dba4, 0x60ef, 0x4201, 0xaa, 0x87, 0x54, 0x10, 0x3e, 0xef, 0x59, 0x4e) ; #endif
280
898
<filename>heroic-component/src/main/java/com/spotify/heroic/shell/protocol/MessageBuilder.java /* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.shell.protocol; import com.google.protobuf.ByteString; import com.spotify.heroic.proto.ShellMessage.CommandEvent; import com.spotify.heroic.proto.ShellMessage.CommandsResponse; import com.spotify.heroic.proto.ShellMessage.FileEvent; import com.spotify.heroic.proto.ShellMessage.FileStream; import com.spotify.heroic.proto.ShellMessage.Message; import java.util.List; public class MessageBuilder { public static Message acknowledge() { final Message.Builder builder = Message.newBuilder(); builder.getAcknowledgeBuilder(); return builder.build(); } public static Message evaluateRequest(final List<String> commands) { final Message.Builder builder = Message.newBuilder(); builder.getEvaluateRequestBuilder().addAllCommand(commands); return builder.build(); } public static Message commandEvent(CommandEvent.Event event) { final Message.Builder builder = Message.newBuilder(); builder.getCommandEventBuilder().setEvent(event); return builder.build(); } public static Message commandEvent(CommandEvent.Event event, String data) { final Message.Builder builder = Message.newBuilder(); builder.getCommandEventBuilder().setEvent(event).setData(data); return builder.build(); } public static Message commandsResponse(Iterable<CommandsResponse.CommandDefinition> commands) { final Message.Builder builder = Message.newBuilder(); builder.getCommandsResponseBuilder().addAllCommands(commands); return builder.build(); } public static Message fileEvent(Integer handle, FileEvent.Event event) { final Message.Builder builder = Message.newBuilder(); builder.getFileEventBuilder().setHandle(handle).setEvent(event); return builder.build(); } public static Message fileRead(int handle, int length) { final Message.Builder builder = Message.newBuilder(); builder.getFileReadBuilder().setHandle(handle).setLength(length); return builder.build(); } public static Message fileReadResult(ByteString bytes) { final Message.Builder builder = Message.newBuilder(); builder.getFileReadResultBuilder().setDataBytes(bytes); return builder.build(); } public static Message fileStream(String path, FileStream.Type type) { final Message.Builder builder = Message.newBuilder(); builder.getFileStreamBuilder().setPath(path).setType(type); return builder.build(); } public static Message fileWrite(int handle, ByteString data) { final Message.Builder builder = Message.newBuilder(); builder.getFileWriteBuilder().setHandle(handle).setDataBytes(data); return builder.build(); } }
1,163
839
<gh_stars>100-1000 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jca.core.classloader; import java.io.*; import java.net.*; import java.util.*; import java.util.logging.Logger; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.jca.jarloader.JarLoader; public final class PlugInClassLoaderHelper { private static final Logger LOG = LogUtils.getL7dLogger(PlugInClassLoaderHelper.class); private static Map<String, byte[]> nonClassesMap = new HashMap<>(); private PlugInClassLoaderHelper() { // singleton } public static boolean hasResource(String name) { try { return getResourceAsBytes(name) != null; } catch (IOException ex) { LOG.fine("unexpected exception: " + ex); return false; } } public static byte[] getResourceAsBytes(String name) throws IOException { // check nonClassCache for properties etc.. if (!name.endsWith(".class") && nonClassesMap.containsKey(name)) { return nonClassesMap.get(name); } // first check file path directorys, then check jars if (!isJarReference(name)) { // try direct load of url try { return JarLoader.getBytesFromInputStream(new URL(name).openStream()); } catch (java.net.MalformedURLException mue) { throw new IOException(mue.getMessage()); } } // something with !/ // check for a nested directory reference if (isNestedDirectoryReference(name)) { throw new IOException( "Accessing contents of directories within jars is currently not supported"); } String enclosingJar = name.substring(0, name.lastIndexOf("!/") + 2); String resourceName = name.substring(name.lastIndexOf("!/") + 2); Map<?, ?> jarMap = JarLoader.getJarContents(enclosingJar); if (null != jarMap && jarMap.containsKey(resourceName)) { byte[] bytes = (byte[])jarMap.get(resourceName); // this class will not be looked for again // once it is loaded so to save memory we // remove it form the map, if it is not a // class we add it to the nonClasses cache, // this is only true for in memory cache. // REVISIT - this needs to be more specific, // some classes Home|Remote interfaces are // loaded multiple times - see remote class // downloading for the moment disable this // jarMap.remove(resourceName); // if (!name.endsWith(".class")) { nonClassesMap.put(name, bytes); } return bytes; } // failed to locate the resource return null; } private static boolean isJarReference(String name) { return name.indexOf("!/") != -1; } private static boolean isNestedDirectoryReference(String path) { String nestedDir = path.substring(path.lastIndexOf("!/") + 2); return !"".equals(nestedDir) && nestedDir.endsWith("/"); } }
1,498
318
package org.neo4j.ogm.domain.autoindex; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.RelationshipEntity; /** * @author <NAME> */ @RelationshipEntity(type = "SAME_TYPE") public class RelationshipEntityWithSameType1 { @Id private Long id; }
106
719
version https://git-lfs.github.com/spec/v1 oid sha256:0db39a84fc660f0b9f0411d0c47ee64e2edeec7bc16cac8de33186471c67135d size 8308
66
504
/*********************************************************************** * * Copyright (c) Berkeley Softworks 1989 -- All Rights Reserved * * PROJECT: PCGEOS * MODULE: Swat -- X11 interface, common definitions * FILE: x11.h * * AUTHOR: <NAME>: Jul 18, 1989 * * REVISION HISTORY: * Date Name Description * ---- ---- ----------- * 7/18/89 ardeb Initial version * * DESCRIPTION: * Common definitions for the X11 interface * * * $Id: x11.h,v 1.1 89/07/21 04:03:12 adam Exp $ * ***********************************************************************/ #ifndef _X11_H_ #define _X11_H_ #define Boolean XtBool #define Opaque XtOpaque #include <X11/StringDefs.h> #include <X11/Intrinsic.h> #undef Opaque #undef Boolean extern Widget shell, /* Top-most window */ tty, /* Main I/O window */ curWin; /* Current text window */ extern XtAppContext ctxt; /* Context to which above are attached */ extern Display *dpy; /* Display connection */ extern Time lastEvent; /* Timestamp from last-received event */ /* * State Of The Interface */ extern int x11Flags; #define X11_GETCHAR 0x00000001 /* Set if fetching a character */ #define X11_ECHO 0x00000002 /* Set if should echo fetched character */ #define X11_GETCMD 0x00000004 /* Set if fetching a command */ #define X11_GETLINE 0x00000008 /* Set if fetching just a line */ #endif /* _X11_H_ */
528
852
<reponame>ckamtsikis/cmssw import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer ecalPreshowerRecoSummary = DQMEDAnalyzer('ESRecoSummary', prefixME = cms.untracked.string('EcalPreshower'), superClusterCollection_EE = cms.InputTag("correctedMulti5x5SuperClustersWithPreshower"), recHitCollection_ES = cms.InputTag("ecalPreshowerRecHit","EcalRecHitsES"), ClusterCollectionX_ES = cms.InputTag("multi5x5SuperClustersWithPreshower","preshowerXClusters"), ClusterCollectionY_ES = cms.InputTag("multi5x5SuperClustersWithPreshower","preshowerYClusters"), )
244
335
<reponame>zhouruqin/MaskNet import torch import torch.nn as nn import torch.nn.functional as F def rmseOnFeatures(feature_difference): # |feature_difference| should be 0 gt = torch.zeros_like(feature_difference) return torch.nn.functional.mse_loss(feature_difference, gt, size_average=False) class RMSEFeaturesLoss(nn.Module): def __init__(self): super(RMSEFeaturesLoss, self).__init__() def forward(self, feature_difference): return rmseOnFeatures(feature_difference)
167
1,127
<reponame>ryanloney/openvino-1 // Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <sys/stat.h> #if (defined(_WIN32) || defined(_WIN64) ) #include "win_usb.h" #include "win_time.h" #include "win_pthread.h" #else #include <unistd.h> #include <getopt.h> #include <libusb.h> #include <pthread.h> #endif #include "usb_boot.h" #include "XLinkStringUtils.h" #include "XLinkPublicDefines.h" #define DEFAULT_VID 0x03E7 #define DEFAULT_WRITE_TIMEOUT 2000 #define DEFAULT_CONNECT_TIMEOUT 20000 #define DEFAULT_SEND_FILE_TIMEOUT 10000 #define USB1_CHUNKSZ 64 #define MVLOG_UNIT_NAME xLinkUsb #include "XLinkLog.h" /* * ADDRESS_BUFF_SIZE 35 = 4*7+7. * '255-' x 7 (also gives us nul-terminator for last entry) * 7 => to add "-maXXXX" */ #define ADDRESS_BUFF_SIZE 35 #define OPEN_DEV_ERROR_MESSAGE_LENGTH 128 static unsigned int bulk_chunklen = DEFAULT_CHUNKSZ; static int write_timeout = DEFAULT_WRITE_TIMEOUT; static int connect_timeout = DEFAULT_CONNECT_TIMEOUT; static int initialized; typedef struct { int pid; char name[10]; } deviceBootInfo_t; static deviceBootInfo_t supportedDevices[] = { #if 0 // Myriad 2 device has been deprecated since 2020.4 release { .pid = 0x2150, .name = "ma2450" }, #endif { .pid = 0x2485, .name = "ma2480" }, { //To support the case where the port name change, or it's already booted .pid = DEFAULT_OPENPID, .name = "" } }; // for now we'll only use the loglevel for usb boot. can bring it into // the rest of usblink later // use same levels as mvnc_loglevel for now #if (defined(_WIN32) || defined(_WIN64) ) void initialize_usb_boot() { if (initialized == 0) { usb_init(); } // We sanitize the situation by trying to reset the devices that have been left open initialized = 1; } #else void __attribute__((constructor)) usb_library_load() { initialized = !libusb_init(NULL); } void __attribute__((destructor)) usb_library_unload() { if(initialized) libusb_exit(NULL); } #endif typedef struct timespec highres_time_t; static inline void highres_gettime(highres_time_t *ptr) { clock_gettime(CLOCK_REALTIME, ptr); } static inline double highres_elapsed_ms(highres_time_t *start, highres_time_t *end) { struct timespec temp; if((end->tv_nsec - start->tv_nsec) < 0) { temp.tv_sec = end->tv_sec - start->tv_sec - 1; temp.tv_nsec = 1000000000 + end->tv_nsec-start->tv_nsec; } else { temp.tv_sec = end->tv_sec - start->tv_sec; temp.tv_nsec = end->tv_nsec - start->tv_nsec; } return (double)(temp.tv_sec * 1000) + (((double)temp.tv_nsec) * 0.000001); } static const char *get_pid_name(int pid) { int n = sizeof(supportedDevices)/sizeof(supportedDevices[0]); int i; for (i = 0; i < n; i++) { if (supportedDevices[i].pid == pid) return supportedDevices[i].name; } return NULL; } const char * usb_get_pid_name(int pid) { return get_pid_name(pid); } int get_pid_by_name(const char* name) { char* p = strchr(name, '-'); if (p == NULL) { mvLog(MVLOG_DEBUG, "Device name (%s) not supported", name); return -1; } p++; //advance to point to the name int i; int n = sizeof(supportedDevices)/sizeof(supportedDevices[0]); for (i = 0; i < n; i++) { if (strcmp(supportedDevices[i].name, p) == 0) return supportedDevices[i].pid; } return -1; } static int is_pid_supported(int pid) { int n = sizeof(supportedDevices)/sizeof(supportedDevices[0]); int i; for (i = 0; i < n; i++) { if (supportedDevices[i].pid == pid) return 1; } return 0; } static int isMyriadDevice(const int idVendor, const int idProduct) { // Device is Myriad and pid supported if (idVendor == DEFAULT_VID && is_pid_supported(idProduct) == 1) return 1; // Device is Myriad and device booted if (idVendor == DEFAULT_OPENVID && idProduct == DEFAULT_OPENPID) return 1; return 0; } static int isBootedMyriadDevice(const int idVendor, const int idProduct) { // Device is Myriad, booted device pid if (idVendor == DEFAULT_VID && idProduct == DEFAULT_OPENPID) { return 1; } return 0; } static int isNotBootedMyriadDevice(const int idVendor, const int idProduct) { // Device is Myriad, pid supported and it's is not booted device if (idVendor == DEFAULT_VID && is_pid_supported(idProduct) == 1 && idProduct != DEFAULT_OPENPID) { return 1; } return 0; } #if (!defined(_WIN32) && !defined(_WIN64) ) static const char *gen_addr(libusb_device *dev, int pid) { static char buff[ADDRESS_BUFF_SIZE]; uint8_t pnums[7]; int pnum_cnt, i; char *p; pnum_cnt = libusb_get_port_numbers(dev, pnums, 7); if (pnum_cnt == LIBUSB_ERROR_OVERFLOW) { // shouldn't happen! mv_strcpy(buff, ADDRESS_BUFF_SIZE, "<error>"); return buff; } p = buff; #ifdef XLINK_USE_BUS uint8_t bus = libusb_get_bus_number(dev); p += snprintf(p, sizeof(buff), "%u.", bus); #endif for (i = 0; i < pnum_cnt - 1; i++) p += snprintf(p, sizeof(buff),"%u.", pnums[i]); p += snprintf(p, sizeof(buff),"%u", pnums[i]); const char* dev_name = get_pid_name(pid); if (dev_name != NULL) { snprintf(p, sizeof(buff),"-%s", dev_name); } else { mv_strcpy(buff, ADDRESS_BUFF_SIZE,"<error>"); return buff; } return buff; } static pthread_mutex_t globalMutex = PTHREAD_MUTEX_INITIALIZER; /** * @brief Find usb device address * @param input_addr Device name (address) which would be returned. If not empty, we will try to * find device with this name * * @details * Find any device (device = 0): * <br> 1) Any myriad device: vid = AUTO_VID & pid = AUTO_PID * <br> 2) Any not booted myriad device: vid = AUTO_VID & pid = AUTO_UNBOOTED_PID * <br> 3) Any booted myriad device: vid = AUTO_VID & pid = DEFAULT_OPENPID * <br> 4) Specific Myriad 2 or Myriad X device: vid = AUTO_VID & pid = DEFAULT_UNBOOTPID_2485 or DEFAULT_UNBOOTPID_2150 * <br><br> Find specific device (device != 0): * <br> device arg should be not null, search by addr (name) and return device struct * * @note * Index can be used to iterate through all connected myriad devices and save their names. * It will loop only over suitable devices specified by vid and pid */ usbBootError_t usb_find_device_with_bcd(unsigned idx, char *input_addr, unsigned addrsize, void **device, int vid, int pid, uint16_t* bcdusb) { if (pthread_mutex_lock(&globalMutex)) { mvLog(MVLOG_ERROR, "globalMutex lock failed"); return USB_BOOT_ERROR; } int searchByName = 0; static libusb_device **devs = NULL; libusb_device *dev = NULL; struct libusb_device_descriptor desc; int count = 0; size_t i; int res; if (!initialized) { mvLog(MVLOG_ERROR, "Library has not been initialized when loaded"); if (pthread_mutex_unlock(&globalMutex)) { mvLog(MVLOG_ERROR, "globalMutex unlock failed"); } return USB_BOOT_ERROR; } if (strlen(input_addr) > 1) { searchByName = 1; } // Update device list if empty or if indx 0 if (!devs || idx == 0) { if (devs) { libusb_free_device_list(devs, 1); devs = 0; } if ((res = libusb_get_device_list(NULL, &devs)) < 0) { mvLog(MVLOG_DEBUG, "Unable to get USB device list: %s", libusb_strerror(res)); if (pthread_mutex_unlock(&globalMutex)) { mvLog(MVLOG_ERROR, "globalMutex unlock failed"); } return USB_BOOT_ERROR; } } // Loop over all usb devices, increase count only if myriad device i = 0; while ((dev = devs[i++]) != NULL) { if ((res = libusb_get_device_descriptor(dev, &desc)) < 0) { mvLog(MVLOG_DEBUG, "Unable to get USB device descriptor: %s", libusb_strerror(res)); continue; } // If found device have the same id and vid as input if ( (desc.idVendor == vid && desc.idProduct == pid) // Any myriad device || (vid == AUTO_VID && pid == AUTO_PID && isMyriadDevice(desc.idVendor, desc.idProduct)) // Any not booted myriad device || (vid == AUTO_VID && (pid == AUTO_UNBOOTED_PID) && isNotBootedMyriadDevice(desc.idVendor, desc.idProduct)) // Any not booted with specific pid || (vid == AUTO_VID && pid == desc.idProduct && isNotBootedMyriadDevice(desc.idVendor, desc.idProduct)) // Any booted device || (vid == AUTO_VID && pid == DEFAULT_OPENPID && isBootedMyriadDevice(desc.idVendor, desc.idProduct)) ) { if (device) { const char *dev_addr = gen_addr(dev, get_pid_by_name(input_addr)); if (!strcmp(dev_addr, input_addr)) { #if 0 // To avoid spam in Debug mode mvLog(MVLOG_DEBUG, "Found Address: %s - VID/PID %04x:%04x", input_addr, desc.idVendor, desc.idProduct); #endif libusb_ref_device(dev); libusb_free_device_list(devs, 1); if (bcdusb) *bcdusb = desc.bcdUSB; *device = dev; devs = 0; if (pthread_mutex_unlock(&globalMutex)) { mvLog(MVLOG_ERROR, "globalMutex unlock failed"); } return USB_BOOT_SUCCESS; } } else if (searchByName) { const char *dev_addr = gen_addr(dev, desc.idProduct); // If the same add as input if (!strcmp(dev_addr, input_addr)) { #if 0 // To avoid spam in Debug mode mvLog(MVLOG_DEBUG, "Found Address: %s - VID/PID %04x:%04x", input_addr, desc.idVendor, desc.idProduct); #endif if (pthread_mutex_unlock(&globalMutex)) { mvLog(MVLOG_ERROR, "globalMutex unlock failed"); } return USB_BOOT_SUCCESS; } } else if (idx == count) { const char *caddr = gen_addr(dev, desc.idProduct); #if 0 // To avoid spam in Debug mode mvLog(MVLOG_DEBUG, "Device %d Address: %s - VID/PID %04x:%04x", idx, caddr, desc.idVendor, desc.idProduct); #endif mv_strncpy(input_addr, addrsize, caddr, addrsize - 1); if (pthread_mutex_unlock(&globalMutex)) { mvLog(MVLOG_ERROR, "globalMutex unlock failed"); } return USB_BOOT_SUCCESS; } count++; } } libusb_free_device_list(devs, 1); devs = 0; if (pthread_mutex_unlock(&globalMutex)) { mvLog(MVLOG_ERROR, "globalMutex unlock failed"); } return USB_BOOT_DEVICE_NOT_FOUND; } #endif #if (defined(_WIN32) || defined(_WIN64) ) usbBootError_t usb_find_device(unsigned idx, char *addr, unsigned addrsize, void **device, int vid, int pid) { if (!addr) return USB_BOOT_ERROR; int specificDevice = 0; if (strlen(addr) > 1) specificDevice = 1; // TODO There is no global mutex as in linux version int res; // 2 => vid // 2 => pid // '255-' x 7 (also gives us nul-terminator for last entry) // 7 => to add "-maXXXX" static uint8_t devs[128][2 + 2 + 4 * 7 + 7] = { 0 };//to store ven_id,dev_id; static int devs_cnt = 0; int count = 0; size_t i; if(!initialized) { mvLog(MVLOG_ERROR, "Library has not been initialized when loaded"); return USB_BOOT_ERROR; } if (devs_cnt == 0 || idx == 0) { devs_cnt = 0; if (((res = usb_list_devices(vid, pid, devs)) < 0)) { mvLog(MVLOG_DEBUG, "Unable to get USB device list: %s", libusb_strerror(res)); return USB_BOOT_ERROR; } devs_cnt = res; } else { res = devs_cnt; } i = 0; while (res-- > 0) { int idVendor = (int)(devs[res][0] << 8 | devs[res][1]); int idProduct = (devs[res][2] << 8 | devs[res][3]); // If found device have the same id and vid as input if ( (idVendor == vid && idProduct == pid) // Any myriad device || (vid == AUTO_VID && pid == AUTO_PID && isMyriadDevice(idVendor, idProduct)) // Any unbooted myriad device || (vid == AUTO_VID && (pid == AUTO_UNBOOTED_PID) && isNotBootedMyriadDevice(idVendor, idProduct)) // Any unbooted with same pid || (vid == AUTO_VID && pid == idProduct && isNotBootedMyriadDevice(idVendor, idProduct)) // Any booted device || (vid == AUTO_VID && pid == DEFAULT_OPENPID && isBootedMyriadDevice(idVendor, idProduct)) ) { if (device) { const char *caddr = &devs[res][4]; if (strncmp(addr, caddr, XLINK_MAX_NAME_SIZE) == 0) { mvLog(MVLOG_DEBUG, "Found Address: %s - VID/PID %04x:%04x", caddr, (int)(devs[res][0] << 8 | devs[res][1]), (int)(devs[res][2] << 8 | devs[res][3])); *device = enumerate_usb_device(vid, pid, caddr, 0); devs_cnt = 0; return USB_BOOT_SUCCESS; } } else if (specificDevice) { const char *caddr = &devs[res][4]; if (strncmp(addr, caddr, XLINK_MAX_NAME_SIZE) == 0) { mvLog(MVLOG_DEBUG, "Found Address: %s - VID/PID %04x:%04x", caddr, (int)(devs[res][0] << 8 | devs[res][1]), (int)(devs[res][2] << 8 | devs[res][3])); return USB_BOOT_SUCCESS; } } else if (idx == count) { const char *caddr = &devs[res][4]; mvLog(MVLOG_DEBUG, "Device %d Address: %s - VID/PID %04x:%04x", idx, caddr, (int)(devs[res][0] << 8 | devs[res][1]), (int)(devs[res][2] << 8 | devs[res][3])); mv_strncpy(addr, addrsize, caddr, addrsize - 1); return USB_BOOT_SUCCESS; } count++; } } devs_cnt = 0; return USB_BOOT_DEVICE_NOT_FOUND; } #endif #if (!defined(_WIN32) && !defined(_WIN64) ) static libusb_device_handle *usb_open_device(libusb_device *dev, uint8_t *endpoint, char *err_string_buff, int err_max_len) { struct libusb_config_descriptor *cdesc; const struct libusb_interface_descriptor *ifdesc; libusb_device_handle *h = NULL; int res, i; if((res = libusb_open(dev, &h)) < 0) { snprintf(err_string_buff, err_max_len, "cannot open device: %s\n", libusb_strerror(res)); return 0; } if((res = libusb_set_configuration(h, 1)) < 0) { snprintf(err_string_buff, err_max_len, "setting config 1 failed: %s\n", libusb_strerror(res)); libusb_close(h); return 0; } if((res = libusb_claim_interface(h, 0)) < 0) { snprintf(err_string_buff, err_max_len, "claiming interface 0 failed: %s\n", libusb_strerror(res)); libusb_close(h); return 0; } if((res = libusb_get_config_descriptor(dev, 0, &cdesc)) < 0) { snprintf(err_string_buff, err_max_len, "Unable to get USB config descriptor: %s\n", libusb_strerror(res)); libusb_close(h); return 0; } ifdesc = cdesc->interface->altsetting; for(i=0; i<ifdesc->bNumEndpoints; i++) { mvLog(MVLOG_DEBUG, "Found EP 0x%02x : max packet size is %u bytes", ifdesc->endpoint[i].bEndpointAddress, ifdesc->endpoint[i].wMaxPacketSize); if((ifdesc->endpoint[i].bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) != LIBUSB_TRANSFER_TYPE_BULK) continue; if( !(ifdesc->endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) ) { *endpoint = ifdesc->endpoint[i].bEndpointAddress; bulk_chunklen = ifdesc->endpoint[i].wMaxPacketSize; libusb_free_config_descriptor(cdesc); return h; } } libusb_free_config_descriptor(cdesc); mv_strcpy(err_string_buff, OPEN_DEV_ERROR_MESSAGE_LENGTH, "Unable to find BULK OUT endpoint\n"); libusb_close(h); return 0; } #endif // timeout: -1 = no (infinite) timeout, 0 = must happen immediately #if (!defined(_WIN32) && !defined(_WIN64) ) static int wait_findopen(const char *device_address, int timeout, libusb_device **dev, libusb_device_handle **devh, uint8_t *endpoint,uint16_t* bcdusb) #else static int wait_findopen(const char *device_address, int timeout, libusb_device **dev, libusb_device_handle **devh, uint8_t *endpoint) #endif { int i, rc; char last_open_dev_err[OPEN_DEV_ERROR_MESSAGE_LENGTH]; double elapsedTime = 0; highres_time_t t1, t2; if (device_address == NULL) { return USB_BOOT_ERROR; } usleep(100000); if(timeout == -1) mvLog(MVLOG_DEBUG, "Starting wait for connect, no timeout"); else if(timeout == 0) mvLog(MVLOG_DEBUG, "Trying to connect"); else mvLog(MVLOG_DEBUG, "Starting wait for connect with %ums timeout", timeout); last_open_dev_err[0] = 0; i = 0; for(;;) { highres_gettime(&t1); int addr_size = (int)strlen(device_address); #if (!defined(_WIN32) && !defined(_WIN64) ) rc = usb_find_device_with_bcd(0, (char*)device_address, addr_size, (void**)dev, DEFAULT_VID, get_pid_by_name(device_address), bcdusb); #else rc = usb_find_device(0, (char *)device_address, addr_size, (void **)dev, DEFAULT_VID, get_pid_by_name(device_address)); #endif if(rc < 0) return USB_BOOT_ERROR; if(!rc) { #if (!defined(_WIN32) && !defined(_WIN64) ) *devh = usb_open_device(*dev, endpoint, last_open_dev_err, OPEN_DEV_ERROR_MESSAGE_LENGTH); #else *devh = usb_open_device(*dev, endpoint, 0, last_open_dev_err, OPEN_DEV_ERROR_MESSAGE_LENGTH); #endif if(*devh != NULL) { mvLog(MVLOG_DEBUG, "Found and opened device"); return 0; } #if (!defined(_WIN32) && !defined(_WIN64) ) libusb_unref_device(*dev); *dev = NULL; #endif } highres_gettime(&t2); elapsedTime += highres_elapsed_ms(&t1, &t2); if(timeout != -1) { if(last_open_dev_err[0]) mvLog(MVLOG_DEBUG, "Last opened device name: %s", last_open_dev_err); return rc ? USB_BOOT_DEVICE_NOT_FOUND : USB_BOOT_TIMEOUT; } else if (elapsedTime > (double)timeout) { return rc ? USB_BOOT_DEVICE_NOT_FOUND : USB_BOOT_TIMEOUT; } i++; usleep(100000); } return 0; } #if (!defined(_WIN32) && !defined(_WIN64) ) static int send_file(libusb_device_handle* h, uint8_t endpoint, const uint8_t* tx_buf, unsigned filesize,uint16_t bcdusb) #else static int send_file(libusb_device_handle *h, uint8_t endpoint, const uint8_t *tx_buf, unsigned filesize) #endif { const uint8_t *p; int rc; int wb, twb, wbr; double elapsedTime; highres_time_t t1, t2; int bulk_chunklen=DEFAULT_CHUNKSZ; elapsedTime = 0; twb = 0; p = tx_buf; #if (!defined(_WIN32) && !defined(_WIN64) ) if(bcdusb < 0x200) { bulk_chunklen = USB1_CHUNKSZ; } #endif mvLog(MVLOG_DEBUG, "Performing bulk write of %u bytes...", filesize); while((unsigned)twb < filesize) { highres_gettime(&t1); wb = filesize - twb; if(wb > bulk_chunklen) wb = bulk_chunklen; wbr = 0; #if (!defined(_WIN32) && !defined(_WIN64) ) rc = libusb_bulk_transfer(h, endpoint, (void *)p, wb, &wbr, write_timeout); #else rc = usb_bulk_write(h, endpoint, (void *)p, wb, &wbr, write_timeout); #endif if(rc || (wb != wbr)) { if(rc == LIBUSB_ERROR_NO_DEVICE) break; mvLog(MVLOG_WARN, "bulk write: %s (%d bytes written, %d bytes to write)", libusb_strerror(rc), wbr, wb); if(rc == LIBUSB_ERROR_TIMEOUT) return USB_BOOT_TIMEOUT; else return USB_BOOT_ERROR; } highres_gettime(&t2); elapsedTime += highres_elapsed_ms(&t1, &t2); if (elapsedTime > DEFAULT_SEND_FILE_TIMEOUT) { return USB_BOOT_TIMEOUT; } twb += wbr; p += wbr; } #ifndef NDEBUG double MBpS = ((double)filesize / 1048576.) / (elapsedTime * 0.001); mvLog(MVLOG_DEBUG, "Successfully sent %u bytes of data in %lf ms (%lf MB/s)", filesize, elapsedTime, MBpS); #endif return 0; } int usb_boot(const char *addr, const void *mvcmd, unsigned size) { int rc = 0; uint8_t endpoint; #if (defined(_WIN32) || defined(_WIN64) ) void *dev = NULL; struct _usb_han *h; rc = wait_findopen(addr, connect_timeout, &dev, &h, &endpoint); if(rc) { usb_close_device(h); usb_free_device(dev); return rc; } rc = send_file(h, endpoint, mvcmd, size); usb_close_device(h); usb_free_device(dev); #else libusb_device *dev; libusb_device_handle *h; uint16_t bcdusb=-1; rc = wait_findopen(addr, connect_timeout, &dev, &h, &endpoint,&bcdusb); if(rc) { return rc; } rc = send_file(h, endpoint, mvcmd, size,bcdusb); if (h) { libusb_release_interface(h, 0); libusb_close(h); } if (dev) { libusb_unref_device(dev); } #endif return rc; }
10,831
4,036
<reponame>vadi2/codeql<filename>cpp/ql/test/library-tests/pointsto/new-virtual/test.cpp class MyClassBase { public: virtual void method(int *ptr) { *ptr = 1; } int a; }; class MyClass : public MyClassBase { virtual void method(int *ptr) { *ptr = 2; } }; void myFunction() { MyClassBase *ptr1 = new MyClassBase(); MyClassBase *ptr2 = new MyClass(); int i; int j; ptr1->method(&i); ptr2->method(&j); }
183
749
<reponame>richardsheridan/anyio from abc import abstractmethod from typing import Optional from ._resources import AsyncResource from ._streams import ByteReceiveStream, ByteSendStream class Process(AsyncResource): """An asynchronous version of :class:`subprocess.Popen`.""" @abstractmethod async def wait(self) -> int: """ Wait until the process exits. :return: the exit code of the process """ @abstractmethod def terminate(self) -> None: """ Terminates the process, gracefully if possible. On Windows, this calls ``TerminateProcess()``. On POSIX systems, this sends ``SIGTERM`` to the process. .. seealso:: :meth:`subprocess.Popen.terminate` """ @abstractmethod def kill(self) -> None: """ Kills the process. On Windows, this calls ``TerminateProcess()``. On POSIX systems, this sends ``SIGKILL`` to the process. .. seealso:: :meth:`subprocess.Popen.kill` """ @abstractmethod def send_signal(self, signal: int) -> None: """ Send a signal to the subprocess. .. seealso:: :meth:`subprocess.Popen.send_signal` :param signal: the signal number (e.g. :data:`signal.SIGHUP`) """ @property @abstractmethod def pid(self) -> int: """The process ID of the process.""" @property @abstractmethod def returncode(self) -> Optional[int]: """ The return code of the process. If the process has not yet terminated, this will be ``None``. """ @property @abstractmethod def stdin(self) -> Optional[ByteSendStream]: """The stream for the standard input of the process.""" @property @abstractmethod def stdout(self) -> Optional[ByteReceiveStream]: """The stream for the standard output of the process.""" @property @abstractmethod def stderr(self) -> Optional[ByteReceiveStream]: """The stream for the standard error output of the process."""
800
980
<filename>samples/main/java/org/jcodec/samples/mux/AVCMP4Demux.java package org.jcodec.samples.mux; import java.io.File; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author The JCodec project * */ public class AVCMP4Demux { public static void main(String[] args) { if (args.length < 2) { System.out.println("Syntax: <in.264> <out.mp4>\n" + "\tWhere:\n" + "\t-q\tLook for stream parameters only in the beginning of stream"); return; } File in = new File(args[0]); File out = new File(args[1]); } }
289
368
/* Plugin-SDK (Grand Theft Auto 3) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CBaseModelInfo.h" PLUGIN_SOURCE_FILE int ctor_addr_o(CBaseModelInfo, void(ModelInfoType)) = ADDRESS_BY_VERSION(0x4F6A50, 0x4F6B00, 0x4F6A90); int ctor_gaddr_o(CBaseModelInfo, void(ModelInfoType)) = GLOBAL_ADDRESS_BY_VERSION(0x4F6A50, 0x4F6B00, 0x4F6A90); int dtor_addr(CBaseModelInfo) = ADDRESS_BY_VERSION(0x4F6C00, 0x4F6CB0, 0x4F6C40); int dtor_gaddr(CBaseModelInfo) = GLOBAL_ADDRESS_BY_VERSION(0x4F6C00, 0x4F6CB0, 0x4F6C40); int del_dtor_addr(CBaseModelInfo) = ADDRESS_BY_VERSION(0x4F6BC0, 0x4F6C70, 0x4F6C00); int del_dtor_gaddr(CBaseModelInfo) = GLOBAL_ADDRESS_BY_VERSION(0x4F6BC0, 0x4F6C70, 0x4F6C00); int addrof(CBaseModelInfo::Shutdown) = ADDRESS_BY_VERSION(0x4F6A90, 0x4F6B40, 0x4F6AD0); int gaddrof(CBaseModelInfo::Shutdown) = GLOBAL_ADDRESS_BY_VERSION(0x4F6A90, 0x4F6B40, 0x4F6AD0); void CBaseModelInfo::Shutdown() { plugin::CallVirtualMethod<1, CBaseModelInfo *>(this); } int addrof(CBaseModelInfo::Add2dEffect) = ADDRESS_BY_VERSION(0x4F6B20, 0x4F6BD0, 0x4F6B60); int gaddrof(CBaseModelInfo::Add2dEffect) = GLOBAL_ADDRESS_BY_VERSION(0x4F6B20, 0x4F6BD0, 0x4F6B60); void CBaseModelInfo::Add2dEffect(C2dEffect *effect) { plugin::CallMethodDynGlobal<CBaseModelInfo *, C2dEffect *>(gaddrof(CBaseModelInfo::Add2dEffect), this, effect); } int addrof(CBaseModelInfo::AddRef) = ADDRESS_BY_VERSION(0x4F6BA0, 0x4F6C50, 0x4F6BE0); int gaddrof(CBaseModelInfo::AddRef) = GLOBAL_ADDRESS_BY_VERSION(0x4F6BA0, 0x4F6C50, 0x4F6BE0); void CBaseModelInfo::AddRef() { plugin::CallMethodDynGlobal<CBaseModelInfo *>(gaddrof(CBaseModelInfo::AddRef), this); } int addrof(CBaseModelInfo::AddTexDictionaryRef) = ADDRESS_BY_VERSION(0x4F6B80, 0x4F6C30, 0x4F6BC0); int gaddrof(CBaseModelInfo::AddTexDictionaryRef) = GLOBAL_ADDRESS_BY_VERSION(0x4F6B80, 0x4F6C30, 0x4F6BC0); void CBaseModelInfo::AddTexDictionaryRef() { plugin::CallMethodDynGlobal<CBaseModelInfo *>(gaddrof(CBaseModelInfo::AddTexDictionaryRef), this); } int addrof(CBaseModelInfo::ClearTexDictionary) = ADDRESS_BY_VERSION(0x4F6B70, 0x4F6C20, 0x4F6BB0); int gaddrof(CBaseModelInfo::ClearTexDictionary) = GLOBAL_ADDRESS_BY_VERSION(0x4F6B70, 0x4F6C20, 0x4F6BB0); void CBaseModelInfo::ClearTexDictionary() { plugin::CallMethodDynGlobal<CBaseModelInfo *>(gaddrof(CBaseModelInfo::ClearTexDictionary), this); } int addrof(CBaseModelInfo::DeleteCollisionModel) = ADDRESS_BY_VERSION(0x4F6AC0, 0x4F6B70, 0x4F6B00); int gaddrof(CBaseModelInfo::DeleteCollisionModel) = GLOBAL_ADDRESS_BY_VERSION(0x4F6AC0, 0x4F6B70, 0x4F6B00); void CBaseModelInfo::DeleteCollisionModel() { plugin::CallMethodDynGlobal<CBaseModelInfo *>(gaddrof(CBaseModelInfo::DeleteCollisionModel), this); } int addrof(CBaseModelInfo::Get2dEffect) = ADDRESS_BY_VERSION(0x4F6B00, 0x4F6BB0, 0x4F6B40); int gaddrof(CBaseModelInfo::Get2dEffect) = GLOBAL_ADDRESS_BY_VERSION(0x4F6B00, 0x4F6BB0, 0x4F6B40); C2dEffect *CBaseModelInfo::Get2dEffect(int effectNumber) { return plugin::CallMethodAndReturnDynGlobal<C2dEffect *, CBaseModelInfo *, int>(gaddrof(CBaseModelInfo::Get2dEffect), this, effectNumber); } int addrof(CBaseModelInfo::Init2dEffects) = ADDRESS_BY_VERSION(0x4F6AF0, 0x4F6BA0, 0x4F6B30); int gaddrof(CBaseModelInfo::Init2dEffects) = GLOBAL_ADDRESS_BY_VERSION(0x4F6AF0, 0x4F6BA0, 0x4F6B30); void CBaseModelInfo::Init2dEffects() { plugin::CallMethodDynGlobal<CBaseModelInfo *>(gaddrof(CBaseModelInfo::Init2dEffects), this); } int addrof(CBaseModelInfo::RemoveRef) = ADDRESS_BY_VERSION(0x4F6BB0, 0x4F6C60, 0x4F6BF0); int gaddrof(CBaseModelInfo::RemoveRef) = GLOBAL_ADDRESS_BY_VERSION(0x4F6BB0, 0x4F6C60, 0x4F6BF0); void CBaseModelInfo::RemoveRef() { plugin::CallMethodDynGlobal<CBaseModelInfo *>(gaddrof(CBaseModelInfo::RemoveRef), this); } int addrof(CBaseModelInfo::RemoveTexDictionaryRef) = ADDRESS_BY_VERSION(0x4F6B90, 0x4F6C40, 0x4F6BD0); int gaddrof(CBaseModelInfo::RemoveTexDictionaryRef) = GLOBAL_ADDRESS_BY_VERSION(0x4F6B90, 0x4F6C40, 0x4F6BD0); void CBaseModelInfo::RemoveTexDictionaryRef() { plugin::CallMethodDynGlobal<CBaseModelInfo *>(gaddrof(CBaseModelInfo::RemoveTexDictionaryRef), this); } int addrof(CBaseModelInfo::SetTexDictionary) = ADDRESS_BY_VERSION(0x4F6B40, 0x4F6BF0, 0x4F6B80); int gaddrof(CBaseModelInfo::SetTexDictionary) = GLOBAL_ADDRESS_BY_VERSION(0x4F6B40, 0x4F6BF0, 0x4F6B80); void CBaseModelInfo::SetTexDictionary(char const *txdName) { plugin::CallMethodDynGlobal<CBaseModelInfo *, char const *>(gaddrof(CBaseModelInfo::SetTexDictionary), this, txdName); }
2,122
406
<reponame>maximbaz/Hauk package info.varden.hauk.http; import android.content.Context; import android.location.Location; import android.util.Base64; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import javax.crypto.Cipher; import info.varden.hauk.Constants; import info.varden.hauk.R; import info.varden.hauk.http.parameter.LocationProvider; import info.varden.hauk.struct.Session; import info.varden.hauk.struct.Version; import info.varden.hauk.utils.Log; import info.varden.hauk.utils.TimeUtils; /** * Packet that is sent to update the client's location on the map. * * @author <NAME> */ public abstract class LocationUpdatePacket extends Packet { /** * Called whenever a list of currently active shares are received from the server. This list may * be updated by the server if the user is adopted into a group share. This function is called * so that the UI can be updated with these additional group shares, making the user aware that * they have been adopted and are now part of a new group. * * @since 1.2 * @param linkFormat A string that can be used to construct a public view link for each share * in the {@code shares} array through {@code String.format(linkFormat, * shareID)}. * @param shares A list of share IDs active for the user's current session on the backend. */ protected abstract void onShareListReceived(String linkFormat, String[] shares); /** * Creates the packet. * * @param ctx Android application context. * @param session The session for which location is being updated. * @param location The updated location data obtained from GNSS/network sensors. */ protected LocationUpdatePacket(Context ctx, Session session, Location location, LocationProvider accuracy) { super(ctx, session.getServerURL(), session.getConnectionParameters(), Constants.URL_PATH_POST_LOCATION); setParameter(Constants.PACKET_PARAM_SESSION_ID, session.getID()); if (session.getDerivableE2EKey() == null) { // If not using end-to-end encryption, send parameters in plain text. setParameter(Constants.PACKET_PARAM_LATITUDE, String.valueOf(location.getLatitude())); setParameter(Constants.PACKET_PARAM_LONGITUDE, String.valueOf(location.getLongitude())); setParameter(Constants.PACKET_PARAM_PROVIDER_ACCURACY, String.valueOf(accuracy.getMode())); setParameter(Constants.PACKET_PARAM_TIMESTAMP, String.valueOf(System.currentTimeMillis() / (double) TimeUtils.MILLIS_PER_SECOND)); // Not all devices provide these parameters: if (location.hasSpeed()) setParameter(Constants.PACKET_PARAM_SPEED, String.valueOf(location.getSpeed())); if (location.hasAccuracy()) setParameter(Constants.PACKET_PARAM_ACCURACY, String.valueOf(location.getAccuracy())); } else { // We're using end-to-end encryption - generate an IV and encrypt all parameters. try { Cipher cipher = Cipher.getInstance(Constants.E2E_TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, session.getDerivableE2EKey().deriveSpec(), new SecureRandom()); byte[] iv = cipher.getIV(); setParameter(Constants.PACKET_PARAM_INIT_VECTOR, Base64.encodeToString(iv, Base64.DEFAULT)); setParameter(Constants.PACKET_PARAM_LATITUDE, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getLatitude()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT)); setParameter(Constants.PACKET_PARAM_LONGITUDE, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getLongitude()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT)); setParameter(Constants.PACKET_PARAM_PROVIDER_ACCURACY, Base64.encodeToString(cipher.doFinal(String.valueOf(accuracy.getMode()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT)); setParameter(Constants.PACKET_PARAM_TIMESTAMP, Base64.encodeToString(cipher.doFinal(String.valueOf(System.currentTimeMillis() / (double) TimeUtils.MILLIS_PER_SECOND).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT)); // Not all devices provide these parameters: if (location.hasSpeed()) setParameter(Constants.PACKET_PARAM_SPEED, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getSpeed()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT)); if (location.hasAccuracy()) setParameter(Constants.PACKET_PARAM_ACCURACY, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getAccuracy()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT)); } catch (Exception e) { Log.e("Error was thrown when encrypting location data", e); //NON-NLS } } } @SuppressWarnings("DesignForExtension") @Override protected void onSuccess(String[] data, Version backendVersion) throws ServerException { // Somehow the data array can be empty? Check for this. if (data.length < 1) { throw new ServerException(getContext(), R.string.err_empty); } if (data[0].equals(Constants.PACKET_RESPONSE_OK)) { // If the backend is >= v1.2, post.php returns a list of currently active share links. // Update the user interface to include these. if (backendVersion.isAtLeast(Constants.VERSION_COMPAT_VIEW_ID)) { // The share link list is comma-separated. String linkFormat = data[1]; String shareCSV = data[2]; if (!shareCSV.isEmpty()) { onShareListReceived(linkFormat, shareCSV.split(",")); } else { onShareListReceived(linkFormat, new String[0]); } } } else { // If the first line of the response is not "OK", an error of some sort has occurred and // should be displayed to the user. StringBuilder err = new StringBuilder(); for (String line : data) { err.append(line); err.append(System.lineSeparator()); } throw new ServerException(err.toString()); } } }
2,536
1,754
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ratpack.gson.internal; import com.google.gson.Gson; import ratpack.gson.GsonParseOpts; import java.util.Optional; public class DefaultGsonParseOpts implements GsonParseOpts { public static final GsonParseOpts INSTANCE = new DefaultGsonParseOpts(null); private final Optional<Gson> gson; public DefaultGsonParseOpts(Gson gson) { this.gson = Optional.ofNullable(gson); } @Override public Optional<Gson> getGson() { return gson; } @Override public String toString() { return "GsonParseOpts{json=" + gson.orElse(null) + '}'; } }
370
645
<reponame>xuantan/viewfinder // Copyright 2012 Viewfinder. All rights reserved. // Author: <NAME>. #import "AppState.h" #import "ContactManager.h" #import "DayTable.h" #import "EpisodeTable.h" #import "FullTextIndex.h" #import "LazyStaticPtr.h" #import "LocationUtils.h" #import "NetworkQueue.h" #import "PlacemarkHistogram.h" #import "STLUtils.h" #import "StringUtils.h" #import "Timer.h" #import "WallTime.h" namespace { const int kEpisodeFSCKVersion = 7; const string kEpisodeParentChildKeyPrefix = DBFormat::episode_parent_child_key(string()); const string kEpisodePhotoKeyPrefix = DBFormat::episode_photo_key(string()); const string kEpisodeSelectionKeyPrefix = DBFormat::episode_selection_key(string()); const string kEpisodeStatsKey = DBFormat::metadata_key("episode_stats"); const string kEpisodeTimestampKeyPrefix = DBFormat::episode_timestamp_key(string()); const string kPhotoEpisodeKeyPrefix = DBFormat::photo_episode_key(string()); const string kEpisodeIndexName = "ep"; const string kLocationIndexName = "epl"; const double kMaxTimeDist = 60 * 60; // 1 hour const double kMaxLocDist = 10000; // 10 km const DBRegisterKeyIntrospect kEpisodeKeyIntrospect( DBFormat::episode_key(), NULL, [](Slice value) { return DBIntrospect::FormatProto<EpisodeMetadata>(value); }); const DBRegisterKeyIntrospect kEpisodeServerKeyIntrospect( DBFormat::episode_server_key(), NULL, [](Slice value) { return value.ToString(); }); const DBRegisterKeyIntrospect kEpisodeParentChildKeyIntrospect( kEpisodeParentChildKeyPrefix, [](Slice key) { int64_t parent_id; int64_t child_id; if (!DecodeEpisodeParentChildKey(key, &parent_id, &child_id)) { return string(); } return string(Format("%d/%d", parent_id, child_id)); }, [](Slice value) { return value.ToString(); }); const DBRegisterKeyIntrospect kEpisodePhotoKeyIntrospect( kEpisodePhotoKeyPrefix, [](Slice key) { int64_t episode_id; int64_t photo_id; if (!DecodeEpisodePhotoKey(key, &episode_id, &photo_id)) { return string(); } return string(Format("%d/%d", episode_id, photo_id)); }, [](Slice value) { return value.ToString(); }); const DBRegisterKeyIntrospect kPhotoEpisodeKeyIntrospect( kPhotoEpisodeKeyPrefix, [](Slice key) { int64_t photo_id; int64_t episode_id; if (!DecodePhotoEpisodeKey(key, &photo_id, &episode_id)) { return string(); } return string(Format("%d/%d", photo_id, episode_id)); }, NULL); const DBRegisterKeyIntrospect kEpisodeSelectionKeyIntrospect( kEpisodeSelectionKeyPrefix, NULL, [](Slice value) { return DBIntrospect::FormatProto<EpisodeSelection>(value); }); const DBRegisterKeyIntrospect kEpisodeTimestampKeyIntrospect( kEpisodeTimestampKeyPrefix , [](Slice key) { WallTime timestamp; int64_t episode_id; if (!DecodeEpisodeTimestampKey(key, &timestamp, &episode_id)) { return string(); } return string( Format("%s/%d", DBIntrospect::timestamp(timestamp), episode_id)); }, NULL); class QueryRewriter : public FullTextQueryVisitor { public: QueryRewriter(AppState* state) : state_(state) { } FullTextQuery* ParseAndRewrite(const Slice& query) { ScopedPtr<FullTextQuery> parsed_query(FullTextQuery::Parse(query)); stack_.push_back(Accumulator()); VisitNode(*parsed_query); CHECK_EQ(stack_.size(), 1); CHECK_EQ(stack_[0].size(), 1); return stack_[0][0]; } void VisitTermNode(const FullTextQueryTermNode& node) { vector<FullTextQuery*> terms; terms.push_back(new FullTextQueryTermNode(node)); AddContactTerms(node.term(), false, &terms); stack_.back().push_back(new FullTextQueryOrNode(terms)); } void VisitPrefixNode(const FullTextQueryPrefixNode& node) { vector<FullTextQuery*> terms; terms.push_back(new FullTextQueryPrefixNode(node)); AddContactTerms(node.prefix(), true, &terms); stack_.back().push_back(new FullTextQueryOrNode(terms)); } void VisitParentNode(const FullTextQueryParentNode& node) { stack_.push_back(Accumulator()); VisitChildren(node); FullTextQuery* new_node; if (node.type() == FullTextQuery::AND) { new_node = new FullTextQueryAndNode(stack_.back()); } else { new_node = new FullTextQueryOrNode(stack_.back()); } stack_.pop_back(); stack_.back().push_back(new_node); } private: void AddContactTerms(const string& query, bool prefix, vector<FullTextQuery*>* terms) { // Rewrite each term to its union with any matching contact entries. vector<ContactMetadata> contact_results; int options = ContactManager::SORT_BY_NAME | ContactManager::VIEWFINDER_USERS_ONLY; if (prefix) { options |= ContactManager::PREFIX_MATCH; } state_->contact_manager()->Search(query, &contact_results, NULL, options); for (const ContactMetadata& c : contact_results) { // Even if the underlying query is in prefix mode, the resulting tokens are always exact matches. terms->push_back(new FullTextQueryTermNode(ContactManager::FormatUserToken(c.user_id()))); } } AppState* state_; typedef vector<FullTextQuery*> Accumulator; vector<Accumulator> stack_; }; } // namespace string EncodeEpisodePhotoKey(int64_t episode_id, int64_t photo_id) { string s; OrderedCodeEncodeInt64Pair(&s, episode_id, photo_id); return DBFormat::episode_photo_key(s); } string EncodePhotoEpisodeKey(int64_t photo_id, int64_t episode_id) { string s; OrderedCodeEncodeInt64Pair(&s, photo_id, episode_id); return DBFormat::photo_episode_key(s); } string EncodeEpisodeTimestampKey(WallTime timestamp, int64_t episode_id) { string s; OrderedCodeEncodeVarint32(&s, timestamp); OrderedCodeEncodeVarint64(&s, episode_id); return DBFormat::episode_timestamp_key(s); } string EncodeEpisodeParentChildKey(int64_t parent_id, int64_t child_id) { string s; OrderedCodeEncodeInt64Pair(&s, parent_id, child_id); return DBFormat::episode_parent_child_key(s); } bool DecodeEpisodePhotoKey(Slice key, int64_t* episode_id, int64_t* photo_id) { if (!key.starts_with(kEpisodePhotoKeyPrefix)) { return false; } key.remove_prefix(kEpisodePhotoKeyPrefix.size()); OrderedCodeDecodeInt64Pair(&key, episode_id, photo_id); return true; } bool DecodePhotoEpisodeKey(Slice key, int64_t* photo_id, int64_t* episode_id) { if (!key.starts_with(kPhotoEpisodeKeyPrefix)) { return false; } key.remove_prefix(kPhotoEpisodeKeyPrefix.size()); OrderedCodeDecodeInt64Pair(&key, photo_id, episode_id); return true; } bool DecodeEpisodeTimestampKey( Slice key, WallTime* timestamp, int64_t* episode_id) { if (!key.starts_with(kEpisodeTimestampKeyPrefix)) { return false; } key.remove_prefix(kEpisodeTimestampKeyPrefix.size()); *timestamp = OrderedCodeDecodeVarint32(&key); *episode_id = OrderedCodeDecodeVarint64(&key); return true; } bool DecodeEpisodeParentChildKey(Slice key, int64_t* parent_id, int64_t* child_id) { if (!key.starts_with(kEpisodeParentChildKeyPrefix)) { return false; } key.remove_prefix(kEpisodeParentChildKeyPrefix.size()); OrderedCodeDecodeInt64Pair(&key, parent_id, child_id); return true; } //// // EpisodeTable_Episode EpisodeTable_Episode::EpisodeTable_Episode(AppState* state, const DBHandle& db, int64_t id) : state_(state), db_(db), additions_(0), hiddens_(0), quarantines_(0), removals_(0), unshares_(0), have_photo_state_(false), recompute_timestamp_range_(false), resolved_location_(false) { mutable_id()->set_local_id(id); } void EpisodeTable_Episode::MergeFrom(const EpisodeMetadata& m) { // Some assertions that immutable properties don't change. if (parent_id().has_server_id() && m.parent_id().has_server_id()) { DCHECK_EQ(parent_id().server_id(), m.parent_id().server_id()); } if (viewpoint_id().has_server_id() && m.viewpoint_id().has_server_id()) { DCHECK_EQ(viewpoint_id().server_id(), m.viewpoint_id().server_id()); } if (has_user_id() && m.has_user_id()) { DCHECK_EQ(user_id(), m.user_id()); } EpisodeMetadata::MergeFrom(m); } void EpisodeTable_Episode::MergeFrom(const ::google::protobuf::Message&) { DIE("MergeFrom(Message&) should not be used"); } int64_t EpisodeTable_Episode::GetDeviceId() const { if (!id().has_server_id()) { return state_->device_id(); } int64_t device_id = 0; int64_t dummy_id = 0; WallTime dummy_timestamp = 0; DecodeEpisodeId( id().server_id(), &device_id, &dummy_id, &dummy_timestamp); return device_id; } int64_t EpisodeTable_Episode::GetUserId() const { return has_user_id() ? user_id() : state_->user_id(); } void EpisodeTable_Episode::AddPhoto(int64_t photo_id) { PhotoState* s = NULL; if (photos_.get()) { s = FindPtrOrNull(photos_.get(), photo_id); } bool new_photo = false; if (!s && !have_photo_state_) { // Optimize the common case where photo state has not been // initialized. Load only the photo state for the photo being added. if (!photos_.get()) { photos_.reset(new PhotoStateMap); } const string value = db_->Get<string>( EncodeEpisodePhotoKey(id().local_id(), photo_id)); if (!value.empty()) { s = &(*photos_)[photo_id]; if (value == EpisodeTable::kHiddenValue) { *s = HIDDEN; } else if (value == EpisodeTable::kPostedValue) { *s = POSTED; } else if (value == EpisodeTable::kQuarantinedValue) { *s = QUARANTINED; } else if (value == EpisodeTable::kRemovedValue) { *s = REMOVED; } else if (value == EpisodeTable::kUnsharedValue) { *s = UNSHARED; } else { CHECK(false) << "unexpected value: " << value; } } } if (!s) { new_photo = true; additions_++; s = &(*photos_)[photo_id]; } else if (*s == HIDDEN) { additions_++; hiddens_--; } else if (*s == QUARANTINED) { additions_++; quarantines_--; } else if (*s == REMOVED) { additions_++; removals_--; } else if (*s == UNSHARED) { additions_++; unshares_--; } else { CHECK_NE(*s, HIDE_PENDING) << "hidden pending"; CHECK_NE(*s, QUARANTINE_PENDING) << "quarantine pending"; CHECK_NE(*s, REMOVE_PENDING) << "remove pending"; CHECK_NE(*s, UNSHARE_PENDING) << "unshare pending"; } *s = POST_PENDING; // When a new photo is added we can incrementally update the timestamp // range. Otherwise, we have to recompute the timestamp range from scratch. if (!new_photo) { recompute_timestamp_range_ = true; } } void EpisodeTable_Episode::HidePhoto(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); PhotoState* s = FindPtrOrNull(photos_.get(), photo_id); if (s) { if (*s == POSTED) { additions_--; hiddens_++; *s = HIDE_PENDING; } else if (*s == QUARANTINED) { quarantines_--; hiddens_++; *s = HIDE_PENDING; } else if (*s == REMOVED) { removals_--; hiddens_++; *s = HIDE_PENDING; } else { CHECK_NE(*s, POST_PENDING) << "post pending"; CHECK_NE(*s, QUARANTINE_PENDING) << "quarantine pending"; CHECK_NE(*s, REMOVE_PENDING) << "remove pending"; CHECK_NE(*s, UNSHARE_PENDING) << "unshare pending"; } } else { // We've queried a photo as part of this episode which has been // removed. We still need to record it, but with state removed. hiddens_++; (*photos_)[photo_id] = HIDE_PENDING; } recompute_timestamp_range_ = true; } void EpisodeTable_Episode::QuarantinePhoto(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); PhotoState* s = FindPtrOrNull(photos_.get(), photo_id); if (s) { if (*s == HIDDEN) { quarantines_++; hiddens_--; *s = QUARANTINE_PENDING; } else if (*s == POSTED) { quarantines_++; additions_--; *s = QUARANTINE_PENDING; } else if (*s == REMOVED) { quarantines_++; removals_--; *s = QUARANTINE_PENDING; } else { CHECK_NE(*s, HIDE_PENDING) << "hidden pending"; CHECK_NE(*s, POST_PENDING) << "post pending"; CHECK_NE(*s, REMOVE_PENDING) << "remove pending"; CHECK_NE(*s, UNSHARE_PENDING) << "unshare pending"; } } else { // We've queried a photo as part of this episode which has been // removed. We still need to record it, but with state unshared. quarantines_++; (*photos_)[photo_id] = QUARANTINE_PENDING; } recompute_timestamp_range_ = true; } void EpisodeTable_Episode::RemovePhoto(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); PhotoState* s = FindPtrOrNull(photos_.get(), photo_id); if (s) { if (*s == HIDDEN) { hiddens_--; removals_++; *s = REMOVE_PENDING; } else if (*s == POSTED) { additions_--; removals_++; *s = REMOVE_PENDING; } else if (*s == QUARANTINED) { quarantines_--; removals_++; *s = REMOVE_PENDING; } else { CHECK_NE(*s, HIDE_PENDING) << "hidden pending"; CHECK_NE(*s, POST_PENDING) << "post pending"; CHECK_NE(*s, QUARANTINE_PENDING) << "quarantine pending"; CHECK_NE(*s, UNSHARE_PENDING) << "unshare pending"; } } else { // We've queried a photo as part of this episode which has been // removed. We still need to record it, but with state removed. removals_++; (*photos_)[photo_id] = REMOVE_PENDING; } recompute_timestamp_range_ = true; } void EpisodeTable_Episode::UnsharePhoto(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); PhotoState* s = FindPtrOrNull(photos_.get(), photo_id); if (s) { if (*s == HIDDEN) { hiddens_--; unshares_++; *s = UNSHARE_PENDING; } else if (*s == POSTED) { additions_--; unshares_++; *s = UNSHARE_PENDING; } else if (*s == QUARANTINED) { quarantines_--; unshares_++; *s = UNSHARE_PENDING; } else if (*s == REMOVED) { removals_--; unshares_++; *s = UNSHARE_PENDING; } else { CHECK_NE(*s, HIDE_PENDING) << "hidden pending"; CHECK_NE(*s, POST_PENDING) << "post pending"; CHECK_NE(*s, QUARANTINE_PENDING) << "quarantine pending"; CHECK_NE(*s, REMOVE_PENDING) << "remove pending"; } } else { // We've queried a photo as part of this episode which has been // removed. We still need to record it, but with state unshared. unshares_++; (*photos_)[photo_id] = UNSHARE_PENDING; } recompute_timestamp_range_ = true; } bool EpisodeTable_Episode::IsHidden(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); const PhotoState state = FindOrDefault(*photos_, photo_id, REMOVED); return (state == HIDDEN || state == HIDE_PENDING); } bool EpisodeTable_Episode::IsPosted(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); const PhotoState state = FindOrDefault(*photos_, photo_id, REMOVED); return (state == POSTED || state == POST_PENDING); } bool EpisodeTable_Episode::IsQuarantined(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); const PhotoState state = FindOrDefault(*photos_, photo_id, REMOVED); return (state == QUARANTINED || state == QUARANTINE_PENDING); } bool EpisodeTable_Episode::IsRemoved(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); const PhotoState state = FindOrDefault(*photos_, photo_id, REMOVED); return (state == REMOVED || state == REMOVE_PENDING); } bool EpisodeTable_Episode::IsUnshared(int64_t photo_id) { MutexLock lock(&photos_mu_); EnsurePhotoState(); const PhotoState state = FindOrDefault(*photos_, photo_id, REMOVED); return (state == UNSHARED || state == UNSHARE_PENDING); } int EpisodeTable_Episode::CountPhotos() { MutexLock lock(&photos_mu_); EnsurePhotoState(); int count = 0; for (PhotoStateMap::iterator iter(photos_->begin()); iter != photos_->end(); ++iter) { if (iter->second == POSTED || iter->second == POST_PENDING) { ++count; } } return count; } void EpisodeTable_Episode::ListPhotos(vector<int64_t>* photo_ids) { MutexLock lock(&photos_mu_); EnsurePhotoState(); for (PhotoStateMap::iterator iter(photos_->begin()); iter != photos_->end(); ++iter) { const bool posted = (iter->second == POSTED || iter->second == POST_PENDING); if (posted) { photo_ids->push_back(iter->first); } } } void EpisodeTable_Episode::ListAllPhotos(vector<int64_t>* photo_ids) { MutexLock lock(&photos_mu_); EnsurePhotoState(); for (PhotoStateMap::iterator iter(photos_->begin()); iter != photos_->end(); ++iter) { photo_ids->push_back(iter->first); } } void EpisodeTable_Episode::ListUnshared(vector<int64_t>* unshared_ids) { MutexLock lock(&photos_mu_); EnsurePhotoState(); for (PhotoStateMap::iterator iter(photos_->begin()); iter != photos_->end(); ++iter) { if (iter->second == UNSHARED || iter->second == UNSHARE_PENDING) { unshared_ids->push_back(iter->first); } } } bool EpisodeTable_Episode::InLibrary() { if (!has_viewpoint_id()) { // If there's no viewpoint, user hasn't uploaded episode; always show. return true; } // Otherwise, show any episode which is part of the default viewpoint. ViewpointHandle vh = state_->viewpoint_table()->LoadViewpoint(viewpoint_id(), db_); return vh.get() && vh->is_default(); } bool EpisodeTable_Episode::GetTimeRange( WallTime* earliest, WallTime* latest) { if (!has_earliest_photo_timestamp() && !has_latest_photo_timestamp()) { return false; } *earliest = earliest_photo_timestamp(); *latest = latest_photo_timestamp(); return true; } bool EpisodeTable_Episode::GetLocation(Location* loc, Placemark* pm) { if (resolved_location_) { if (!location_.get()) { return false; } *loc = *location_; if (pm) { *pm = *placemark_; } return true; } resolved_location_ = true; location_.reset(new Location); placemark_.reset(new Placemark); vector<int64_t> photo_ids; ListPhotos(&photo_ids); for (int i = 0; i < photo_ids.size(); ++i) { PhotoHandle ph = state_->photo_table()->LoadPhoto(photo_ids[i], db_); if (ph.get() && ph->GetLocation(location_.get(), placemark_.get())) { *loc = *location_; if (pm) { *pm = *placemark_; } return true; } } location_.reset(NULL); placemark_.reset(NULL); return false; } bool EpisodeTable_Episode::MaybeSetServerId() { const int64_t device_id = state_->device_id(); if (id().has_server_id() || !device_id) { return false; } mutable_id()->set_server_id( EncodeEpisodeId(device_id, id().local_id(), timestamp())); return true; } string EpisodeTable_Episode::FormatLocation(bool shorten) { Location loc; Placemark pm; if (GetLocation(&loc, &pm)) { string loc_str; state_->placemark_histogram()->FormatLocation(loc, pm, shorten, &loc_str); return ToUppercase(loc_str); } return shorten ? "" : "Location Unavailable"; } string EpisodeTable_Episode::FormatTimeRange(bool shorten, WallTime now) { WallTime earliest, latest; if (!GetTimeRange(&earliest, &latest)) { return ""; } // If shorten is true, format just the earliest time. if (shorten) { return FormatRelativeTime(earliest, now == 0 ? earliest : now); } // Format a time range, using start of the day corresponding // to the latest time as "now". This results in the time // range being expressed as times only. return FormatDateRange(earliest, latest, now == 0 ? latest : now); } string EpisodeTable_Episode::FormatContributor(bool shorten) { if (!has_user_id() || user_id() == state_->user_id()) { return ""; } if (shorten) { return state_->contact_manager()->FirstName(user_id()); } else { return state_->contact_manager()->FullName(user_id()); } } void EpisodeTable_Episode::Invalidate(const DBHandle& updates) { typedef ContentTable<EpisodeTable_Episode>::Content Content; EpisodeHandle eh(reinterpret_cast<Content*>(this)); state_->day_table()->InvalidateEpisode(eh, updates); // Invalidate any activities which shared photos from this episode. if (id().has_server_id()) { vector<int64_t> activity_ids; state_->activity_table()->ListEpisodeActivities(id().server_id(), &activity_ids, updates); for (int i = 0; i < activity_ids.size(); ++i) { ActivityHandle ah = state_->activity_table()->LoadActivity(activity_ids[i], updates); state_->day_table()->InvalidateActivity(ah, updates); } } } bool EpisodeTable_Episode::Load() { disk_timestamp_ = timestamp(); return true; } void EpisodeTable_Episode::SaveHook(const DBHandle& updates) { bool has_posted_photo = false; bool update_episode_timestamp = false; if (photos_.get()) { if (recompute_timestamp_range_) { clear_earliest_photo_timestamp(); clear_latest_photo_timestamp(); } // Persist any photo additions/removals. int photo_count = 0; int updated = 0; for (PhotoStateMap::iterator iter(photos_->begin()); iter != photos_->end(); ++iter) { const int64_t photo_id = iter->first; const string episode_photo_key = EncodeEpisodePhotoKey(id().local_id(), photo_id); const string photo_episode_key = EncodePhotoEpisodeKey(photo_id, id().local_id()); // Keep earliest and latest photo timestamps up to date. Note that in the // common case where a photo is being added, we're simply updating the // existing range and not recomputing it from scratch. if ((recompute_timestamp_range_ && iter->second == POSTED) || iter->second == POST_PENDING) { PhotoHandle ph = state_->photo_table()->LoadPhoto(photo_id, updates); if (!ph.get()) { LOG("couldn't load photo %d", photo_id); continue; } // Keep earliest and latest photo timestamps up-to-date. if (!has_earliest_photo_timestamp() || ph->timestamp() < earliest_photo_timestamp()) { set_earliest_photo_timestamp(ph->timestamp()); } if (!has_latest_photo_timestamp() || ph->timestamp() > latest_photo_timestamp()) { set_latest_photo_timestamp(ph->timestamp()); } } // Counts of the number of episodes the photo resides in immediately // before/after performing an addition or deletion. Used to determine if // the total count of photos in episodes is changing. int pre_add_episode_count = -1; int post_delete_episode_count = -1; if (iter->second == HIDE_PENDING) { pre_add_episode_count = state_->episode_table()->CountEpisodes(photo_id, updates); updates->Put(episode_photo_key, EpisodeTable::kHiddenValue); updates->Put(photo_episode_key, string()); iter->second = HIDDEN; ++updated; } else if (iter->second == POST_PENDING) { pre_add_episode_count = state_->episode_table()->CountEpisodes(photo_id, updates); updates->Put(episode_photo_key, EpisodeTable::kPostedValue); updates->Put(photo_episode_key, string()); iter->second = POSTED; ++updated; } else if (iter->second == QUARANTINE_PENDING) { // NOTE: quarantined photos count against total count of photos. pre_add_episode_count = state_->episode_table()->CountEpisodes(photo_id, updates); updates->Put(episode_photo_key, EpisodeTable::kQuarantinedValue); updates->Put(photo_episode_key, string()); iter->second = QUARANTINED; ++updated; } else if (iter->second == REMOVE_PENDING) { updates->Put(episode_photo_key, EpisodeTable::kRemovedValue); if (updates->Exists(photo_episode_key)) { // Decrement the photo ref count for this episode. updates->Delete(photo_episode_key); } post_delete_episode_count = state_->episode_table()->CountEpisodes(photo_id, updates); iter->second = REMOVED; ++updated; } else if (iter->second == UNSHARE_PENDING) { updates->Put(episode_photo_key, EpisodeTable::kUnsharedValue); if (updates->Exists(photo_episode_key)) { updates->Delete(photo_episode_key); post_delete_episode_count = state_->episode_table()->CountEpisodes(photo_id, updates); } iter->second = UNSHARED; ++updated; } if (iter->second == POSTED) { has_posted_photo = true; } if (pre_add_episode_count == 0) { // Photo was added to its first episode. ++photo_count; } if (post_delete_episode_count == 0) { // Photo was deleted from its last episode. Delete any images // associated with the photo. state_->photo_table()->DeleteAllImages(photo_id, updates); --photo_count; } } if (photo_count != 0) { VLOG("saved episode had net addition of %d photos", photo_count); } if (!has_earliest_photo_timestamp()) { DCHECK(!has_latest_photo_timestamp()); set_earliest_photo_timestamp(timestamp()); set_latest_photo_timestamp(timestamp()); } // Update the episode timestamp mapping any time a photo is added, // hidden, removed or unshared. update_episode_timestamp = updated > 0; } if (disk_timestamp_ != timestamp() || update_episode_timestamp) { if (disk_timestamp_ > 0) { updates->Delete( EncodeEpisodeTimestampKey(disk_timestamp_, id().local_id())); } disk_timestamp_ = timestamp(); } // We reference has_posted_photo to avoid counting photos in the episode // unnecessarily. if (disk_timestamp_ > 0 && (has_posted_photo || CountPhotos() > 0)) { // Only add the episode to the <timestamp>,<episode-id> map if the // episode contains POSTED photos. updates->Put(EncodeEpisodeTimestampKey(disk_timestamp_, id().local_id()), string()); } if (has_parent_id()) { updates->Put(EncodeEpisodeParentChildKey(parent_id().local_id(), id().local_id()), string()); } additions_ = 0; hiddens_ = 0; quarantines_ = 0; removals_ = 0; unshares_ = 0; recompute_timestamp_range_ = false; Invalidate(updates); } void EpisodeTable_Episode::DeleteHook(const DBHandle& updates) { int photo_count = 0; MutexLock lock(&photos_mu_); EnsurePhotoState(); for (PhotoStateMap::iterator iter(photos_->begin()); iter != photos_->end(); ++iter) { const int64_t photo_id = iter->first; const string episode_photo_key = EncodeEpisodePhotoKey(id().local_id(), photo_id); const string photo_episode_key = EncodePhotoEpisodeKey(photo_id, id().local_id()); updates->Delete(episode_photo_key); updates->Delete(photo_episode_key); if (!state_->episode_table()->CountEpisodes(photo_id, updates)) { // Photo was deleted from its last episode. Delete any images // associated with the photo. state_->photo_table()->DeleteAllImages(photo_id, updates); --photo_count; } } if (photo_count != 0) { VLOG("deleted episode had net addition of %d photos", photo_count); } if (disk_timestamp_ > 0) { updates->Delete( EncodeEpisodeTimestampKey(disk_timestamp_, id().local_id())); } if (has_parent_id()) { updates->Delete(EncodeEpisodeParentChildKey(parent_id().local_id(), id().local_id())); } // Delete episode selection key. if (id().has_server_id()) { updates->Delete(DBFormat::episode_selection_key(id().server_id())); } Invalidate(updates); } void EpisodeTable_Episode::EnsurePhotoState() { photos_mu_.AssertHeld(); if (have_photo_state_) { return; } if (!photos_.get()) { photos_.reset(new PhotoStateMap); } have_photo_state_ = true; for (ScopedPtr<EpisodeTable::EpisodePhotoIterator> iter( new EpisodeTable::EpisodePhotoIterator(id().local_id(), db_)); !iter->done(); iter->Next()) { const int64_t photo_id = iter->photo_id(); if (ContainsKey(*photos_, photo_id)) { // Note that the disk photo state gets layered in underneath the existing // photo state. continue; } const Slice value = iter->value(); if (value == EpisodeTable::kHiddenValue) { (*photos_)[photo_id] = HIDDEN; } else if (value == EpisodeTable::kPostedValue) { (*photos_)[photo_id] = POSTED; } else if (value == EpisodeTable::kQuarantinedValue) { (*photos_)[photo_id] = QUARANTINED; } else if (value == EpisodeTable::kRemovedValue) { (*photos_)[photo_id] = REMOVED; } else if (value == EpisodeTable::kUnsharedValue) { (*photos_)[photo_id] = UNSHARED; } } } //// // EpisodeIterator EpisodeTable::EpisodeIterator::EpisodeIterator( EpisodeTable* table, WallTime start, bool reverse, const DBHandle& db) : ContentIterator(db->NewIterator(), reverse), table_(table), db_(db), timestamp_(0), episode_id_(0) { Seek(start); } EpisodeHandle EpisodeTable::EpisodeIterator::GetEpisode() { if (done()) { return EpisodeHandle(); } return table_->LoadContent(episode_id_, db_); } void EpisodeTable::EpisodeIterator::Seek(WallTime seek_time) { ContentIterator::Seek(EncodeEpisodeTimestampKey( seek_time, reverse_ ? std::numeric_limits<int64_t>::max() : 0)); } bool EpisodeTable::EpisodeIterator::IteratorDone(const Slice& key) { return !key.starts_with(kEpisodeTimestampKeyPrefix); } bool EpisodeTable::EpisodeIterator::UpdateStateHook(const Slice& key) { return DecodeEpisodeTimestampKey(key, &timestamp_, &episode_id_); } //// // EpisodePhotoIterator EpisodeTable::EpisodePhotoIterator::EpisodePhotoIterator( int64_t episode_id, const DBHandle& db) : ContentIterator(db->NewIterator(), false), episode_prefix_(EncodeEpisodePhotoKey(episode_id, 0)), photo_id_(0) { Seek(episode_prefix_); } bool EpisodeTable::EpisodePhotoIterator::IteratorDone(const Slice& key) { return !key.starts_with(episode_prefix_); } bool EpisodeTable::EpisodePhotoIterator::UpdateStateHook(const Slice& key) { int64_t episode_id; return DecodeEpisodePhotoKey(key, &episode_id, &photo_id_); } //// // EpisodeTable const string EpisodeTable::kHiddenValue = "h"; const string EpisodeTable::kPostedValue = "a"; const string EpisodeTable::kQuarantinedValue = "q"; const string EpisodeTable::kRemovedValue = "r"; const string EpisodeTable::kUnsharedValue = "u"; EpisodeTable::EpisodeTable(AppState* state) : ContentTable<Episode>(state, DBFormat::episode_key(), DBFormat::episode_server_key(), kEpisodeFSCKVersion, DBFormat::metadata_key("episode_table_fsck")), stats_initialized_(false), episode_index_(new FullTextIndex(state_, kEpisodeIndexName)), location_index_(new FullTextIndex(state_, kLocationIndexName)) { } EpisodeTable::~EpisodeTable() { } void EpisodeTable::Reset() { MutexLock l(&stats_mu_); stats_initialized_ = false; stats_.Clear(); } EpisodeHandle EpisodeTable::LoadEpisode(const EpisodeId& id, const DBHandle& db) { EpisodeHandle eh; if (id.has_local_id()) { eh = LoadEpisode(id.local_id(), db); } if (!eh.get() && id.has_server_id()) { eh = LoadEpisode(id.server_id(), db); } return eh; } EpisodeTable::ContentHandle EpisodeTable::MatchPhotoToEpisode( const PhotoHandle& p, const DBHandle& db) { const WallTime max_time = p->timestamp() + kMaxTimeDist; const WallTime min_time = std::max<WallTime>(0, p->timestamp() - kMaxTimeDist); for (ScopedPtr<EpisodeTable::EpisodeIterator> iter( NewEpisodeIterator(min_time, false, db)); !iter->done() && iter->timestamp() <= max_time; iter->Next()) { EpisodeHandle e = LoadEpisode(iter->episode_id(), db); if (!e.get() || // Only match to episodes owned by this user. e->GetUserId() != p->GetUserId() || // Server disallows match to an episode created on another device. e->GetDeviceId() != p->GetDeviceId() || // Don't match a photo to an episode which is a reshare! e->has_parent_id()) { continue; } // We use a photo iterator instead of ListPhotos() because we most likely // will match on the first photo. for (ScopedPtr<EpisodeTable::EpisodePhotoIterator> photo_iter( new EpisodeTable::EpisodePhotoIterator(e->id().local_id(), db)); !photo_iter->done(); photo_iter->Next()) { if (photo_iter->value() != EpisodeTable::kPostedValue) { continue; } PhotoHandle q = state_->photo_table()->LoadPhoto(photo_iter->photo_id(), db); if (!q.get()) { continue; } if (p->has_timestamp() && q->has_timestamp()) { const double time_dist = fabs(p->timestamp() - q->timestamp()); if (time_dist >= kMaxTimeDist) { continue; } } if (p->has_location() && q->has_location()) { const double loc_dist = DistanceBetweenLocations( p->location(), q->location()); if (loc_dist >= kMaxLocDist) { continue; } } return e; } } return EpisodeHandle(); } void EpisodeTable::AddPhotoToEpisode(const PhotoHandle& p, const DBHandle& updates) { if (!p->ShouldAddPhotoToEpisode()) { return; } EpisodeHandle e = MatchPhotoToEpisode(p, updates); if (!e.get()) { e = NewEpisode(updates); e->Lock(); e->set_timestamp(p->timestamp()); e->set_upload_episode(true); e->MaybeSetServerId(); VLOG("photo: new episode: %s", e->id()); } else { e->Lock(); } p->mutable_episode_id()->CopyFrom(e->id()); e->AddPhoto(p->id().local_id()); e->SaveAndUnlock(updates); } int EpisodeTable::CountEpisodes(int64_t photo_id, const DBHandle& db) { int count = 0; for (DB::PrefixIterator iter(db, EncodePhotoEpisodeKey(photo_id, 0)); iter.Valid(); iter.Next()) { int64_t photo_id; int64_t episode_id; if (DecodePhotoEpisodeKey(iter.key(), &photo_id, &episode_id)) { ++count; } } return count; } bool EpisodeTable::ListEpisodes( int64_t photo_id, vector<int64_t>* episode_ids, const DBHandle& db) { for (DB::PrefixIterator iter(db, EncodePhotoEpisodeKey(photo_id, 0)); iter.Valid(); iter.Next()) { int64_t photo_id; int64_t episode_id; if (DecodePhotoEpisodeKey(iter.key(), &photo_id, &episode_id)) { if (episode_ids) { episode_ids->push_back(episode_id); } else { return true; } } } return episode_ids && !episode_ids->empty(); } bool EpisodeTable::ListLibraryEpisodes( int64_t photo_id, vector<int64_t>* episode_ids, const DBHandle& db) { vector<int64_t> raw_episode_ids; if (!ListEpisodes(photo_id, &raw_episode_ids, db)) { return false; } for (int i = 0; i < raw_episode_ids.size(); ++i) { EpisodeHandle eh = LoadEpisode(raw_episode_ids[i], db); if (eh.get() && eh->InLibrary()) { if (episode_ids) { episode_ids->push_back(raw_episode_ids[i]); } else { return true; } } } return episode_ids && !episode_ids->empty(); } void EpisodeTable::RemovePhotos( const PhotoSelectionVec& photo_ids, const DBHandle& updates) { typedef std::unordered_map<int64_t, vector<int64_t> > EpisodeToPhotoMap; EpisodeToPhotoMap episodes; for (int i = 0; i < photo_ids.size(); ++i) { episodes[photo_ids[i].episode_id].push_back(photo_ids[i].photo_id); } ServerOperation op; ServerOperation::RemovePhotos* r = op.mutable_remove_photos(); // Process the episodes in the same order as specified in the photo_ids // vector to ease testing. for (int i = 0; !episodes.empty() && i < photo_ids.size(); ++i) { const int64_t episode_id = photo_ids[i].episode_id; const vector<int64_t>* v = FindPtrOrNull(episodes, episode_id); if (!v) { continue; } const EpisodeHandle eh = LoadEpisode(episode_id, updates); if (!eh.get()) { episodes.erase(episode_id); continue; } eh->Lock(); ActivityMetadata::Episode* e = NULL; for (int j = 0; j < v->size(); ++j) { const int64_t photo_id = (*v)[j]; if (!state_->photo_table()->LoadPhoto(photo_id, updates).get()) { continue; } if (!e) { // Only add an episode to the server operation when the first valid // photo id is found. e = r->add_episodes(); e->mutable_episode_id()->CopyFrom(eh->id()); } e->add_photo_ids()->set_local_id(photo_id); eh->RemovePhoto(photo_id); } if (e) { eh->SaveAndUnlock(updates); } else { eh->Unlock(); } episodes.erase(episode_id); } if (r->episodes_size() > 0) { // Only queue the operation if photos were removed. op.mutable_headers()->set_op_id(state_->NewLocalOperationId()); op.mutable_headers()->set_op_timestamp(WallTime_Now()); state_->net_queue()->Add(PRIORITY_UI_ACTIVITY, op, updates); } } EpisodeHandle EpisodeTable::GetEpisodeForPhoto( const PhotoHandle& p, const DBHandle& db) { // Start with the photo's putative episode. EpisodeHandle eh = LoadEpisode(p->episode_id(), db); if (eh.get()) { return eh; } // Otherwise, get a list of all episodes the photo belongs to // and find the first which has been uploaded, and for which the // photo has neither been removed or unshared. vector<int64_t> episode_ids; ListEpisodes(p->id().local_id(), &episode_ids, db); for (int i = 0; i < episode_ids.size(); ++i) { eh = LoadEpisode(episode_ids[i], db); if (eh.get() && !eh->upload_episode() && !eh->IsRemoved(p->id().local_id()) && !eh->IsUnshared(p->id().local_id())) { return eh; } } return EpisodeHandle(); } void EpisodeTable::Validate( const EpisodeSelection& s, const DBHandle& updates) { const string key(DBFormat::episode_selection_key(s.episode_id())); // Load any existing episode selection and clear attributes which have been // queried by "s". If no attributes remain set, the selection is deleted. EpisodeSelection existing; if (updates->GetProto(key, &existing)) { if (s.get_attributes()) { existing.clear_get_attributes(); } if (s.get_photos()) { if (!existing.get_photos() || s.photo_start_key() <= existing.photo_start_key()) { existing.clear_get_photos(); existing.clear_photo_start_key(); } } else if (existing.get_photos()) { existing.set_photo_start_key( std::max(existing.photo_start_key(), s.photo_start_key())); } } if (existing.has_get_attributes() || existing.has_get_photos()) { updates->PutProto(key, existing); } else { updates->Delete(key); } } void EpisodeTable::Invalidate( const EpisodeSelection& s, const DBHandle& updates) { const string key(DBFormat::episode_selection_key(s.episode_id())); // Load any existing episode selection and merge invalidations from "s". EpisodeSelection existing; if (!updates->GetProto(key, &existing)) { existing.set_episode_id(s.episode_id()); } if (s.get_attributes()) { existing.set_get_attributes(true); } if (s.get_photos()) { if (existing.get_photos()) { existing.set_photo_start_key(std::min<string>(existing.photo_start_key(), s.photo_start_key())); } else { existing.set_photo_start_key(s.photo_start_key()); } existing.set_get_photos(true); } updates->PutProto(key, existing); } void EpisodeTable::ListInvalidations( vector<EpisodeSelection>* v, int limit, const DBHandle& db) { v->clear(); ScopedPtr<leveldb::Iterator> iter(db->NewIterator()); iter->Seek(kEpisodeSelectionKeyPrefix); while (iter->Valid() && (limit <= 0 || v->size() < limit)) { Slice key = ToSlice(iter->key()); if (!key.starts_with(kEpisodeSelectionKeyPrefix)) { break; } EpisodeSelection eps; if (db->GetProto(key, &eps)) { v->push_back(eps); } else { LOG("unable to read episode selection at key %s", key); } iter->Next(); } } void EpisodeTable::ClearAllInvalidations(const DBHandle& updates) { ScopedPtr<leveldb::Iterator> iter(updates->NewIterator()); iter->Seek(kEpisodeSelectionKeyPrefix); for (; iter->Valid(); iter->Next()) { Slice key = ToSlice(iter->key()); if (!key.starts_with(kEpisodeSelectionKeyPrefix)) { break; } updates->Delete(key); } } void EpisodeTable::ListEpisodesByParentId( int64_t parent_id, vector<int64_t>* children, const DBHandle& db) { for (DB::PrefixIterator iter(db, EncodeEpisodeParentChildKey(parent_id, 0)); iter.Valid(); iter.Next()) { int64_t parent_id; int64_t child_id; if (DecodeEpisodeParentChildKey(iter.key(), &parent_id, &child_id)) { children->push_back(child_id); } } } EpisodeTable::EpisodeIterator* EpisodeTable::NewEpisodeIterator( WallTime start, bool reverse, const DBHandle& db) { return new EpisodeIterator(this, start, reverse, db); } EpisodeStats EpisodeTable::stats() { EnsureStatsInit(); MutexLock l(&stats_mu_); return stats_; } bool EpisodeTable::FSCKImpl(int prev_fsck_version, const DBHandle& updates) { LOG("FSCK: EpisodeTable"); bool changes = false; if (FSCKEpisode(prev_fsck_version, updates)) { changes = true; } // Handle any duplicates in secondary indexes by timestamp. These can exist // as a result of a server bug which rounded up timestamps. if (FSCKEpisodeTimestampIndex(updates)) { changes = true; } return changes; } bool EpisodeTable::FSCKEpisode(int prev_fsck_version, const DBHandle& updates) { bool changes = false; for (DB::PrefixIterator iter(updates, DBFormat::episode_key()); iter.Valid(); iter.Next()) { const Slice key = iter.key(); const Slice value = iter.value(); EpisodeMetadata em; if (em.ParseFromArray(value.data(), value.size())) { EpisodeHandle eh = LoadEpisode(em.id().local_id(), updates); eh->Lock(); bool save_eh = false; if (key != EncodeContentKey(DBFormat::episode_key(), em.id().local_id())) { LOG("FSCK: episode id %d does not equal key %s; deleting key and re-saving", em.id().local_id(), key); updates->Delete(key); save_eh = true; } // Check required fields. if (!eh->has_id() || !eh->has_timestamp()) { LOG("FSCK: episode missing required fields: %s", *eh); } // Check viewpoint; lookup first by server id. if (eh->has_viewpoint_id()) { ViewpointHandle vh = state_->viewpoint_table()->LoadViewpoint(eh->viewpoint_id(), updates); if (vh.get() && !eh->viewpoint_id().local_id()) { LOG("FSCK: missing local id for viewpoint %s", vh->id()); eh->mutable_viewpoint_id()->CopyFrom(vh->id()); save_eh = true; } else if (!vh.get()) { if (eh->viewpoint_id().has_server_id()) { LOG("FSCK: missing viewpoint %s; setting invalidation", eh->viewpoint_id()); state_->viewpoint_table()->InvalidateFull(eh->viewpoint_id().server_id(), updates); changes = true; } else { LOG("FSCK: invalid reference to viewpoint %s; clearing", eh->viewpoint_id()); eh->clear_viewpoint_id(); save_eh = true; } } } // Check secondary indexes. if (eh->has_timestamp() && eh->CountPhotos() > 0) { const string ts_episode_key = EncodeEpisodeTimestampKey( eh->timestamp(), eh->id().local_id()); if (!updates->Exists(ts_episode_key)) { LOG("FSCK: missing timestamp episode key"); save_eh = true; } } // Verify photo timestamp range is set. if (!eh->has_earliest_photo_timestamp() || !eh->has_latest_photo_timestamp()) { LOG("FSCK: missing photo timestamp range; recomputing..."); eh->recompute_timestamp_range_ = true; save_eh = true; } if (save_eh) { LOG("FSCK: rewriting episode %s", *eh); eh->SaveAndUnlock(updates); changes = true; } else { eh->Unlock(); } } } return changes; } bool EpisodeTable::FSCKEpisodeTimestampIndex(const DBHandle& updates) { // Map from episode id to secondary index key. std::unordered_map<int64_t, string>* episode_ids( new std::unordered_map<int64_t, string>); bool changes = false; for (DB::PrefixIterator iter(updates, kEpisodeTimestampKeyPrefix); iter.Valid(); iter.Next()) { const Slice key = iter.key(); WallTime timestamp; int64_t episode_id; if (!DecodeEpisodeTimestampKey(key, &timestamp, &episode_id)) { LOG("FSCK: unreadable episode timestamp secondary index: %s", key); updates->Delete(key); changes = true; } else { if (ContainsKey(*episode_ids, episode_id)) { LOG("FSCK: episode timestamp secondary index contains duplicate entries for %d; " "deleting earlier instance (%s)", episode_id, (*episode_ids)[episode_id]); updates->Delete((*episode_ids)[episode_id]); changes = true; } (*episode_ids)[episode_id] = ToString(key); } } delete episode_ids; return changes; } void EpisodeTable::Search(const Slice& query, EpisodeSearchResults* results) { QueryRewriter rewriter(state_); ScopedPtr<FullTextQuery> parsed_query(rewriter.ParseAndRewrite(query)); FullTextQueryIteratorBuilder builder({episode_index_.get(), location_index_.get()}, state_->db()); for (ScopedPtr<FullTextResultIterator> iter(builder.BuildIterator(*parsed_query)); iter->Valid(); iter->Next()) { results->push_back(FastParseInt64(iter->doc_id())); } } void EpisodeTable::SaveContentHook(Episode* episode, const DBHandle& updates) { vector<FullTextIndexTerm> terms; vector<FullTextIndexTerm> location_terms; int pos = 0; int location_pos = 0; // Don't index anything/remove all indexed terms if all photos have been removed. if (episode->CountPhotos() > 0) { Location loc; Placemark pm; // Index the location at several granularities. This lets us have separate autocomplete // entries for "Soho, NYC" and "New York, NY". if (episode->GetLocation(&loc, &pm)) { StringSet seen_location_terms; auto IndexLocationTerm = [&](const string& term) { if (term.empty() || ContainsKey(seen_location_terms, term)) { return; } seen_location_terms.insert(term); // Index each location term as both a bag of words in the main index and a single term in the // location index (for better autocomplete). pos = episode_index_->ParseIndexTerms(pos, term, &terms); // TODO(ben): this raw term should go through the denormalization process so "i" can // autocomplete to "Île-de-France". location_terms.push_back(FullTextIndexTerm(ToLowercase(term), term, location_pos++)); }; IndexLocationTerm(FormatPlacemarkWithReferencePlacemark(pm, NULL, false, PM_SUBLOCALITY, 2)); IndexLocationTerm(FormatPlacemarkWithReferencePlacemark(pm, NULL, false, PM_LOCALITY, 2)); IndexLocationTerm(FormatPlacemarkWithReferencePlacemark(pm, NULL, false, PM_STATE, 2)); } if (episode->has_timestamp()) { // Index the month, date and year. const string date = FormatDate("%B %e %Y", episode->timestamp()); pos = episode_index_->ParseIndexTerms(pos, date, &terms); } if (episode->user_id() != 0 && episode->user_id() != state_->user_id()) { pos = episode_index_->AddVerbatimToken(pos, ContactManager::FormatUserToken(episode->user_id()), &terms); } if (episode->viewpoint_id().local_id() != 0) { pos = episode_index_->AddVerbatimToken(pos, ViewpointTable::FormatViewpointToken(episode->viewpoint_id().local_id()), &terms); } } episode_index_->UpdateIndex(terms, ToString(episode->id().local_id()), FullTextIndex::TimestampSortKey(episode->timestamp()), episode->mutable_indexed_terms(), updates); location_index_->UpdateIndex(location_terms, ToString(episode->id().local_id()), FullTextIndex::TimestampSortKey(episode->timestamp()), episode->mutable_indexed_location_terms(), updates); EnsureStatsInit(); MutexLock l(&stats_mu_); stats_.set_hidden_photos(stats_.hidden_photos() + episode->hiddens()); stats_.set_posted_photos(stats_.posted_photos() + episode->additions()); stats_.set_quarantined_photos(stats_.quarantined_photos() + episode->quarantines()); stats_.set_removed_photos(stats_.removed_photos() + episode->removals()); stats_.set_unshared_photos(stats_.unshared_photos() + episode->unshares()); } void EpisodeTable::DeleteContentHook(Episode* episode, const DBHandle& updates) { episode_index_->RemoveTerms(episode->mutable_indexed_terms(), updates); location_index_->RemoveTerms(episode->mutable_indexed_location_terms(), updates); } void EpisodeTable::EnsureStatsInit() { if (stats_initialized_) { return; } MutexLock l(&stats_mu_); stats_initialized_ = true; // ScopedTimer timer("episode stats"); // The stats could not be loaded; Regenerate from scratch. int hidden_photos = 0; int posted_photos = 0; int quarantined_photos = 0; int removed_photos = 0; int unshared_photos = 0; for (DB::PrefixIterator iter(state_->db(), EncodeEpisodePhotoKey(0, 0)); iter.Valid(); iter.Next()) { const Slice value = iter.value(); int64_t episode_id; int64_t photo_id; if (DecodeEpisodePhotoKey(iter.key(), &episode_id, &photo_id)) { if (value == EpisodeTable::kHiddenValue) { hidden_photos++; } else if (value == EpisodeTable::kPostedValue) { posted_photos++; } else if (value == EpisodeTable::kQuarantinedValue) { quarantined_photos++; } else if (value == EpisodeTable::kRemovedValue) { removed_photos++; } else if (value == EpisodeTable::kUnsharedValue) { unshared_photos++; } } } stats_.set_hidden_photos(hidden_photos); stats_.set_posted_photos(posted_photos); stats_.set_quarantined_photos(quarantined_photos); stats_.set_removed_photos(removed_photos); stats_.set_unshared_photos(unshared_photos); } // local variables: // mode: c++ // end:
19,833
2,659
<filename>cases/function/spark/generate_yaml_case.py<gh_stars>1000+ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 4Paradigm # # 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. # -*- coding: utf-8 -*- # pip3 install -U ruamel.yaml pyspark first import argparse from datetime import date import random import string import time import sys import pyspark import pyspark.sql from pyspark.sql.types import * import ruamel.yaml as yaml from ruamel.yaml import RoundTripDumper, RoundTripLoader from ruamel.yaml.scalarstring import LiteralScalarString, DoubleQuotedScalarString YAML_TEST_TEMPLATE = """ db: test_db cases: - id: 1 desc: yaml 测试用例模版 inputs: [] sql: | select * from t1 expect: success: true """ INPUT_TEMPLATE = """ columns: [] indexs: [] rows: [] """ def random_string(prefix, n): return "{}_{}".format(prefix, ''.join(random.choices(string.ascii_letters + string.digits, k=n))) # random date in current year def random_date(): start_dt = date.today().replace(day=1, month=1).toordinal() end_dt = date.today().toordinal() random_day = date.fromordinal(random.randint(start_dt, end_dt)) return random_day def to_column_str(field): tp = '{unknown_type}' if isinstance(field.dataType, BooleanType): tp = 'bool' elif isinstance(field.dataType, ShortType): tp = 'int16' elif isinstance(field.dataType, IntegerType): tp = 'int32' elif isinstance(field.dataType, LongType): tp = 'int64' elif isinstance(field.dataType, StringType): tp = 'string' elif isinstance(field.dataType, TimestampType): tp = 'timestamp' elif isinstance(field.dataType, DateType): tp = 'date' elif isinstance(field.dataType, DoubleType): tp = 'double' elif isinstance(field.dataType, FloatType): tp = 'float' return "%s %s" % (field.name, tp) def random_row(schema): row = [] for field_schema in schema.fields: field_type = field_schema.dataType if isinstance(field_type, BooleanType): row.append(random.choice([True, False])) elif isinstance(field_type, ShortType): row.append(random.randint(- (1 << 15), 1 << 15 - 1)) elif isinstance(field_type, IntegerType): row.append(random.randint(- (1 << 31), 1 << 31 - 1)) elif isinstance(field_type, LongType): row.append(random.randint(-(1 << 63), 1 << 63 - 1)) elif isinstance(field_type, StringType): row.append(random_string(field_schema.name, 10)) elif isinstance(field_type, TimestampType): # in milliseconds row.append(int(time.time()) * 1000) elif isinstance(field_type, DateType): row.append(random_date()) elif isinstance(field_type, DoubleType): row.append(random.uniform(-128.0, 128.0)) elif isinstance(field_type, FloatType): row.append(random.uniform(-128.0, 128.0)) else: row.append('{unknown}') return row def to_string(value): if isinstance(value, date): return DoubleQuotedScalarString(value.strftime("%Y-%m-%d")) if isinstance(value, float): return float("%.2f" % value) if isinstance(value, str): return DoubleQuotedScalarString(value) return value sess = None def gen_inputs_column_and_rows(parquet_file, table_name=''): global sess if sess is None: sess = pyspark.sql.SparkSession(pyspark.SparkContext()) dataframe = sess.read.parquet(parquet_file) hdfs_schema = dataframe.schema schema = [DoubleQuotedScalarString(to_column_str(f)) for f in hdfs_schema.fields] table = yaml.load(INPUT_TEMPLATE, Loader=RoundTripLoader) if table_name: table['name'] = table_name table['columns'] = schema data_set = [] row_cnt = random.randint(1, 10) for _ in range(row_cnt): data_set.append(random_row(hdfs_schema)) table['rows'] = [list(map(to_string, row)) for row in data_set] return table if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--sql", required=True, help="sql text path") group = parser.add_mutually_exclusive_group() group.add_argument("--schema-file", help="path to hdfs content(in parquet format), used to detect table schema") group.add_argument("--schema-list-file", help="list file conataining a list of hdfs files, \"table_name: file path\" per line") parser.add_argument("--output", required=True, help="path to output yaml file") args = parser.parse_args() sql = args.sql schema_file = args.schema_file schema_list_file = args.schema_list_file output = args.output yaml_test = yaml.load(YAML_TEST_TEMPLATE, Loader=RoundTripLoader, preserve_quotes=True) if schema_file: tb = gen_inputs_column_and_rows(schema_file) yaml_test['cases'][0]['inputs'].append(tb) elif schema_list_file: with open(schema_list_file, 'r') as l: for schema_file in l: sf = schema_file.strip() if not sf: continue table_name, parquet_file, *_ = sf.split(':') parquet_file = parquet_file.strip() if parquet_file: tb = gen_inputs_column_and_rows(parquet_file, table_name) yaml_test['cases'][0]['inputs'].append(tb) else: print("error") sys.exit(1) with open(sql, 'r') as f: yaml_test['cases'][0]['sql'] = LiteralScalarString(f.read().strip()) with open(output, 'w') as f: f.write(yaml.dump(yaml_test, Dumper=RoundTripDumper, allow_unicode=True))
2,672
322
<filename>experimental/broken_examples/mass_spring_partial_tightening.c /* * This file is part of acados. * * acados is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * acados is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with acados; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <math.h> #include <stdio.h> #include <stdlib.h> // flush denormals to zero #if defined(TARGET_X64_AVX2) || defined(TARGET_X64_AVX) || \ defined(TARGET_X64_SSE3) || defined(TARGET_X86_ATOM) || \ defined(TARGET_AMD_SSE3) #include <xmmintrin.h> // needed to flush to zero sub-normals with _MM_SET_FLUSH_ZERO_MODE (_MM_FLUSH_ZERO_ON); in the main() #endif #include "hpmpc/include/aux_d.h" #include "hpmpc/include/mpc_solvers.h" #include "acados/ocp_qp/ocp_qp_common.h" #include "acados/ocp_qp/ocp_qp_hpmpc.h" #include "acados/utils/timing.h" #include "acados/utils/math.h" #include "acados/utils/types.h" // define IP solver arguments && number of repetitions #define NREP 1 #define MAXITER 50 #define TOL 1e-8 #define MINSTEP 1e-8 /************************************************ Mass-spring system: nx/2 masses connected each other with springs (in a row), and the first and the last one to walls. nu (<=nx) controls act on the first nu masses. The system is sampled with sampling time Ts. ************************************************/ void mass_spring_system(double Ts, int nx, int nu, double *A, double *B, double *b, double *x0) { int nx2 = nx * nx; int info = 0; int pp = nx / 2; // number of masses /************************************************ * build the continuous time system ************************************************/ double *T; d_zeros(&T, pp, pp); int ii; for (ii = 0; ii < pp; ii++) T[ii * (pp + 1)] = -2; for (ii = 0; ii < pp - 1; ii++) T[ii * (pp + 1) + 1] = 1; for (ii = 1; ii < pp; ii++) T[ii * (pp + 1) - 1] = 1; double *Z; d_zeros(&Z, pp, pp); double *I; d_zeros(&I, pp, pp); for (ii = 0; ii < pp; ii++) I[ii * (pp + 1)] = 1.0; // = eye(pp); double *Ac; d_zeros(&Ac, nx, nx); dmcopy(pp, pp, Z, pp, Ac, nx); dmcopy(pp, pp, T, pp, Ac + pp, nx); dmcopy(pp, pp, I, pp, Ac + pp * nx, nx); dmcopy(pp, pp, Z, pp, Ac + pp * (nx + 1), nx); free(T); free(Z); free(I); d_zeros(&I, nu, nu); for (ii = 0; ii < nu; ii++) I[ii * (nu + 1)] = 1.0; // I = eye(nu); double *Bc; d_zeros(&Bc, nx, nu); dmcopy(nu, nu, I, nu, Bc + pp, nx); free(I); /************************************************ * compute the discrete time system ************************************************/ double *bb; d_zeros(&bb, nx, 1); dmcopy(nx, 1, bb, nx, b, nx); dmcopy(nx, nx, Ac, nx, A, nx); dscal_3l(nx2, Ts, A); expm(nx, A); d_zeros(&T, nx, nx); d_zeros(&I, nx, nx); for (ii = 0; ii < nx; ii++) I[ii * (nx + 1)] = 1.0; // I = eye(nx); dmcopy(nx, nx, A, nx, T, nx); daxpy_3l(nx2, -1.0, I, T); dgemm_nn_3l(nx, nu, nx, T, nx, Bc, nx, B, nx); int *ipiv = (int *)malloc(nx * sizeof(int)); dgesv_3l(nx, nu, Ac, nx, ipiv, B, nx, &info); free(ipiv); free(Ac); free(Bc); free(bb); /************************************************ * initial state ************************************************/ if (nx == 4) { x0[0] = 5; x0[1] = 10; x0[2] = 15; x0[3] = 20; } else { int jj; for (jj = 0; jj < nx; jj++) x0[jj] = 1; } } int main() { printf("\n"); printf("\n"); printf("\n"); printf( " HPMPC -- Library for High-Performance implementation of solvers for " "MPC.\n"); printf( " Copyright (C) 2014-2015 by Technical University of Denmark. All " "rights reserved.\n"); printf("\n"); printf(" HPMPC is distributed in the hope that it will be useful,\n"); printf(" but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf(" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"); printf(" See the GNU Lesser General Public License for more details.\n"); printf("\n"); printf("\n"); printf("\n"); #if defined(TARGET_X64_AVX2) || defined(TARGET_X64_AVX) || \ defined(TARGET_X64_SSE3) || defined(TARGET_X86_ATOM) || \ defined(TARGET_AMD_SSE3) _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); // flush to zero subnormals !!! // works only with one thread // !!! #endif int ii, jj; int rep, nrep = NREP; int nx = 8; // number of states (it has to be even for the mass-spring // system test problem) int nu = 3; // number of inputs (controllers) (it has to be at least 1 and // at most nx/2 for the mass-spring system test problem) int N = 20; // horizon length int M = 2; // int nb = 11; // number of box constrained inputs and states int ng = 0; // 4; // number of general constraints int ngN = 0; // 4; // number of general constraints at the last stage // int nbu = nu < nb ? nu : nb; // int nbx = nb - nu > 0 ? nb - nu : 0; int nbu = 3; int nbx = 4; // stage-wise variant size int nxx[N + 1]; nxx[0] = 0; for (ii = 1; ii <= N; ii++) nxx[ii] = nx; int nuu[N + 1]; for (ii = 0; ii < N; ii++) nuu[ii] = nu; nuu[N] = 0; int nbb[N + 1]; // nbb[0] = nbu; // for (ii = 1; ii < N; ii++) nbb[ii] = nb; // nbb[N] = nbx; // Andrea XXX change this back to 11 bounds, changed to debug the strmat // interface for (ii = 0; ii < M; ii++) // XXX not M !!! nbb[ii] = nuu[ii] + nxx[ii] / 2; for (; ii <= N; ii++) nbb[ii] = 0; int ngg[N + 1]; for (ii = 0; ii < N; ii++) ngg[ii] = ng; ngg[N] = ngN; printf( " Test problem: mass-spring system with %d masses and %d controls.\n", nx / 2, nu); printf("\n"); printf( " MPC problem size: %d states, %d inputs, %d horizon length, %d " "two-sided box constraints, %d two-sided general constraints.\n", nx, nu, N, 7, ng); printf("\n"); printf( " IP method parameters: predictor-corrector IP, double precision, %d " "maximum iterations, %5.1e exit tolerance in duality measure.\n", MAXITER, TOL); printf("\n"); #if defined(TARGET_X64_AVX2) printf(" HPMPC built for the AVX2 architecture\n"); #endif #if defined(TARGET_X64_AVX) printf(" HPMPC built for the AVX architecture\n"); #endif printf("\n"); /************************************************ * dynamical system ************************************************/ // state space matrices & initial state double *A; d_zeros(&A, nx, nx); // states update matrix double *B; d_zeros(&B, nx, nu); // inputs matrix double *b; d_zeros(&b, nx, 1); // states offset double *x0; d_zeros(&x0, nx, 1); // initial state // mass-spring system double Ts = 0.5; // sampling time mass_spring_system(Ts, nx, nu, A, B, b, x0); for (jj = 0; jj < nx; jj++) b[jj] = 0.1; for (jj = 0; jj < nx; jj++) x0[jj] = 0; x0[0] = 2.5; x0[1] = 2.5; // d_print_mat(nx, nx, A, nx); // d_print_mat(nx, nu, B, nx); // d_print_mat(nx, 1, b, nx); // d_print_mat(nx, 1, x0, nx); // compute b0 = b + A*x0 double *b0; d_zeros(&b0, nx, 1); dcopy_3l(nx, b, 1, b0, 1); dgemv_n_3l(nx, nx, A, nx, x0, b0); // d_print_mat(nx, 1, b, nx); // d_print_mat(nx, 1, b0, nx); // then A0 is a matrix of size 0x0 double *A0; d_zeros(&A0, 0, 0); /************************************************ * general constraints ************************************************/ double *C; d_zeros(&C, ng, nx); double *D; d_zeros(&D, ng, nu); double *lg; d_zeros(&lg, ng, 1); double *ug; d_zeros(&ug, ng, 1); double *CN; d_zeros(&CN, ngN, nx); // for (ii = 0; ii < ngN; ii++) CN[ii * (ngN + 1)] = 1.0; // d_print_mat(ngN, nx, CN, ngN); double *lgN; d_zeros(&lgN, ngN, 1); // force all states to 0 at the last stage double *ugN; d_zeros(&ugN, ngN, 1); // force all states to 0 at the last stage /************************************************ * box & general constraints ************************************************/ int *idxb0; int_zeros(&idxb0, nbb[0], 1); // double *d0; d_zeros(&d0, 2*nb[0]+2*ng[0], 1); double *lb0; d_zeros(&lb0, nbb[1], 1); double *ub0; d_zeros(&ub0, nbb[1], 1); for (ii = 0; ii < nbb[0]; ii++) { if (ii < nuu[0]) { lb0[ii] = -0.5; // umin ub0[ii] = 0.5; // umax } else { lb0[ii] = -4.0; // xmin ub0[ii] = 4.0; // xmax } idxb0[ii] = ii; } // for(ii=0; ii<ng; ii++) //Andrea: no general constraints atm // { // // d0[2*nb[0]+ii] = - 100.0; // dmin // // d0[2*nb[0]+ng[0]+ii] = 100.0; // dmax // } // i_print_mat(1, nb[0], idxb0, 1); // d_print_mat(1, 2*nb[0]+2*ng[0], d0, 1); int *idxb1; int_zeros(&idxb1, nbb[1], 1); // double *d1; d_zeros(&d1, 2*nb[1]+2*ng[1], 1); int_zeros(&idxb1, nbb[1], 1); double *lb1; d_zeros(&lb1, nbb[1], 1); double *ub1; d_zeros(&ub1, nbb[1], 1); for (ii = 0; ii < nbb[1]; ii++) { if (ii < nuu[1]) { // input lb1[ii] = -0.5; // umin ub1[ii] = 0.5; // umax } else { // state lb1[ii] = -4.0; // xmin ub1[ii] = 4.0; // xmax } idxb1[ii] = ii; } // for(ii=0; ii<ng[1]; ii++) //Andrea: no general constraints atm // { // // d1[2*nb[1]+ii] = - 100.0; // dmin // // d1[2*nb[1]+ng[1]+ii] = 100.0; // dmax // } // i_print_mat(1, nb[1], idxb1, 1); // d_print_mat(1, 2*nb[1]+2*ng[1], d1, 1); int *idxbN; int_zeros(&idxbN, nbb[N], 1); // double *dN; d_zeros(&dN, 2*nb[N]+2*ng[N], 1); int_zeros(&idxbN, nbb[N], 1); double *lbN; d_zeros(&lbN, nbb[N], 1); double *ubN; d_zeros(&ubN, nbb[N], 1); for (ii = 0; ii < nbb[N]; ii++) { if (ii < nuu[N]) { lbN[ii] = -0.5; // umin ubN[ii] = 0.5; // umax } else { lbN[ii] = -4.0; // xmin ubN[ii] = 4.0; // xmax } idxbN[ii] = ii; } // for(ii=0; ii<ng[N]; ii++)//Andrea: no general constraints atm // { // // dN[2*nb[N]+ii] = - 100.0; // dmin // // dN[2*nb[N]+ng[N]+ii] = 100.0; // dmax // } // i_print_mat(1, nb[N], idxbN, 1); // d_print_mat(1, 2*nb[N]+2*ng[N], dN, 1); /************************************************ * cost function ************************************************/ double *Q; d_zeros(&Q, nx, nx); for (ii = 0; ii < nx; ii++) Q[ii * (nx + 1)] = 1.0; double *R; d_zeros(&R, nu, nu); for (ii = 0; ii < nu; ii++) R[ii * (nu + 1)] = 2.0; double *S; d_zeros(&S, nu, nx); double *q; d_zeros(&q, nx, 1); for (ii = 0; ii < nx; ii++) q[ii] = 0.1; double *r; d_zeros(&r, nu, 1); for (ii = 0; ii < nu; ii++) r[ii] = 0.2; // Q0 and q0 are matrices of size 0 double *Q0; d_zeros(&Q0, 0, 0); double *q0; d_zeros(&q0, 0, 1); // compute r0 = r + S*x0 double *r0; d_zeros(&r0, nu, 1); dcopy_3l(nu, r, 1, r0, 1); dgemv_n_3l(nu, nx, S, nu, x0, r0); // then S0 is a matrix of size nux0 double *S0; d_zeros(&S0, nu, 0); /************************************************ * problems data ************************************************/ double *hA[N]; double *hB[N]; double *hb[N]; double *hQ[N + 1]; double *hS[N]; double *hR[N]; double *hq[N + 1]; double *hr[N]; double *hlb[N + 1]; double *hub[N + 1]; int *hidxb[N + 1]; double *hC[N + 1]; double *hD[N]; double *hlg[N + 1]; double *hug[N + 1]; hA[0] = A0; hB[0] = B; hb[0] = b0; hQ[0] = Q0; hS[0] = S0; hR[0] = R; hq[0] = q0; hr[0] = r0; hlb[0] = lb0; hub[0] = ub0; hidxb[0] = idxb0; hC[0] = C; hD[0] = D; hlg[0] = lg; hug[0] = ug; for (ii = 1; ii < N; ii++) { hA[ii] = A; hB[ii] = B; hb[ii] = b; hQ[ii] = Q; hS[ii] = S; hR[ii] = R; hq[ii] = q; hr[ii] = r; hlb[ii] = lb1; hub[ii] = ub1; hidxb[ii] = idxb1; hC[ii] = C; hD[ii] = D; hlg[ii] = lg; hug[ii] = ug; } hQ[N] = Q; // or maybe initialize to the solution of the DARE??? hq[N] = q; // or maybe initialize to the solution of the DARE??? hlb[N] = lbN; hub[N] = ubN; hidxb[N] = idxbN; hC[N] = CN; hlg[N] = lgN; hug[N] = ugN; /************************************************ * solution ************************************************/ double *hx[N + 1]; double *hu[N]; double *hpi[N]; double *hlam[N + 1]; double *ht[N + 1]; double *lam_in[N + 1]; double *t_in[N + 1]; for (ii = 0; ii < N; ii++) { d_zeros(&hx[ii], nxx[ii], 1); d_zeros(&hu[ii], nuu[ii], 1); d_zeros(&hpi[ii], nxx[ii + 1], 1); d_zeros(&hlam[ii], 2 * nbb[ii] + 2 * ngg[ii], 1); d_zeros(&ht[ii], 2 * nbb[ii] + 2 * ngg[ii], 1); d_zeros(&lam_in[ii], 2 * nbb[ii] + 2 * ngg[ii], 1); d_zeros(&t_in[ii], 2 * nbb[ii] + 2 * ngg[ii], 1); // Init multipliers and slacks for (jj = 0; jj < 2 * nbb[ii] + 2 * ngg[ii]; jj++) { lam_in[ii][jj] = 1.0; t_in[ii][jj] = 1.0; } } d_zeros(&hx[N], nxx[N], 1); d_zeros(&hlam[N], 2 * nbb[N] + 2 * ngg[N], 1); d_zeros(&ht[N], 2 * nbb[N] + 2 * ngg[N], 1); d_zeros(&lam_in[N], 2 * nbb[N] + 2 * ngg[N], 1); d_zeros(&t_in[N], 2 * nbb[N] + 2 * ngg[N], 1); // Init multipliers and slacks for (jj = 0; jj < 2 * nbb[ii] + 2 * ngg[ii]; jj++) { lam_in[N][jj] = 1.0; t_in[N][jj] = 1.0; } /************************************************ * Solver arguments ************************************************/ // solver arguments ocp_qp_hpmpc_opts hpmpc_args; hpmpc_args.tol = TOL; hpmpc_args.max_iter = MAXITER; // hpmpc_args.min_step = MINSTEP; hpmpc_args.mu0 = 0.1; // hpmpc_args.sigma_min = 1e-3; hpmpc_args.warm_start = 0; hpmpc_args.N2 = N; hpmpc_args.lam0 = lam_in; hpmpc_args.t0 = t_in; /************************************************ * work space ************************************************/ int work_space_size = d_ip2_res_mpc_hard_work_space_size_bytes_libstr(N, nxx, nuu, nbb, ngg); // Adding memory for data for (int ii = 0; ii <= N; ii++) { work_space_size += blasfeo_memsize_dmat(nuu[ii] + nxx[ii] + 1, nxx[ii + 1]); work_space_size += blasfeo_memsize_dvec(nxx[ii + 1]); work_space_size += blasfeo_memsize_dmat(nuu[ii] + nxx[ii] + 1, nuu[ii] + nxx[ii]); work_space_size += blasfeo_memsize_dvec(nuu[ii] + nxx[ii]); work_space_size += blasfeo_memsize_dmat(nuu[ii] + nxx[ii] + 1, ngg[ii]); work_space_size += blasfeo_memsize_dvec(2 * nbb[ii] + 2 * ngg[ii]); work_space_size += blasfeo_memsize_dvec(nuu[ii] + nxx[ii]); work_space_size += blasfeo_memsize_dvec(nxx[ii + 1]); work_space_size += blasfeo_memsize_dvec(2 * nbb[ii] + 2 * ngg[ii]); work_space_size += blasfeo_memsize_dvec(2 * nbb[ii] + 2 * ngg[ii]); work_space_size += blasfeo_memsize_dvec(2 * nbb[ii] + 2 * ngg[ii]); work_space_size += blasfeo_memsize_dvec(2 * nbb[ii] + 2 * ngg[ii]); } work_space_size += 10000 * sizeof(double) * (N + 1); void *workspace; v_zeros_align(&workspace, work_space_size); /************************************************ * create the in and out struct ************************************************/ ocp_qp_in qp_in; qp_in.N = N; qp_in.nx = (const int *)nxx; qp_in.nu = (const int *)nuu; qp_in.nb = (const int *)nbb; qp_in.nc = (const int *)ngg; qp_in.A = (const double **)hA; qp_in.B = (const double **)hB; qp_in.b = (const double **)hb; qp_in.Q = (const double **)hQ; qp_in.S = (const double **)hS; qp_in.R = (const double **)hR; qp_in.q = (const double **)hq; qp_in.r = (const double **)hr; qp_in.idxb = (const int **)hidxb; qp_in.lb = (const double **)hlb; qp_in.ub = (const double **)hub; qp_in.Cx = (const double **)hC; qp_in.Cu = (const double **)hD; qp_in.lc = (const double **)hlg; qp_in.uc = (const double **)hug; ocp_qp_out qp_out; qp_out.x = hx; qp_out.u = hu; qp_out.pi = hpi; qp_out.lam = hlam; /************************************************ * call the solver ************************************************/ int return_value; acados_timer tv0; acados_tic(&tv0); // start // call the QP OCP solver // return_value = ocp_qp_hpmpc_libstr(&qp_in, &qp_out, &hpmpc_args, // workspace); return_value = ocp_qp_hpmpc_libstr_pt(&qp_in, &qp_out, &hpmpc_args, M, 0.1, workspace); double time = acados_toc(&tv0); // stop if (return_value == ACADOS_SUCCESS) printf("\nACADOS status: solution found\n"); if (return_value == ACADOS_MAXITER) printf("\nACADOS status: maximum number of iterations reached\n"); if (return_value == ACADOS_MINSTEP) printf("\nACADOS status: below minimum step size length\n"); printf("\nu = \n"); for (ii = 0; ii < N; ii++) d_print_mat(1, nuu[ii], hu[ii], 1); printf("\nx = \n"); for (ii = 0; ii <= N; ii++) d_print_mat(1, nxx[ii], hx[ii], 1); printf("\n"); printf(" Average solution time over %d runs: %5.2e seconds\n", nrep, time); printf("\n\n"); /************************************************ * free memory ************************************************/ // d_free(A); // d_free(B); // d_free(b); // d_free(x0); // d_free(A0); // d_free(b0); // d_free(Q); // d_free(S); // d_free(R); // d_free(q); // d_free(r); // d_free(Q0); // d_free(S0); // d_free(q0); // d_free(r0); // i_free(idxb0); // d_free(lb0); // d_free(ub0); // i_free(idxb1); // d_free(lb1); // d_free(ub1); // i_free(idxbN); // d_free(lbN); // d_free(ubN); // d_free(C); // d_free(D); // d_free(lg); // d_free(ug); // d_free(CN); // d_free(lgN); // d_free(ugN); // for (ii = 0; ii < N; ii++) { // d_free(hx[ii]); // d_free(hu[ii]); // } // d_free(hx[N]); // free(workspace); return 0; }
9,716
1,510
/* * 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.store.phoenix; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_CAT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.phoenix.query.BaseTest; import org.apache.phoenix.queryserver.QueryServerProperties; import org.apache.phoenix.util.ReadOnlyProps; import org.apache.phoenix.util.ThinClientUtil; import org.slf4j.LoggerFactory; public class QueryServerBasicsIT extends BaseTest { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(QueryServerBasicsIT.class); private static QueryServerThread AVATICA_SERVER; private static Configuration CONF; protected static String CONN_STRING; public static synchronized void doSetup() throws Exception { setUpTestDriver(ReadOnlyProps.EMPTY_PROPS); CONF = config; if(System.getProperty("do.not.randomize.pqs.port") == null) { CONF.setInt(QueryServerProperties.QUERY_SERVER_HTTP_PORT_ATTRIB, 0); } String url = getUrl(); AVATICA_SERVER = new QueryServerThread(new String[] { url }, CONF, QueryServerBasicsIT.class.getName()); AVATICA_SERVER.start(); AVATICA_SERVER.getQueryServer().awaitRunning(); final int port = AVATICA_SERVER.getQueryServer().getPort(); logger.info("Avatica server started on port " + port); CONN_STRING = ThinClientUtil.getConnectionUrl("localhost", port); logger.info("JDBC connection string is " + CONN_STRING); } public static void testCatalogs() throws Exception { try (final Connection connection = DriverManager.getConnection(CONN_STRING)) { assertFalse(connection.isClosed()); try (final ResultSet resultSet = connection.getMetaData().getCatalogs()) { final ResultSetMetaData metaData = resultSet.getMetaData(); assertFalse("unexpected populated resultSet", resultSet.next()); assertEquals(1, metaData.getColumnCount()); assertEquals(TABLE_CAT, metaData.getColumnName(1)); } } } public static synchronized void afterClass() throws Exception { if (AVATICA_SERVER != null) { AVATICA_SERVER.join(TimeUnit.SECONDS.toSeconds(3)); Throwable t = AVATICA_SERVER.getQueryServer().getThrowable(); if (t != null) { fail("query server threw. " + t.getMessage()); } assertEquals("query server didn't exit cleanly", 0, AVATICA_SERVER.getQueryServer().getRetCode()); } } }
1,142
1,909
<reponame>state303/spring-batch<gh_stars>1000+ /* * Copyright 2006-2018 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.batch.integration.async; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.ItemStreamWriter; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; public class AsyncItemWriter<T> implements ItemStreamWriter<Future<T>>, InitializingBean { private static final Log logger = LogFactory.getLog(AsyncItemWriter.class); private ItemWriter<T> delegate; public void afterPropertiesSet() throws Exception { Assert.notNull(delegate, "A delegate ItemWriter must be provided."); } /** * @param delegate ItemWriter that does the actual writing of the Future results */ public void setDelegate(ItemWriter<T> delegate) { this.delegate = delegate; } /** * In the processing of the {@link java.util.concurrent.Future}s passed, nulls are <em>not</em> passed to the * delegate since they are considered filtered out by the {@link org.springframework.batch.integration.async.AsyncItemProcessor}'s * delegated {@link org.springframework.batch.item.ItemProcessor}. If the unwrapping * of the {@link Future} results in an {@link ExecutionException}, that will be * unwrapped and the cause will be thrown. * * @param items {@link java.util.concurrent.Future}s to be unwrapped and passed to the delegate * @throws Exception The exception returned by the Future if one was thrown */ public void write(List<? extends Future<T>> items) throws Exception { List<T> list = new ArrayList<>(); for (Future<T> future : items) { try { T item = future.get(); if(item != null) { list.add(future.get()); } } catch (ExecutionException e) { Throwable cause = e.getCause(); if(cause != null && cause instanceof Exception) { logger.debug("An exception was thrown while processing an item", e); throw (Exception) cause; } else { throw e; } } } delegate.write(list); } @Override public void open(ExecutionContext executionContext) throws ItemStreamException { if (delegate instanceof ItemStream) { ((ItemStream) delegate).open(executionContext); } } @Override public void update(ExecutionContext executionContext) throws ItemStreamException { if (delegate instanceof ItemStream) { ((ItemStream) delegate).update(executionContext); } } @Override public void close() throws ItemStreamException { if (delegate instanceof ItemStream) { ((ItemStream) delegate).close(); } } }
1,214
2,151
# (c) 2005 <NAME> and contributors; written for Paste # (http://pythonpaste.org) # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php """ Routines for testing WSGI applications. """ from webtest.app import TestApp from webtest.app import TestRequest from webtest.app import TestResponse from webtest.app import AppError from webtest.forms import Form from webtest.forms import Field from webtest.forms import Select from webtest.forms import Radio from webtest.forms import Checkbox from webtest.forms import Text from webtest.forms import Textarea from webtest.forms import Hidden from webtest.forms import Submit from webtest.forms import Upload
185
4,047
extern "C" int foo(void); int main(void) { return foo() != 42; }
31
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 _DBAUI_DBFINDEX_HXX_ #define _DBAUI_DBFINDEX_HXX_ #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef __SGI_STL_LIST #include <list> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= OTableIndex //========================================================================= /// represents a single dbf index class OTableIndex { private: String aIndexFileName; public: OTableIndex() { } OTableIndex( const OTableIndex& _rSource) : aIndexFileName(_rSource.aIndexFileName) { } OTableIndex( const String& rFileName ) : aIndexFileName( rFileName ) { } void SetIndexFileName( const String& rFileName ) { aIndexFileName = rFileName; } String GetIndexFileName() const { return aIndexFileName; } }; //------------------------------------------------------------------------- typedef ::std::list< OTableIndex > TableIndexList; DECLARE_STL_ITERATORS(TableIndexList); //========================================================================= //= OTableInfo //========================================================================= class ODbaseIndexDialog; /** holds the INF file of a table */ class OTableInfo { friend class ODbaseIndexDialog; private: String aTableName; TableIndexList aIndexList; public: OTableInfo() { } OTableInfo( const String& rName ) : aTableName(rName) { } void WriteInfFile( const String& rDSN ) const; }; //------------------------------------------------------------------------- typedef ::std::list< OTableInfo > TableInfoList; DECLARE_STL_ITERATORS(TableInfoList); ////////////////////////////////////////////////////////////////////////// // IndexDialog class ODbaseIndexDialog : public ModalDialog { protected: OKButton aPB_OK; CancelButton aPB_CANCEL; HelpButton aPB_HELP; FixedText m_FT_Tables; ComboBox aCB_Tables; FixedLine m_FL_Indexes; FixedText m_FT_TableIndexes; ListBox aLB_TableIndexes; FixedText m_FT_AllIndexes; ListBox aLB_FreeIndexes; ImageButton aIB_Add; ImageButton aIB_Remove; ImageButton aIB_AddAll; ImageButton aIB_RemoveAll; DECL_LINK( TableSelectHdl, ComboBox* ); DECL_LINK( AddClickHdl, PushButton* ); DECL_LINK( RemoveClickHdl, PushButton* ); DECL_LINK( AddAllClickHdl, PushButton* ); DECL_LINK( RemoveAllClickHdl, PushButton* ); DECL_LINK( OKClickHdl, PushButton* ); DECL_LINK( OnListEntrySelected, ListBox* ); String m_aDSN; TableInfoList m_aTableInfoList; TableIndexList m_aFreeIndexList; sal_Bool m_bCaseSensitiv; void Init(); void SetCtrls(); sal_Bool GetTable(const String& rName, TableInfoListIterator& _rPosition); OTableIndex implRemoveIndex(const String& _rName, TableIndexList& _rList, ListBox& _rDisplay, sal_Bool _bMustExist); void implInsertIndex(const OTableIndex& _rIndex, TableIndexList& _rList, ListBox& _rDisplay); OTableIndex RemoveFreeIndex( const String& _rName, sal_Bool _bMustExist ) { return implRemoveIndex(_rName, m_aFreeIndexList, aLB_FreeIndexes, _bMustExist); } void InsertFreeIndex( const OTableIndex& _rIndex ) { implInsertIndex(_rIndex, m_aFreeIndexList, aLB_FreeIndexes); } OTableIndex RemoveTableIndex( const String& _rTableName, const String& _rIndexName, sal_Bool _bMustExist ); void InsertTableIndex( const String& _rTableName, const OTableIndex& _rIndex ); void checkButtons(); public: ODbaseIndexDialog( Window * pParent, String aDataSrcName ); virtual ~ODbaseIndexDialog(); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_DBFINDEX_HXX_
1,602
1,444
<reponame>GabrielSturtevant/mage package mage.cards.d; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.LoyaltyAbility; import mage.abilities.common.PlaneswalkerEntersWithLoyaltyCountersAbility; import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.SearchEffect; import mage.abilities.effects.common.continuous.BoostTargetEffect; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.SuperType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; import mage.filter.common.FilterArtifactCard; import mage.filter.common.FilterControlledArtifactPermanent; import mage.game.Game; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.TargetPlayer; import mage.target.common.TargetCardInLibrary; import mage.target.common.TargetControlledPermanent; import mage.target.common.TargetCreaturePermanent; /** * * @author Styxo */ public final class DarthTyranusCountOfSerenno extends CardImpl { public DarthTyranusCountOfSerenno(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.PLANESWALKER},"{1}{W}{U}{B}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.DOOKU); this.addAbility(new PlaneswalkerEntersWithLoyaltyCountersAbility(3)); // +1: Up to one target creature gets -6/-0 until your next turn. Effect effect = new BoostTargetEffect(-6, 0, Duration.UntilYourNextTurn); effect.setText("Up to one target creature gets -6/-0 until your next turn"); Ability ability = new LoyaltyAbility(effect, 1); ability.addTarget(new TargetCreaturePermanent(0, 1)); this.addAbility(ability); // -3: Sacrifice an artifact. If you do, you may search your library for an artifact card and put that card onto the battlefield. Shuffle your library. this.addAbility(new LoyaltyAbility(new TransmuteArtifactEffect(), -3)); // -6: Target player's life total becomes 5. Another target players's life total becomes 30. ability = new LoyaltyAbility(new DarthTyranusEffect(), -6); ability.addTarget(new TargetPlayer(2)); this.addAbility(ability); } private DarthTyranusCountOfSerenno(final DarthTyranusCountOfSerenno card) { super(card); } @Override public DarthTyranusCountOfSerenno copy() { return new DarthTyranusCountOfSerenno(this); } } class DarthTyranusEffect extends OneShotEffect { public DarthTyranusEffect() { super(Outcome.Benefit); staticText = "Target player's life total becomes 5. Another target players's life total becomes 30"; } public DarthTyranusEffect(DarthTyranusEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { Player player1 = game.getPlayer(targetPointer.getTargets(game, source).get(0)); Player player2 = game.getPlayer(targetPointer.getTargets(game, source).get(1)); if (player1 != null && player2 != null) { player1.setLife(5, game, source); player1.setLife(30, game, source); return true; } return false; } @Override public DarthTyranusEffect copy() { return new DarthTyranusEffect(this); } } class TransmuteArtifactEffect extends SearchEffect { public TransmuteArtifactEffect() { super(new TargetCardInLibrary(new FilterArtifactCard()), Outcome.PutCardInPlay); staticText = "Sacrifice an artifact. If you do, search your library for an artifact card and put that card onto the battlefield. Shuffle your library"; } public TransmuteArtifactEffect(final TransmuteArtifactEffect effect) { super(effect); } @Override public TransmuteArtifactEffect copy() { return new TransmuteArtifactEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { boolean sacrifice = false; TargetControlledPermanent targetArtifact = new TargetControlledPermanent(new FilterControlledArtifactPermanent()); if (controller.chooseTarget(Outcome.Sacrifice, targetArtifact, source, game)) { Permanent permanent = game.getPermanent(targetArtifact.getFirstTarget()); if (permanent != null) { sacrifice = permanent.sacrifice(source, game); } } if (sacrifice && controller.searchLibrary(target, source, game)) { if (!target.getTargets().isEmpty()) { for (UUID cardId : target.getTargets()) { Card card = controller.getLibrary().getCard(cardId, game); if (card != null) { controller.moveCards(card, Zone.BATTLEFIELD, source, game); controller.shuffleLibrary(source, game); return true; } } } controller.shuffleLibrary(source, game); } } return false; } }
2,101
495
<reponame>marlon-br/media-for-mobile /* * Copyright 2014-2016 Media for Mobile * * 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.m4m.domain.dsl; import org.m4m.domain.AudioEncoder; import org.m4m.domain.Frame; import org.m4m.domain.ICommandProcessor; import org.m4m.domain.IOutput; import org.m4m.domain.MediaSource; import org.m4m.domain.MultipleMediaSource; import org.m4m.domain.Pipeline; import org.m4m.domain.Plugin; import org.m4m.domain.Render; import org.m4m.domain.VideoEffector; import org.m4m.domain.VideoEncoder; public class PipelineFather { private final Father create; private Pipeline pipeline; private IOutput mediaSource; private VideoDecoderFather videoDecoderFather; private Plugin decoder; private Render sink; private ICommandProcessor commandProcessor; private VideoEncoderFather videoEncoderFather; private VideoEncoder videoEncoder; private Plugin audioDecoder; private AudioEncoder audioEncoder; private VideoEffectorFather effectorFather; private VideoEffector effector; public PipelineFather(Father create) { this.create = create; with(create.mediaSource().with(Frame.EOF()).construct()); with(create.render()); with(create.commandProcessor().construct()); } public PipelineFather with(MediaSource mediaSource) { this.mediaSource = mediaSource; return this; } public PipelineFather with(MediaSourceFather mediaSourceFather) { this.mediaSource = mediaSourceFather.construct(); return this; } public PipelineFather with(MultipleMediaSource multipleMediaSource) { mediaSource = multipleMediaSource; return this; } public PipelineFather withVideoDecoder(Plugin decoder) { this.decoder = decoder; this.videoDecoderFather = null; return this; } public PipelineFather with(VideoDecoderFather decoder) { this.videoDecoderFather = decoder; this.decoder = null; return this; } public PipelineFather withVideoEffector(VideoEffector effector) { this.effectorFather = null; this.effector = effector; return this; } public PipelineFather withVideoEffector(VideoEffectorFather effector) { this.effectorFather = effector; this.effector = null; return this; } public PipelineFather with(VideoEncoder encoder) { this.videoEncoder = encoder; return this; } public PipelineFather with(VideoEncoderFather videoEncoderFather) { this.videoEncoderFather = videoEncoderFather; return this; } public PipelineFather with(Render sink) { this.sink = sink; return this; } public PipelineFather with(RenderFather sink) { this.sink = sink.construct(); return this; } public PipelineFather with(ICommandProcessor processor) { this.commandProcessor = processor; return this; } public PipelineFather withAudioDecoder() { return withAudioDecoder(create.audioDecoder().construct()); } public PipelineFather withAudioDecoder(Plugin audioDecoder) { this.audioDecoder = audioDecoder; return this; } public PipelineFather withAudioEncoder(AudioEncoder audioEncoder) { this.audioEncoder = audioEncoder; return this; } public Pipeline construct() { pipeline = new Pipeline(commandProcessor); pipeline.setMediaSource(mediaSource); if (videoDecoderFather != null) { pipeline.addVideoDecoder(videoDecoderFather.construct()); } if (decoder != null) { pipeline.addTransform(decoder); } if (audioDecoder != null) { pipeline.addAudioDecoder(audioDecoder); } if (audioEncoder != null) { pipeline.addAudioEncoder(audioEncoder); } if (videoEncoder != null) { pipeline.addVideoEncoder(videoEncoder); } if (videoEncoderFather != null) { pipeline.addVideoEncoder(videoEncoderFather.construct()); } pipeline.setSink(sink); return pipeline; } }
1,750
1,118
<gh_stars>1000+ {"deu":{"common":"Vatikanstadt","official":"Staat Vatikanstadt"},"fin":{"common":"Vatikaani","official":"Vatikaanin kaupunkivaltio"},"fra":{"common":"Cité du Vatican","official":"Cité du Vatican"},"hrv":{"common":"Vatikan","official":"Vatikan"},"ita":{"common":"Città del Vaticano","official":"Città del Vaticano"},"jpn":{"common":"バチカン市国","official":"バチカン市国の状態"},"nld":{"common":"Vaticaanstad","official":"Vaticaanstad"},"por":{"common":"Cidade do Vaticano","official":"Cidade do Vaticano"},"rus":{"common":"Ватикан","official":"Город-государство Ватикан"},"spa":{"common":"Ciudad del Vaticano","official":"Ciudad del Vaticano"}}
244
312
<reponame>Fruit-Pi/mpp /* * Copyright 2015 Rockchip Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __MPP_ALLOCATOR_H__ #define __MPP_ALLOCATOR_H__ #include "rk_type.h" #include "mpp_buffer.h" typedef void *MppAllocator; typedef struct MppAllocatorCfg_t { // input size_t alignment; RK_U32 flags; } MppAllocatorCfg; typedef struct MppAllocatorApi_t { RK_U32 size; RK_U32 version; MPP_RET (*alloc)(MppAllocator allocator, MppBufferInfo *data); MPP_RET (*free)(MppAllocator allocator, MppBufferInfo *data); MPP_RET (*import)(MppAllocator allocator, MppBufferInfo *data); MPP_RET (*release)(MppAllocator allocator, MppBufferInfo *data); MPP_RET (*mmap)(MppAllocator allocator, MppBufferInfo *data); } MppAllocatorApi; #ifdef __cplusplus extern "C" { #endif MPP_RET mpp_allocator_get(MppAllocator *allocator, MppAllocatorApi **api, MppBufferType type); MPP_RET mpp_allocator_put(MppAllocator *allocator); #ifdef __cplusplus } #endif #endif /*__MPP_ALLOCATOR_H__*/
622
377
# Copyright 2021 The ByT5 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. """Tests for byt5.metrics.""" from absl.testing import absltest from byt5 import metrics class MetricsTest(absltest.TestCase): def test_edit_distance(self): d = metrics.cer(["abcd", "aaaa", "ab"], ["abde", "bbbb", "a"]) # abcd -> abde (2 edits). Target length = 4. # aaaa -> bbbb (4 edits). Target length = 4. # ab -> a (1 edit). Target length = 2. # CER = Total # of edits / Total # of target chars = 7 / 10 = 0.7 self.assertDictEqual(d, {"cer": 0.7}) def test_normalize_text(self): output = metrics._normalize_text(" THIS is a string!") expected = "this is string" self.assertEqual(output, expected) def test_bleu1_full_match(self): targets = ["this is a string", "this is a string", "this is a string", "this is a string"] predictions = ["this is a string", "THIS is a string", "this is a string!", "this is string"] d = metrics.bleu1(targets, predictions) # Normalization should remove articles, extra spaces and punctuations, # resulting in a BLEU-1 score of 100.0. self.assertDictEqual(d, {"bleu1": 100.0}) def test_bleu1_no_full_match(self): targets = ["this is a string"] predictions = ["this is not a string"] d = metrics.bleu1(targets, predictions) self.assertDictEqual(d, {"bleu1": 75.0}) def test_rouge_full_match(self): targets = ["this is a string", "this is a string", "this is a string", "this is a string"] predictions = ["this is a string", "THIS is a string", "this is a string!", "this is string"] d = metrics.rouge(targets, predictions) self.assertDictEqual(d, {"rouge1": 100, "rouge2": 100, "rougeLsum": 100}) def test_rouge_no_match(self): targets = ["this is a string"] predictions = ["", ""] d = metrics.rouge(targets, predictions) self.assertDictEqual(d, {"rouge1": 0.0, "rouge2": 0.0, "rougeLsum": 0.0}) if __name__ == "__main__": absltest.main()
965
625
<reponame>DataSketches/sketches-core /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.datasketches.kll; import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; import static org.apache.datasketches.kll.KllPreambleUtil.N_LONG_ADR; import static org.apache.datasketches.kll.KllSketch.Error.SRC_MUST_BE_DOUBLE; import static org.apache.datasketches.kll.KllSketch.Error.SRC_MUST_BE_FLOAT; import static org.apache.datasketches.kll.KllSketch.Error.TGT_IS_READ_ONLY; import static org.apache.datasketches.kll.KllSketch.Error.kllSketchThrow; import static org.apache.datasketches.kll.KllSketch.SketchType.DOUBLES_SKETCH; import static org.apache.datasketches.kll.KllSketch.SketchType.FLOATS_SKETCH; import java.util.Random; import org.apache.datasketches.SketchesArgumentException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.MemoryRequestServer; import org.apache.datasketches.memory.WritableMemory; /* * Sampled stream data (floats or doubles) is stored as an array or as part of a Memory object. * This array is partitioned into sections called levels and the indices into the array of items * are tracked by a small integer array called levels or levels array. * The data for level i lies in positions levelsArray[i] through levelsArray[i + 1] - 1 inclusive. * Hence, the levelsArray must contain (numLevels + 1) indices. * The valid portion of items array is completely packed and sorted, except for level 0, * which is filled from the top down. Any items below the index levelsArray[0] is garbage and will be * overwritten by subsequent updates. * * Invariants: * 1) After a compaction, or an update, or a merge, every level is sorted except for level zero. * 2) After a compaction, (sum of capacities) - (sum of items) >= 1, * so there is room for least 1 more item in level zero. * 3) There are no gaps except at the bottom, so if levels_[0] = 0, * the sketch is exactly filled to capacity and must be compacted or the itemsArray and levelsArray * must be expanded to include more levels. * 4) Sum of weights of all retained items == N. * 5) Current total item capacity = itemsArray.length = levelsArray[numLevels]. */ /** * This class is the root of the KLL sketch class hierarchy. It includes the public API that is independent * of either sketch type (float or double) and independent of whether the sketch is targeted for use on the * heap or Direct (off-heap). * * <p>Please refer to the documentation in the package-info:<br> * {@link org.apache.datasketches.kll}</p> * * @author <NAME>, <NAME> */ public abstract class KllSketch { /** * Used to define the variable type of the current instance of this class. */ public enum SketchType { FLOATS_SKETCH, DOUBLES_SKETCH } enum Error { TGT_IS_READ_ONLY("Given sketch Memory is immutable, cannot write."), SRC_MUST_BE_DOUBLE("Given sketch must be of type Double."), SRC_MUST_BE_FLOAT("Given sketch must be of type Float."), MUST_NOT_CALL("This is an artifact of inheritance and should never be called."), SINGLE_ITEM_IMPROPER_CALL("Improper method use for single-item sketch"), MRS_MUST_NOT_BE_NULL("MemoryRequestServer cannot be null."), NOT_SINGLE_ITEM("Sketch is not single item."), MUST_NOT_BE_UPDATABLE_FORMAT("Given Memory object must not be in updatableFormat."); private String msg; private Error(final String msg) { this.msg = msg; } final static void kllSketchThrow(final Error errType) { throw new SketchesArgumentException(errType.getMessage()); } private String getMessage() { return msg; } } /** * The default value of K */ public static final int DEFAULT_K = 200; /** * The maximum value of K */ public static final int MAX_K = (1 << 16) - 1; // serialized as an unsigned short /** * The default value of M. The parameter <i>m</i> is the minimum level size in number of items. * Currently, the public default is 8, but this can be overridden using Package Private methods to * 2, 4, 6 or 8, and the sketch works just fine. The value 8 was chosen as a compromise between speed and size. * Choosing smaller values of <i>m</i> less than 8 will make the sketch slower. */ static final int DEFAULT_M = 8; static final int MAX_M = 8; //The maximum value of M static final int MIN_M = 2; //The minimum value of M static final Random random = new Random(); final SketchType sketchType; final boolean updatableMemFormat; final MemoryRequestServer memReqSvr; final boolean readOnly; int[] levelsArr; WritableMemory wmem; /** * Constructor for on-heap and off-heap. * If both wmem and memReqSvr are null, this is a heap constructor. * If wmem != null and wmem is not readOnly, then memReqSvr must not be null. * If wmem was derived from an original Memory instance via a cast, it will be readOnly. * @param sketchType either DOUBLE_SKETCH or FLOAT_SKETCH * @param wmem the current WritableMemory or null * @param memReqSvr the given MemoryRequestServer or null */ KllSketch(final SketchType sketchType, final WritableMemory wmem, final MemoryRequestServer memReqSvr) { this.sketchType = sketchType; this.wmem = wmem; if (wmem != null) { this.updatableMemFormat = KllPreambleUtil.getMemoryUpdatableFormatFlag(wmem); this.readOnly = wmem.isReadOnly() || !updatableMemFormat; if (readOnly) { this.memReqSvr = null; } else { if (memReqSvr == null) { kllSketchThrow(Error.MRS_MUST_NOT_BE_NULL); } this.memReqSvr = memReqSvr; } } else { //wmem is null, heap case this.updatableMemFormat = false; this.memReqSvr = null; this.readOnly = false; } } /** * Gets the approximate value of <em>k</em> to use given epsilon, the normalized rank error. * @param epsilon the normalized rank error between zero and one. * @param pmf if true, this function returns the value of <em>k</em> assuming the input epsilon * is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function * returns the value of <em>k</em> assuming the input epsilon is the desired "single-sided" * epsilon for all the other queries. * * <p>Please refer to the documentation in the package-info:<br> * {@link org.apache.datasketches.kll}</p> * @return the value of <i>k</i> given a value of epsilon. */ public static int getKFromEpsilon(final double epsilon, final boolean pmf) { return KllHelper.getKFromEpsilon(epsilon, pmf); } /** * Returns upper bound on the compact serialized size of a FloatsSketch given a parameter * <em>k</em> and stream length. This method can be used if allocation of storage * is necessary beforehand. * @param k parameter that controls size of the sketch and accuracy of estimates * @param n stream length * @return upper bound on the compact serialized size * @deprecated Instead use getMaxSerializedSizeBytes(int, long, boolean) * from the descendants of this class, or * getMaxSerializedSizeBytes(int, long, SketchType, boolean) from this class. * Version 3.2.0 */ @Deprecated public static int getMaxSerializedSizeBytes(final int k, final long n) { final KllHelper.GrowthStats gStats = KllHelper.getGrowthSchemeForGivenN(k, DEFAULT_M, n, FLOATS_SKETCH, false); return gStats.compactBytes; } /** * Returns upper bound on the serialized size of a KllSketch given the following parameters. * @param k parameter that controls size of the sketch and accuracy of estimates * @param n stream length * @param sketchType either DOUBLES_SKETCH or FLOATS_SKETCH * @param updatableMemFormat true if updatable Memory format, otherwise the standard compact format. * @return upper bound on the serialized size of a KllSketch. */ public static int getMaxSerializedSizeBytes(final int k, final long n, final SketchType sketchType, final boolean updatableMemFormat) { final KllHelper.GrowthStats gStats = KllHelper.getGrowthSchemeForGivenN(k, DEFAULT_M, n, sketchType, false); return updatableMemFormat ? gStats.updatableBytes : gStats.compactBytes; } /** * Gets the normalized rank error given k and pmf. * Static method version of the <i>getNormalizedRankError(boolean)</i>. * @param k the configuration parameter * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. * Otherwise, it is the "single-sided" normalized rank error for all the other queries. * @return if pmf is true, the normalized rank error for the getPMF() function. * Otherwise, it is the "single-sided" normalized rank error for all the other queries. */ public static double getNormalizedRankError(final int k, final boolean pmf) { return KllHelper.getNormalizedRankError(k, pmf); } //numItems can be either numRetained, or current max capacity at given K and numLevels. static int getCurrentSerializedSizeBytes(final int numLevels, final int numItems, final SketchType sketchType, final boolean updatableMemFormat) { final int typeBytes = (sketchType == DOUBLES_SKETCH) ? Double.BYTES : Float.BYTES; int levelsBytes = 0; if (updatableMemFormat) { levelsBytes = (numLevels + 1) * Integer.BYTES; } else { if (numItems == 0) { return N_LONG_ADR; } if (numItems == 1) { return DATA_START_ADR_SINGLE_ITEM + typeBytes; } levelsBytes = numLevels * Integer.BYTES; } return DATA_START_ADR + levelsBytes + (numItems + 2) * typeBytes; //+2 is for min & max } /** * Returns the current number of bytes this sketch would require to store in the compact Memory Format. * @return the current number of bytes this sketch would require to store in the compact Memory Format. */ public final int getCurrentCompactSerializedSizeBytes() { return getCurrentSerializedSizeBytes(getNumLevels(), getNumRetained(), sketchType, false); } /** * Returns the current number of bytes this sketch would require to store in the updatable Memory Format. * @return the current number of bytes this sketch would require to store in the updatable Memory Format. */ public final int getCurrentUpdatableSerializedSizeBytes() { final int itemCap = KllHelper.computeTotalItemCapacity(getK(), getM(), getNumLevels()); return getCurrentSerializedSizeBytes(getNumLevels(), itemCap, sketchType, true); } /** * Returns the user configured parameter k * @return the user configured parameter k */ public abstract int getK(); /** * Returns the length of the input stream in items. * @return stream length */ public abstract long getN(); /** * Gets the approximate rank error of this sketch normalized as a fraction between zero and one. * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. * Otherwise, it is the "single-sided" normalized rank error for all the other queries. * The epsilon value returned is a best fit to 99 percentile empirically measured max error in * thousands of trials * @return if pmf is true, returns the normalized rank error for the getPMF() function. * Otherwise, it is the "single-sided" normalized rank error for all the other queries. * * <p>Please refer to the documentation in the package-info:<br> * {@link org.apache.datasketches.kll}</p> */ public final double getNormalizedRankError(final boolean pmf) { return getNormalizedRankError(getMinK(), pmf); } /** * Returns the number of retained items (samples) in the sketch. * @return the number of retained items (samples) in the sketch */ public final int getNumRetained() { return levelsArr[getNumLevels()] - levelsArr[0]; } /** * Returns the current number of bytes this Sketch would require if serialized. * @return the number of bytes this sketch would require if serialized. */ public int getSerializedSizeBytes() { return (updatableMemFormat) ? getCurrentUpdatableSerializedSizeBytes() : getCurrentCompactSerializedSizeBytes(); } /** * This returns the WritableMemory for Direct type sketches, * otherwise returns null. * @return the WritableMemory for Direct type sketches, otherwise null. */ WritableMemory getWritableMemory() { return wmem; } /** * Returns true if this sketch's data structure is backed by Memory or WritableMemory. * @return true if this sketch's data structure is backed by Memory or WritableMemory. */ public boolean hasMemory() { return (wmem != null); } /** * Returns true if the backing resource is direct, i.e., actually allocated in off-heap memory. * This is the case for off-heap memory and memory mapped files. * This backing resource could be either Memory(read-only) or WritableMemory. * However, if the backing Memory or WritabelMemory resource is allocated on-heap, * this will return false. * @return true if the backing resource is off-heap memory. */ public boolean isDirect() { return wmem.isDirect(); } /** * Returns true if this sketch is empty. * @return empty flag */ public final boolean isEmpty() { return getN() == 0; } /** * Returns true if this sketch is in estimation mode. * @return estimation mode flag */ public final boolean isEstimationMode() { return getNumLevels() > 1; } /** * Returns true if the backing WritableMemory is in updatable format. * @return true if the backing WritableMemory is in updatable format. */ public final boolean isMemoryUpdatableFormat() { return hasMemory() && updatableMemFormat; } /** * Returns true if this sketch is read only. * @return true if this sketch is read only. */ public final boolean isReadOnly() { return readOnly; } /** * Returns true if the backing resource of <i>this</i> is identical with the backing resource * of <i>that</i>. The capacities must be the same. If <i>this</i> is a region, * the region offset must also be the same. * @param that A different non-null object * @return true if the backing resource of <i>this</i> is the same as the backing resource * of <i>that</i>. */ public final boolean isSameResource(final Memory that) { return (wmem != null) && wmem.isSameResource(that); } /** * Merges another sketch into this one. * Attempting to merge a KllDoublesSketch with a KllFloatsSketch will * throw an exception. * @param other sketch to merge into this one */ public final void merge(final KllSketch other) { if (readOnly) { kllSketchThrow(TGT_IS_READ_ONLY); } if (sketchType == DOUBLES_SKETCH) { if (!other.isDoublesSketch()) { kllSketchThrow(SRC_MUST_BE_DOUBLE); } KllDoublesHelper.mergeDoubleImpl(this, other); } else { if (!other.isFloatsSketch()) { kllSketchThrow(SRC_MUST_BE_FLOAT); } KllFloatsHelper.mergeFloatImpl(this, other); } } /** * This resets the current sketch back to zero entries. * It retains key parameters such as <i>k</i> and * <i>SketchType (double or float)</i>. */ public final void reset() { if (readOnly) { kllSketchThrow(TGT_IS_READ_ONLY); } final int k = getK(); setN(0); setMinK(k); setNumLevels(1); setLevelZeroSorted(false); setLevelsArray(new int[] {k, k}); if (sketchType == DOUBLES_SKETCH) { setMinDoubleValue(Double.NaN); setMaxDoubleValue(Double.NaN); setDoubleItemsArray(new double[k]); } else { setMinFloatValue(Float.NaN); setMaxFloatValue(Float.NaN); setFloatItemsArray(new float[k]); } } /** * Returns serialized sketch in a compact byte array form. * @return serialized sketch in a compact byte array form. */ public byte[] toByteArray() { return KllHelper.toCompactByteArrayImpl(this); } @Override public final String toString() { return toString(false, false); } /** * Returns a summary of the sketch as a string. * @param withLevels if true include information about levels * @param withData if true include sketch data * @return string representation of sketch summary */ public String toString(final boolean withLevels, final boolean withData) { return KllHelper.toStringImpl(this, withLevels, withData); } /** * @return full size of internal items array including garbage. */ abstract double[] getDoubleItemsArray(); abstract double getDoubleSingleItem(); /** * @return full size of internal items array including garbage. */ abstract float[] getFloatItemsArray(); abstract float getFloatSingleItem(); final int[] getLevelsArray() { return levelsArr; } /** * Returns the configured parameter <i>m</i>, which is the minimum level size in number of items. * Currently, the public default is 8, but this can be overridden using Package Private methods to * 2, 4, 6 or 8, and the sketch works just fine. The value 8 was chosen as a compromise between speed and size. * Choosing smaller values of <i>m</i> will make the sketch much slower. * @return the configured parameter m */ abstract int getM(); abstract double getMaxDoubleValue(); abstract float getMaxFloatValue(); abstract double getMinDoubleValue(); abstract float getMinFloatValue(); /** * MinK is the value of K that results from a merge with a sketch configured with a value of K lower than * the k of this sketch. This value is then used in computing the estimated upper and lower bounds of error. * @return The minimum K as a result of merging with lower values of k. */ abstract int getMinK(); final int getNumLevels() { return levelsArr.length - 1; } abstract void incN(); abstract void incNumLevels(); final boolean isCompactSingleItem() { return hasMemory() && !updatableMemFormat && (getN() == 1); } boolean isDoublesSketch() { return sketchType == DOUBLES_SKETCH; } boolean isFloatsSketch() { return sketchType == FLOATS_SKETCH; } abstract boolean isLevelZeroSorted(); /** * First determine that this is a singleItem sketch before calling this. * @return the value of the single item */ boolean isSingleItem() { return getN() == 1; } abstract void setDoubleItemsArray(double[] floatItems); abstract void setDoubleItemsArrayAt(int index, double value); abstract void setFloatItemsArray(float[] floatItems); abstract void setFloatItemsArrayAt(int index, float value); final void setLevelsArray(final int[] levelsArr) { if (readOnly) { kllSketchThrow(TGT_IS_READ_ONLY); } this.levelsArr = levelsArr; if (wmem != null) { wmem.putIntArray(DATA_START_ADR, this.levelsArr, 0, levelsArr.length); } } final void setLevelsArrayAt(final int index, final int value) { if (readOnly) { kllSketchThrow(TGT_IS_READ_ONLY); } this.levelsArr[index] = value; if (wmem != null) { final int offset = DATA_START_ADR + index * Integer.BYTES; wmem.putInt(offset, value); } } abstract void setLevelZeroSorted(boolean sorted); abstract void setMaxDoubleValue(double value); abstract void setMaxFloatValue(float value); abstract void setMinDoubleValue(double value); abstract void setMinFloatValue(float value); abstract void setMinK(int minK); abstract void setN(long n); abstract void setNumLevels(int numLevels); }
6,528
892
<filename>advisories/github-reviewed/2022/01/GHSA-x9r5-jxvq-4387/GHSA-x9r5-jxvq-4387.json { "schema_version": "1.2.0", "id": "GHSA-x9r5-jxvq-4387", "modified": "2022-01-06T19:18:42Z", "published": "2022-01-06T22:48:56Z", "aliases": [ "CVE-2021-43862" ], "summary": "Self XSS on user input in jquery.terminal", "details": "### Impact\nThis is low impact and limited XSS, because code for XSS payload is always visible, but attacker can use other techniques to hide the code the victim sees.\n\nAlso if the application use execHash option and execute code from URL the attacker can use this URL to execute his code. The scope is limited because the javascript code inside html attribute used is added to span tag, so no automatic execution like with `onerror` on images is possible.\n\n### Patches\nFixed version 2.31.1\n\n### Workarounds\nThe user can use formatting that wrap whole user input and it's no op.\n\n```javascript\n$.terminal.new_formatter([/([\\s\\S]+)/g, '[[;;]$1]']);\n```\nThe fix will only work when user of the library is not using different formatters (e.g. to highlight code in different way).\n\n### References\nThe issue was reported here [jcubic/jquery.terminal#727](https://github.com/jcubic/jquery.terminal/issues/727)\n\n### For more information\nIf you have any questions or comments about this advisory:\n* Open an issue in [jcubic/jquery.terminal](https://github.com/jcubic/jquery.terminal)\n* Email us at [<EMAIL>](mailto:<EMAIL>)\n", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N" } ], "affected": [ { "package": { "ecosystem": "npm", "name": "jquery.terminal" }, "ranges": [ { "type": "ECOSYSTEM", "events": [ { "introduced": "0" }, { "fixed": "2.31.1" } ] } ] } ], "references": [ { "type": "WEB", "url": "https://github.com/jcubic/jquery.terminal/security/advisories/GHSA-x9r5-jxvq-4387" }, { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-43862" }, { "type": "WEB", "url": "https://github.com/jcubic/jquery.terminal/issues/727" }, { "type": "WEB", "url": "https://github.com/jcubic/jquery.terminal/commit/77eb044d0896e990d48a9157f0bc6648f81a84b5" }, { "type": "WEB", "url": "https://github.com/jcubic/jquery.terminal/releases/tag/2.31.1" }, { "type": "PACKAGE", "url": "https://github.com/jcubic/jquery.terminal/" } ], "database_specific": { "cwe_ids": [ "CWE-80" ], "severity": "LOW", "github_reviewed": true } }
1,281
731
#include "bind/syscmd/source.hpp" #include "bind/binded_func.hpp" #include "entry.hpp" #include "err_logger.hpp" #include "g_maps.hpp" #include "g_params.hpp" #include "key/char_logger.hpp" #include "mode.hpp" #include "opt/vcmdline.hpp" #include "parser/bindings_parser.hpp" #include "parser/rc_parser.hpp" #include "path.hpp" #include "util/def.hpp" #include "bind/syscmd/command.hpp" #include "bind/syscmd/map.hpp" #include "bind/syscmd/set.hpp" #include <fstream> #include <sstream> #include <stdexcept> #include <string> #if defined(DEBUG) #include <iostream> #endif namespace { template <typename Str> void do_runcommand(vind::rcparser::RunCommandsIndex rcindex, Str&& args) { using namespace vind ; using vind::rcparser::RunCommandsIndex ; switch(rcindex) { case RunCommandsIndex::SET: SyscmdSet::sprocess(std::forward<Str>(args), false) ; return ; case RunCommandsIndex::COMMAND: SyscmdCommand::sprocess(std::forward<Str>(args), false) ; return ; case RunCommandsIndex::DELCOMMAND: SyscmdDelcommand::sprocess(std::forward<Str>(args), false) ; return ; case RunCommandsIndex::COMCLEAR: if(!args.empty()) { throw std::invalid_argument("Comclear") ; } SyscmdComclear::sprocess(false) ; return ; default: break ; } using mode::Mode ; auto mode = static_cast<Mode>(rcindex & RunCommandsIndex::MASK_MODE) ; if(rcindex & RunCommandsIndex::MASK_MAP) { SyscmdMap::sprocess(mode, std::forward<Str>(args), false) ; } else if(rcindex & RunCommandsIndex::MASK_NOREMAP) { SyscmdNoremap::sprocess(mode, std::forward<Str>(args), false) ; } else if(rcindex & RunCommandsIndex::MASK_UNMAP) { SyscmdUnmap::sprocess(mode, std::forward<Str>(args), false) ; } else if(rcindex & RunCommandsIndex::MASK_MAPCLEAR) { if(!args.empty()) { throw std::invalid_argument("Mapclear") ; } SyscmdMapclear::sprocess(mode, false) ; } else { throw std::domain_error(std::to_string(static_cast<int>(rcindex))) ; } } } namespace vind { SyscmdSource::SyscmdSource() : BindedFuncCreator("system_command_source") { auto f = path::to_u8path(path::RC()) ; std::ifstream ifs(f) ; if(!ifs.is_open()) { std::ofstream ofs(f, std::ios::trunc) ; } } void SyscmdSource::sprocess( const std::string& path, bool reload_config) { auto return_to_default = [] { gparams::reset() ; gmaps::reset() ; } ; return_to_default() ; std::ifstream ifs(path::to_u8path(path), std::ios::in) ; if(!ifs.is_open()) { VCmdLine::print(ErrorMessage("Could not open \"" + path + "\".\n")) ; return ; } std::string aline ; std::size_t lnum = 0 ; while(getline(ifs, aline)) { lnum ++ ; try { rcparser::remove_dbquote_comment(aline) ; auto [cmd, args] = rcparser::divide_cmd_and_args(aline) ; if(cmd.empty()) { continue ; } auto rcindex = rcparser::parse_run_command(cmd) ; do_runcommand(rcindex, args) ; } catch(const std::domain_error& e) { auto ltag = "L:" + std::to_string(lnum) ; VCmdLine::print(ErrorMessage("E: Not command (" + ltag + ")")) ; std::stringstream ss ; ss << "RunCommandsIndex: " << e.what() << " is not supported." ; ss << " (" << path << ", " << ltag << ") " ; PRINT_ERROR(ss.str()) ; return_to_default() ; break ; } catch(const std::invalid_argument& e) { auto ltag = "L:" + std::to_string(lnum) ; VCmdLine::print(ErrorMessage("E: Invalid Argument (" + ltag + ")")) ; std::stringstream ss ; ss << e.what() << " is recieved invalid arguments." ; ss << " (" << path << ", " << ltag << ") " ; PRINT_ERROR(ss.str()) ; return_to_default() ; break ; } catch(const std::logic_error& e) { auto ltag = "L:" + std::to_string(lnum) ; VCmdLine::print(ErrorMessage("E: Invalid Syntax (" + ltag + ")")) ; std::stringstream ss ; ss << e.what() ; ss << " (" + path + ", " + ltag + ")" ; PRINT_ERROR(ss.str()) ; return_to_default() ; break ; } catch(const std::runtime_error& e) { auto ltag = "L:" + std::to_string(lnum) ; VCmdLine::print(ErrorMessage("E: Invalid Syntax (" + ltag + ")")) ; std::stringstream ss ; ss << e.what() ; ss << " (" + path + ", " + ltag + ")" ; PRINT_ERROR(ss.str()) ; return_to_default() ; break ; } } // while(getline()) if(reload_config) { vind::reconstruct_all_components() ; // Apply settings } } void SyscmdSource::sprocess(NTypeLogger&) { } void SyscmdSource::sprocess(const CharLogger& parent_lgr) { try { auto str = parent_lgr.to_str() ; if(str.empty()) { throw RUNTIME_EXCEPT("Empty command") ; } auto [cmd, args] = rcparser::divide_cmd_and_args(str) ; if(args.empty()) { sprocess(path::RC(), true) ; } else { sprocess(args, true) ; } } // If received syntax error as std::logic_error, // convert to runtime_error not to terminate application. catch(const std::exception& e) { throw std::runtime_error(e.what()) ; } } }
3,590
368
#include "pch.h" #include "MainWindow.xaml.h" #if __has_include("MainWindow.g.cpp") #include "MainWindow.g.cpp" #endif using namespace winrt; using namespace Microsoft::UI::Xaml; using namespace AuthoringTest; namespace winrt::AuthoringWinUITest::implementation { std::wstring GetLastCustomButtonString(Microsoft::UI::Xaml::Controls::UIElementCollection buttons) { std::wstring str = L""; for (auto button : buttons) { if (auto customButton = button.try_as<CustomButton>()) { str = customButton.GetText().c_str(); } } if (str != L"Custom row 5") { throw winrt::hresult_error(); } return str; } MainWindow::MainWindow() { InitializeComponent(); myStackPanel().Children().Append(ButtonUtils::GetButton()); myStackPanel().Children().Append(ButtonUtils::GetCustomButton()); myStackPanel().Children().Append(ButtonUtils::GetCustomButton(L"Custom row 4")); myStackPanel().Children().Append(CustomButton()); myStackPanel().Children().Append(CustomButton(L"Custom row 5")); myStackPanel().Children().Append(CustomButton(GetLastCustomButtonString(myStackPanel().Children()))); } void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { myButton().Content(box_value(L"Clicked")); } }
644
571
package de.gurkenlabs.litiengine.graphics; public enum StaticShadowType { DOWN, DOWNLEFT, DOWNRIGHT, LEFT, LEFTDOWN, LEFTRIGHT, NONE, NOOFFSET, RIGHT, RIGHTDOWN, RIGHTLEFT; public static StaticShadowType get(final String mapObjectType) { if (mapObjectType == null || mapObjectType.isEmpty()) { return StaticShadowType.NOOFFSET; } try { return StaticShadowType.valueOf(mapObjectType); } catch (final IllegalArgumentException iae) { return StaticShadowType.NOOFFSET; } } }
237
1,056
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * NewServlet.java * * Created on February 19, 2005, 12:41 PM */ package abc; import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; /** * * @author mg116726 * @version */ public class NewServlet extends HttpServlet { /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); /* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet NewServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet NewServlet at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); */ out.close(); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold> }
953
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _COMPHELPER_COMPONENTFACTORY_HXX #define _COMPHELPER_COMPONENTFACTORY_HXX #include "comphelper/comphelperdllapi.h" #include <com/sun/star/lang/XSingleServiceFactory.hpp> /** * @Descr * Utilities to get an instance of a component if a ProcessServiceFactory * is not available like it is the case in "small tools" as the Setup. */ #include <com/sun/star/uno/Reference.h> #ifdef UNX // "libNAMExy.so" (__DLLEXTENSION == "xy.so") #define LLCF_LIBNAME( name ) "lib" name __DLLEXTENSION #else // "NAMExy.dll" (__DLLEXTENSION == "xy") #define LLCF_LIBNAME( name ) name __DLLEXTENSION ".dll" #endif namespace rtl { class OUString; } namespace com { namespace sun { namespace star { namespace uno { class XInterface; } namespace lang { class XSingleServiceFactory; class XMultiServiceFactory; } namespace registry { class XRegistryKey; } }}} namespace comphelper { /** * Get an instance of the component <code>rImplementationName</code> located * in library <code>rLibraryName</code>. The instance must then be queried * for the desired interface with a queryInterface call. * The library name must be constructed with the macro * <code>LLCF_LIBNAME( name )</code> if it is a library from the normal build * process which includes build number and platform name. * * @example:C++ * <listing> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; Reference< whatever::XYourComponent > xComp; // library name, e.g. xyz603mi.dll or libxyz603.so ::rtl::OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( LLCF_LIBNAME( "xyz" ) ) ); ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.whatever.YourComponent" ) ); Reference< Xinterface > xI = ::comphelper::getComponentInstance( aLibName, aImplName ); if ( xI.is() ) { Any x = xI->queryInterface( ::getCppuType((const Reference< whatever::XYourComponent >*)0) ); x >>= xComp; } if ( !xComp.is() ) // you're lost * </listing> */ COMPHELPER_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getComponentInstance( const ::rtl::OUString & rLibraryName, const ::rtl::OUString & rImplementationName ); ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > loadLibComponentFactory( const ::rtl::OUString & rLibraryName, const ::rtl::OUString & rImplementationName, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF, const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey > & xKey ); } // namespace comphelper #endif // _COMPHELPER_COMPONENTFACTORY_HXX
1,163
2,208
#!/usr/bin/env python ######################################################################### # Reinforcement Learning with PGPE on the ShipSteering Environment # # Requirements: pylab (for plotting only). If not available, comment the # last 3 lines out # Author: <NAME>, <EMAIL> ######################################################################### __author__ = "<NAME>, <NAME>" __version__ = '$Id$' from pybrain.tools.example_tools import ExTools from pybrain.structure.modules.tanhlayer import TanhLayer from pybrain.tools.shortcuts import buildNetwork from pybrain.rl.environments.shipsteer import ShipSteeringEnvironment from pybrain.rl.environments.shipsteer import GoNorthwardTask from pybrain.rl.agents import OptimizationAgent from pybrain.optimization import PGPE from pybrain.rl.experiments import EpisodicExperiment batch=1 #number of samples per learning step prnts=50 #number of learning steps after results are printed epis=2000/batch/prnts #number of roleouts numbExp=10 #number of experiments et = ExTools(batch, prnts) #tool for printing and plotting env = None for runs in range(numbExp): # create environment #Options: Bool(OpenGL), Bool(Realtime simu. while client is connected), ServerIP(default:localhost), Port(default:21560) if env != None: env.closeSocket() env = ShipSteeringEnvironment() # create task task = GoNorthwardTask(env,maxsteps = 500) # create controller network net = buildNetwork(task.outdim, task.indim, outclass=TanhLayer) # create agent with controller and learner (and its options) agent = OptimizationAgent(net, PGPE(learningRate = 0.3, sigmaLearningRate = 0.15, momentum = 0.0, epsilon = 2.0, rprop = False, storeAllEvaluations = True)) et.agent = agent #create experiment experiment = EpisodicExperiment(task, agent) #Do the experiment for updates in range(epis): for i in range(prnts): experiment.doEpisodes(batch) et.printResults((agent.learner._allEvaluations)[-50:-1], runs, updates) et.addExps() et.showExps() #To view what the simulation is doing at the moment set the environment with True, go to pybrain/rl/environments/ode/ and start viewer.py (python-openGL musst be installed, see PyBrain documentation)
869
493
<filename>src/com/jdh/microcraft/gui/PlayerInventoryMenu.java package com.jdh.microcraft.gui; import com.jdh.microcraft.Global; import com.jdh.microcraft.entity.EntityPlayer; import com.jdh.microcraft.gui.crafting.InventoryCraftingMenu; import com.jdh.microcraft.item.ItemStack; import com.jdh.microcraft.item.armor.*; import com.jdh.microcraft.sound.Sound; import com.jdh.microcraft.util.ControlHandler; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class PlayerInventoryMenu extends InventoryMenu { private class PlayerArmorMenu extends ItemListMenu { public PlayerArmorMenu() { super( PlayerInventoryMenu.this.x + (PlayerInventoryMenu.this.width + 2) * 8, PlayerInventoryMenu.this.y, 14, 6 ); } @Override public List<ItemStack> getItems() { return Arrays.stream(PlayerInventoryMenu.this.player.armor) .filter(Objects::nonNull) .collect(Collectors.toList()); } @Override public String getItemName(int index) { return this.getItems().get(index).instance.item.getName(); } @Override public int getItemTextColor(int index) { return 444; } @Override public String getName() { return "ARMOR"; } } private final PlayerArmorMenu armorMenu; private final EntityPlayer player; private final boolean showArmor; public PlayerInventoryMenu(EntityPlayer player, boolean showArmor) { super(player.inventory, true); this.player = player; this.showArmor = showArmor; this.focused = true; this.armorMenu = new PlayerArmorMenu(); List<ItemStack> items = this.getItems(); int selected = items.indexOf(this.player.equipped); this.selectedIndex = selected == -1 ? 0 : selected; this.updateOffset(); } @Override public void tick() { super.tick(); List<ItemStack> items = this.getItems(); ItemStack selectedItem = this.selectedIndex >= 0 && this.selectedIndex < items.size() ? items.get(this.selectedIndex) : null; this.player.equipped = selectedItem; if (this.showArmor) { if (ControlHandler.MENU_EQUIP.pressedTick() && selectedItem != null && selectedItem.instance.item instanceof ItemArmor) { ItemArmor armor = (ItemArmor) selectedItem.instance.item; if (this.player.armor[armor.slot] == selectedItem) { this.player.armor[armor.slot] = null; } else { Sound.EQUIP.play(); this.player.armor[armor.slot] = selectedItem; } } this.armorMenu.tick(); } if (ControlHandler.DROP.pressedTick() && selectedItem != null && selectedItem.instance.item.isDroppable()) { this.player.drop(selectedItem); } if (ControlHandler.TOGGLE_CRAFTING.pressedTick()) { // direct inventory -> crafting transition Global.game.setMenu(new InventoryCraftingMenu(this.player)); } } @Override public void render() { super.render(); if (this.showArmor) { this.armorMenu.render(); } } @Override public void update() { if (this.showArmor) { this.armorMenu.update(); } } }
1,611
545
<reponame>rofl0r/pspsdk<gh_stars>100-1000 /* * PSP Software Development Kit - https://github.com/pspdev * ----------------------------------------------------------------------- * Licensed under the BSD license, see LICENSE in PSPSDK root for details. * * Copyright (c) 2005 <NAME> */ #include "guInternal.h" void sceGuTexFunc(int tfx, int tcc) { GuContext* context = &gu_contexts[gu_curr_context]; context->texture_function = (tcc << 8) | tfx; sendCommandi(201,((tcc << 8)|tfx)|context->fragment_2x); }
174
32,544
package com.baeldung.charencoding.controller; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.filter.CharacterEncodingFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; class CharEncodingCheckControllerUnitTest { @Test void whenCharEncodingFilter_thenVerifyEncoding() throws ServletException, IOException { HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = new MockFilterChain(); CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); filter.setForceEncoding(true); filter.doFilter(request, response, chain); assertEquals("UTF-8", request.getCharacterEncoding()); assertEquals("UTF-8", response.getCharacterEncoding()); } }
422
432
/* * Copyright 2018 <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <inttypes.h> #include <vector> #include "elftypes.h" #include "common/attribute.h" class ElfReader { public: explicit ElfReader(const char *file_name); virtual unsigned loadableSectionTotal() { return loadSectionList_.size(); } virtual const char *sectionName(unsigned idx) { return loadSectionList_[idx][LoadSh_name].to_string(); } virtual uint64_t sectionAddress(unsigned idx) { return loadSectionList_[idx][LoadSh_addr].to_uint64(); } virtual uint64_t sectionSize(unsigned idx) { return loadSectionList_[idx][LoadSh_size].to_uint64(); } virtual uint8_t *sectionData(unsigned idx) { return loadSectionList_[idx][LoadSh_data].data(); } void writeRawImage(AttributeType *ofiles, uint32_t fixed_size = 0); void writeRomHexArray(AttributeType *ofiles, int bytes_per_line, int fixed_size = 0); private: int readElfHeader(); int loadSections(); void processDebugSymbol(SectionHeaderType *sh); private: enum ELoadSectionItem { LoadSh_name, LoadSh_addr, LoadSh_size, LoadSh_data, LoadSh_Total, }; enum ESymbolInfoListItem { Symbol_Name, Symbol_Addr, Symbol_Size, Symbol_Type, Symbol_Total }; enum ESymbolType { SYMBOL_TYPE_FILE = 0x01, SYMBOL_TYPE_FUNCTION = 0x02, SYMBOL_TYPE_DATA = 0x04 }; enum EMode { Mode_32bits, Mode_64bits } emode_; AttributeType sourceProc_; AttributeType symbolList_; AttributeType loadSectionList_; uint8_t *image_; ElfHeaderType *header_; SectionHeaderType **sh_tbl_; char *sectionNames_; char *symbolNames_; uint64_t lastLoadAdr_; };
1,005
1,030
{ "if": { "field": "type", "equals": "Microsoft.Batch/batchAccounts" }, "then": { "effect": "AuditIfNotExists", "details": { "type": "Microsoft.Insights/alertRules", "existenceScope": "Subscription", "existenceCondition": { "allOf": [ { "field": "Microsoft.Insights/alertRules/isEnabled", "equals": "true" }, { "field": "Microsoft.Insights/alertRules/condition.dataSource.metricName", "equals": "[parameters('metricName')]" }, { "field": "Microsoft.Insights/alertRules/condition.dataSource.resourceUri", "equals": "[concat('/subscriptions/', subscription().subscriptionId, '/resourcegroups/', resourceGroup().name, '/providers/Microsoft.Batch/batchAccounts/', field('name'))]" } ] } } } }
468
527
// Copyright (C) 2020-2021 <NAME> <<EMAIL>> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef LEXY_DSL_WHITESPACE_HPP_INCLUDED #define LEXY_DSL_WHITESPACE_HPP_INCLUDED #include <lexy/action/base.hpp> #include <lexy/dsl/base.hpp> #include <lexy/dsl/choice.hpp> #include <lexy/dsl/loop.hpp> #include <lexy/dsl/token.hpp> //=== implementation ===// namespace lexy::_detail { struct tag_no_whitespace {}; template <typename Rule> struct ws_production { static constexpr auto max_recursion_depth = 0; static constexpr auto rule = lexy::dsl::loop(Rule{} | lexy::dsl::break_); }; template <typename Context> struct whitespace_handler { Context* parent; //=== events ===// template <typename Production> struct marker { constexpr void get_value() && {} }; template <typename Production> constexpr bool get_action_result(bool parse_result, marker<Production>&&) && { return parse_result; } template <typename Rule, typename Iterator> constexpr auto on(parse_events::production_start<ws_production<Rule>>, Iterator) { return marker<ws_production<Rule>>{}; } template <typename Production, typename Iterator> constexpr auto on(parse_events::production_start<Production>, Iterator) { static_assert(_detail::error<Production>, "whitespace rule must not contain `dsl::p` or `dsl::recurse`;" "use `dsl::inline_` instead"); return marker<Production>{}; } template <typename Production, typename Iterator> constexpr auto on(marker<Production>, parse_events::list, Iterator) { return lexy::noop.sink(); } template <typename Production, typename Error> constexpr void on(marker<Production>, parse_events::error ev, Error&& error) { parent->on(ev, LEXY_FWD(error)); } template <typename... Args> constexpr void on(const Args&...) {} }; template <typename Rule, typename NextParser> struct manual_ws_parser { template <typename Context, typename Reader, typename... Args> LEXY_PARSER_FUNC static bool parse(Context& context, Reader& reader, Args&&... args) { auto result = true; auto begin = reader.position(); if constexpr (lexy::is_token_rule<Rule>) { // Parsing a token repeatedly cannot fail, so we can optimize it. while (lexy::try_match_token(Rule{}, reader)) {} } else { // Parse the rule using a special handler that only forwards errors. using production = ws_production<Rule>; whitespace_handler<Context> ws_handler{&context}; result = lexy::do_action<production>(LEXY_MOV(ws_handler), reader); } auto end = reader.position(); if (result) { // Add a whitespace token node. if (begin != end) context.on(lexy::parse_events::token{}, lexy::whitespace_token_kind, begin, end); // And continue. return NextParser::parse(context, reader, LEXY_FWD(args)...); } else { // Add an error token node. if (begin != end) context.on(lexy::parse_events::token{}, lexy::error_token_kind, begin, end); // And cancel. return false; } } }; template <typename NextParser> struct manual_ws_parser<void, NextParser> : NextParser {}; template <typename Context> using context_whitespace = lexy::production_whitespace<typename Context::production, typename Context::root_production>; template <typename NextParser> struct automatic_ws_parser { template <typename Context, typename Reader, typename... Args> LEXY_PARSER_FUNC static bool parse(Context& context, Reader& reader, Args&&... args) { if constexpr (Context::contains(lexy::_detail::tag_no_whitespace{})) { // Automatic whitespace skipping is disabled. return NextParser::parse(context, reader, LEXY_FWD(args)...); } else { // Skip the appropriate whitespace. using rule = context_whitespace<Context>; return manual_ws_parser<rule, NextParser>::parse(context, reader, LEXY_FWD(args)...); } } }; } // namespace lexy::_detail //=== whitespace ===// namespace lexyd { template <typename Rule> struct _wsr : rule_base { template <typename NextParser> using p = lexy::_detail::manual_ws_parser<Rule, NextParser>; template <typename R> friend constexpr auto operator|(_wsr<Rule>, R r) { return _wsr<decltype(Rule{} | r)>{}; } template <typename R> friend constexpr auto operator|(R r, _wsr<Rule>) { return _wsr<decltype(r | Rule{})>{}; } template <typename R> friend constexpr auto operator/(_wsr<Rule>, R r) { return _wsr<decltype(Rule{} / r)>{}; } template <typename R> friend constexpr auto operator/(R r, _wsr<Rule>) { return _wsr<decltype(r / Rule{})>{}; } }; struct _ws : rule_base { template <typename NextParser> using p = lexy::_detail::automatic_ws_parser<NextParser>; /// Overrides implicit whitespace detection. template <typename Rule> constexpr auto operator()(Rule) const { return _wsr<Rule>{}; } }; /// Matches whitespace. constexpr auto whitespace = _ws{}; } // namespace lexyd //=== no_whitespace ===// namespace lexyd { template <typename Rule> struct _wsn : _copy_base<Rule> { template <typename NextParser> struct _pc { template <typename ParentContext, typename Id, typename T, typename Reader, typename Context, typename... Args> LEXY_PARSER_FUNC static bool parse(lexy::_detail::parse_context_var<ParentContext, Id, T>&, Reader& reader, Context& context, Args&&... args) { static_assert(std::is_same_v<ParentContext, Context> // && std::is_same_v<Id, lexy::_detail::tag_no_whitespace> // && std::is_same_v<Id, T>, "cannot create context variables inside `lexy::dsl::no_whitespace()`"); // Continue with the normal context, after skipping whitespace. return lexy::whitespace_parser<Context, NextParser>::parse(context, reader, LEXY_FWD(args)...); } }; template <typename Context, typename Reader, typename Whitespace = lexy::_detail::context_whitespace<Context>> struct bp { using whitespace_context = lexy::_detail::parse_context_var<Context, lexy::_detail::tag_no_whitespace>; lexy::branch_parser_for<Rule, whitespace_context, Reader> rule; constexpr auto try_parse(Context& context, const Reader& reader) { // Create a context that doesn't allow whitespace. // This is essentially free, so we can do it twice. whitespace_context ws_context(context); // Try parse the rule in that context. return rule.try_parse(ws_context, reader); } template <typename NextParser, typename... Args> LEXY_PARSER_FUNC auto finish(Context& context, Reader& reader, Args&&... args) { // Finish the rule with on another whitespace context. whitespace_context ws_context(context); return rule.template finish<_pc<NextParser>>(ws_context, reader, context, LEXY_FWD(args)...); } }; // Optimization: if there is no whitespace rule, we just parse Rule directly. template <typename Context, typename Reader> struct bp<Context, Reader, void> : lexy::branch_parser_for<Rule, Context, Reader> {}; template <typename NextParser> struct p { template <typename Context, typename Reader, typename... Args> LEXY_PARSER_FUNC static bool parse(Context& context, Reader& reader, Args&&... args) { if constexpr (std::is_void_v<lexy::_detail::context_whitespace<Context>>) { // No whitespace, just parse the rule. return lexy::parser_for<Rule, NextParser>::parse(context, reader, LEXY_FWD(args)...); } else { // Parse the rule in the whitespace context. lexy::_detail::parse_context_var ws_context(context, lexy::_detail::tag_no_whitespace{}, lexy::_detail::tag_no_whitespace{}); using parser = lexy::parser_for<Rule, _pc<NextParser>>; return parser::parse(ws_context, reader, context, LEXY_FWD(args)...); } } }; }; /// Disables automatic skipping of whitespace for all tokens of the given rule. template <typename Rule> constexpr auto no_whitespace(Rule) { if constexpr (lexy::is_token_rule<Rule>) return Rule{}; // Token already behaves that way. else return _wsn<Rule>{}; } } // namespace lexyd #endif // LEXY_DSL_WHITESPACE_HPP_INCLUDED
4,296
653
//==---------- persistent_device_code_cache.cpp -----------------*- C++-*---==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <cstdio> #include <detail/device_impl.hpp> #include <detail/persistent_device_code_cache.hpp> #include <detail/plugin.hpp> #include <detail/program_manager/program_manager.hpp> #if defined(__SYCL_RT_OS_LINUX) #include <unistd.h> #else #include <direct.h> #include <io.h> #endif __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace detail { /* Lock file suffix */ const char LockCacheItem::LockSuffix[] = ".lock"; LockCacheItem::LockCacheItem(const std::string &Path) : FileName(Path + LockSuffix) { int fd; /* If the lock fail is not created */ if ((fd = open(FileName.c_str(), O_CREAT | O_EXCL, S_IWRITE)) != -1) { close(fd); Owned = true; } else { PersistentDeviceCodeCache::trace("Failed to aquire lock file: " + FileName); } } LockCacheItem::~LockCacheItem() { if (Owned && std::remove(FileName.c_str())) PersistentDeviceCodeCache::trace("Failed to release lock file: " + FileName); } /* Returns true if specified image should be cached on disk. It checks if * cache is enabled, image has SPIRV type and matches thresholds. */ bool PersistentDeviceCodeCache::isImageCached(const RTDeviceBinaryImage &Img) { // Cache shoould be enabled and image type should be SPIR-V if (!isEnabled() || Img.getFormat() != PI_DEVICE_BINARY_TYPE_SPIRV) return false; // Disable cache for ITT-profiled images. if (SYCLConfig<INTEL_ENABLE_OFFLOAD_ANNOTATIONS>::get()) { return false; } static auto MaxImgSize = getNumParam<SYCL_CACHE_MAX_DEVICE_IMAGE_SIZE>( DEFAULT_MAX_DEVICE_IMAGE_SIZE); static auto MinImgSize = getNumParam<SYCL_CACHE_MIN_DEVICE_IMAGE_SIZE>( DEFAULT_MIN_DEVICE_IMAGE_SIZE); // Make sure that image size is between caching thresholds if they are set. // Zero values for threshold is treated as disabled threshold. if ((MaxImgSize && (Img.getSize() > MaxImgSize)) || (MinImgSize && (Img.getSize() < MinImgSize))) return false; return true; } /* Stores built program in persisten cache */ void PersistentDeviceCodeCache::putItemToDisc( const device &Device, const RTDeviceBinaryImage &Img, const SerializedObj &SpecConsts, const std::string &BuildOptionsString, const RT::PiProgram &NativePrg) { std::string DirName = getCacheItemPath(Device, Img, SpecConsts, BuildOptionsString); if (!isImageCached(Img) || DirName.empty()) return; auto Plugin = detail::getSyclObjImpl(Device)->getPlugin(); size_t i = 0; std::string FileName; do { FileName = DirName + "/" + std::to_string(i++); } while (OSUtil::isPathPresent(FileName + ".bin")); unsigned int DeviceNum = 0; Plugin.call<PiApiKind::piProgramGetInfo>( NativePrg, PI_PROGRAM_INFO_NUM_DEVICES, sizeof(DeviceNum), &DeviceNum, nullptr); std::vector<size_t> BinarySizes(DeviceNum); Plugin.call<PiApiKind::piProgramGetInfo>( NativePrg, PI_PROGRAM_INFO_BINARY_SIZES, sizeof(size_t) * BinarySizes.size(), BinarySizes.data(), nullptr); std::vector<std::vector<char>> Result; std::vector<char *> Pointers; for (size_t I = 0; I < BinarySizes.size(); ++I) { Result.emplace_back(BinarySizes[I]); Pointers.push_back(Result[I].data()); } Plugin.call<PiApiKind::piProgramGetInfo>(NativePrg, PI_PROGRAM_INFO_BINARIES, sizeof(char *) * Pointers.size(), Pointers.data(), nullptr); try { OSUtil::makeDir(DirName.c_str()); LockCacheItem Lock{FileName}; if (Lock.isOwned()) { std::string FullFileName = FileName + ".bin"; writeBinaryDataToFile(FullFileName, Result); trace("device binary has been cached: " + FullFileName); writeSourceItem(FileName + ".src", Device, Img, SpecConsts, BuildOptionsString); } } catch (...) { // If a problem happens on storing cache item, do nothing } } /* Program binaries built for one or more devices are read from persistent * cache and returned in form of vector of programs. Each binary program is * stored in vector of chars. */ std::vector<std::vector<char>> PersistentDeviceCodeCache::getItemFromDisc( const device &Device, const RTDeviceBinaryImage &Img, const SerializedObj &SpecConsts, const std::string &BuildOptionsString) { std::string Path = getCacheItemPath(Device, Img, SpecConsts, BuildOptionsString); if (!isImageCached(Img) || Path.empty() || !OSUtil::isPathPresent(Path)) return {}; int i = 0; std::string FileName{Path + "/" + std::to_string(i)}; while (OSUtil::isPathPresent(FileName + ".bin") || OSUtil::isPathPresent(FileName + ".src")) { if (!LockCacheItem::isLocked(FileName) && isCacheItemSrcEqual(FileName + ".src", Device, Img, SpecConsts, BuildOptionsString)) { try { std::string FullFileName = FileName + ".bin"; std::vector<std::vector<char>> res = readBinaryDataFromFile(FullFileName); trace("using cached device binary: " + FullFileName); return res; // subject for NRVO } catch (...) { // If read was unsuccessfull try the next item } } FileName = Path + "/" + std::to_string(++i); } return {}; } /* Returns string value which can be used to identify different device */ std::string PersistentDeviceCodeCache::getDeviceIDString(const device &Device) { return Device.get_platform().get_info<sycl::info::platform::name>() + "/" + Device.get_info<sycl::info::device::name>() + "/" + Device.get_info<sycl::info::device::version>() + "/" + Device.get_info<sycl::info::device::driver_version>(); } /* Write built binary to persistent cache * Format: numImages, 1stImageSize, Image[, NthImageSize, NthImage...] * Return on first unsuccessfull file operation */ void PersistentDeviceCodeCache::writeBinaryDataToFile( const std::string &FileName, const std::vector<std::vector<char>> &Data) { std::ofstream FileStream{FileName, std::ios::binary}; size_t Size = Data.size(); FileStream.write((char *)&Size, sizeof(Size)); for (size_t i = 0; i < Data.size(); ++i) { Size = Data[i].size(); FileStream.write((char *)&Size, sizeof(Size)); FileStream.write(Data[i].data(), Size); } FileStream.close(); if (FileStream.fail()) trace("Failed to write binary file " + FileName); } /* Read built binary to persistent cache * Format: numImages, 1stImageSize, Image[, NthImageSize, NthImage...] */ std::vector<std::vector<char>> PersistentDeviceCodeCache::readBinaryDataFromFile(const std::string &FileName) { std::ifstream FileStream{FileName, std::ios::binary}; size_t ImgNum = 0, ImgSize = 0; FileStream.read((char *)&ImgNum, sizeof(ImgNum)); std::vector<std::vector<char>> Res(ImgNum); for (size_t i = 0; i < ImgNum; ++i) { FileStream.read((char *)&ImgSize, sizeof(ImgSize)); std::vector<char> ImgData(ImgSize); FileStream.read(ImgData.data(), ImgSize); Res[i] = std::move(ImgData); } FileStream.close(); if (FileStream.fail()) { trace("Failed to read binary file from " + FileName); return {}; } return Res; } /* Writing cache item key sources to be used for reliable identification * Format: Four pairs of [size, value] for device, build options, specialization * constant values, device code SPIR-V image. */ void PersistentDeviceCodeCache::writeSourceItem( const std::string &FileName, const device &Device, const RTDeviceBinaryImage &Img, const SerializedObj &SpecConsts, const std::string &BuildOptionsString) { std::ofstream FileStream{FileName, std::ios::binary}; std::string DeviceString{getDeviceIDString(Device)}; size_t Size = DeviceString.size(); FileStream.write((char *)&Size, sizeof(Size)); FileStream.write(DeviceString.data(), Size); Size = BuildOptionsString.size(); FileStream.write((char *)&Size, sizeof(Size)); FileStream.write(BuildOptionsString.data(), Size); Size = SpecConsts.size(); FileStream.write((char *)&Size, sizeof(Size)); FileStream.write((const char *)SpecConsts.data(), Size); Size = Img.getSize(); FileStream.write((char *)&Size, sizeof(Size)); FileStream.write((const char *)Img.getRawData().BinaryStart, Size); FileStream.close(); if (FileStream.fail()) { trace("Failed to write source file to " + FileName); } } /* Check that cache item key sources are equal to the current program. * If file read operations fail cache item is treated as not equal. */ bool PersistentDeviceCodeCache::isCacheItemSrcEqual( const std::string &FileName, const device &Device, const RTDeviceBinaryImage &Img, const SerializedObj &SpecConsts, const std::string &BuildOptionsString) { std::ifstream FileStream{FileName, std::ios::binary}; std::string ImgString{(const char *)Img.getRawData().BinaryStart, Img.getSize()}; std::string SpecConstsString{(const char *)SpecConsts.data(), SpecConsts.size()}; size_t Size = 0; FileStream.read((char *)&Size, sizeof(Size)); std::string res(Size, '\0'); FileStream.read(&res[0], Size); if (getDeviceIDString(Device).compare(res)) return false; FileStream.read((char *)&Size, sizeof(Size)); res.resize(Size); FileStream.read(&res[0], Size); if (BuildOptionsString.compare(res)) return false; FileStream.read((char *)&Size, sizeof(Size)); res.resize(Size); FileStream.read(&res[0], Size); if (SpecConstsString.compare(res)) return false; FileStream.read((char *)&Size, sizeof(Size)); res.resize(Size); FileStream.read(&res[0], Size); if (ImgString.compare(res)) return false; FileStream.close(); if (FileStream.fail()) { trace("Failed to read source file from " + FileName); } return true; } /* Returns directory name to store specific kernel image for specified * device, build options and specialization constants values. */ std::string PersistentDeviceCodeCache::getCacheItemPath( const device &Device, const RTDeviceBinaryImage &Img, const SerializedObj &SpecConsts, const std::string &BuildOptionsString) { static std::string cache_root{getRootDir()}; if (cache_root.empty()) { trace("Disable persistent cache due to unconfigured cache root."); return {}; } std::string ImgString{(const char *)Img.getRawData().BinaryStart, Img.getSize()}; std::string DeviceString{getDeviceIDString(Device)}; std::string SpecConstsString{(const char *)SpecConsts.data(), SpecConsts.size()}; std::hash<std::string> StringHasher{}; return cache_root + "/" + std::to_string(StringHasher(DeviceString)) + "/" + std::to_string(StringHasher(ImgString)) + "/" + std::to_string(StringHasher(SpecConstsString)) + "/" + std::to_string(StringHasher(BuildOptionsString)); } // TODO Currently parsing configuration variables and error reporting is not // centralized, and is basically re-implemented (with different level of // reliability) for each particular variable. As a variant, this can go into // the SYCLConfigBase class, which can be templated by value type, default value // and value parser (combined with error checker). It can also have typed get() // function returning one-time parsed and error-checked value. // Parses persistent cache configuration and checks it for errors. // Returns true if it is enabled, false otherwise. static bool parsePersistentCacheConfig() { constexpr bool Default = false; // default is disabled // Check if deprecated opt-out env var is used, then warn. if (SYCLConfig<SYCL_CACHE_DISABLE_PERSISTENT>::get()) { std::cerr << "WARNING: " << SYCLConfig<SYCL_CACHE_DISABLE_PERSISTENT>::getName() << " environment variable is deprecated " << "and has no effect. By default, persistent device code caching is " << (Default ? "enabled." : "disabled.") << " Use " << SYCLConfig<SYCL_CACHE_PERSISTENT>::getName() << "=1/0 to enable/disable.\n"; } bool Ret = Default; const char *RawVal = SYCLConfig<SYCL_CACHE_PERSISTENT>::get(); if (RawVal) { if (!std::strcmp(RawVal, "0")) { Ret = false; } else if (!std::strcmp(RawVal, "1")) { Ret = true; } else { std::string Msg = std::string{"Invalid value for bool configuration variable "} + SYCLConfig<SYCL_CACHE_PERSISTENT>::getName() + std::string{": "} + RawVal; throw runtime_error(Msg, PI_INVALID_OPERATION); } } PersistentDeviceCodeCache::trace(Ret ? "enabled" : "disabled"); return Ret; } /* Returns true if persistent cache is enabled. */ bool PersistentDeviceCodeCache::isEnabled() { static bool Val = parsePersistentCacheConfig(); return Val; } /* Returns path for device code cache root directory * If environment variables are not available return an empty string to identify * that cache is not available. */ std::string PersistentDeviceCodeCache::getRootDir() { static const char *RootDir = SYCLConfig<SYCL_CACHE_DIR>::get(); if (RootDir) return RootDir; constexpr char DeviceCodeCacheDir[] = "/libsycl_cache"; // Use static to calculate directory only once per program run #if defined(__SYCL_RT_OS_LINUX) static const char *CacheDir = std::getenv("XDG_CACHE_HOME"); static const char *HomeDir = std::getenv("HOME"); if (!CacheDir && !HomeDir) return {}; static std::string Res{ std::string(CacheDir ? CacheDir : (std::string(HomeDir) + "/.cache")) + DeviceCodeCacheDir}; #else static const char *AppDataDir = std::getenv("AppData"); if (!AppDataDir) return {}; static std::string Res{std::string(AppDataDir) + DeviceCodeCacheDir}; #endif return Res; } } // namespace detail } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
5,093
1,016
package com.thinkbiganalytics.kylo.nifi.teradata.tdch.api; /*- * #%L * nifi-teradata-tdch-api * %% * Copyright (C) 2017 - 2018 ThinkBig Analytics, a Teradata Company * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.controller.ControllerService; /** * Interface for a connection provider service for Teradata used by TDCH */ @Tags({"kylo", "thinkbig", "teradata", "tdch", "rdbms", "database", "table"}) @CapabilityDescription("Provides information for connecting to Teradata system for running a TDCH job") public interface TdchConnectionService extends ControllerService { /** * The JDBC driver class used by the source and target Teradata plugins when connecting to the Teradata system. * * @return JDBC driver class */ String getJdbcDriverClassName(); /** * The JDBC url used by the source and target Teradata plugins to connect to the Teradata system. * * @return JDBC Connection url */ String getJdbcConnectionUrl(); /** * The authentication username used by the source and target Teradata plugins to connect to the Teradata system. Note that the value can include Teradata Wallet references in order to use user name * information from the current user's wallet. * * @return username */ String getUserName(); /** * The authentication password used by the source and target Teradata plugins to connect to the Teradata system. Note that the value can include Teradata Wallet references in order to use user name * information from the current user's wallet. * * @return password */ String getPassword(); /** * The full path to teradata-connector-version.jar. This is referred via $USERLIBTDCH variable in TDCH documentation. Tested with version 1.5.4 * * @return path to teradata-connector-version.jar */ String getTdchJarPath(); /** * The paths to Hadoop and Hive library JARs required by TDCH. This is referred via $LIB_JARS variable in TDCH documentation. Delimiter to use between the entries is a comma (,) * * @return comma separated strings representing paths to Hadoop and Hive library JARs required by TDCH */ String getTdchLibraryJarsPath(); /** * The paths that constitute Hadoop classpath as required by TDCH. This is referred via $HADOOP_CLASSPATH variable in TDCH documentation. Delimiter to use between the entries is a colon (:) * * @return colon separated strings representing paths to Hadoop classpath as required by TDCH */ String getTdchHadoopClassPath(); }
987
545
#include <vector> #include <iostream> void printVecInt(const std::vector<int>::iterator bg, const std::vector<int>::iterator ed) { #ifndef NDEBUG std::cout << "In function: " << __func__ << ", " << "Vector size: " << ed - bg << std::endl; #endif if (bg == ed) return; std::cout << *bg << std::endl; printVecInt(bg + 1, ed); } int main() { std::vector<int> vi; int i; while (std::cin >> i) vi.push_back(i); printVecInt(vi.begin(), vi.end()); return 0; }
230
455
package netflix.karyon.examples.hellonoss.common; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import netflix.karyon.transport.interceptor.DuplexInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; /** * @author <NAME> */ public class LoggingInterceptor implements DuplexInterceptor<HttpServerRequest<ByteBuf>, HttpServerResponse<ByteBuf>> { private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class); private static int count; private final int id; public LoggingInterceptor() { id = ++count; } @Override public Observable<Void> in(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { logger.info("Logging interceptor with id {} invoked for direction IN.", id); return Observable.empty(); } @Override public Observable<Void> out(HttpServerResponse<ByteBuf> response) { logger.info("Logging interceptor with id {} invoked for direction OUT.", id); return Observable.empty(); } }
410
1,244
#include <string.h> #include <locale.h> char *strerror_l(int err, locale_t l) { return strerror(err); }
48
350
package ar.rulosoft.mimanganu.utils; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import androidx.annotation.NonNull; import androidx.preference.PreferenceManager; import ar.rulosoft.mimanganu.Exceptions.NoConnectionException; import ar.rulosoft.mimanganu.Exceptions.NoWifiException; import ar.rulosoft.mimanganu.MainActivity; import ar.rulosoft.mimanganu.MainFragment; import ar.rulosoft.mimanganu.services.AutomaticUpdateTask; /* Base from <NAME> from http://stackoverflow.com/questions/32242384/getallnetworkinfo-is-deprecated-how-to-use-getallnetworks-to-check-network */ public class NetworkUtilsAndReceiver extends BroadcastReceiver { public static ConnectionStatus connectionStatus = ConnectionStatus.UNCHECKED; //-1 not checked or changed, 0 no connection wifi, 1 no connection general, 2 connect public static boolean ONLY_WIFI; public static boolean isConnectedNonDestructive(@NonNull Context context) { SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(context); if (!pm.getBoolean("disable_internet_detection", false)) { boolean result; switch (connectionStatus) { case UNCHECKED: if (ONLY_WIFI) { result = isWifiConnected(context); if (result) { connectionStatus = ConnectionStatus.CONNECTED; } else { connectionStatus = ConnectionStatus.NO_WIFI_CONNECTED; } return result; } else { result = _isConnected(context); if (result) { connectionStatus = ConnectionStatus.CONNECTED; } else { connectionStatus = ConnectionStatus.NO_INET_CONNECTED; } return result; } case NO_WIFI_CONNECTED: return false; case NO_INET_CONNECTED: return false; case CONNECTED: return true; default: return true; } } else { return true; } } public static boolean isConnected(@NonNull Context context) throws Exception { SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(context); if (!pm.getBoolean("disable_internet_detection", false)) { boolean result; switch (connectionStatus) { case UNCHECKED: if (ONLY_WIFI) { result = isWifiConnected(context); if (result) { connectionStatus = ConnectionStatus.CONNECTED; } else { connectionStatus = ConnectionStatus.NO_WIFI_CONNECTED; throw new NoWifiException(context); } return result; } else { result = _isConnected(context); if (result) { connectionStatus = ConnectionStatus.CONNECTED; } else { connectionStatus = ConnectionStatus.NO_INET_CONNECTED; throw new NoConnectionException(context); } return result; } case NO_WIFI_CONNECTED: throw new NoWifiException(context); case NO_INET_CONNECTED: throw new NoConnectionException(context); case CONNECTED: return true; default: return true; } } else { return true; } } public static ConnectionStatus getConnectionStatus(@NonNull Context context) { return getConnectionStatus(context, ONLY_WIFI); } public static ConnectionStatus getConnectionStatus(@NonNull Context context, boolean only_wifi) { boolean result; if (connectionStatus == ConnectionStatus.UNCHECKED) { if (only_wifi) { result = isWifiConnected(context); if (result) { connectionStatus = ConnectionStatus.CONNECTED; } else { connectionStatus = ConnectionStatus.NO_WIFI_CONNECTED; } } else { result = _isConnected(context); if (result) { connectionStatus = ConnectionStatus.CONNECTED; } else { connectionStatus = ConnectionStatus.NO_INET_CONNECTED; } } } return connectionStatus; } public static void reset() { connectionStatus = ConnectionStatus.UNCHECKED; } public static boolean _isConnected(@NonNull Context context) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } public static boolean isWifiConnected(@NonNull Context context) { return isConnected(context, ConnectivityManager.TYPE_WIFI); } public static boolean isMobileConnected(@NonNull Context context) { return isConnected(context, ConnectivityManager.TYPE_MOBILE); } private static boolean isConnected(@NonNull Context context, int type) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { NetworkInfo networkInfo = connMgr.getNetworkInfo(type); return networkInfo != null && networkInfo.isConnected(); } else { return isConnected(connMgr, type); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static boolean isConnected(@NonNull ConnectivityManager connMgr, int type) { try { Network[] networks = connMgr.getAllNetworks(); NetworkInfo networkInfo; for (Network mNetwork : networks) { networkInfo = connMgr.getNetworkInfo(mNetwork); if (networkInfo != null && networkInfo.getType() == type && networkInfo.isConnected()) { return true; } } } catch (Exception e) { //ignore return false } return false; } @Override public void onReceive(Context context, Intent intent) { SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(context); connectionStatus = ConnectionStatus.UNCHECKED; if (!pm.getBoolean("disable_internet_detection", false)) { if (isWifiConnected(context) || isMobileConnected(context)) { Log.d("NUAR", "onRec Connected"); MainActivity.isConnected = true; } else { Log.d("NUAR", "onRec Disconnected"); MainActivity.isConnected = false; } } else { MainActivity.isConnected = true; } try { if (isConnected(context)) { long last_check = pm.getLong(MainFragment.LAST_CHECK, 0); long current_time = System.currentTimeMillis(); long interval = Long.parseLong(pm.getString("update_interval", "0")); if (interval > 0) { if (interval < current_time - last_check) { new AutomaticUpdateTask(context, null, pm, null).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } } } catch (Exception e) { e.printStackTrace(); } } public enum ConnectionStatus {UNCHECKED, NO_INET_CONNECTED, NO_WIFI_CONNECTED, CONNECTED} }
4,107
1,604
package java.security.cert; import java.util.ArrayList; import java.util.Collection; /** * Parameters used as input for the Collection <code>CertStore</code> * algorithm.<br /> * <br /> * This class is used to provide necessary configuration parameters * to implementations of the Collection <code>CertStore</code> * algorithm. The only parameter included in this class is the * <code>Collection</code> from which the <code>CertStore</code> will * retrieve certificates and CRLs.<br /> * <br /> * <b>Concurrent Access</b><br /> * <br /> * Unless otherwise specified, the methods defined in this class are not * thread-safe. Multiple threads that need to access a single * object concurrently should synchronize amongst themselves and * provide the necessary locking. Multiple threads each manipulating * separate objects need not synchronize. * * @see java.util.Collection * @see CertStore **/ public class CollectionCertStoreParameters implements CertStoreParameters { private Collection collection; /** * Creates an instance of <code>CollectionCertStoreParameters</code> * which will allow certificates and CRLs to be retrieved from the * specified <code>Collection</code>. If the specified * <code>Collection</code> contains an object that is not a * <code>Certificate</code> or <code>CRL</code>, that object will be * ignored by the Collection <code>CertStore</code>.<br /> * <br /> * The <code>Collection</code> is <b>not</b> copied. Instead, a * reference is used. This allows the caller to subsequently add or * remove <code>Certificates</code> or <code>CRL</code>s from the * <code>Collection</code>, thus changing the set of * <code>Certificates</code> or <code>CRL</code>s available to the * Collection <code>CertStore</code>. The Collection <code>CertStore</code> * will not modify the contents of the <code>Collection</code>.<br /> * <br /> * If the <code>Collection</code> will be modified by one thread while * another thread is calling a method of a Collection <code>CertStore</code> * that has been initialized with this <code>Collection</code>, the * <code>Collection</code> must have fail-fast iterators. * * @param collection a <code>Collection</code> of * <code>Certificate</code>s and <code>CRL</code>s * * @exception NullPointerException if <code>collection</code> is * <code>null</code> */ public CollectionCertStoreParameters(Collection collection) { if ( collection == null ) throw new NullPointerException("collection must be non-null"); this.collection = collection; } /** * Creates an instance of <code>CollectionCertStoreParameters</code> with * the an empty Collection. */ public CollectionCertStoreParameters() { collection = new ArrayList(); } /** * Returns the <code>Collection</code> from which <code>Certificate</code>s * and <code>CRL</code>s are retrieved. This is <b>not</b> a copy of the * <code>Collection</code>, it is a reference. This allows the caller to * subsequently add or remove <code>Certificates</code> or * <code>CRL</code>s from the <code>Collection</code>. * * @return the <code>Collection</code> (never null) */ public Collection getCollection() { return collection; } /** * Returns a copy of this object. Note that only a reference to the * <code>Collection</code> is copied, and not the contents. * * @return the copy */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { /* Cannot happen */ throw new InternalError(e.toString()); } } /** * Returns a formatted string describing the parameters. * * @return a formatted string describing the parameters */ public String toString() { StringBuffer s = new StringBuffer(); s.append("CollectionCertStoreParameters: [\n collections:\n"); s.append( getCollection()); s.append("\n]" ); return s.toString(); } }
1,409
571
package camelinaction; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.spring.Main; /** * A Camel Router */ public class MyRouteBuilder extends RouteBuilder { /** * A main() so we can easily run these routing rules in our IDE */ public static void main(String... args) throws Exception { Main.main(args); } /** * Lets configure the Camel routing rules using Java code... */ public void configure() { from("ftp://rider@localhost:21000/order?password=<PASSWORD>") .to("jms:incomingOrders"); from("cxf:bean:orderEndpoint") .to("jms:incomingOrders"); from("jms:incomingOrders").to("log:camelinaction.order"); } }
283
381
<reponame>cmeier76/JGiven<filename>jgiven-tests/src/main/java/com/tngtech/jgiven/tags/FeatureDuration.java package com.tngtech.jgiven.tags; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import com.tngtech.jgiven.annotation.IsTag; @FeatureCore @IsTag( name = "Duration", description = "The duration of steps, cases, and scenarios is measured and reported" ) @Retention( RetentionPolicy.RUNTIME ) public @interface FeatureDuration { }
154
344
from imap_tools import MailBox # get size of message and attachments with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox: for msg in mailbox.fetch(): print(msg.date_str, msg.subject) print('-- RFC822.SIZE message size', msg.size_rfc822) print('-- bytes size', msg.size) # will returns headers size only when fetch headers_only=True for att in msg.attachments: print('---- ATT:', att.filename) print('-- bytes size', att.size)
197
627
/* Copyright 2017 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef __CROS_EC_TOUCHPAD_H #define __CROS_EC_TOUCHPAD_H void touchpad_interrupt(enum gpio_signal signal); /* Reset the touchpad, mainly used to recover it from malfunction. */ void board_touchpad_reset(void); #endif
128
917
package dev.ahamed.mva.sample.view.widget; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.widget.FrameLayout; public class BottomBar extends FrameLayout { public BottomBar(Context context) { super(context); setInsetsListener(); } public BottomBar(Context context, @Nullable AttributeSet attrs) { super(context, attrs); setInsetsListener(); } public BottomBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setInsetsListener(); } public void setInsetsListener() { setOnApplyWindowInsetsListener((v, insets) -> { v.setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()); return insets; }); } }
293
1,673
<reponame>C-Chads/cc65 /*****************************************************************************/ /* */ /* _vic2.h */ /* */ /* Internal include file, do not use directly */ /* */ /* */ /* */ /* (C) 1998-2012, <NAME> */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: <EMAIL> */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #ifndef __VIC2_H #define __VIC2_H /* Define a structure with the vic register offsets. In cc65 mode, there ** are aliases for the field accessible as arrays. */ #if __CC65_STD__ == __CC65_STD_CC65__ struct __vic2 { union { struct { unsigned char spr0_x; /* Sprite 0, X coordinate */ unsigned char spr0_y; /* Sprite 0, Y coordinate */ unsigned char spr1_x; /* Sprite 1, X coordinate */ unsigned char spr1_y; /* Sprite 1, Y coordinate */ unsigned char spr2_x; /* Sprite 2, X coordinate */ unsigned char spr2_y; /* Sprite 2, Y coordinate */ unsigned char spr3_x; /* Sprite 3, X coordinate */ unsigned char spr3_y; /* Sprite 3, Y coordinate */ unsigned char spr4_x; /* Sprite 4, X coordinate */ unsigned char spr4_y; /* Sprite 4, Y coordinate */ unsigned char spr5_x; /* Sprite 5, X coordinate */ unsigned char spr5_y; /* Sprite 5, Y coordinate */ unsigned char spr6_x; /* Sprite 6, X coordinate */ unsigned char spr6_y; /* Sprite 6, Y coordinate */ unsigned char spr7_x; /* Sprite 7, X coordinate */ unsigned char spr7_y; /* Sprite 7, Y coordinate */ }; struct { unsigned char x; /* X coordinate */ unsigned char y; /* Y coordinate */ } spr_pos[8]; }; unsigned char spr_hi_x; /* High bits of X coordinate */ unsigned char ctrl1; /* Control register 1 */ unsigned char rasterline; /* Current raster line */ union { struct { unsigned char strobe_x; /* Light pen, X position */ unsigned char strobe_y; /* Light pen, Y position */ }; struct { unsigned char x; /* Light pen, X position */ unsigned char y; /* Light pen, Y position */ } strobe; }; unsigned char spr_ena; /* Enable sprites */ unsigned char ctrl2; /* Control register 2 */ unsigned char spr_exp_y; /* Expand sprites in Y dir */ unsigned char addr; /* Address of chargen and video ram */ unsigned char irr; /* Interrupt request register */ unsigned char imr; /* Interrupt mask register */ unsigned char spr_bg_prio; /* Priority to background */ unsigned char spr_mcolor; /* Sprite multicolor bits */ unsigned char spr_exp_x; /* Expand sprites in X dir */ unsigned char spr_coll; /* Sprite/sprite collision reg */ unsigned char spr_bg_coll; /* Sprite/background collision reg */ unsigned char bordercolor; /* Border color */ union { struct { unsigned char bgcolor0; /* Background color 0 */ unsigned char bgcolor1; /* Background color 1 */ unsigned char bgcolor2; /* Background color 2 */ unsigned char bgcolor3; /* Background color 3 */ }; unsigned char bgcolor[4]; /* Background colors */ }; union { struct { unsigned char spr_mcolor0; /* Color 0 for multicolor sprites */ unsigned char spr_mcolor1; /* Color 1 for multicolor sprites */ }; /* spr_color is already used ... */ unsigned char spr_mcolors[2]; /* Color for multicolor sprites */ }; union { struct { unsigned char spr0_color; /* Color sprite 0 */ unsigned char spr1_color; /* Color sprite 1 */ unsigned char spr2_color; /* Color sprite 2 */ unsigned char spr3_color; /* Color sprite 3 */ unsigned char spr4_color; /* Color sprite 4 */ unsigned char spr5_color; /* Color sprite 5 */ unsigned char spr6_color; /* Color sprite 6 */ unsigned char spr7_color; /* Color sprite 7 */ }; unsigned char spr_color[8]; /* Colors for the sprites */ }; /* The following ones are only valid in the C128: */ unsigned char x_kbd; /* Additional keyboard lines */ unsigned char clock; /* Clock switch bit */ }; #else struct __vic2 { unsigned char spr0_x; /* Sprite 0, X coordinate */ unsigned char spr0_y; /* Sprite 0, Y coordinate */ unsigned char spr1_x; /* Sprite 1, X coordinate */ unsigned char spr1_y; /* Sprite 1, Y coordinate */ unsigned char spr2_x; /* Sprite 2, X coordinate */ unsigned char spr2_y; /* Sprite 2, Y coordinate */ unsigned char spr3_x; /* Sprite 3, X coordinate */ unsigned char spr3_y; /* Sprite 3, Y coordinate */ unsigned char spr4_x; /* Sprite 4, X coordinate */ unsigned char spr4_y; /* Sprite 4, Y coordinate */ unsigned char spr5_x; /* Sprite 5, X coordinate */ unsigned char spr5_y; /* Sprite 5, Y coordinate */ unsigned char spr6_x; /* Sprite 6, X coordinate */ unsigned char spr6_y; /* Sprite 6, Y coordinate */ unsigned char spr7_x; /* Sprite 7, X coordinate */ unsigned char spr7_y; /* Sprite 7, Y coordinate */ unsigned char spr_hi_x; /* High bits of X coordinate */ unsigned char ctrl1; /* Control register 1 */ unsigned char rasterline; /* Current raster line */ unsigned char strobe_x; /* Light pen, X position */ unsigned char strobe_y; /* Light pen, Y position */ unsigned char spr_ena; /* Enable sprites */ unsigned char ctrl2; /* Control register 2 */ unsigned char spr_exp_y; /* Expand sprites in Y dir */ unsigned char addr; /* Address of chargen and video ram */ unsigned char irr; /* Interrupt request register */ unsigned char imr; /* Interrupt mask register */ unsigned char spr_bg_prio; /* Priority to background */ unsigned char spr_mcolor; /* Sprite multicolor bits */ unsigned char spr_exp_x; /* Expand sprites in X dir */ unsigned char spr_coll; /* Sprite/sprite collision reg */ unsigned char spr_bg_coll; /* Sprite/background collision reg */ unsigned char bordercolor; /* Border color */ unsigned char bgcolor0; /* Background color 0 */ unsigned char bgcolor1; /* Background color 1 */ unsigned char bgcolor2; /* Background color 2 */ unsigned char bgcolor3; /* Background color 3 */ unsigned char spr_mcolor0; /* Color 0 for multicolor sprites */ unsigned char spr_mcolor1; /* Color 1 for multicolor sprites */ unsigned char spr0_color; /* Color sprite 0 */ unsigned char spr1_color; /* Color sprite 1 */ unsigned char spr2_color; /* Color sprite 2 */ unsigned char spr3_color; /* Color sprite 3 */ unsigned char spr4_color; /* Color sprite 4 */ unsigned char spr5_color; /* Color sprite 5 */ unsigned char spr6_color; /* Color sprite 6 */ unsigned char spr7_color; /* Color sprite 7 */ /* The following ones are only valid in the C128: */ unsigned char x_kbd; /* Additional keyboard lines */ unsigned char clock; /* Clock switch bit */ }; #endif /* End of _vic2.h */ #endif
5,473
347
<reponame>hbraha/ovirt-engine package org.ovirt.engine.ui.webadmin.section.main.presenter.tab.disk; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.storage.Disk; import org.ovirt.engine.ui.common.presenter.AbstractSubTabPresenter; import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider; import org.ovirt.engine.ui.uicommonweb.models.disks.DiskListModel; import org.ovirt.engine.ui.uicommonweb.models.disks.DiskStorageListModel; import org.ovirt.engine.ui.uicommonweb.place.WebAdminApplicationPlaces; import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.DetailTabDataIndex; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; import com.gwtplatform.mvp.client.TabData; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.annotations.TabInfo; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace; public class SubTabDiskStoragePresenter extends AbstractSubTabDiskPresenter<DiskStorageListModel, SubTabDiskStoragePresenter.ViewDef, SubTabDiskStoragePresenter.ProxyDef> { @ProxyCodeSplit @NameToken(WebAdminApplicationPlaces.diskStorageSubTabPlace) public interface ProxyDef extends TabContentProxyPlace<SubTabDiskStoragePresenter> { } public interface ViewDef extends AbstractSubTabPresenter.ViewDef<Disk> { } @TabInfo(container = DiskSubTabPanelPresenter.class) static TabData getTabData() { return DetailTabDataIndex.DISKS_STORAGE; } @Inject public SubTabDiskStoragePresenter(EventBus eventBus, ViewDef view, ProxyDef proxy, PlaceManager placeManager, DiskMainSelectedItems selectedItems, SearchableDetailModelProvider<StorageDomain, DiskListModel, DiskStorageListModel> modelProvider) { // View has no action panel, passing null super(eventBus, view, proxy, placeManager, modelProvider, selectedItems, null, DiskSubTabPanelPresenter.TYPE_SetTabContent); } }
746
1,882
__version__ = "0.11.1" from supervised.automl import AutoML
23
843
#!/usr/bin/env python import uuid # Generate build id for Dockerfile.deploy print('BUILD_ID = "%s"' % uuid.uuid4())
45
2,293
<gh_stars>1000+ /***************************************************************************** * * * This file is part of the BeanShell Java Scripting distribution. * * Documentation and updates may be found at http://www.beanshell.org/ * * * * Sun Public License Notice: * * * * The contents of this file are subject to the Sun Public License Version * * 1.0 (the "License"); you may not use this file except in compliance with * * the License. A copy of the License is available at http://www.sun.com * * * * The Original Code is BeanShell. The Initial Developer of the Original * * Code is <NAME>. Portions created by <NAME> are Copyright * * (C) 2000. All Rights Reserved. * * * * GNU Public License Notice: * * * * Alternatively, the contents of this file may be used under the terms of * * the GNU Lesser General Public License (the "LGPL"), in which case the * * provisions of LGPL are applicable instead of those above. If you wish to * * allow use of your version of this file only under the terms of the LGPL * * and not to allow others to use your version of this file under the SPL, * * indicate your decision by deleting the provisions above and replace * * them with the notice and other provisions required by the LGPL. If you * * do not delete the provisions above, a recipient may use your version of * * this file under either the SPL or the LGPL. * * * * <NAME> (<EMAIL>) * * Author of Learning Java, O'Reilly & Associates * * http://www.pat.net/~pat/ * * * *****************************************************************************/ package bsh; class BSHFormalParameters extends SimpleNode { private String [] paramNames; /** For loose type parameters the paramTypes are null. */ // unsafe caching of types Class [] paramTypes; int numArgs; String [] typeDescriptors; BSHFormalParameters(int id) { super(id); } void insureParsed() { if ( paramNames != null ) return; this.numArgs = jjtGetNumChildren(); String [] paramNames = new String[numArgs]; for(int i=0; i<numArgs; i++) { BSHFormalParameter param = (BSHFormalParameter)jjtGetChild(i); paramNames[i] = param.name; } this.paramNames = paramNames; } public String [] getParamNames() { insureParsed(); return paramNames; } public String [] getTypeDescriptors( CallStack callstack, Interpreter interpreter, String defaultPackage ) { if ( typeDescriptors != null ) return typeDescriptors; insureParsed(); String [] typeDesc = new String[numArgs]; for(int i=0; i<numArgs; i++) { BSHFormalParameter param = (BSHFormalParameter)jjtGetChild(i); typeDesc[i] = param.getTypeDescriptor( callstack, interpreter, defaultPackage ); } this.typeDescriptors = typeDesc; return typeDesc; } /** Evaluate the types. Note that type resolution does not require the interpreter instance. */ public Object eval( CallStack callstack, Interpreter interpreter ) throws EvalError { if ( paramTypes != null ) return paramTypes; insureParsed(); Class [] paramTypes = new Class[numArgs]; for(int i=0; i<numArgs; i++) { BSHFormalParameter param = (BSHFormalParameter)jjtGetChild(i); paramTypes[i] = (Class)param.eval( callstack, interpreter ); } this.paramTypes = paramTypes; return paramTypes; } }
1,949
764
{ "symbol": "EBTC", "account_name": "bitpietokens", "overview": { "en": "EBTC is the mapping of Bitcoin on the EOS network, anchoring the BTC in 1:1, and is accepted in both directions by the cross-chain gateway operated by Bitpie." }, "website": "https://eosstablecoin.com/" }
114
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/searchlib/fef/blueprint.h> #include <vespa/vespalib/util/priority_queue.h> namespace search::features { //----------------------------------------------------------------------------- struct FlowCompletenessParams { uint32_t fieldId; feature_t fieldWeight; feature_t fieldCompletenessImportance; FlowCompletenessParams() : fieldId(fef::IllegalFieldId), fieldWeight(0), fieldCompletenessImportance(0.5) {} }; //----------------------------------------------------------------------------- const uint32_t IllegalElementId = 0xffffffff; const uint32_t IllegalTermId = 0xffffffff; const uint32_t IllegalPosId = 0xffffffff; class FlowCompletenessExecutor : public fef::FeatureExecutor { private: struct Term { fef::TermFieldHandle termHandle; int termWeight; Term(fef::TermFieldHandle handle, int weight) : termHandle(handle), termWeight(weight) {} }; struct Item { uint32_t elemId; uint32_t termIdx; fef::TermFieldMatchData::PositionsIterator pos; fef::TermFieldMatchData::PositionsIterator end; Item(uint32_t idx, fef::TermFieldMatchData::PositionsIterator p, fef::TermFieldMatchData::PositionsIterator e) : elemId(IllegalElementId), termIdx(idx), pos(p), end(e) { if (p != e) elemId = p->getElementId(); } bool operator< (const Item &other) const { return (elemId < other.elemId); } }; FlowCompletenessParams _params; std::vector<Term> _terms; vespalib::PriorityQueue<Item> _queue; int _sumTermWeight; const fef::MatchData *_md; static bool nextElement(Item &item); void handle_bind_match_data(const fef::MatchData &md) override; public: FlowCompletenessExecutor(const fef::IQueryEnvironment &env, const FlowCompletenessParams &params); bool isPure() override { return _terms.empty(); } void execute(uint32_t docId) override; }; //----------------------------------------------------------------------------- class FlowCompletenessBlueprint : public fef::Blueprint { private: std::vector<vespalib::string> _output; FlowCompletenessParams _params; public: FlowCompletenessBlueprint(); void visitDumpFeatures(const fef::IIndexEnvironment & env, fef::IDumpFeatureVisitor & visitor) const override; fef::Blueprint::UP createInstance() const override; fef::ParameterDescriptions getDescriptions() const override { return fef::ParameterDescriptions().desc().indexField(fef::ParameterCollection::ANY); } bool setup(const fef::IIndexEnvironment &env, const fef::ParameterList &params) override; fef::FeatureExecutor &createExecutor(const fef::IQueryEnvironment &env, vespalib::Stash &stash) const override; }; //----------------------------------------------------------------------------- }
1,193
981
#if !(defined(GO) && defined(GOM) && defined(GO2) && defined(DATA)) #error Meh.... #endif //GO(_dsa_generate_dss_g, //GO(dsa_generate_dss_keypair, //GO(_dsa_generate_dss_pq, //GO(_dsa_validate_dss_g, //GO(_dsa_validate_dss_pq, //GO(gnutls_aead_cipher_decrypt, //GO(gnutls_aead_cipher_deinit, //GO(gnutls_aead_cipher_encrypt, //GO(gnutls_aead_cipher_init, GO(gnutls_alert_get, pFp) GO(gnutls_alert_get_name, pFp) //GO(gnutls_alert_get_strname, //GO(gnutls_alert_send, //GO(gnutls_alert_send_appropriate, GO(gnutls_alpn_get_selected_protocol, iFpp) GO(gnutls_alpn_set_protocols, iFppuu) //GO(gnutls_anon_allocate_client_credentials, //GO(gnutls_anon_allocate_server_credentials, //GO(gnutls_anon_free_client_credentials, //GO(gnutls_anon_free_server_credentials, //GO(gnutls_anon_set_params_function, //GO(gnutls_anon_set_server_dh_params, //GO(gnutls_anon_set_server_known_dh_params, //GO(gnutls_anon_set_server_params_function, //GO(gnutls_auth_client_get_type, //GO(gnutls_auth_get_type, //GO(gnutls_auth_server_get_type, //GO(_gnutls_bin2hex, //GO(gnutls_buffer_append_data, //GO(_gnutls_buffer_append_str, //GO(_gnutls_buffer_init, //GO(_gnutls_buffer_to_datum, //GO(gnutls_bye, //GO(gnutls_certificate_activation_time_peers, GO(gnutls_certificate_allocate_credentials, iFp) //GO(gnutls_certificate_client_get_request_status, //GO(gnutls_certificate_expiration_time_peers, //GO(gnutls_certificate_free_ca_names, //GO(gnutls_certificate_free_cas, GO(gnutls_certificate_free_credentials, vFp) //GO(gnutls_certificate_free_crls, //GO(gnutls_certificate_free_keys, //GO(gnutls_certificate_get_crt_raw, //GO(gnutls_certificate_get_issuer, //GO(gnutls_certificate_get_openpgp_crt, //GO(gnutls_certificate_get_openpgp_key, //GO(gnutls_certificate_get_ours, GO(gnutls_certificate_get_peers, pFpp) //GO(gnutls_certificate_get_peers_subkey_id, //GO(gnutls_certificate_get_trust_list, //GO(gnutls_certificate_get_verify_flags, //GO(gnutls_certificate_get_x509_crt, //GO(gnutls_certificate_get_x509_key, //GO(gnutls_certificate_send_x509_rdn_sequence, //GO(gnutls_certificate_server_set_request, //GO(gnutls_certificate_set_dh_params, //GO(gnutls_certificate_set_flags, //GO(gnutls_certificate_set_key, //GO(gnutls_certificate_set_known_dh_params, //GO(gnutls_certificate_set_ocsp_status_request_file, //GO(gnutls_certificate_set_ocsp_status_request_function, //GO(gnutls_certificate_set_ocsp_status_request_function2, //GO(gnutls_certificate_set_openpgp_key, //GO(gnutls_certificate_set_openpgp_key_file, //GO(gnutls_certificate_set_openpgp_key_file2, //GO(gnutls_certificate_set_openpgp_key_mem, //GO(gnutls_certificate_set_openpgp_key_mem2, //GO(gnutls_certificate_set_openpgp_keyring_file, //GO(gnutls_certificate_set_openpgp_keyring_mem, //GO(gnutls_certificate_set_params_function, //GO(gnutls_certificate_set_pin_function, //GO(gnutls_certificate_set_retrieve_function, //GO(gnutls_certificate_set_retrieve_function2, //GO(gnutls_certificate_set_trust_list, //GO(gnutls_certificate_set_verify_flags, //GO(gnutls_certificate_set_verify_function, //GO(gnutls_certificate_set_verify_limits, //GO(gnutls_certificate_set_x509_crl, //GO(gnutls_certificate_set_x509_crl_file, //GO(gnutls_certificate_set_x509_crl_mem, GO(gnutls_certificate_set_x509_key, iFppip) //GO(gnutls_certificate_set_x509_key_file, //GO(gnutls_certificate_set_x509_key_file2, //GO(gnutls_certificate_set_x509_key_mem, //GO(gnutls_certificate_set_x509_key_mem2, //GO(gnutls_certificate_set_x509_simple_pkcs12_file, //GO(gnutls_certificate_set_x509_simple_pkcs12_mem, //GO(gnutls_certificate_set_x509_system_trust, //GO(gnutls_certificate_set_x509_trust, //GO(gnutls_certificate_set_x509_trust_dir, //GO(gnutls_certificate_set_x509_trust_file, //GO(gnutls_certificate_set_x509_trust_mem, //GO(gnutls_certificate_type_get, //GO(gnutls_certificate_type_get_id, //GO(gnutls_certificate_type_get_name, //GO(gnutls_certificate_type_list, //GO(gnutls_certificate_verification_status_print, //GO(gnutls_certificate_verify_peers, //GO(gnutls_certificate_verify_peers2, //GO(gnutls_certificate_verify_peers3, GO(gnutls_check_version, pFp) //GO(_gnutls_cidr_to_string, GO(gnutls_cipher_add_auth, iFppL) GO(gnutls_cipher_decrypt, iFppL) GO(gnutls_cipher_decrypt2, iFppLpL) GO(gnutls_cipher_deinit, vFp) GO(gnutls_cipher_encrypt, iFppL) GO(gnutls_cipher_encrypt2, iFppLpL) GO(gnutls_cipher_get, pFp) GO(gnutls_cipher_get_block_size, uFp) //GO(gnutls_cipher_get_id, //GO(gnutls_cipher_get_iv_size, GO(gnutls_cipher_get_key_size, LFp) //GO(gnutls_cipher_get_name, //GO(gnutls_cipher_get_tag_size, GO(gnutls_cipher_init, iFpppp) //GO(gnutls_cipher_list, //GO(gnutls_cipher_set_iv, //GO(gnutls_cipher_suite_get_name, //GO(gnutls_cipher_suite_info, GO(gnutls_cipher_tag, iFppL) //GO(gnutls_compression_get, //GO(gnutls_compression_get_id, //GO(gnutls_compression_get_name, //GO(gnutls_compression_list, //GO(gnutls_credentials_clear, //GO(gnutls_credentials_get, GO(gnutls_credentials_set, iFppp) //GO(gnutls_crypto_register_aead_cipher, //GO(gnutls_crypto_register_cipher, //GO(gnutls_crypto_register_digest, //GO(gnutls_crypto_register_mac, //GO(gnutls_db_check_entry, //GO(gnutls_db_check_entry_time, //GO(gnutls_db_get_default_cache_expiration, //GO(gnutls_db_get_ptr, //GO(gnutls_db_remove_session, //GO(gnutls_db_set_cache_expiration, //GO(gnutls_db_set_ptr, //GO(gnutls_db_set_remove_function, //GO(gnutls_db_set_retrieve_function, //GO(gnutls_db_set_store_function, GO(gnutls_decode_rs_value, iFppp) // not always present //GO(gnutls_decode_ber_digest_info, //GO(_gnutls_decode_ber_rs_raw, GO(gnutls_deinit, vFp) //GO(gnutls_dh_get_group, //GO(gnutls_dh_get_peers_public_bits, //GO(gnutls_dh_get_prime_bits, //GO(gnutls_dh_get_pubkey, //GO(gnutls_dh_get_secret_bits, //GO(gnutls_dh_params_cpy, //GO(gnutls_dh_params_deinit, //GO(gnutls_dh_params_export2_pkcs3, //GO(gnutls_dh_params_export_pkcs3, //GO(gnutls_dh_params_export_raw, //GO(gnutls_dh_params_generate2, //GO(gnutls_dh_params_import_dsa, //GO(gnutls_dh_params_import_pkcs3, //GO(gnutls_dh_params_import_raw, //GO(gnutls_dh_params_import_raw2, //GO(gnutls_dh_params_init, //GO(gnutls_dh_set_prime_bits, //GO(_gnutls_digest_exists, //GO(gnutls_digest_get_id, //GO(gnutls_digest_get_name, //GO(gnutls_digest_get_oid, //GO(gnutls_digest_list, //GO(gnutls_dtls_cookie_send, //GO(gnutls_dtls_cookie_verify, //GO(gnutls_dtls_get_data_mtu, //GO(gnutls_dtls_get_mtu, //GO(gnutls_dtls_get_timeout, //GO(gnutls_dtls_prestate_set, //GO(gnutls_dtls_set_data_mtu, //GO(gnutls_dtls_set_mtu, //GO(gnutls_dtls_set_timeouts, //GO(gnutls_ecc_curve_get, //GO(gnutls_ecc_curve_get_id, //GO(gnutls_ecc_curve_get_name, //GO(gnutls_ecc_curve_get_oid, //GO(gnutls_ecc_curve_get_pk, //GO(gnutls_ecc_curve_get_size, //GO(gnutls_ecc_curve_list, //GO(gnutls_encode_ber_digest_info, //GO(_gnutls_encode_ber_rs_raw, //GO(gnutls_error_is_fatal, //GO(gnutls_error_to_alert, //GO(gnutls_est_record_overhead_size, //GO(gnutls_ext_get_data, //GO(gnutls_ext_get_name, //GO(gnutls_ext_register, //GO(gnutls_ext_set_data, //GO(gnutls_fingerprint, //GO(gnutls_fips140_mode_enabled, GO(gnutls_global_deinit, vFv) GO(gnutls_global_init, iFv) //GO(gnutls_global_set_audit_log_function, GOM(gnutls_global_set_log_function, vFEp) GO(gnutls_global_set_log_level, vFi) //GO(gnutls_global_set_mem_functions, //GO(gnutls_global_set_mutex, //GO(gnutls_global_set_time_function, GO(gnutls_handshake, iFp) //GO(gnutls_handshake_description_get_name, //GO(gnutls_handshake_get_last_in, //GO(gnutls_handshake_get_last_out, //GO(gnutls_handshake_set_hook_function, //GO(gnutls_handshake_set_max_packet_length, //GO(gnutls_handshake_set_post_client_hello_function, //GO(gnutls_handshake_set_private_extensions, //GO(gnutls_handshake_set_random, //GO(gnutls_handshake_set_timeout, //GO(gnutls_hash, //GO(gnutls_hash_deinit, //GO(gnutls_hash_fast, //GO(gnutls_hash_get_len, //GO(gnutls_hash_init, //GO(gnutls_hash_output, //GO(gnutls_heartbeat_allowed, //GO(gnutls_heartbeat_enable, //GO(gnutls_heartbeat_get_timeout, //GO(gnutls_heartbeat_ping, //GO(gnutls_heartbeat_pong, //GO(gnutls_heartbeat_set_timeouts, //GO(_gnutls_hello_set_default_version, //GO(gnutls_hex2bin, //GO(gnutls_hex_decode, //GO(gnutls_hex_decode2, //GO(gnutls_hex_encode, //GO(gnutls_hex_encode2, //GO(gnutls_hmac, //GO(gnutls_hmac_deinit, //GO(gnutls_hmac_fast, //GO(gnutls_hmac_get_len, //GO(gnutls_hmac_init, //GO(gnutls_hmac_output, //GO(gnutls_hmac_set_nonce, //GO(gnutls_idna_map, //GO(gnutls_idna_reverse_map, GO(gnutls_init, iFpu) //GO(_gnutls_ip_to_string, //GO(gnutls_key_generate, GO(gnutls_kx_get, pFp) //GO(gnutls_kx_get_id, //GO(gnutls_kx_get_name, //GO(gnutls_kx_list, //GO(_gnutls_lib_simulate_error, //GO(gnutls_load_file, //GO(_gnutls_log, GO(gnutls_mac_get, pFp) //GO(gnutls_mac_get_id, GO(gnutls_mac_get_key_size, LFp) //GO(gnutls_mac_get_name, //GO(gnutls_mac_get_nonce_size, //GO(gnutls_mac_list, //GO(_gnutls_mac_to_entry, //GO(gnutls_memcmp, //GO(gnutls_memset, //GO(_gnutls_mpi_log, //GO(gnutls_ocsp_req_add_cert, //GO(gnutls_ocsp_req_add_cert_id, //GO(gnutls_ocsp_req_deinit, //GO(gnutls_ocsp_req_export, //GO(gnutls_ocsp_req_get_cert_id, //GO(gnutls_ocsp_req_get_extension, //GO(gnutls_ocsp_req_get_nonce, //GO(gnutls_ocsp_req_get_version, //GO(gnutls_ocsp_req_import, //GO(gnutls_ocsp_req_init, //GO(gnutls_ocsp_req_print, //GO(gnutls_ocsp_req_randomize_nonce, //GO(gnutls_ocsp_req_set_extension, //GO(gnutls_ocsp_req_set_nonce, //GO(gnutls_ocsp_resp_check_crt, //GO(gnutls_ocsp_resp_deinit, //GO(gnutls_ocsp_resp_export, //GO(gnutls_ocsp_resp_get_certs, //GO(gnutls_ocsp_resp_get_extension, //GO(gnutls_ocsp_resp_get_nonce, //GO(gnutls_ocsp_resp_get_produced, //GO(gnutls_ocsp_resp_get_responder, //GO(gnutls_ocsp_resp_get_responder2, //GO(gnutls_ocsp_resp_get_responder_raw_id, //GO(gnutls_ocsp_resp_get_response, //GO(gnutls_ocsp_resp_get_signature, //GO(gnutls_ocsp_resp_get_signature_algorithm, //GO(gnutls_ocsp_resp_get_single, //GO(gnutls_ocsp_resp_get_status, //GO(gnutls_ocsp_resp_get_version, //GO(gnutls_ocsp_resp_import, //GO(gnutls_ocsp_resp_init, //GO(gnutls_ocsp_resp_print, //GO(gnutls_ocsp_resp_verify, //GO(gnutls_ocsp_resp_verify_direct, //GO(gnutls_ocsp_status_request_enable_client, //GO(gnutls_ocsp_status_request_get, //GO(gnutls_ocsp_status_request_is_checked, //GO(gnutls_oid_to_digest, //GO(gnutls_oid_to_ecc_curve, //GO(gnutls_oid_to_mac, //GO(gnutls_oid_to_pk, //GO(gnutls_oid_to_sign, //GO(gnutls_openpgp_crt_check_email, //GO(gnutls_openpgp_crt_check_hostname, //GO(gnutls_openpgp_crt_check_hostname2, //GO(gnutls_openpgp_crt_deinit, //GO(gnutls_openpgp_crt_export, //GO(gnutls_openpgp_crt_export2, //GO(gnutls_openpgp_crt_get_auth_subkey, //GO(gnutls_openpgp_crt_get_creation_time, //GO(gnutls_openpgp_crt_get_expiration_time, //GO(gnutls_openpgp_crt_get_fingerprint, //GO(gnutls_openpgp_crt_get_key_id, //GO(gnutls_openpgp_crt_get_key_usage, //GO(gnutls_openpgp_crt_get_name, //GO(gnutls_openpgp_crt_get_pk_algorithm, //GO(gnutls_openpgp_crt_get_pk_dsa_raw, //GO(gnutls_openpgp_crt_get_pk_rsa_raw, //GO(gnutls_openpgp_crt_get_preferred_key_id, //GO(gnutls_openpgp_crt_get_revoked_status, //GO(gnutls_openpgp_crt_get_subkey_count, //GO(gnutls_openpgp_crt_get_subkey_creation_time, //GO(gnutls_openpgp_crt_get_subkey_expiration_time, //GO(gnutls_openpgp_crt_get_subkey_fingerprint, //GO(gnutls_openpgp_crt_get_subkey_id, //GO(gnutls_openpgp_crt_get_subkey_idx, //GO(gnutls_openpgp_crt_get_subkey_pk_algorithm, //GO(gnutls_openpgp_crt_get_subkey_pk_dsa_raw, //GO(gnutls_openpgp_crt_get_subkey_pk_rsa_raw, //GO(gnutls_openpgp_crt_get_subkey_revoked_status, //GO(gnutls_openpgp_crt_get_subkey_usage, //GO(gnutls_openpgp_crt_get_version, //GO(gnutls_openpgp_crt_import, //GO(gnutls_openpgp_crt_init, //GO(gnutls_openpgp_crt_print, //GO(gnutls_openpgp_crt_set_preferred_key_id, //GO(gnutls_openpgp_crt_verify_ring, //GO(gnutls_openpgp_crt_verify_self, //GO(gnutls_openpgp_keyring_check_id, //GO(gnutls_openpgp_keyring_deinit, //GO(gnutls_openpgp_keyring_get_crt, //GO(gnutls_openpgp_keyring_get_crt_count, //GO(gnutls_openpgp_keyring_import, //GO(gnutls_openpgp_keyring_init, //GO(gnutls_openpgp_privkey_deinit, //GO(gnutls_openpgp_privkey_export, //GO(gnutls_openpgp_privkey_export2, //GO(gnutls_openpgp_privkey_export_dsa_raw, //GO(gnutls_openpgp_privkey_export_rsa_raw, //GO(gnutls_openpgp_privkey_export_subkey_dsa_raw, //GO(gnutls_openpgp_privkey_export_subkey_rsa_raw, //GO(gnutls_openpgp_privkey_get_fingerprint, //GO(gnutls_openpgp_privkey_get_key_id, //GO(gnutls_openpgp_privkey_get_pk_algorithm, //GO(gnutls_openpgp_privkey_get_preferred_key_id, //GO(gnutls_openpgp_privkey_get_revoked_status, //GO(gnutls_openpgp_privkey_get_subkey_count, //GO(gnutls_openpgp_privkey_get_subkey_creation_time, //GO(gnutls_openpgp_privkey_get_subkey_expiration_time, //GO(gnutls_openpgp_privkey_get_subkey_fingerprint, //GO(gnutls_openpgp_privkey_get_subkey_id, //GO(gnutls_openpgp_privkey_get_subkey_idx, //GO(gnutls_openpgp_privkey_get_subkey_pk_algorithm, //GO(gnutls_openpgp_privkey_get_subkey_revoked_status, //GO(gnutls_openpgp_privkey_import, //GO(gnutls_openpgp_privkey_init, //GO(gnutls_openpgp_privkey_sec_param, //GO(gnutls_openpgp_privkey_set_preferred_key_id, //GO(gnutls_openpgp_privkey_sign_hash, //GO(gnutls_openpgp_send_cert, //GO(gnutls_openpgp_set_recv_key_function, //GO(gnutls_packet_deinit, //GO(gnutls_packet_get, //GO(gnutls_pcert_deinit, //GO(gnutls_pcert_export_openpgp, //GO(gnutls_pcert_export_x509, //GO(gnutls_pcert_import_openpgp, //GO(gnutls_pcert_import_openpgp_raw, //GO(gnutls_pcert_import_x509, //GO(gnutls_pcert_import_x509_list, //GO(gnutls_pcert_import_x509_raw, //GO(gnutls_pcert_list_import_x509_raw, //GO(gnutls_pem_base64_decode, //GO(gnutls_pem_base64_decode2, //GO(gnutls_pem_base64_encode, //GO(gnutls_pem_base64_encode2, GO(gnutls_perror, vFi) //GO(gnutls_pk_algorithm_get_name, //GO(gnutls_pk_bits_to_sec_param, //GO(gnutls_pkcs11_add_provider, //GO(gnutls_pkcs11_copy_attached_extension, //GO(gnutls_pkcs11_copy_pubkey, //GO(gnutls_pkcs11_copy_secret_key, //GO(gnutls_pkcs11_copy_x509_crt2, //GO(gnutls_pkcs11_copy_x509_privkey2, //GO(gnutls_pkcs11_crt_is_known, //GO(gnutls_pkcs11_deinit, //GO(gnutls_pkcs11_delete_url, //GO(gnutls_pkcs11_get_pin_function, //GO(gnutls_pkcs11_get_raw_issuer, //GO(gnutls_pkcs11_get_raw_issuer_by_dn, //GO(gnutls_pkcs11_get_raw_issuer_by_subject_key_id, //GO(gnutls_pkcs11_init, //GO(gnutls_pkcs11_obj_deinit, //GO(gnutls_pkcs11_obj_export, //GO(gnutls_pkcs11_obj_export2, //GO(gnutls_pkcs11_obj_export3, //GO(gnutls_pkcs11_obj_export_url, //GO(gnutls_pkcs11_obj_flags_get_str, //GO(gnutls_pkcs11_obj_get_exts, //GO(gnutls_pkcs11_obj_get_flags, //GO(gnutls_pkcs11_obj_get_info, //GO(gnutls_pkcs11_obj_get_type, //GO(gnutls_pkcs11_obj_import_url, //GO(gnutls_pkcs11_obj_init, //GO(gnutls_pkcs11_obj_list_import_url3, //GO(gnutls_pkcs11_obj_list_import_url4, //GO(gnutls_pkcs11_obj_set_info, //GO(gnutls_pkcs11_obj_set_pin_function, //GO(gnutls_pkcs11_privkey_cpy, //GO(gnutls_pkcs11_privkey_deinit, //GO(gnutls_pkcs11_privkey_export_pubkey, //GO(gnutls_pkcs11_privkey_export_url, //GO(gnutls_pkcs11_privkey_generate3, //GO(gnutls_pkcs11_privkey_get_info, //GO(gnutls_pkcs11_privkey_get_pk_algorithm, //GO(gnutls_pkcs11_privkey_import_url, //GO(gnutls_pkcs11_privkey_init, //GO(gnutls_pkcs11_privkey_set_pin_function, //GO(gnutls_pkcs11_privkey_status, //GO(gnutls_pkcs11_reinit, //GO(gnutls_pkcs11_set_pin_function, //GO(gnutls_pkcs11_set_token_function, //GO(gnutls_pkcs11_token_get_flags, //GO(gnutls_pkcs11_token_get_info, //GO(gnutls_pkcs11_token_get_mechanism, //GO(gnutls_pkcs11_token_get_random, //GO(gnutls_pkcs11_token_get_url, //GO(gnutls_pkcs11_token_init, //GO(gnutls_pkcs11_token_set_pin, //GO(gnutls_pkcs11_type_get_name, //GO(gnutls_pkcs12_bag_decrypt, //GO(gnutls_pkcs12_bag_deinit, //GO(gnutls_pkcs12_bag_enc_info, //GO(gnutls_pkcs12_bag_encrypt, //GO(gnutls_pkcs12_bag_get_count, //GO(gnutls_pkcs12_bag_get_data, //GO(gnutls_pkcs12_bag_get_friendly_name, //GO(gnutls_pkcs12_bag_get_key_id, //GO(gnutls_pkcs12_bag_get_type, //GO(gnutls_pkcs12_bag_init, //GO(gnutls_pkcs12_bag_set_crl, //GO(gnutls_pkcs12_bag_set_crt, //GO(gnutls_pkcs12_bag_set_data, //GO(gnutls_pkcs12_bag_set_friendly_name, //GO(gnutls_pkcs12_bag_set_key_id, //GO(gnutls_pkcs12_bag_set_privkey, GO(gnutls_pkcs12_deinit, vFp) //GO(gnutls_pkcs12_export, //GO(gnutls_pkcs12_export2, //GO(gnutls_pkcs12_generate_mac, //GO(gnutls_pkcs12_generate_mac2, //GO(gnutls_pkcs12_get_bag, GO(gnutls_pkcs12_import, iFpppu) GO(gnutls_pkcs12_init, iFp) //GO(gnutls_pkcs12_mac_info, //GO(gnutls_pkcs12_set_bag, GO(gnutls_pkcs12_simple_parse, iFppppppppu) //GO(_gnutls_pkcs12_string_to_key, //GO(gnutls_pkcs12_verify_mac, //GO(gnutls_pkcs7_add_attr, //GO(gnutls_pkcs7_attrs_deinit, //GO(gnutls_pkcs7_deinit, //GO(gnutls_pkcs7_delete_crl, //GO(gnutls_pkcs7_delete_crt, //GO(gnutls_pkcs7_export, //GO(gnutls_pkcs7_export2, //GO(gnutls_pkcs7_get_attr, //GO(gnutls_pkcs7_get_crl_count, //GO(gnutls_pkcs7_get_crl_raw, //GO(gnutls_pkcs7_get_crl_raw2, //GO(gnutls_pkcs7_get_crt_count, //GO(gnutls_pkcs7_get_crt_raw, //GO(gnutls_pkcs7_get_crt_raw2, //GO(gnutls_pkcs7_get_embedded_data, //GO(gnutls_pkcs7_get_embedded_data_oid, //GO(gnutls_pkcs7_get_signature_count, //GO(gnutls_pkcs7_get_signature_info, //GO(gnutls_pkcs7_import, //GO(gnutls_pkcs7_init, //GO(gnutls_pkcs7_print, //GO(gnutls_pkcs7_set_crl, //GO(gnutls_pkcs7_set_crl_raw, //GO(gnutls_pkcs7_set_crt, //GO(gnutls_pkcs7_set_crt_raw, //GO(gnutls_pkcs7_sign, //GO(gnutls_pkcs7_signature_info_deinit, //GO(gnutls_pkcs7_verify, //GO(gnutls_pkcs7_verify_direct, //GO(gnutls_pkcs8_info, //GO(gnutls_pkcs_schema_get_name, //GO(gnutls_pkcs_schema_get_oid, //GO(gnutls_pk_get_id, //GO(gnutls_pk_get_name, //GO(gnutls_pk_get_oid, //GO(gnutls_pk_list, GO(gnutls_pk_to_sign, pFpp) //GO(gnutls_prf, //GO(gnutls_prf_raw, //GO(gnutls_prf_rfc5705, //GO(gnutls_priority_certificate_type_list, //GO(gnutls_priority_cipher_list, //GO(gnutls_priority_compression_list, //GO(gnutls_priority_deinit, //GO(gnutls_priority_ecc_curve_list, //GO(gnutls_priority_get_cipher_suite_index, //GO(gnutls_priority_init, //GO(gnutls_priority_kx_list, //GO(gnutls_priority_mac_list, //GO(gnutls_priority_protocol_list, //GO(gnutls_priority_set, GO(gnutls_priority_set_direct, iFppp) //GO(gnutls_priority_sign_list, //GO(gnutls_priority_string_list, GO(gnutls_privkey_decrypt_data, iFpipp) GO(gnutls_privkey_deinit, vFp) GO(gnutls_privkey_export_dsa_raw, iFpppppp) GO(gnutls_privkey_export_ecc_raw, iFppppp) //GO(gnutls_privkey_export_openpgp, //GO(gnutls_privkey_export_pkcs11, GO(gnutls_privkey_export_rsa_raw, iFppppppppp) GO(gnutls_privkey_export_x509, iFpp) GO(gnutls_privkey_generate, iFppuu) //GO(gnutls_privkey_generate2, //GO(gnutls_privkey_get_pk_algorithm, //GO(gnutls_privkey_get_seed, //GO(gnutls_privkey_get_type, GO(gnutls_privkey_import_dsa_raw, iFpppppp) GO(gnutls_privkey_import_ecc_raw, iFppppp) //GO(gnutls_privkey_import_ext, //GO(gnutls_privkey_import_ext2, //GO(gnutls_privkey_import_ext3, //GO(gnutls_privkey_import_openpgp, //GO(gnutls_privkey_import_openpgp_raw, //GO(gnutls_privkey_import_pkcs11, GO(gnutls_privkey_import_rsa_raw, iFppppppppp) //GO(gnutls_privkey_import_tpm_raw, //GO(gnutls_privkey_import_tpm_url, //GO(gnutls_privkey_import_url, //GO(gnutls_privkey_import_x509, //GO(gnutls_privkey_import_x509_raw, GO(gnutls_privkey_init, iFp) //GO(gnutls_privkey_set_flags, //GO(gnutls_privkey_set_pin_function, //GO(gnutls_privkey_sign_data, GO(gnutls_privkey_sign_hash, iFppupp) //GO(gnutls_privkey_status, //GO(gnutls_privkey_verify_params, //GO(gnutls_privkey_verify_seed, //GO(gnutls_protocol_get_id, //GO(gnutls_protocol_get_name, GO(gnutls_protocol_get_version, iFp) //GO(gnutls_protocol_list, //GO(gnutls_psk_allocate_client_credentials, //GO(gnutls_psk_allocate_server_credentials, //GO(gnutls_psk_client_get_hint, //GO(gnutls_psk_free_client_credentials, //GO(gnutls_psk_free_server_credentials, //GO(gnutls_psk_server_get_username, //GO(gnutls_psk_set_client_credentials, //GO(gnutls_psk_set_client_credentials_function, //GO(gnutls_psk_set_params_function, //GO(gnutls_psk_set_server_credentials_file, //GO(gnutls_psk_set_server_credentials_function, //GO(gnutls_psk_set_server_credentials_hint, //GO(gnutls_psk_set_server_dh_params, //GO(gnutls_psk_set_server_known_dh_params, //GO(gnutls_psk_set_server_params_function, GO(gnutls_pubkey_deinit, vFp) //GO(gnutls_pubkey_encrypt_data, //GO(gnutls_pubkey_export, //GO(gnutls_pubkey_export2, //GO(gnutls_pubkey_export_dsa_raw, //GO(gnutls_pubkey_export_ecc_raw, //GO(gnutls_pubkey_export_ecc_x962, //GO(gnutls_pubkey_export_rsa_raw, //GO(gnutls_pubkey_get_key_id, //GO(gnutls_pubkey_get_key_usage, //GO(gnutls_pubkey_get_openpgp_key_id, //GO(gnutls_pubkey_get_pk_algorithm, //GO(gnutls_pubkey_get_preferred_hash_algorithm, //GO(gnutls_pubkey_import, GO(gnutls_pubkey_import_dsa_raw, iFppppp) GO(gnutls_pubkey_import_ecc_raw, iFpppp) //GO(gnutls_pubkey_import_ecc_x962, //GO(gnutls_pubkey_import_openpgp, //GO(gnutls_pubkey_import_openpgp_raw, //GO(gnutls_pubkey_import_pkcs11, //GO(gnutls_pubkey_import_privkey, GO(gnutls_pubkey_import_rsa_raw, iFppp) //GO(gnutls_pubkey_import_tpm_raw, //GO(gnutls_pubkey_import_tpm_url, //GO(gnutls_pubkey_import_url, //GO(gnutls_pubkey_import_x509, //GO(gnutls_pubkey_import_x509_crq, //GO(gnutls_pubkey_import_x509_raw, GO(gnutls_pubkey_init, iFp) //GO(gnutls_pubkey_print, //GO(gnutls_pubkey_set_key_usage, //GO(gnutls_pubkey_set_pin_function, //GO(gnutls_pubkey_verify_data2, GO(gnutls_pubkey_verify_hash2, iFppupp) //GO(gnutls_pubkey_verify_params, //GO(gnutls_random_art, //GO(gnutls_range_split, //GO(gnutls_record_can_use_length_hiding, //GO(gnutls_record_check_corked, //GO(gnutls_record_check_pending, //GO(gnutls_record_cork, //GO(gnutls_record_disable_padding, //GO(gnutls_record_discard_queued, //GO(gnutls_record_get_direction, //GO(gnutls_record_get_discarded, GO(gnutls_record_get_max_size, LFp) //GO(gnutls_record_get_state, //GO(gnutls_record_overhead_size, GO(gnutls_record_recv, lFppL) //GO(gnutls_record_recv_packet, //GO(gnutls_record_recv_seq, GO(gnutls_record_send, lFppL) //GO(gnutls_record_send_range, //GO(_gnutls_record_set_default_version, //GO(gnutls_record_set_max_size, //GO(gnutls_record_set_state, //GO(gnutls_record_set_timeout, //GO(gnutls_record_uncork, //GO(gnutls_register_custom_url, //GO(gnutls_rehandshake, //GO(_gnutls_resolve_priorities, //GO(gnutls_rnd, //GO(gnutls_rnd_refresh, //GO(_gnutls_rsa_pms_set_version, //GO(gnutls_safe_renegotiation_status, //GO(gnutls_sec_param_get_name, //GO(gnutls_sec_param_to_pk_bits, //GO(gnutls_sec_param_to_symmetric_bits, //GO(gnutls_server_name_get, GO(gnutls_server_name_set, iFpppL) //GO(_gnutls_server_name_set_raw, //GO(gnutls_session_channel_binding, //GO(gnutls_session_enable_compatibility_mode, //GO(gnutls_session_etm_status, //GO(gnutls_session_ext_master_secret_status, //GO(gnutls_session_ext_register, //GO(gnutls_session_force_valid, //GO(gnutls_session_get_data, //GO(gnutls_session_get_data2, //GO(gnutls_session_get_desc, //GO(gnutls_session_get_flags, //GO(gnutls_session_get_id, //GO(gnutls_session_get_id2, //GO(gnutls_session_get_master_secret, //GO(gnutls_session_get_ptr, //GO(gnutls_session_get_random, //GO(gnutls_session_get_verify_cert_status, //GO(gnutls_session_is_resumed, //GO(gnutls_session_resumption_requested, //GO(gnutls_session_set_data, //GO(gnutls_session_set_id, //GO(gnutls_session_set_premaster, //GO(gnutls_session_set_ptr, //GO(gnutls_session_set_verify_cert, //GO(gnutls_session_set_verify_cert2, //GO(gnutls_session_set_verify_function, //GO(gnutls_session_supplemental_register, //GO(gnutls_session_ticket_enable_client, //GO(gnutls_session_ticket_enable_server, //GO(gnutls_session_ticket_key_generate, //GO(gnutls_set_default_priority, //GO(gnutls_sign_algorithm_get, //GO(gnutls_sign_algorithm_get_client, //GO(gnutls_sign_algorithm_get_requested, //GO(gnutls_sign_get_hash_algorithm, //GO(gnutls_sign_get_id, //GO(gnutls_sign_get_name, //GO(gnutls_sign_get_oid, //GO(gnutls_sign_get_pk_algorithm, //GO(gnutls_sign_is_secure, //GO(gnutls_sign_list, //GO(gnutls_srp_allocate_client_credentials, //GO(gnutls_srp_allocate_server_credentials, //GO(gnutls_srp_base64_decode, //GO(gnutls_srp_base64_decode2, //GO(gnutls_srp_base64_encode, //GO(gnutls_srp_base64_encode2, //GO(gnutls_srp_free_client_credentials, //GO(gnutls_srp_free_server_credentials, //GO(gnutls_srp_server_get_username, //GO(gnutls_srp_set_client_credentials, //GO(gnutls_srp_set_client_credentials_function, //GO(gnutls_srp_set_prime_bits, //GO(gnutls_srp_set_server_credentials_file, //GO(gnutls_srp_set_server_credentials_function, //GO(gnutls_srp_set_server_fake_salt_seed, //GO(gnutls_srp_verifier, //GO(gnutls_srtp_get_keys, //GO(gnutls_srtp_get_mki, //GO(gnutls_srtp_get_profile_id, //GO(gnutls_srtp_get_profile_name, //GO(gnutls_srtp_get_selected_profile, //GO(gnutls_srtp_set_mki, //GO(gnutls_srtp_set_profile, //GO(gnutls_srtp_set_profile_direct, //GO(gnutls_store_commitment, //GO(gnutls_store_pubkey, //GO(gnutls_strerror, //GO(gnutls_strerror_name, //GO(gnutls_subject_alt_names_deinit, //GO(gnutls_subject_alt_names_get, //GO(gnutls_subject_alt_names_init, //GO(gnutls_subject_alt_names_set, //GO(gnutls_supplemental_get_name, //GO(gnutls_supplemental_recv, //GO(gnutls_supplemental_register, //GO(gnutls_supplemental_send, //GO(gnutls_system_key_add_x509, //GO(gnutls_system_key_delete, //GO(gnutls_system_key_iter_deinit, //GO(gnutls_system_key_iter_get_info, //GO(gnutls_system_recv_timeout, //GO(gnutls_tdb_deinit, //GO(gnutls_tdb_init, //GO(gnutls_tdb_set_store_commitment_func, //GO(gnutls_tdb_set_store_func, //GO(gnutls_tdb_set_verify_func, //GO(gnutls_tpm_get_registered, //GO(gnutls_tpm_key_list_deinit, //GO(gnutls_tpm_key_list_get_url, //GO(gnutls_tpm_privkey_delete, //GO(gnutls_tpm_privkey_generate, //GO(gnutls_transport_get_int, //GO(gnutls_transport_get_int2, GO(gnutls_transport_get_ptr, pFp) //GO(gnutls_transport_get_ptr2, GO(gnutls_transport_set_errno, vFpi) //GO(gnutls_transport_set_errno_function, //GO(gnutls_transport_set_fastopen, //GO(gnutls_transport_set_int2, GO(gnutls_transport_set_ptr, vFpp) //GO(gnutls_transport_set_ptr2, GOM(gnutls_transport_set_pull_function, vFEpp) //GO(gnutls_transport_set_pull_timeout_function, GOM(gnutls_transport_set_push_function, vFEpp) //GO(gnutls_transport_set_vec_push_function, //GO(_gnutls_ucs2_to_utf8, //GO(gnutls_url_is_supported, //GO(gnutls_utf8_password_normalize, //GO(_gnutls_utf8_to_ucs2, //GO(gnutls_verify_stored_pubkey, //GO(gnutls_x509_aia_deinit, //GO(gnutls_x509_aia_get, //GO(gnutls_x509_aia_init, //GO(gnutls_x509_aia_set, //GO(gnutls_x509_aki_deinit, //GO(gnutls_x509_aki_get_cert_issuer, //GO(gnutls_x509_aki_get_id, //GO(gnutls_x509_aki_init, //GO(gnutls_x509_aki_set_cert_issuer, //GO(gnutls_x509_aki_set_id, //GO(gnutls_x509_cidr_to_rfc5280, //GO(gnutls_x509_crl_check_issuer, //GO(gnutls_x509_crl_deinit, //GO(gnutls_x509_crl_dist_points_deinit, //GO(gnutls_x509_crl_dist_points_get, //GO(gnutls_x509_crl_dist_points_init, //GO(gnutls_x509_crl_dist_points_set, //GO(gnutls_x509_crl_export, //GO(gnutls_x509_crl_export2, //GO(gnutls_x509_crl_get_authority_key_gn_serial, //GO(gnutls_x509_crl_get_authority_key_id, //GO(gnutls_x509_crl_get_crt_count, //GO(gnutls_x509_crl_get_crt_serial, //GO(gnutls_x509_crl_get_dn_oid, //GO(gnutls_x509_crl_get_extension_data, //GO(gnutls_x509_crl_get_extension_data2, //GO(gnutls_x509_crl_get_extension_info, //GO(gnutls_x509_crl_get_extension_oid, //GO(gnutls_x509_crl_get_issuer_dn, //GO(gnutls_x509_crl_get_issuer_dn2, //GO(gnutls_x509_crl_get_issuer_dn3, //GO(gnutls_x509_crl_get_issuer_dn_by_oid, //GO(gnutls_x509_crl_get_next_update, //GO(gnutls_x509_crl_get_number, //GO(gnutls_x509_crl_get_raw_issuer_dn, //GO(gnutls_x509_crl_get_signature, //GO(gnutls_x509_crl_get_signature_algorithm, //GO(gnutls_x509_crl_get_signature_oid, //GO(gnutls_x509_crl_get_this_update, //GO(gnutls_x509_crl_get_version, //GO(gnutls_x509_crl_import, //GO(gnutls_x509_crl_init, //GO(gnutls_x509_crl_iter_crt_serial, //GO(gnutls_x509_crl_iter_deinit, //GO(gnutls_x509_crl_list_import, //GO(gnutls_x509_crl_list_import2, //GO(gnutls_x509_crl_print, //GO(gnutls_x509_crl_privkey_sign, //GO(gnutls_x509_crl_set_authority_key_id, //GO(gnutls_x509_crl_set_crt, //GO(gnutls_x509_crl_set_crt_serial, //GO(gnutls_x509_crl_set_next_update, //GO(gnutls_x509_crl_set_number, //GO(gnutls_x509_crl_set_this_update, //GO(gnutls_x509_crl_set_version, //GO(gnutls_x509_crl_sign, //GO(gnutls_x509_crl_sign2, //GO(gnutls_x509_crl_verify, //GO(gnutls_x509_crq_deinit, //GO(gnutls_x509_crq_export, //GO(gnutls_x509_crq_export2, //GO(gnutls_x509_crq_get_attribute_by_oid, //GO(gnutls_x509_crq_get_attribute_data, //GO(gnutls_x509_crq_get_attribute_info, //GO(gnutls_x509_crq_get_basic_constraints, //GO(gnutls_x509_crq_get_challenge_password, //GO(gnutls_x509_crq_get_dn, //GO(gnutls_x509_crq_get_dn2, //GO(gnutls_x509_crq_get_dn3, //GO(gnutls_x509_crq_get_dn_by_oid, //GO(gnutls_x509_crq_get_dn_oid, //GO(gnutls_x509_crq_get_extension_by_oid, //GO(gnutls_x509_crq_get_extension_by_oid2, //GO(gnutls_x509_crq_get_extension_data, //GO(gnutls_x509_crq_get_extension_data2, //GO(gnutls_x509_crq_get_extension_info, //GO(gnutls_x509_crq_get_key_id, //GO(gnutls_x509_crq_get_key_purpose_oid, //GO(gnutls_x509_crq_get_key_rsa_raw, //GO(gnutls_x509_crq_get_key_usage, //GO(gnutls_x509_crq_get_pk_algorithm, //GO(gnutls_x509_crq_get_pk_oid, //GO(gnutls_x509_crq_get_private_key_usage_period, //GO(gnutls_x509_crq_get_signature_algorithm, //GO(gnutls_x509_crq_get_signature_oid, //GO(gnutls_x509_crq_get_subject_alt_name, //GO(gnutls_x509_crq_get_subject_alt_othername_oid, //GO(gnutls_x509_crq_get_tlsfeatures, //GO(gnutls_x509_crq_get_version, //GO(gnutls_x509_crq_import, //GO(gnutls_x509_crq_init, //GO(gnutls_x509_crq_print, //GO(gnutls_x509_crq_privkey_sign, //GO(gnutls_x509_crq_set_attribute_by_oid, //GO(gnutls_x509_crq_set_basic_constraints, //GO(gnutls_x509_crq_set_challenge_password, //GO(gnutls_x509_crq_set_dn, //GO(gnutls_x509_crq_set_dn_by_oid, //GO(gnutls_x509_crq_set_extension_by_oid, //GO(gnutls_x509_crq_set_key, //GO(gnutls_x509_crq_set_key_purpose_oid, //GO(gnutls_x509_crq_set_key_rsa_raw, //GO(gnutls_x509_crq_set_key_usage, //GO(gnutls_x509_crq_set_private_key_usage_period, //GO(gnutls_x509_crq_set_pubkey, //GO(gnutls_x509_crq_set_subject_alt_name, //GO(gnutls_x509_crq_set_subject_alt_othername, //GO(gnutls_x509_crq_set_tlsfeatures, //GO(gnutls_x509_crq_set_version, //GO(gnutls_x509_crq_sign, //GO(gnutls_x509_crq_sign2, //GO(gnutls_x509_crq_verify, //GO(gnutls_x509_crt_check_email, //GO(gnutls_x509_crt_check_hostname, //GO(gnutls_x509_crt_check_hostname2, //GO(gnutls_x509_crt_check_issuer, //GO(gnutls_x509_crt_check_key_purpose, //GO(gnutls_x509_crt_check_revocation, //GO(gnutls_x509_crt_cpy_crl_dist_points, GO(gnutls_x509_crt_deinit, vFp) //GO(gnutls_x509_crt_equals, //GO(gnutls_x509_crt_equals2, GO(gnutls_x509_crt_export, iFpppp) //GO(gnutls_x509_crt_export2, //GO(gnutls_x509_crt_get_activation_time, //GO(gnutls_x509_crt_get_authority_info_access, //GO(gnutls_x509_crt_get_authority_key_gn_serial, //GO(gnutls_x509_crt_get_authority_key_id, //GO(gnutls_x509_crt_get_basic_constraints, //GO(gnutls_x509_crt_get_ca_status, //GO(gnutls_x509_crt_get_crl_dist_points, //GO(gnutls_x509_crt_get_dn, //GO(gnutls_x509_crt_get_dn2, //GO(gnutls_x509_crt_get_dn3, //GO(gnutls_x509_crt_get_dn_by_oid, //GO(gnutls_x509_crt_get_dn_oid, //GO(gnutls_x509_crt_get_expiration_time, //GO(gnutls_x509_crt_get_extension_by_oid, //GO(gnutls_x509_crt_get_extension_by_oid2, //GO(gnutls_x509_crt_get_extension_data, //GO(gnutls_x509_crt_get_extension_data2, //GO(gnutls_x509_crt_get_extension_info, //GO(gnutls_x509_crt_get_extension_oid, //GO(gnutls_x509_crt_get_fingerprint, //GO(gnutls_x509_crt_get_issuer, //GO(gnutls_x509_crt_get_issuer_alt_name, //GO(gnutls_x509_crt_get_issuer_alt_name2, //GO(gnutls_x509_crt_get_issuer_alt_othername_oid, //GO(gnutls_x509_crt_get_issuer_dn, //GO(gnutls_x509_crt_get_issuer_dn2, //GO(gnutls_x509_crt_get_issuer_dn3, //GO(gnutls_x509_crt_get_issuer_dn_by_oid, //GO(gnutls_x509_crt_get_issuer_dn_oid, //GO(gnutls_x509_crt_get_issuer_unique_id, //GO(gnutls_x509_crt_get_key_id, //GO(gnutls_x509_crt_get_key_purpose_oid, //GO(gnutls_x509_crt_get_key_usage, //GO(gnutls_x509_crt_get_name_constraints, //GO(gnutls_x509_crt_get_pk_algorithm, //GO(gnutls_x509_crt_get_pk_dsa_raw, //GO(gnutls_x509_crt_get_pk_ecc_raw, //GO(gnutls_x509_crt_get_pk_oid, //GO(gnutls_x509_crt_get_pk_rsa_raw, //GO(gnutls_x509_crt_get_policy, //GO(gnutls_x509_crt_get_preferred_hash_algorithm, //GO(gnutls_x509_crt_get_private_key_usage_period, //GO(gnutls_x509_crt_get_proxy, //GO(gnutls_x509_crt_get_raw_dn, //GO(gnutls_x509_crt_get_raw_issuer_dn, //GO(gnutls_x509_crt_get_serial, //GO(gnutls_x509_crt_get_signature, //GO(gnutls_x509_crt_get_signature_algorithm, //GO(gnutls_x509_crt_get_signature_oid, //GO(gnutls_x509_crt_get_subject, //GO(gnutls_x509_crt_get_subject_alt_name, //GO(gnutls_x509_crt_get_subject_alt_name2, //GO(gnutls_x509_crt_get_subject_alt_othername_oid, //GO(gnutls_x509_crt_get_subject_key_id, //GO(gnutls_x509_crt_get_subject_unique_id, //GO(gnutls_x509_crt_get_tlsfeatures, //GO(gnutls_x509_crt_get_version, GO(gnutls_x509_crt_import, iFppp) //GO(gnutls_x509_crt_import_pkcs11, //GO(gnutls_x509_crt_import_url, GO(gnutls_x509_crt_init, iFp) //GO(gnutls_x509_crt_list_import, //GO(gnutls_x509_crt_list_import2, //GO(gnutls_x509_crt_list_import_pkcs11, //GO(gnutls_x509_crt_list_verify, //GO(gnutls_x509_crt_print, //GO(gnutls_x509_crt_privkey_sign, //GO(gnutls_x509_crt_set_activation_time, //GO(gnutls_x509_crt_set_authority_info_access, //GO(gnutls_x509_crt_set_authority_key_id, //GO(gnutls_x509_crt_set_basic_constraints, //GO(gnutls_x509_crt_set_ca_status, //GO(gnutls_x509_crt_set_crl_dist_points, //GO(gnutls_x509_crt_set_crl_dist_points2, //GO(gnutls_x509_crt_set_crq, //GO(gnutls_x509_crt_set_crq_extension_by_oid, //GO(gnutls_x509_crt_set_crq_extensions, //GO(gnutls_x509_crt_set_dn, //GO(gnutls_x509_crt_set_dn_by_oid, //GO(gnutls_x509_crt_set_expiration_time, //GO(gnutls_x509_crt_set_extension_by_oid, //GO(gnutls_x509_crt_set_issuer_alt_name, //GO(gnutls_x509_crt_set_issuer_alt_othername, //GO(gnutls_x509_crt_set_issuer_dn, //GO(gnutls_x509_crt_set_issuer_dn_by_oid, //GO(gnutls_x509_crt_set_issuer_unique_id, //GO(gnutls_x509_crt_set_key, //GO(gnutls_x509_crt_set_key_purpose_oid, //GO(gnutls_x509_crt_set_key_usage, //GO(gnutls_x509_crt_set_name_constraints, //GO(gnutls_x509_crt_set_pin_function, //GO(gnutls_x509_crt_set_policy, //GO(gnutls_x509_crt_set_private_key_usage_period, //GO(gnutls_x509_crt_set_proxy, //GO(gnutls_x509_crt_set_proxy_dn, //GO(gnutls_x509_crt_set_pubkey, //GO(gnutls_x509_crt_set_serial, //GO(gnutls_x509_crt_set_subject_alternative_name, //GO(gnutls_x509_crt_set_subject_alt_name, //GO(gnutls_x509_crt_set_subject_alt_othername, //GO(gnutls_x509_crt_set_subject_key_id, //GO(gnutls_x509_crt_set_subject_unique_id, //GO(gnutls_x509_crt_set_tlsfeatures, //GO(gnutls_x509_crt_set_version, //GO(gnutls_x509_crt_sign, //GO(gnutls_x509_crt_sign2, //GO(gnutls_x509_crt_verify, //GO(gnutls_x509_crt_verify_data2, //GO(gnutls_x509_dn_deinit, //GO(gnutls_x509_dn_export, //GO(gnutls_x509_dn_export2, //GO(gnutls_x509_dn_get_rdn_ava, //GO(gnutls_x509_dn_get_str, //GO(gnutls_x509_dn_get_str2, //GO(gnutls_x509_dn_import, //GO(gnutls_x509_dn_init, //GO(gnutls_x509_dn_oid_known, //GO(gnutls_x509_dn_oid_name, //GO(gnutls_x509_dn_set_str, //GO(gnutls_x509_ext_deinit, //GO(gnutls_x509_ext_export_aia, //GO(gnutls_x509_ext_export_authority_key_id, //GO(gnutls_x509_ext_export_basic_constraints, //GO(gnutls_x509_ext_export_crl_dist_points, //GO(gnutls_x509_ext_export_key_purposes, //GO(gnutls_x509_ext_export_key_usage, //GO(gnutls_x509_ext_export_name_constraints, //GO(gnutls_x509_ext_export_policies, //GO(gnutls_x509_ext_export_private_key_usage_period, //GO(gnutls_x509_ext_export_proxy, //GO(gnutls_x509_ext_export_subject_alt_names, //GO(gnutls_x509_ext_export_subject_key_id, //GO(gnutls_x509_ext_export_tlsfeatures, //GO(gnutls_x509_ext_import_aia, //GO(gnutls_x509_ext_import_authority_key_id, //GO(gnutls_x509_ext_import_basic_constraints, //GO(gnutls_x509_ext_import_crl_dist_points, //GO(gnutls_x509_ext_import_key_purposes, //GO(gnutls_x509_ext_import_key_usage, //GO(gnutls_x509_ext_import_name_constraints, //GO(gnutls_x509_ext_import_policies, //GO(gnutls_x509_ext_import_private_key_usage_period, //GO(gnutls_x509_ext_import_proxy, //GO(gnutls_x509_ext_import_subject_alt_names, //GO(gnutls_x509_ext_import_subject_key_id, //GO(gnutls_x509_ext_import_tlsfeatures, //GO(gnutls_x509_ext_print, //GO(gnutls_x509_key_purpose_deinit, //GO(gnutls_x509_key_purpose_get, //GO(gnutls_x509_key_purpose_init, //GO(gnutls_x509_key_purpose_set, //GO(gnutls_x509_name_constraints_add_excluded, //GO(gnutls_x509_name_constraints_add_permitted, //GO(gnutls_x509_name_constraints_check, //GO(gnutls_x509_name_constraints_check_crt, //GO(gnutls_x509_name_constraints_deinit, //GO(gnutls_x509_name_constraints_get_excluded, //GO(gnutls_x509_name_constraints_get_permitted, //GO(gnutls_x509_name_constraints_init, //GO(_gnutls_x509_name_constraints_merge, //GO(gnutls_x509_othername_to_virtual, //GO(gnutls_x509_policies_deinit, //GO(gnutls_x509_policies_get, //GO(gnutls_x509_policies_init, //GO(gnutls_x509_policies_set, //GO(gnutls_x509_policy_release, //GO(gnutls_x509_privkey_cpy, GO(gnutls_x509_privkey_deinit, vFp) //GO(gnutls_x509_privkey_export, //GO(gnutls_x509_privkey_export2, //GO(gnutls_x509_privkey_export2_pkcs8, //GO(gnutls_x509_privkey_export_dsa_raw, //GO(gnutls_x509_privkey_export_ecc_raw, //GO(gnutls_x509_privkey_export_pkcs8, //GO(gnutls_x509_privkey_export_rsa_raw, GO(gnutls_x509_privkey_export_rsa_raw2, iFppppppppp) //GO(gnutls_x509_privkey_fix, //GO(gnutls_x509_privkey_generate, //GO(gnutls_x509_privkey_generate2, //GO(gnutls_x509_privkey_get_key_id, //GO(gnutls_x509_privkey_get_pk_algorithm, GO(gnutls_x509_privkey_get_pk_algorithm2, iFpp) //GO(gnutls_x509_privkey_get_seed, //GO(gnutls_x509_privkey_import, //GO(gnutls_x509_privkey_import2, //GO(gnutls_x509_privkey_import_dsa_raw, //GO(gnutls_x509_privkey_import_ecc_raw, //GO(gnutls_x509_privkey_import_openssl, //GO(gnutls_x509_privkey_import_pkcs8, //GO(gnutls_x509_privkey_import_rsa_raw, //GO(gnutls_x509_privkey_import_rsa_raw2, //GO(gnutls_x509_privkey_init, //GO(gnutls_x509_privkey_sec_param, //GO(gnutls_x509_privkey_set_flags, //GO(gnutls_x509_privkey_set_pin_function, //GO(gnutls_x509_privkey_sign_data, //GO(gnutls_x509_privkey_sign_hash, //GO(gnutls_x509_privkey_verify_params, //GO(gnutls_x509_privkey_verify_seed, //GO(gnutls_x509_rdn_get, //GO(gnutls_x509_rdn_get2, //GO(gnutls_x509_rdn_get_by_oid, //GO(gnutls_x509_rdn_get_oid, //GO(gnutls_x509_tlsfeatures_add, //GO(gnutls_x509_tlsfeatures_check_crt, //GO(gnutls_x509_tlsfeatures_deinit, //GO(gnutls_x509_tlsfeatures_get, //GO(gnutls_x509_tlsfeatures_init, //GO(gnutls_x509_trust_list_add_cas, //GO(gnutls_x509_trust_list_add_crls, //GO(gnutls_x509_trust_list_add_named_crt, //GO(gnutls_x509_trust_list_add_system_trust, //GO(gnutls_x509_trust_list_add_trust_dir, //GO(gnutls_x509_trust_list_add_trust_file, //GO(gnutls_x509_trust_list_add_trust_mem, //GO(gnutls_x509_trust_list_deinit, //GO(gnutls_x509_trust_list_get_issuer, //GO(gnutls_x509_trust_list_get_issuer_by_dn, //GO(gnutls_x509_trust_list_get_issuer_by_subject_key_id, //GO(gnutls_x509_trust_list_init, //GO(gnutls_x509_trust_list_iter_deinit, //GO(gnutls_x509_trust_list_iter_get_ca, //GO(gnutls_x509_trust_list_remove_cas, //GO(gnutls_x509_trust_list_remove_trust_file, //GO(gnutls_x509_trust_list_remove_trust_mem, //GO(gnutls_x509_trust_list_verify_crt, //GO(gnutls_x509_trust_list_verify_crt2, //GO(gnutls_x509_trust_list_verify_named_crt, //GO(_rsa_generate_fips186_4_keypair,
21,373
481
<reponame>alpv95/MemeProject def DankGrammar(sentence): #given a input list of strings, joins them in a grammatically correct fashion #outputs a single string, the final joined sentence final = sentence[0] for i,word in enumerate(sentence[1:]): if final[-1] != ',' and final[-1] != '.' and final[-1] != '!' and final[-1] != '?' and final[-1] != '*' and final[-1] != "'" and final[-1] != ':' and final[-1] != ';' and final != '%' and final != '...' and final != '$': if word == ',' or word == '.' or word == '!' or word == '?' or word == '*' or word == "'" or word == ':' or word == ';' or word == '%' or word == '...': final += word else: final += ' ' + word else: if final[-1] == ',' or final[-1] == '.' or final[-1]==':' or final[-1]==';' or final[-1] == '%' or final[-1] == '...': if word == '.': final += word else: final += ' ' + word elif final[-1] == '!' or final[-1] == '?': if word == '!' or word == '?' or word == '*': final += word else: final += ' ' + word else: final += word return final def DankStrip(sentence): #takes list of strings, splits the sentence, return two lists of strings, upper and lower text #with punctuation: punct = [] deleters = [] for i,word in enumerate(sentence): if word == ',' or word == '.' or word == '!' or word == '?' or word == ':' or word == ';' or word == '...': punct.append(i) if punct: for i, punc in enumerate(punct): if i != len(punct)-1: if punct[i+1] == punc+1: deleters.append(i) for i, ting in enumerate(deleters): del punct[ting-i] print(punct) if min(punct) < len(sentence)*4/5: upper = sentence[:min(punct)+1] lower = sentence[min(punct)+1:] else: #some special cases, starter words: if sentence[0] == 'dude' or sentence[0] == 'hey': upper = [sentence[0]] lower = sentence[1:] elif 'still' in sentence: upper = sentence[:sentence.index('still')] lower = sentence[sentence.index('still'):] else: if len(sentence) < 7: upper = sentence lower =[] else: #last resort is just to split in half upper = sentence[:int(len(sentence)/2)] lower = sentence[int(len(sentence)/2):] #no punctuation else: #some special cases, starter words: if sentence[0] == 'dude' or sentence[0] == 'hey': upper = [sentence[0]] lower = sentence[1:] elif 'still' in sentence: upper = sentence[:sentence.index('still')] lower = sentence[sentence.index('still'):] else: if len(sentence) < 6: upper = sentence lower =[] else: #last resort is just to split in half upper = sentence[:int(len(sentence)/2)] lower = sentence[int(len(sentence)/2):] return upper,lower
1,736
403
<reponame>kthoms/code package com.camunda.consulting.openapi.client.handler; import com.camunda.consulting.openapi.client.handler.ApiClient; import com.camunda.consulting.openapi.client.model.BatchDto; import com.camunda.consulting.openapi.client.model.CompleteExternalTaskDto; import com.camunda.consulting.openapi.client.model.CountResultDto; import com.camunda.consulting.openapi.client.model.ExceptionDto; import com.camunda.consulting.openapi.client.model.ExtendLockOnExternalTaskDto; import com.camunda.consulting.openapi.client.model.ExternalTaskBpmnError; import com.camunda.consulting.openapi.client.model.ExternalTaskDto; import com.camunda.consulting.openapi.client.model.ExternalTaskFailureDto; import com.camunda.consulting.openapi.client.model.ExternalTaskQueryDto; import com.camunda.consulting.openapi.client.model.FetchExternalTasksDto; import com.camunda.consulting.openapi.client.model.LockExternalTaskDto; import com.camunda.consulting.openapi.client.model.LockedExternalTaskDto; import java.time.OffsetDateTime; import com.camunda.consulting.openapi.client.model.PriorityDto; import com.camunda.consulting.openapi.client.model.RetriesDto; import com.camunda.consulting.openapi.client.model.SetRetriesForExternalTasksDto; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestClientException; import org.springframework.web.client.HttpClientErrorException; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-11-19T11:53:20.948992+01:00[Europe/Berlin]") @Component("com.camunda.consulting.openapi.client.handler.ExternalTaskApi") public class ExternalTaskApi { private ApiClient apiClient; public ExternalTaskApi() { this(new ApiClient()); } @Autowired public ExternalTaskApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Complete * Completes an external task by id and updates process variables. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task&#39;s most recent lock was not acquired by the provided worker. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>500</b> - Returned if the corresponding process instance could not be resumed successfully. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the task to complete. (required) * @param completeExternalTaskDto (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void completeExternalTaskResource(String id, CompleteExternalTaskDto completeExternalTaskDto) throws RestClientException { completeExternalTaskResourceWithHttpInfo(id, completeExternalTaskDto); } /** * Complete * Completes an external task by id and updates process variables. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task&#39;s most recent lock was not acquired by the provided worker. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>500</b> - Returned if the corresponding process instance could not be resumed successfully. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the task to complete. (required) * @param completeExternalTaskDto (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> completeExternalTaskResourceWithHttpInfo(String id, CompleteExternalTaskDto completeExternalTaskDto) throws RestClientException { Object postBody = completeExternalTaskDto; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling completeExternalTaskResource"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/complete", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Extend Lock * Extends the timeout of the lock by a given amount of time. * <p><b>204</b> - Request successful. * <p><b>400</b> - In case the new lock duration is negative or the external task is not locked by the given worker or not locked at all, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task. (required) * @param extendLockOnExternalTaskDto (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void extendLock(String id, ExtendLockOnExternalTaskDto extendLockOnExternalTaskDto) throws RestClientException { extendLockWithHttpInfo(id, extendLockOnExternalTaskDto); } /** * Extend Lock * Extends the timeout of the lock by a given amount of time. * <p><b>204</b> - Request successful. * <p><b>400</b> - In case the new lock duration is negative or the external task is not locked by the given worker or not locked at all, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task. (required) * @param extendLockOnExternalTaskDto (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> extendLockWithHttpInfo(String id, ExtendLockOnExternalTaskDto extendLockOnExternalTaskDto) throws RestClientException { Object postBody = extendLockOnExternalTaskDto; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling extendLock"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/extendLock", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Fetch and Lock * Fetches and locks a specific number of external tasks for execution by a worker. Query can be restricted to specific task topics and for each task topic an individual lock time can be provided. * <p><b>200</b> - Request successful. * <p><b>400</b> - Bad Request. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param fetchExternalTasksDto (optional) * @return List&lt;LockedExternalTaskDto&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public List<LockedExternalTaskDto> fetchAndLock(FetchExternalTasksDto fetchExternalTasksDto) throws RestClientException { return fetchAndLockWithHttpInfo(fetchExternalTasksDto).getBody(); } /** * Fetch and Lock * Fetches and locks a specific number of external tasks for execution by a worker. Query can be restricted to specific task topics and for each task topic an individual lock time can be provided. * <p><b>200</b> - Request successful. * <p><b>400</b> - Bad Request. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param fetchExternalTasksDto (optional) * @return ResponseEntity&lt;List&lt;LockedExternalTaskDto&gt;&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<List<LockedExternalTaskDto>> fetchAndLockWithHttpInfo(FetchExternalTasksDto fetchExternalTasksDto) throws RestClientException { Object postBody = fetchExternalTasksDto; String path = apiClient.expandPath("/external-task/fetchAndLock", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<List<LockedExternalTaskDto>> returnType = new ParameterizedTypeReference<List<LockedExternalTaskDto>>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Get * Retrieves an external task by id, corresponding to the &#x60;ExternalTask&#x60; interface in the engine. * <p><b>200</b> - Request successful. * <p><b>404</b> - External task with the given id does not exist. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to be retrieved. (required) * @return ExternalTaskDto * @throws RestClientException if an error occurs while attempting to invoke the API */ public ExternalTaskDto getExternalTask(String id) throws RestClientException { return getExternalTaskWithHttpInfo(id).getBody(); } /** * Get * Retrieves an external task by id, corresponding to the &#x60;ExternalTask&#x60; interface in the engine. * <p><b>200</b> - Request successful. * <p><b>404</b> - External task with the given id does not exist. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to be retrieved. (required) * @return ResponseEntity&lt;ExternalTaskDto&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<ExternalTaskDto> getExternalTaskWithHttpInfo(String id) throws RestClientException { Object postBody = null; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getExternalTask"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<ExternalTaskDto> returnType = new ParameterizedTypeReference<ExternalTaskDto>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Get Error Details * Retrieves the error details in the context of a running external task by id. * <p><b>200</b> - Request successful. * <p><b>204</b> - Request successful. In case the external task has no error details. * <p><b>500</b> - An external task with the given id does not exist. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task for which the error details should be retrieved. (required) * @return String * @throws RestClientException if an error occurs while attempting to invoke the API */ public String getExternalTaskErrorDetails(String id) throws RestClientException { return getExternalTaskErrorDetailsWithHttpInfo(id).getBody(); } /** * Get Error Details * Retrieves the error details in the context of a running external task by id. * <p><b>200</b> - Request successful. * <p><b>204</b> - Request successful. In case the external task has no error details. * <p><b>500</b> - An external task with the given id does not exist. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task for which the error details should be retrieved. (required) * @return ResponseEntity&lt;String&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<String> getExternalTaskErrorDetailsWithHttpInfo(String id) throws RestClientException { Object postBody = null; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getExternalTaskErrorDetails"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/errorDetails", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "text/plain", "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<String> returnType = new ParameterizedTypeReference<String>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Get List * Queries for the external tasks that fulfill given parameters. Parameters may be static as well as dynamic runtime properties of executions. The size of the result set can be retrieved by using the [Get External Task Count](https://docs.camunda.org/manual/7.16/reference/rest/external-task/get-query-count/) method. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid, for example if a &#x60;sortOrder&#x60; parameter is supplied, but no &#x60;sortBy&#x60;. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param externalTaskId Filter by an external task&#39;s id. (optional) * @param externalTaskIdIn Filter by the comma-separated list of external task ids. (optional) * @param topicName Filter by an external task topic. (optional) * @param workerId Filter by the id of the worker that the task was most recently locked by. (optional) * @param locked Only include external tasks that are currently locked (i.e., they have a lock time and it has not expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param notLocked Only include external tasks that are currently not locked (i.e., they have no lock or it has expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withRetriesLeft Only include external tasks that have a positive (&amp;gt; 0) number of retries (or &#x60;null&#x60;). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param noRetriesLeft Only include external tasks that have 0 retries. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param lockExpirationAfter Restrict to external tasks that have a lock that expires after a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param lockExpirationBefore Restrict to external tasks that have a lock that expires before a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param activityId Filter by the id of the activity that an external task is created for. (optional) * @param activityIdIn Filter by the comma-separated list of ids of the activities that an external task is created for. (optional) * @param executionId Filter by the id of the execution that an external task belongs to. (optional) * @param processInstanceId Filter by the id of the process instance that an external task belongs to. (optional) * @param processInstanceIdIn Filter by a comma-separated list of process instance ids that an external task may belong to. (optional) * @param processDefinitionId Filter by the id of the process definition that an external task belongs to. (optional) * @param tenantIdIn Filter by a comma-separated list of tenant ids. An external task must have one of the given tenant ids. (optional) * @param active Only include active tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param suspended Only include suspended tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param priorityHigherThanOrEquals Only include jobs with a priority higher than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @param priorityLowerThanOrEquals Only include jobs with a priority lower than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @param sortBy Sort the results lexicographically by a given criterion. Must be used in conjunction with the sortOrder parameter. (optional) * @param sortOrder Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. (optional) * @param firstResult Pagination of results. Specifies the index of the first result to return. (optional) * @param maxResults Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. (optional) * @return List&lt;ExternalTaskDto&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public List<ExternalTaskDto> getExternalTasks(String externalTaskId, String externalTaskIdIn, String topicName, String workerId, Boolean locked, Boolean notLocked, Boolean withRetriesLeft, Boolean noRetriesLeft, OffsetDateTime lockExpirationAfter, OffsetDateTime lockExpirationBefore, String activityId, String activityIdIn, String executionId, String processInstanceId, String processInstanceIdIn, String processDefinitionId, String tenantIdIn, Boolean active, Boolean suspended, Long priorityHigherThanOrEquals, Long priorityLowerThanOrEquals, String sortBy, String sortOrder, Integer firstResult, Integer maxResults) throws RestClientException { return getExternalTasksWithHttpInfo(externalTaskId, externalTaskIdIn, topicName, workerId, locked, notLocked, withRetriesLeft, noRetriesLeft, lockExpirationAfter, lockExpirationBefore, activityId, activityIdIn, executionId, processInstanceId, processInstanceIdIn, processDefinitionId, tenantIdIn, active, suspended, priorityHigherThanOrEquals, priorityLowerThanOrEquals, sortBy, sortOrder, firstResult, maxResults).getBody(); } /** * Get List * Queries for the external tasks that fulfill given parameters. Parameters may be static as well as dynamic runtime properties of executions. The size of the result set can be retrieved by using the [Get External Task Count](https://docs.camunda.org/manual/7.16/reference/rest/external-task/get-query-count/) method. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid, for example if a &#x60;sortOrder&#x60; parameter is supplied, but no &#x60;sortBy&#x60;. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param externalTaskId Filter by an external task&#39;s id. (optional) * @param externalTaskIdIn Filter by the comma-separated list of external task ids. (optional) * @param topicName Filter by an external task topic. (optional) * @param workerId Filter by the id of the worker that the task was most recently locked by. (optional) * @param locked Only include external tasks that are currently locked (i.e., they have a lock time and it has not expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param notLocked Only include external tasks that are currently not locked (i.e., they have no lock or it has expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withRetriesLeft Only include external tasks that have a positive (&amp;gt; 0) number of retries (or &#x60;null&#x60;). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param noRetriesLeft Only include external tasks that have 0 retries. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param lockExpirationAfter Restrict to external tasks that have a lock that expires after a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param lockExpirationBefore Restrict to external tasks that have a lock that expires before a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param activityId Filter by the id of the activity that an external task is created for. (optional) * @param activityIdIn Filter by the comma-separated list of ids of the activities that an external task is created for. (optional) * @param executionId Filter by the id of the execution that an external task belongs to. (optional) * @param processInstanceId Filter by the id of the process instance that an external task belongs to. (optional) * @param processInstanceIdIn Filter by a comma-separated list of process instance ids that an external task may belong to. (optional) * @param processDefinitionId Filter by the id of the process definition that an external task belongs to. (optional) * @param tenantIdIn Filter by a comma-separated list of tenant ids. An external task must have one of the given tenant ids. (optional) * @param active Only include active tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param suspended Only include suspended tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param priorityHigherThanOrEquals Only include jobs with a priority higher than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @param priorityLowerThanOrEquals Only include jobs with a priority lower than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @param sortBy Sort the results lexicographically by a given criterion. Must be used in conjunction with the sortOrder parameter. (optional) * @param sortOrder Sort the results in a given order. Values may be asc for ascending order or desc for descending order. Must be used in conjunction with the sortBy parameter. (optional) * @param firstResult Pagination of results. Specifies the index of the first result to return. (optional) * @param maxResults Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. (optional) * @return ResponseEntity&lt;List&lt;ExternalTaskDto&gt;&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<List<ExternalTaskDto>> getExternalTasksWithHttpInfo(String externalTaskId, String externalTaskIdIn, String topicName, String workerId, Boolean locked, Boolean notLocked, Boolean withRetriesLeft, Boolean noRetriesLeft, OffsetDateTime lockExpirationAfter, OffsetDateTime lockExpirationBefore, String activityId, String activityIdIn, String executionId, String processInstanceId, String processInstanceIdIn, String processDefinitionId, String tenantIdIn, Boolean active, Boolean suspended, Long priorityHigherThanOrEquals, Long priorityLowerThanOrEquals, String sortBy, String sortOrder, Integer firstResult, Integer maxResults) throws RestClientException { Object postBody = null; String path = apiClient.expandPath("/external-task", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "externalTaskId", externalTaskId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "externalTaskIdIn", externalTaskIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "topicName", topicName)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "workerId", workerId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "locked", locked)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "notLocked", notLocked)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "withRetriesLeft", withRetriesLeft)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "noRetriesLeft", noRetriesLeft)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "lockExpirationAfter", lockExpirationAfter)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "lockExpirationBefore", lockExpirationBefore)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "activityId", activityId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "activityIdIn", activityIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "executionId", executionId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "processInstanceId", processInstanceId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "processInstanceIdIn", processInstanceIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "processDefinitionId", processDefinitionId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "tenantIdIn", tenantIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "active", active)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "suspended", suspended)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "priorityHigherThanOrEquals", priorityHigherThanOrEquals)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "priorityLowerThanOrEquals", priorityLowerThanOrEquals)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sortBy", sortBy)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sortOrder", sortOrder)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "firstResult", firstResult)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "maxResults", maxResults)); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<List<ExternalTaskDto>> returnType = new ParameterizedTypeReference<List<ExternalTaskDto>>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Get List Count * Queries for the number of external tasks that fulfill given parameters. Takes the same parameters as the [Get External Tasks](https://docs.camunda.org/manual/7.16/reference/rest/external-task/get-query/) method. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param externalTaskId Filter by an external task&#39;s id. (optional) * @param externalTaskIdIn Filter by the comma-separated list of external task ids. (optional) * @param topicName Filter by an external task topic. (optional) * @param workerId Filter by the id of the worker that the task was most recently locked by. (optional) * @param locked Only include external tasks that are currently locked (i.e., they have a lock time and it has not expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param notLocked Only include external tasks that are currently not locked (i.e., they have no lock or it has expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withRetriesLeft Only include external tasks that have a positive (&amp;gt; 0) number of retries (or &#x60;null&#x60;). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param noRetriesLeft Only include external tasks that have 0 retries. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param lockExpirationAfter Restrict to external tasks that have a lock that expires after a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param lockExpirationBefore Restrict to external tasks that have a lock that expires before a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param activityId Filter by the id of the activity that an external task is created for. (optional) * @param activityIdIn Filter by the comma-separated list of ids of the activities that an external task is created for. (optional) * @param executionId Filter by the id of the execution that an external task belongs to. (optional) * @param processInstanceId Filter by the id of the process instance that an external task belongs to. (optional) * @param processInstanceIdIn Filter by a comma-separated list of process instance ids that an external task may belong to. (optional) * @param processDefinitionId Filter by the id of the process definition that an external task belongs to. (optional) * @param tenantIdIn Filter by a comma-separated list of tenant ids. An external task must have one of the given tenant ids. (optional) * @param active Only include active tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param suspended Only include suspended tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param priorityHigherThanOrEquals Only include jobs with a priority higher than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @param priorityLowerThanOrEquals Only include jobs with a priority lower than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @return CountResultDto * @throws RestClientException if an error occurs while attempting to invoke the API */ public CountResultDto getExternalTasksCount(String externalTaskId, String externalTaskIdIn, String topicName, String workerId, Boolean locked, Boolean notLocked, Boolean withRetriesLeft, Boolean noRetriesLeft, OffsetDateTime lockExpirationAfter, OffsetDateTime lockExpirationBefore, String activityId, String activityIdIn, String executionId, String processInstanceId, String processInstanceIdIn, String processDefinitionId, String tenantIdIn, Boolean active, Boolean suspended, Long priorityHigherThanOrEquals, Long priorityLowerThanOrEquals) throws RestClientException { return getExternalTasksCountWithHttpInfo(externalTaskId, externalTaskIdIn, topicName, workerId, locked, notLocked, withRetriesLeft, noRetriesLeft, lockExpirationAfter, lockExpirationBefore, activityId, activityIdIn, executionId, processInstanceId, processInstanceIdIn, processDefinitionId, tenantIdIn, active, suspended, priorityHigherThanOrEquals, priorityLowerThanOrEquals).getBody(); } /** * Get List Count * Queries for the number of external tasks that fulfill given parameters. Takes the same parameters as the [Get External Tasks](https://docs.camunda.org/manual/7.16/reference/rest/external-task/get-query/) method. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param externalTaskId Filter by an external task&#39;s id. (optional) * @param externalTaskIdIn Filter by the comma-separated list of external task ids. (optional) * @param topicName Filter by an external task topic. (optional) * @param workerId Filter by the id of the worker that the task was most recently locked by. (optional) * @param locked Only include external tasks that are currently locked (i.e., they have a lock time and it has not expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param notLocked Only include external tasks that are currently not locked (i.e., they have no lock or it has expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withRetriesLeft Only include external tasks that have a positive (&amp;gt; 0) number of retries (or &#x60;null&#x60;). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param noRetriesLeft Only include external tasks that have 0 retries. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param lockExpirationAfter Restrict to external tasks that have a lock that expires after a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param lockExpirationBefore Restrict to external tasks that have a lock that expires before a given date. By [default](https://docs.camunda.org/manual/7.16/reference/rest/overview/date-format/), the date must have the format &#x60;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSSZ&#x60;, e.g., &#x60;2013-01-23T14:42:45.000+0200&#x60;. (optional) * @param activityId Filter by the id of the activity that an external task is created for. (optional) * @param activityIdIn Filter by the comma-separated list of ids of the activities that an external task is created for. (optional) * @param executionId Filter by the id of the execution that an external task belongs to. (optional) * @param processInstanceId Filter by the id of the process instance that an external task belongs to. (optional) * @param processInstanceIdIn Filter by a comma-separated list of process instance ids that an external task may belong to. (optional) * @param processDefinitionId Filter by the id of the process definition that an external task belongs to. (optional) * @param tenantIdIn Filter by a comma-separated list of tenant ids. An external task must have one of the given tenant ids. (optional) * @param active Only include active tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param suspended Only include suspended tasks. Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param priorityHigherThanOrEquals Only include jobs with a priority higher than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @param priorityLowerThanOrEquals Only include jobs with a priority lower than or equal to the given value. Value must be a valid &#x60;long&#x60; value. (optional) * @return ResponseEntity&lt;CountResultDto&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<CountResultDto> getExternalTasksCountWithHttpInfo(String externalTaskId, String externalTaskIdIn, String topicName, String workerId, Boolean locked, Boolean notLocked, Boolean withRetriesLeft, Boolean noRetriesLeft, OffsetDateTime lockExpirationAfter, OffsetDateTime lockExpirationBefore, String activityId, String activityIdIn, String executionId, String processInstanceId, String processInstanceIdIn, String processDefinitionId, String tenantIdIn, Boolean active, Boolean suspended, Long priorityHigherThanOrEquals, Long priorityLowerThanOrEquals) throws RestClientException { Object postBody = null; String path = apiClient.expandPath("/external-task/count", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "externalTaskId", externalTaskId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "externalTaskIdIn", externalTaskIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "topicName", topicName)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "workerId", workerId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "locked", locked)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "notLocked", notLocked)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "withRetriesLeft", withRetriesLeft)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "noRetriesLeft", noRetriesLeft)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "lockExpirationAfter", lockExpirationAfter)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "lockExpirationBefore", lockExpirationBefore)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "activityId", activityId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "activityIdIn", activityIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "executionId", executionId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "processInstanceId", processInstanceId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "processInstanceIdIn", processInstanceIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "processDefinitionId", processDefinitionId)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "tenantIdIn", tenantIdIn)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "active", active)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "suspended", suspended)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "priorityHigherThanOrEquals", priorityHigherThanOrEquals)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "priorityLowerThanOrEquals", priorityLowerThanOrEquals)); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<CountResultDto> returnType = new ParameterizedTypeReference<CountResultDto>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Get External Task Topic Names * Queries for distinct topic names of external tasks that fulfill given parameters. Query can be restricted to only tasks with retries left, tasks that are locked, or tasks that are unlocked. The parameters withLockedTasks and withUnlockedTasks are exclusive. Setting them both to true will return an empty list. Providing no parameters will return a list of all distinct topic names with external tasks. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid. * @param withLockedTasks Only include external tasks that are currently locked (i.e., they have a lock time and it has not expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withUnlockedTasks Only include external tasks that are currently not locked (i.e., they have no lock or it has expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withRetriesLeft Only include external tasks that have a positive (&amp;gt; 0) number of retries (or &#x60;null&#x60;). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @return List&lt;String&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public List<String> getTopicNames(Boolean withLockedTasks, Boolean withUnlockedTasks, Boolean withRetriesLeft) throws RestClientException { return getTopicNamesWithHttpInfo(withLockedTasks, withUnlockedTasks, withRetriesLeft).getBody(); } /** * Get External Task Topic Names * Queries for distinct topic names of external tasks that fulfill given parameters. Query can be restricted to only tasks with retries left, tasks that are locked, or tasks that are unlocked. The parameters withLockedTasks and withUnlockedTasks are exclusive. Setting them both to true will return an empty list. Providing no parameters will return a list of all distinct topic names with external tasks. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid. * @param withLockedTasks Only include external tasks that are currently locked (i.e., they have a lock time and it has not expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withUnlockedTasks Only include external tasks that are currently not locked (i.e., they have no lock or it has expired). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @param withRetriesLeft Only include external tasks that have a positive (&amp;gt; 0) number of retries (or &#x60;null&#x60;). Value may only be &#x60;true&#x60;, as &#x60;false&#x60; matches any external task. (optional) * @return ResponseEntity&lt;List&lt;String&gt;&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<List<String>> getTopicNamesWithHttpInfo(Boolean withLockedTasks, Boolean withUnlockedTasks, Boolean withRetriesLeft) throws RestClientException { Object postBody = null; String path = apiClient.expandPath("/external-task/topic-names", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "withLockedTasks", withLockedTasks)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "withUnlockedTasks", withUnlockedTasks)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "withRetriesLeft", withRetriesLeft)); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<List<String>> returnType = new ParameterizedTypeReference<List<String>>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Handle BPMN Error * Reports a business error in the context of a running external task by id. The error code must be specified to identify the BPMN error handler. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task&#39;s most recent lock was not acquired by the provided worker. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>500</b> - Returned if the corresponding process instance could not be resumed successfully. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task in which context a BPMN error is reported. (required) * @param externalTaskBpmnError (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void handleExternalTaskBpmnError(String id, ExternalTaskBpmnError externalTaskBpmnError) throws RestClientException { handleExternalTaskBpmnErrorWithHttpInfo(id, externalTaskBpmnError); } /** * Handle BPMN Error * Reports a business error in the context of a running external task by id. The error code must be specified to identify the BPMN error handler. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task&#39;s most recent lock was not acquired by the provided worker. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>500</b> - Returned if the corresponding process instance could not be resumed successfully. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task in which context a BPMN error is reported. (required) * @param externalTaskBpmnError (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> handleExternalTaskBpmnErrorWithHttpInfo(String id, ExternalTaskBpmnError externalTaskBpmnError) throws RestClientException { Object postBody = externalTaskBpmnError; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling handleExternalTaskBpmnError"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/bpmnError", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Handle Failure * Reports a failure to execute an external task by id. A number of retries and a timeout until the task can be retried can be specified. If retries are set to 0, an incident for this task is created. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task&#39;s most recent lock was not acquired by the provided worker. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>500</b> - Returned if the corresponding process instance could not be resumed successfully. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to report a failure for. (required) * @param externalTaskFailureDto (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void handleFailure(String id, ExternalTaskFailureDto externalTaskFailureDto) throws RestClientException { handleFailureWithHttpInfo(id, externalTaskFailureDto); } /** * Handle Failure * Reports a failure to execute an external task by id. A number of retries and a timeout until the task can be retried can be specified. If retries are set to 0, an incident for this task is created. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task&#39;s most recent lock was not acquired by the provided worker. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>500</b> - Returned if the corresponding process instance could not be resumed successfully. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to report a failure for. (required) * @param externalTaskFailureDto (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> handleFailureWithHttpInfo(String id, ExternalTaskFailureDto externalTaskFailureDto) throws RestClientException { Object postBody = externalTaskFailureDto; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling handleFailure"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/failure", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * * Lock an external task by a given id for a specified worker and amount of time. * <p><b>204</b> - Request successful. * <p><b>400</b> - In case the lock duration is negative or the external task is already locked by a different worker, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task. (required) * @param lockExternalTaskDto (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void lock(String id, LockExternalTaskDto lockExternalTaskDto) throws RestClientException { lockWithHttpInfo(id, lockExternalTaskDto); } /** * * Lock an external task by a given id for a specified worker and amount of time. * <p><b>204</b> - Request successful. * <p><b>400</b> - In case the lock duration is negative or the external task is already locked by a different worker, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task. (required) * @param lockExternalTaskDto (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> lockWithHttpInfo(String id, LockExternalTaskDto lockExternalTaskDto) throws RestClientException { Object postBody = lockExternalTaskDto; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling lock"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/lock", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Get List (POST) * Queries for external tasks that fulfill given parameters in the form of a JSON object. This method is slightly more powerful than the [Get External Tasks](https://docs.camunda.org/manual/7.16/reference/rest/external-task/get-query/) method because it allows to specify a hierarchical result sorting. * <p><b>200</b> - Request successful. The Response is a JSON array of external task objects. * <p><b>400</b> - Returned if some of the query parameters are invalid, for example if a &#x60;sortOrder&#x60; parameter is supplied, but no &#x60;sortBy&#x60;. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param firstResult Pagination of results. Specifies the index of the first result to return. (optional) * @param maxResults Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. (optional) * @param externalTaskQueryDto (optional) * @return List&lt;ExternalTaskDto&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public List<ExternalTaskDto> queryExternalTasks(Integer firstResult, Integer maxResults, ExternalTaskQueryDto externalTaskQueryDto) throws RestClientException { return queryExternalTasksWithHttpInfo(firstResult, maxResults, externalTaskQueryDto).getBody(); } /** * Get List (POST) * Queries for external tasks that fulfill given parameters in the form of a JSON object. This method is slightly more powerful than the [Get External Tasks](https://docs.camunda.org/manual/7.16/reference/rest/external-task/get-query/) method because it allows to specify a hierarchical result sorting. * <p><b>200</b> - Request successful. The Response is a JSON array of external task objects. * <p><b>400</b> - Returned if some of the query parameters are invalid, for example if a &#x60;sortOrder&#x60; parameter is supplied, but no &#x60;sortBy&#x60;. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param firstResult Pagination of results. Specifies the index of the first result to return. (optional) * @param maxResults Pagination of results. Specifies the maximum number of results to return. Will return less results if there are no more results left. (optional) * @param externalTaskQueryDto (optional) * @return ResponseEntity&lt;List&lt;ExternalTaskDto&gt;&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<List<ExternalTaskDto>> queryExternalTasksWithHttpInfo(Integer firstResult, Integer maxResults, ExternalTaskQueryDto externalTaskQueryDto) throws RestClientException { Object postBody = externalTaskQueryDto; String path = apiClient.expandPath("/external-task", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "firstResult", firstResult)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "maxResults", maxResults)); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<List<ExternalTaskDto>> returnType = new ParameterizedTypeReference<List<ExternalTaskDto>>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Get List Count (POST) * Queries for the number of external tasks that fulfill given parameters. This method takes the same message body as the [Get External Tasks (POST)](https://docs.camunda.org/manual/7.16/reference/rest/external-task/post-query/) method. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param externalTaskQueryDto (optional) * @return CountResultDto * @throws RestClientException if an error occurs while attempting to invoke the API */ public CountResultDto queryExternalTasksCount(ExternalTaskQueryDto externalTaskQueryDto) throws RestClientException { return queryExternalTasksCountWithHttpInfo(externalTaskQueryDto).getBody(); } /** * Get List Count (POST) * Queries for the number of external tasks that fulfill given parameters. This method takes the same message body as the [Get External Tasks (POST)](https://docs.camunda.org/manual/7.16/reference/rest/external-task/post-query/) method. * <p><b>200</b> - Request successful. * <p><b>400</b> - Returned if some of the query parameters are invalid. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param externalTaskQueryDto (optional) * @return ResponseEntity&lt;CountResultDto&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<CountResultDto> queryExternalTasksCountWithHttpInfo(ExternalTaskQueryDto externalTaskQueryDto) throws RestClientException { Object postBody = externalTaskQueryDto; String path = apiClient.expandPath("/external-task/count", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<CountResultDto> returnType = new ParameterizedTypeReference<CountResultDto>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Set Priority * Sets the priority of an existing external task by id. The default value of a priority is 0. * <p><b>204</b> - Request successful. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to set the priority for. (required) * @param priorityDto (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void setExternalTaskResourcePriority(String id, PriorityDto priorityDto) throws RestClientException { setExternalTaskResourcePriorityWithHttpInfo(id, priorityDto); } /** * Set Priority * Sets the priority of an existing external task by id. The default value of a priority is 0. * <p><b>204</b> - Request successful. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to set the priority for. (required) * @param priorityDto (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> setExternalTaskResourcePriorityWithHttpInfo(String id, PriorityDto priorityDto) throws RestClientException { Object postBody = priorityDto; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling setExternalTaskResourcePriority"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/priority", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Set Retries * Sets the number of retries left to execute an external task by id. If retries are set to 0, an incident is created. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - In case the number of retries is negative or null, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to set the number of retries for. (required) * @param retriesDto (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void setExternalTaskResourceRetries(String id, RetriesDto retriesDto) throws RestClientException { setExternalTaskResourceRetriesWithHttpInfo(id, retriesDto); } /** * Set Retries * Sets the number of retries left to execute an external task by id. If retries are set to 0, an incident is created. * <p><b>204</b> - Request successful. * <p><b>400</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - In case the number of retries is negative or null, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to set the number of retries for. (required) * @param retriesDto (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> setExternalTaskResourceRetriesWithHttpInfo(String id, RetriesDto retriesDto) throws RestClientException { Object postBody = retriesDto; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling setExternalTaskResourceRetries"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/retries", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Set Retries Sync * Sets the number of retries left to execute external tasks by id synchronously. If retries are set to 0, an incident is created. * <p><b>204</b> - Request successful. * <p><b>400</b> - In case the number of retries is negative or null, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param setRetriesForExternalTasksDto (optional) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void setExternalTaskRetries(SetRetriesForExternalTasksDto setRetriesForExternalTasksDto) throws RestClientException { setExternalTaskRetriesWithHttpInfo(setRetriesForExternalTasksDto); } /** * Set Retries Sync * Sets the number of retries left to execute external tasks by id synchronously. If retries are set to 0, an incident is created. * <p><b>204</b> - Request successful. * <p><b>400</b> - In case the number of retries is negative or null, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param setRetriesForExternalTasksDto (optional) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> setExternalTaskRetriesWithHttpInfo(SetRetriesForExternalTasksDto setRetriesForExternalTasksDto) throws RestClientException { Object postBody = setRetriesForExternalTasksDto; String path = apiClient.expandPath("/external-task/retries", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Set Retries Async * Sets the number of retries left to execute external tasks by id asynchronously. If retries are set to 0, an incident is created. * <p><b>200</b> - Request successful. * <p><b>400</b> - If neither externalTaskIds nor externalTaskQuery are present or externalTaskIds contains null value or the number of retries is negative or null, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param setRetriesForExternalTasksDto (optional) * @return BatchDto * @throws RestClientException if an error occurs while attempting to invoke the API */ public BatchDto setExternalTaskRetriesAsyncOperation(SetRetriesForExternalTasksDto setRetriesForExternalTasksDto) throws RestClientException { return setExternalTaskRetriesAsyncOperationWithHttpInfo(setRetriesForExternalTasksDto).getBody(); } /** * Set Retries Async * Sets the number of retries left to execute external tasks by id asynchronously. If retries are set to 0, an incident is created. * <p><b>200</b> - Request successful. * <p><b>400</b> - If neither externalTaskIds nor externalTaskQuery are present or externalTaskIds contains null value or the number of retries is negative or null, an exception of type &#x60;InvalidRequestException&#x60; is returned. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param setRetriesForExternalTasksDto (optional) * @return ResponseEntity&lt;BatchDto&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<BatchDto> setExternalTaskRetriesAsyncOperationWithHttpInfo(SetRetriesForExternalTasksDto setRetriesForExternalTasksDto) throws RestClientException { Object postBody = setRetriesForExternalTasksDto; String path = apiClient.expandPath("/external-task/retries-async", Collections.<String, Object>emptyMap()); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { "application/json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<BatchDto> returnType = new ParameterizedTypeReference<BatchDto>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } /** * Unlock * Unlocks an external task by id. Clears the task&#39;s lock expiration time and worker id. * <p><b>204</b> - Request successful. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to unlock. (required) * @throws RestClientException if an error occurs while attempting to invoke the API */ public void unlock(String id) throws RestClientException { unlockWithHttpInfo(id); } /** * Unlock * Unlocks an external task by id. Clears the task&#39;s lock expiration time and worker id. * <p><b>204</b> - Request successful. * <p><b>404</b> - Returned if the task does not exist. This could indicate a wrong task id as well as a cancelled task, e.g., due to a caught BPMN boundary event. See the [Introduction](https://docs.camunda.org/manual/7.16/reference/rest/overview/#error-handling) for the error response format. * @param id The id of the external task to unlock. (required) * @return ResponseEntity&lt;Void&gt; * @throws RestClientException if an error occurs while attempting to invoke the API */ public ResponseEntity<Void> unlockWithHttpInfo(String id) throws RestClientException { Object postBody = null; // verify the required parameter 'id' is set if (id == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling unlock"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); String path = apiClient.expandPath("/external-task/{id}/unlock", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); } }
29,730
1,550
<reponame>digitalLumberjack/EmulationStation #pragma once #include "resources/TextureResource.h" struct NSVGimage; class SVGResource : public TextureResource { public: virtual ~SVGResource(); virtual void unload(std::shared_ptr<ResourceManager>& rm) override; virtual void initFromMemory(const char* image, size_t length) override; void rasterizeAt(size_t width, size_t height); Eigen::Vector2f getSourceImageSize() const; protected: friend TextureResource; SVGResource(const std::string& path, bool tile); void deinitSVG(); NSVGimage* mSVGImage; size_t mLastWidth; size_t mLastHeight; };
202