repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
shibaaaa/bootcamp
|
app/models/comment/after_create_callback.rb
|
# frozen_string_literal: true
class Comment::AfterCreateCallback
def after_create(comment)
if comment.commentable.class.include?(Watchable)
create_watch(comment)
notify_to_watching_user(comment)
elsif comment.sender != comment.receiver
notify_comment(comment)
end
if comment.commentable.instance_of?(Talk)
notify_to_admins(comment)
notify_to_chat(comment) unless comment.sender.admin?
update_unreplied(comment)
end
return unless comment.commentable.instance_of?(Product)
comment.commentable.create_checker_id(comment)
comment.commentable.update_last_commented_at(comment)
comment.commentable.update_commented_at(comment)
delete_product_cache(comment.commentable.id)
delete_assigned_and_unreplied_product_count_cache(comment)
end
private
def notify_comment(comment)
NotificationFacade.came_comment(
comment,
comment.receiver,
"相談部屋で#{comment.sender.login_name}さんからコメントがありました。"
)
end
def notify_to_watching_user(comment)
watchable = comment.commentable
mention_user_ids = comment.new_mention_users.ids
return unless watchable.try(:watched?)
watcher_ids = watchable.watches.pluck(:user_id)
watcher_ids.each do |watcher_id|
if watcher_id != comment.sender.id && !mention_user_ids.include?(watcher_id)
watcher = User.find_by(id: watcher_id)
NotificationFacade.watching_notification(watchable, watcher, comment)
end
end
end
def create_watch(comment)
watchable = comment.commentable
return if watchable.watches.pluck(:user_id).include?(comment.sender.id)
@watch = Watch.new(
user: comment.sender,
watchable: watchable
)
@watch.save!
end
def create_checker_id(comment)
return nil unless comment.user.mentor?
product = comment.commentable
product.checker_id = comment.sender.id unless product.checker_id?
end
def delete_product_cache(product_id)
Rails.cache.delete "/model/product/#{product_id}/last_commented_user"
end
def delete_assigned_and_unreplied_product_count_cache(comment)
product = comment.commentable
return unless product.checker_id.present? && product.replied_status_changed?(comment.previous&.user_id, comment.user_id)
Cache.delete_self_assigned_no_replied_product_count(product.checker_id)
end
def notify_to_admins(comment)
User.admins.each do |admin_user|
next if comment.sender == admin_user
NotificationFacade.came_comment(
comment,
admin_user,
"#{comment.commentable.user.login_name}さんの相談部屋で#{comment.sender.login_name}さんからコメントが届きました。"
)
end
end
def update_unreplied(comment)
unreplied = !comment.user.admin
comment.commentable.update!(unreplied: unreplied)
end
def notify_to_chat(comment)
ChatNotifier.message(<<~TEXT, webhook_url: ENV['DISCORD_ADMIN_WEBHOOK_URL'])
相談部屋にて#{comment.user.login_name}さんからコメントがありました。
本文: #{comment.description}
URL: https://bootcamp.fjord.jp/talks/#{comment.commentable_id}
TEXT
end
end
|
souzamonteiro/maialexa
|
src/MkLexer.js
|
/**
* @license
* Copyright 2020 <NAME>,
* <NAME>,
* <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.
*/
/**
* Lexer core class.
* @class
*/
function MkLexer() {
init();
/**
* Creates the attributes of the class.
*/
function init() {
// Class attributes goes here.
}
/**
* Interpret the options passed on the command line,
* process the files and generate the requested reports.
*/
this.run = function() {
// Supports only the Node.js interpreter.
if (typeof process !== 'undefined') {
var command = 'node';
var argv = process.argv.slice();
var fs = require('fs');
var readTextFile = fs.readFileSync;
// Read file callback.
function read(input) {
if (/^{.*}$/.test(input)) {
return input.substring(1, input.length - 1);
} else {
var content = readTextFile(input, 'utf-8');
return content.length > 0 && content.charCodeAt(0) == 0xFEFF ? content.substring(1) : content;
}
}
// Command line arguments.
system.argv = argv.slice();
system.argc = argv.length;
// Command line options.
var inputFile = '';
var outputFile = '';
// Get command line arguments.
if (argv.length > 2) {
var i = 2;
while (i < argv.length) {
if ((argv[i] == '-h') | (argv[i] == '--help')) {
system.log('MkLexer Command Line Interface (CLI)');
system.log('Usage: mklexer [options] [file.txt] [--] [arguments]');
system.log('Options:');
system.log('-h --help Displays this help message;');
system.log('-o [output.json] Output report file name;');
process.exit(0);
} else if (argv[i] == '-o') {
i++;
outputFile = argv[i];
} else {
inputFile = argv[i];
break;
}
i++;
}
system.argv = argv.slice(i);
system.argc = system.argv.length;
if (inputFile != '') {
var Glob = require('glob');
// Process each file based on glob pattern.
function processFiles(er, files) {
if (files.length == 0) {
system.log('MkLexer Command Line Interface (CLI)');
system.log('Usage: mklexer [options] [file.txt] [--] [arguments]');
} else {
var lexemes = {};
for (var i = 0; i < files.length; i++) {
file = files[i];
var fileName = file.split('.').shift();
var fileExtension = file.split('.').pop();
var fileContents = read(String(file));
var mainObjectName = string.camelize(fileName.split('/').pop().split('_').join(' '));
var thisObjectName = mainObjectName;
lexemes[mainObjectName] = {};
var mainObject = lexemes[mainObjectName];
mainObject[thisObjectName] = [];
var thisObject = mainObject[thisObjectName];
var fileLines = fileContents.split('\n');
for (var j = 0; j < fileLines.length; j++) {
var line = core.trim(fileLines[j].trim(), '\r');
if (line[0] == '#') {
continue;
} else if ((line[0] == '[') && (line[line.length - 1] == ']')) {
thisObjectName = string.camelize(core.trimRight(core.trimLeft(line, '['), ']'));
mainObject[thisObjectName] = [];
thisObject = mainObject[thisObjectName];
} else {
var record = line.split(',');
if (record.length > 1) {
thisObject.push(record);
} else {
thisObject.push(line);
}
}
}
}
if (outputFile == '') {
outputFile = 'lexemes.json';
}
fs.writeFile(outputFile, "var lexemes = " + JSON.stringify(lexemes), function(err) {
if (err) {
throw err;
}
});
}
}
options = {};
// Get all file names based on glob pattern.
var glob = new Glob(inputFile, options, processFiles);
} else {
system.log('MkLexer Command Line Interface (CLI)');
system.log('Usage: mklexer [options] [file.txt] [--] [arguments]');
}
} else {
system.log('MkLexer Command Line Interface (CLI)');
system.log('Usage: mklexer [options] [file.txt] [--] [arguments]');
}
}
}
}
mklexer = new MkLexer();
/*
* Run Lexer code if this script has been invoked
* from the command line.
*/
if (typeof process !== 'undefined') {
// Emulate DOM.
const jsdom = require('jsdom');
const {
JSDOM
} = jsdom;
var doc = new JSDOM();
var DOMParser = doc.window.DOMParser;
var alert = system.log;
mklexer.run();
}
|
metux/chromium-deb
|
chrome/browser/supervised_user/legacy/supervised_user_pref_mapping_service.cc
|
<reponame>metux/chromium-deb
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/supervised_user/legacy/supervised_user_pref_mapping_service.h"
#include "base/bind.h"
#include "base/values.h"
#include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service.h"
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
const int kNoAvatar = -1;
SupervisedUserPrefMappingService::SupervisedUserPrefMappingService(
PrefService* prefs,
SupervisedUserSharedSettingsService* shared_settings)
: prefs_(prefs),
shared_settings_(shared_settings),
supervised_user_id_(prefs->GetString(prefs::kSupervisedUserId)),
weak_ptr_factory_(this) {}
SupervisedUserPrefMappingService::~SupervisedUserPrefMappingService() {}
void SupervisedUserPrefMappingService::Init() {
subscription_ = shared_settings_->Subscribe(
base::Bind(&SupervisedUserPrefMappingService::OnSharedSettingChanged,
weak_ptr_factory_.GetWeakPtr()));
pref_change_registrar_.Init(prefs_);
pref_change_registrar_.Add(
prefs::kProfileAvatarIndex,
base::Bind(&SupervisedUserPrefMappingService::OnAvatarChanged,
weak_ptr_factory_.GetWeakPtr()));
// Check if we need to update the shared setting with the avatar index.
// Otherwise we update the user pref in case we missed a notification.
if (GetChromeAvatarIndex() == kNoAvatar) {
OnAvatarChanged();
} else {
OnSharedSettingChanged(supervised_user_id_,
supervised_users::kChromeAvatarIndex);
}
}
void SupervisedUserPrefMappingService::OnAvatarChanged() {
int new_avatar_index = prefs_->GetInteger(prefs::kProfileAvatarIndex);
if (new_avatar_index < 0)
return;
// First check if the avatar index is a new value.
if (GetChromeAvatarIndex() == new_avatar_index)
return;
// If yes, update the shared settings value.
shared_settings_->SetValue(supervised_user_id_,
supervised_users::kChromeAvatarIndex,
base::Value(new_avatar_index));
}
void SupervisedUserPrefMappingService::OnSharedSettingChanged(
const std::string& su_id,
const std::string& key) {
DCHECK_EQ(su_id, supervised_user_id_);
if (key != supervised_users::kChromeAvatarIndex)
return;
const base::Value* value = shared_settings_->GetValue(su_id, key);
int avatar_index;
bool success = value->GetAsInteger(&avatar_index);
DCHECK(success);
prefs_->SetInteger(prefs::kProfileAvatarIndex, avatar_index);
}
void SupervisedUserPrefMappingService::Shutdown() {
subscription_.reset();
}
int SupervisedUserPrefMappingService::GetChromeAvatarIndex() {
const base::Value* value = shared_settings_->GetValue(
supervised_user_id_, supervised_users::kChromeAvatarIndex);
if (!value)
return kNoAvatar;
int current_avatar_index;
bool success = value->GetAsInteger(¤t_avatar_index);
DCHECK(success);
return current_avatar_index;
}
|
mickknutson/SITE_BOOTCAMP_QA
|
StudentWork/Abdullaht/springboot/petstore/src/main/java/sa/site/lab/petstore/dao/AnimalDao.java
|
<gh_stars>10-100
package sa.site.lab.petstore.dao;
import sa.site.lab.petstore.domain.Animal;
import java.util.List;
public interface AnimalDao {
Animal findPet(int id);
List<Animal> findAll();
}
|
vladisnik/lazy-lxd
|
lazy_lxd/lib/inquirer/input.py
|
from PyInquirer import prompt
from .confirm import confirm
def input_text(msg: str = "Type something") -> str:
"""
Ask user to enter text in response to a request input answer
Args:
msg (str): Message which display to user.
This is request for input text usually.
Returns:
str: Text which user entered
"""
question = [
{
"type": "input",
"name": "input",
"message": msg
}
]
try:
answer = prompt(question)
return answer['input']
except KeyError:
exit = confirm(msg="Do you want cancel script")
if exit:
raise SystemExit
else:
return input_text(msg)
|
VArbiter/CCLocalLibrary
|
FileOperateRecord/2017-06-26 130754/UICollectionViewFlowLayout/UICollectionViewFlowLayout+CCExtension.h
|
//
// UICollectionViewFlowLayout+CCExtension.h
// CCLocalLibrary
//
// Created by 冯明庆 on 2017/4/1.
// Copyright © 2017年 冯明庆. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UICollectionViewFlowLayout (CCExtension)
+ (instancetype) ccCollectionLayoutWithItemSize : (CGSize) sizeItem ;
+ (instancetype) ccCollectionLayoutWithItemSize : (CGSize) sizeItem
withSectionInset : (UIEdgeInsets) edgeInsets ;
+ (instancetype) ccCollectionLayoutWithItemSize : (CGSize) sizeItem
withSectionInset : (UIEdgeInsets) edgeInsets
withHeaderSize : (CGSize) sizeHeader ;
@end
|
lgxkdream/algorithm-problems
|
src/io/github/lgxkdream/test/unit3/LastRemaining.java
|
package io.github.lgxkdream.test.unit3;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author <NAME>
* @version 1.0.0
* @title LastRemaining
* @description https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/
* @since 2020-03-30 12:36
*/
public class LastRemaining {
public static void main(String[] args) {
int n = 5, m = 3;
System.out.println(lastRemaining1(n, m));
}
public static int lastRemaining1(int n, int m) {
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
queue.offer(i);
}
int count = 1;
while (!queue.isEmpty()) {
Integer poll = queue.poll();
if (queue.size() == 0) {
return poll;
}
if (count++ % m != 0) {
queue.offer(poll);
}
}
return -1;
}
public static int lastRemaining(int n, int m) {
if (n == 1) {
return 0;
}
return (lastRemaining(n-1, m) + m) % n - 1;
}
}
|
shuigedeng/taotao-cloud-paren
|
taotao-cloud-java/taotao-cloud-javaee/src/main/java/com/taotao/cloud/java/javaee/s2/c5_redis/web/java/pojo/Menu.java
|
package com.taotao.cloud.java.javaee.s2.c5_redis.web.java.pojo;
import java.util.ArrayList;
import java.util.List;
public class Menu {
private Integer id;
private Integer parentId;
private Integer type;
private String name;
private String url;
private Integer sort;
private List<Menu> children = new ArrayList<>();
private String icon;
private String perms;
private String parentName;//必须加,否则前端修改菜单选择父节点之后输入框不变
}
|
RhoInc/Webcharts
|
src/chart/resize.js
|
<gh_stars>10-100
import { select } from 'd3';
export default function resize() {
let config = this.config;
let aspect2 = 1 / config.aspect;
let div_width = parseInt(this.wrap.style('width'));
let max_width = config.max_width ? config.max_width : div_width;
let preWidth = !config.resizable
? config.width
: !max_width || div_width < max_width ? div_width : this.raw_width;
this.textSize(preWidth);
this.margin = this.setMargins();
let svg_width = config.x.type === 'ordinal' && +config.x.range_band
? this.raw_width + this.margin.left + this.margin.right
: !config.resizable
? this.raw_width
: !config.max_width || div_width < config.max_width ? div_width : this.raw_width;
this.plot_width = svg_width - this.margin.left - this.margin.right;
var svg_height = config.y.type === 'ordinal' && +config.y.range_band
? this.raw_height + this.margin.top + this.margin.bottom
: !config.resizable && config.height
? config.height
: !config.resizable ? svg_width * aspect2 : this.plot_width * aspect2;
this.plot_height = svg_height - this.margin.top - this.margin.bottom;
select(this.svg.node().parentNode)
.attr('width', svg_width)
.attr('height', svg_height)
.select('g')
.attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');
this.svg
.select('.overlay')
.attr('width', this.plot_width)
.attr('height', this.plot_height)
.classed('zoomable', config.zoomable);
this.svg
.select('.plotting-area')
.attr('width', this.plot_width)
.attr('height', this.plot_height + 1)
.attr('transform', 'translate(0, -1)');
this.xScaleAxis();
this.yScaleAxis();
let g_x_axis = this.svg.select('.x.axis');
let g_y_axis = this.svg.select('.y.axis');
let x_axis_label = g_x_axis.select('.axis-title');
let y_axis_label = g_y_axis.select('.axis-title');
if (config.x_location !== 'top') {
g_x_axis.attr('transform', 'translate(0,' + this.plot_height + ')');
}
let gXAxisTrans = config.transitions ? g_x_axis.transition() : g_x_axis;
gXAxisTrans.call(this.xAxis);
let gYAxisTrans = config.transitions ? g_y_axis.transition() : g_y_axis;
gYAxisTrans.call(this.yAxis);
x_axis_label.attr(
'transform',
'translate(' + this.plot_width / 2 + ',' + (this.margin.bottom - 2) + ')'
);
y_axis_label.attr('x', -1 * this.plot_height / 2).attr('y', -1 * this.margin.left);
this.svg
.selectAll('.axis .domain')
.attr({ fill: 'none', stroke: '#ccc', 'stroke-width': 1, 'shape-rendering': 'crispEdges' });
this.svg
.selectAll('.axis .tick line')
.attr({ stroke: '#eee', 'stroke-width': 1, 'shape-rendering': 'crispEdges' });
this.drawGridlines();
//update legend - margins need to be set first
this.makeLegend();
//update the chart's specific marks
this.updateDataMarks();
//call .on("resize") function, if any
this.events.onResize.call(this);
}
|
undr/influxdb-api
|
lib/influxdb/api/namespaces/shards.rb
|
<reponame>undr/influxdb-api
module Influxdb
module Api
module Namespaces
class Shards < Base
resource_path '/cluster/shards'
def create(attributes)
attributes['startTime'] = cast_datetime(attributes['startTime']) if attributes['startTime']
attributes[:startTime] = cast_datetime(attributes[:startTime]) if attributes[:startTime]
attributes['endTime'] = cast_datetime(attributes['endTime']) if attributes['endTime']
attributes[:endTime] = cast_datetime(attributes[:endTime]) if attributes[:endTime]
super(attributes)
end
private
def cast_datetime(value)
value = value.to_i if value && !value.is_a?(Integer)
value
end
end
end
end
end
|
akash-coded/spring-framework
|
eclipse-projects/spring-boot/spring-boot-request-parsing-demo-app/src/main/java/com/spring/boot/request/parsing/demo/SpringBootRequestParsingDemoAppApplication.java
|
<gh_stars>1-10
package com.spring.boot.request.parsing.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootRequestParsingDemoAppApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRequestParsingDemoAppApplication.class, args);
System.out.println("Spring Boot request parsing app works!");
}
}
|
NightKirie/NCKU_NLP_2108_industry3
|
Packages/matplotlib-2.2.2/lib/mpl_examples/lines_bars_and_markers/markevery_demo.py
|
"""
==============
Markevery Demo
==============
This example demonstrates the various options for showing a marker at a
subset of data points using the ``markevery`` property of a Line2D object.
Integer arguments are fairly intuitive. e.g. ``markevery=5`` will plot every
5th marker starting from the first data point.
Float arguments allow markers to be spaced at approximately equal distances
along the line. The theoretical distance along the line between markers is
determined by multiplying the display-coordinate distance of the axes
bounding-box diagonal by the value of ``markevery``. The data points closest
to the theoretical distances will be shown.
A slice or list/array can also be used with ``markevery`` to specify the
markers to show.
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# define a list of markevery cases to plot
cases = [None,
8,
(30, 8),
[16, 24, 30], [0, -1],
slice(100, 200, 3),
0.1, 0.3, 1.5,
(0.0, 0.1), (0.45, 0.1)]
# define the figure size and grid layout properties
figsize = (10, 8)
cols = 3
gs = gridspec.GridSpec(len(cases) // cols + 1, cols)
gs.update(hspace=0.4)
# define the data for cartesian plots
delta = 0.11
x = np.linspace(0, 10 - 2 * delta, 200) + delta
y = np.sin(x) + 1.0 + delta
###############################################################################
# Plot each markevery case for linear x and y scales
fig1 = plt.figure(num=1, figsize=figsize)
ax = []
for i, case in enumerate(cases):
row = (i // cols)
col = i % cols
ax.append(fig1.add_subplot(gs[row, col]))
ax[-1].set_title('markevery=%s' % str(case))
ax[-1].plot(x, y, 'o', ls='-', ms=4, markevery=case)
###############################################################################
# Plot each markevery case for log x and y scales
fig2 = plt.figure(num=2, figsize=figsize)
axlog = []
for i, case in enumerate(cases):
row = (i // cols)
col = i % cols
axlog.append(fig2.add_subplot(gs[row, col]))
axlog[-1].set_title('markevery=%s' % str(case))
axlog[-1].set_xscale('log')
axlog[-1].set_yscale('log')
axlog[-1].plot(x, y, 'o', ls='-', ms=4, markevery=case)
fig2.tight_layout()
###############################################################################
# Plot each markevery case for linear x and y scales but zoomed in
# note the behaviour when zoomed in. When a start marker offset is specified
# it is always interpreted with respect to the first data point which might be
# different to the first visible data point.
fig3 = plt.figure(num=3, figsize=figsize)
axzoom = []
for i, case in enumerate(cases):
row = (i // cols)
col = i % cols
axzoom.append(fig3.add_subplot(gs[row, col]))
axzoom[-1].set_title('markevery=%s' % str(case))
axzoom[-1].plot(x, y, 'o', ls='-', ms=4, markevery=case)
axzoom[-1].set_xlim((6, 6.7))
axzoom[-1].set_ylim((1.1, 1.7))
fig3.tight_layout()
# define data for polar plots
r = np.linspace(0, 3.0, 200)
theta = 2 * np.pi * r
###############################################################################
# Plot each markevery case for polar plots
fig4 = plt.figure(num=4, figsize=figsize)
axpolar = []
for i, case in enumerate(cases):
row = (i // cols)
col = i % cols
axpolar.append(fig4.add_subplot(gs[row, col], projection='polar'))
axpolar[-1].set_title('markevery=%s' % str(case))
axpolar[-1].plot(theta, r, 'o', ls='-', ms=4, markevery=case)
fig4.tight_layout()
plt.show()
|
chreden/trview
|
trview.app/Mocks/Menus/IUpdateChecker.h
|
<reponame>chreden/trview
#pragma once
#include "../../Menus/IUpdateChecker.h"
namespace trview
{
namespace mocks
{
class MockUpdateChecker final : public IUpdateChecker
{
public:
virtual ~MockUpdateChecker() = default;
MOCK_METHOD(void, check_for_updates, ());
};
}
}
|
santhoshkkk/ci-droid-tasks-consumer
|
ci-droid-tasks-consumer-infrastructure/src/main/java/com/societegenerale/cidroid/tasks/consumer/infrastructure/notifiers/EMailActionNotifier.java
|
<reponame>santhoshkkk/ci-droid-tasks-consumer
package com.societegenerale.cidroid.tasks.consumer.infrastructure.notifiers;
import com.societegenerale.cidroid.tasks.consumer.services.model.github.User;
import com.societegenerale.cidroid.tasks.consumer.services.notifiers.ActionNotifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
@Slf4j
public class EMailActionNotifier implements ActionNotifier {
private final MailSender javaMailSender;
private final String mailSender;
@Autowired
public EMailActionNotifier(MailSender javaMailSender, String mailSender) {
this.javaMailSender = javaMailSender;
this.mailSender = mailSender;
}
@Override
public void notify(User recipientUser, String subject, String content) {
SimpleMailMessage email = new SimpleMailMessage();
email.setFrom(mailSender);
email.setTo(recipientUser.getEmail());
email.setSubject(subject);
email.setText(content);
this.javaMailSender.send(email);
}
}
|
oriss68/Panilla
|
glowstone-r2018_9_0/src/main/java/com/ruinscraft/panilla/glowstone/r2018_9_0/io/PacketInspector.java
|
<filename>glowstone-r2018_9_0/src/main/java/com/ruinscraft/panilla/glowstone/r2018_9_0/io/PacketInspector.java
package com.ruinscraft.panilla.glowstone.r2018_9_0.io;
import com.ruinscraft.panilla.api.IPanilla;
import com.ruinscraft.panilla.api.IPanillaPlayer;
import com.ruinscraft.panilla.api.exception.EntityNbtNotPermittedException;
import com.ruinscraft.panilla.api.exception.FailedNbt;
import com.ruinscraft.panilla.api.exception.LegacyEntityNbtNotPermittedException;
import com.ruinscraft.panilla.api.exception.NbtNotPermittedException;
import com.ruinscraft.panilla.api.io.IPacketInspector;
import com.ruinscraft.panilla.api.nbt.INbtTagCompound;
import com.ruinscraft.panilla.api.nbt.checks.NbtChecks;
import com.ruinscraft.panilla.glowstone.r2018_9_0.nbt.GlowNbtHelper;
import com.ruinscraft.panilla.glowstone.r2018_9_0.nbt.NbtTagCompound;
import net.glowstone.entity.GlowEntity;
import net.glowstone.entity.objects.GlowItem;
import net.glowstone.inventory.GlowMetaItem;
import net.glowstone.net.message.play.entity.SpawnMobMessage;
import net.glowstone.net.message.play.inv.CreativeItemMessage;
import net.glowstone.net.message.play.inv.SetWindowSlotMessage;
import net.glowstone.util.nbt.CompoundTag;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import java.util.UUID;
public class PacketInspector implements IPacketInspector {
private final IPanilla panilla;
public PacketInspector(IPanilla panilla) {
this.panilla = panilla;
}
@Override
public void checkPacketPlayInSetCreativeSlot(Object _packet) throws NbtNotPermittedException {
if (_packet instanceof CreativeItemMessage) {
CreativeItemMessage packet = (CreativeItemMessage) _packet;
final int slot = packet.getSlot();
final ItemStack itemStack = packet.getItem();
if (itemStack == null || !(itemStack.getItemMeta() instanceof GlowMetaItem)) {
return;
}
GlowMetaItem meta = (GlowMetaItem) itemStack.getItemMeta();
CompoundTag ngTag = GlowNbtHelper.getNbt(meta);
NbtChecks.checkPacketPlayIn(slot, new NbtTagCompound(ngTag), itemStack.getType().name(), packet.getClass().getSimpleName(), panilla);
}
}
@Override
public void checkPacketPlayOutSetSlot(Object _packet) throws NbtNotPermittedException {
if (_packet instanceof SetWindowSlotMessage) {
SetWindowSlotMessage packet = (SetWindowSlotMessage) _packet;
final int slot = packet.getSlot();
final ItemStack itemStack = packet.getItem();
if (itemStack == null || !(itemStack.getItemMeta() instanceof GlowMetaItem)) {
return;
}
GlowMetaItem meta = (GlowMetaItem) itemStack.getItemMeta();
CompoundTag ngTag = GlowNbtHelper.getNbt(meta);
NbtChecks.checkPacketPlayIn(slot, new NbtTagCompound(ngTag), itemStack.getType().name(), packet.getClass().getSimpleName(), panilla);
}
}
@Override
public void checkPacketPlayOutWindowItems(Object packetHandle) throws NbtNotPermittedException {
// TODO:
}
@Override
public void checkPacketPlayOutSpawnEntity(Object _packet) throws EntityNbtNotPermittedException, LegacyEntityNbtNotPermittedException {
if (_packet instanceof SpawnMobMessage) {
SpawnMobMessage packet = (SpawnMobMessage) _packet;
UUID entityId = packet.getUuid();
Entity bukkitEntity = Bukkit.getEntity(entityId);
GlowEntity glowEntity = (GlowEntity) bukkitEntity;
if (glowEntity instanceof GlowItem) {
GlowItem glowItem = (GlowItem) glowEntity;
ItemStack itemStack = glowItem.getItemStack();
if (itemStack == null) {
return;
}
if (!(itemStack.getItemMeta() instanceof GlowMetaItem)) {
return;
}
GlowMetaItem meta = (GlowMetaItem) glowItem.getItemStack().getItemMeta();
CompoundTag ngTag = GlowNbtHelper.getNbt(meta);
INbtTagCompound tag = new NbtTagCompound(ngTag);
// TODO fix
FailedNbt failedNbt = NbtChecks.checkAll(tag, glowItem.getItemStack().getClass().getSimpleName(), panilla);
if (FailedNbt.fails(failedNbt)) {
throw new EntityNbtNotPermittedException(packet.getClass().getSimpleName(), false, failedNbt, entityId, bukkitEntity.getWorld().getName());
}
}
}
}
@Override
public void sendPacketPlayOutSetSlotAir(IPanillaPlayer player, int slot) {
// TODO:
}
@Override
public void stripNbtFromItemEntity(UUID entityId) {
// TODO:
}
@Override
public void stripNbtFromItemEntityLegacy(int entityId) {
// TODO:
}
@Override
public void validateBaseComponentParse(String string) throws Exception {
// do nothing
}
}
|
uesleicarvalhoo/ProjectStore
|
backend/src/core/models/context.py
|
<filename>backend/src/core/models/context.py
from typing import Union
from uuid import UUID
from pydantic import BaseModel
from src.core.constants import AccessLevel, ContextEnum
class Context(BaseModel):
context: ContextEnum
user_id: Union[UUID, None]
user_access_level: bool = False
method: str
authenticated: bool = False
@property
def user_is_super_user(self) -> bool:
return self.user_access_level == AccessLevel.SUPER_USER
|
zengfanmao/mpds
|
VideoServer/src/mod/event_handlers/mod_amqp/mod_amqp_command.c
|
/*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
* Copyright (C) 2005-2012, <NAME> <<EMAIL>>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
*
* The Initial Developer of the Original Code is
* <NAME> <<EMAIL>>
* Portions created by the Initial Developer are Copyright (C)
* the Initial Developer. All Rights Reserved.
*
* Based on mod_skel by
* <NAME> <<EMAIL>>
*
* Contributor(s):
*
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
* <NAME> <<EMAIL>>
*
* mod_amqp.c -- Sends FreeSWITCH events to an AMQP broker
*
*/
#include "mod_amqp.h"
switch_status_t mod_amqp_command_destroy(mod_amqp_command_profile_t **prof)
{
switch_status_t ret;
mod_amqp_connection_t *conn = NULL, *conn_next = NULL;
switch_memory_pool_t *pool;
mod_amqp_command_profile_t *profile;
if (!prof || !*prof) {
return SWITCH_STATUS_SUCCESS;
}
profile = *prof;
pool = profile->pool;
if (profile->name) {
switch_core_hash_delete(mod_amqp_globals.command_hash, profile->name);
}
profile->running = 0;
if (profile->command_thread) {
switch_thread_join(&ret, profile->command_thread);
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Profile[%s] closing AMQP socket...\n", profile->name);
for (conn = profile->conn_root; conn; conn = conn_next) {
mod_amqp_connection_destroy(&conn);
}
profile->conn_active = NULL;
profile->conn_root = NULL;
if (pool) {
switch_core_destroy_memory_pool(&pool);
}
*prof = NULL;
return SWITCH_STATUS_SUCCESS;
}
switch_status_t mod_amqp_command_create(char *name, switch_xml_t cfg)
{
mod_amqp_command_profile_t *profile = NULL;
switch_xml_t params, param, connections, connection;
switch_threadattr_t *thd_attr = NULL;
switch_memory_pool_t *pool;
char *exchange = NULL, *binding_key = NULL, *queue = NULL;
if (switch_core_new_memory_pool(&pool) != SWITCH_STATUS_SUCCESS) {
goto err;
}
profile = switch_core_alloc(pool, sizeof(mod_amqp_command_profile_t));
profile->pool = pool;
profile->name = switch_core_strdup(profile->pool, name);
profile->running = 1;
profile->reconnect_interval_ms = 1000;
if ((params = switch_xml_child(cfg, "params")) != NULL) {
for (param = switch_xml_child(params, "param"); param; param = param->next) {
char *var = (char *) switch_xml_attr_soft(param, "name");
char *val = (char *) switch_xml_attr_soft(param, "value");
if (!var) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] param missing 'name' attribute\n", profile->name);
continue;
}
if (!val) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] param[%s] missing 'value' attribute\n", profile->name, var);
continue;
}
if (!strncmp(var, "reconnect_interval_ms", 21)) {
int interval = atoi(val);
if ( interval && interval > 0 ) {
profile->reconnect_interval_ms = interval;
}
} else if (!strncmp(var, "exchange-name", 13)) {
exchange = switch_core_strdup(profile->pool, val);
} else if (!strncmp(var, "queue-name", 10)) {
queue = switch_core_strdup(profile->pool, val);
} else if (!strncmp(var, "binding_key", 11)) {
binding_key = switch_core_strdup(profile->pool, val);
}
}
}
/* Handle defaults of string types */
profile->exchange = exchange ? exchange : switch_core_strdup(profile->pool, "TAP.Commands");
profile->queue = queue ? queue : NULL;
profile->binding_key = binding_key ? binding_key : switch_core_strdup(profile->pool, "commandBindingKey");
if ((connections = switch_xml_child(cfg, "connections")) != NULL) {
for (connection = switch_xml_child(connections, "connection"); connection; connection = connection->next) {
if ( ! profile->conn_root ) { /* Handle first root node */
if (mod_amqp_connection_create(&(profile->conn_root), connection, profile->pool) != SWITCH_STATUS_SUCCESS) {
/* Handle connection create failure */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Profile[%s] failed to create connection\n", profile->name);
continue;
}
profile->conn_active = profile->conn_root;
} else {
if (mod_amqp_connection_create(&(profile->conn_active->next), connection, profile->pool) != SWITCH_STATUS_SUCCESS) {
/* Handle connection create failure */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Profile[%s] failed to create connection\n", profile->name);
continue;
}
profile->conn_active = profile->conn_active->next;
}
}
}
profile->conn_active = NULL;
/* We are not going to open the command queue connection on create, but instead wait for the running thread to open it */
/* Start the worker threads */
switch_threadattr_create(&thd_attr, profile->pool);
switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE);
if (switch_thread_create(&profile->command_thread, thd_attr, mod_amqp_command_thread, profile, profile->pool)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot create 'amqp event sender' thread!\n");
goto err;
}
if ( switch_core_hash_insert(mod_amqp_globals.command_hash, name, (void *) profile) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Failed to insert new profile [%s] into mod_amqp profile hash\n", name);
goto err;
}
return SWITCH_STATUS_SUCCESS;
err:
/* Cleanup */
mod_amqp_command_destroy(&profile);
return SWITCH_STATUS_GENERR;
}
static void mod_amqp_command_response(mod_amqp_command_profile_t *profile, char *command, switch_stream_handle_t stream,
char *fs_resp_exchange, char *fs_resp_key, switch_status_t status)
{
char *json_output = NULL;
amqp_basic_properties_t props;
cJSON *message = NULL;
int amqp_status = AMQP_STATUS_OK;
if (! profile->conn_active) {
/* No connection, so we can not send the message. */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] not active\n", profile->name);
return;
}
/* Construct the api response */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Preparing api command response: [%s]\n", (char *)stream.data);
message = cJSON_CreateObject();
cJSON_AddItemToObject(message, "output", cJSON_CreateString((const char *) stream.data));
cJSON_AddItemToObject(message, "command", cJSON_CreateString(command));
cJSON_AddItemToObject(message, "status", cJSON_CreateNumber((double) status));
json_output = cJSON_Print(message);
cJSON_Delete(message);
memset(&props, 0, sizeof(amqp_basic_properties_t));
props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG;
props.content_type = amqp_cstring_bytes("text/json");
amqp_status = amqp_basic_publish(
profile->conn_active->state,
1,
amqp_cstring_bytes(fs_resp_exchange),
amqp_cstring_bytes(fs_resp_key),
0,
0,
&props,
amqp_cstring_bytes(json_output));
switch_safe_free(json_output);
if (amqp_status != AMQP_STATUS_OK) {
const char *errstr = amqp_error_string2(-amqp_status);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Profile[%s] failed to send event on connection[%s]: %s\n",
profile->name, profile->conn_active->name, errstr);
/* This is bad, we couldn't send the message. Clear up any connection */
mod_amqp_connection_close(profile->conn_active);
profile->conn_active = NULL;
return;
}
return;
}
void * SWITCH_THREAD_FUNC mod_amqp_command_thread(switch_thread_t *thread, void *data)
{
mod_amqp_command_profile_t *profile = (mod_amqp_command_profile_t *) data;
while (profile->running) {
amqp_queue_declare_ok_t *recv_queue;
amqp_bytes_t queueName = { 0, NULL };
/* Ensure we have an AMQP connection */
if (!profile->conn_active) {
switch_status_t status;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Amqp no connection- reconnecting...\n");
status = mod_amqp_connection_open(profile->conn_root, &(profile->conn_active), profile->name, profile->custom_attr);
if ( status != SWITCH_STATUS_SUCCESS ) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Profile[%s] failed to connect with code(%d), sleeping for %dms\n",
profile->name, status, profile->reconnect_interval_ms);
switch_sleep(profile->reconnect_interval_ms * 1000);
continue;
}
/* Check if exchange already exists */
amqp_exchange_declare(profile->conn_active->state, 1,
amqp_cstring_bytes(profile->exchange),
amqp_cstring_bytes("topic"),
0, /* passive */
1, /* durable */
amqp_empty_table);
if (mod_amqp_log_if_amqp_error(amqp_get_rpc_reply(profile->conn_active->state), "Checking for command exchange")) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Profile[%s] failed to create missing command exchange", profile->name);
continue;
}
/* Ensure we have a queue */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Creating command queue");
recv_queue = amqp_queue_declare(profile->conn_active->state, // state
1, // channel
profile->queue ? amqp_cstring_bytes(profile->queue) : amqp_empty_bytes, // queue name
0, 0, // passive, durable
0, 1, // exclusive, auto-delete
amqp_empty_table); // args
if (mod_amqp_log_if_amqp_error(amqp_get_rpc_reply(profile->conn_active->state), "Declaring queue")) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Profile[%s] failed to connect with code(%d), sleeping for %dms\n",
profile->name, status, profile->reconnect_interval_ms);
switch_sleep(profile->reconnect_interval_ms * 1000);
continue;
}
if (queueName.bytes) {
amqp_bytes_free(queueName);
}
queueName = amqp_bytes_malloc_dup(recv_queue->queue);
if (!queueName.bytes) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Out of memory while copying queue name");
break;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Created command queue %.*s\n", (int)queueName.len, (char *)queueName.bytes);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Binding command queue to exchange %s\n", profile->exchange);
/* Bind the queue to the exchange */
amqp_queue_bind(profile->conn_active->state, // state
1, // channel
queueName, // queue
amqp_cstring_bytes(profile->exchange), // exchange
amqp_cstring_bytes(profile->binding_key), // routing key
amqp_empty_table); // args
if (mod_amqp_log_if_amqp_error(amqp_get_rpc_reply(profile->conn_active->state), "Binding queue")) {
mod_amqp_connection_close(profile->conn_active);
profile->conn_active = NULL;
switch_sleep(profile->reconnect_interval_ms * 1000);
continue;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Amqp reconnect successful- connected\n");
continue;
}
// Start a command
amqp_basic_consume(profile->conn_active->state, // state
1, // channel
queueName, // queue
amqp_empty_bytes, // command tag
0, 1, 0, // no_local, no_ack, exclusive
amqp_empty_table); // args
if (mod_amqp_log_if_amqp_error(amqp_get_rpc_reply(profile->conn_active->state), "Creating a command")) {
mod_amqp_connection_close(profile->conn_active);
profile->conn_active = NULL;
switch_sleep(profile->reconnect_interval_ms * 1000);
continue;
}
while (profile->running && profile->conn_active) {
amqp_rpc_reply_t res;
amqp_envelope_t envelope;
struct timeval timeout = {0};
char command[1024];
enum ECommandFormat {
COMMAND_FORMAT_UNKNOWN,
COMMAND_FORMAT_PLAINTEXT
} commandFormat = COMMAND_FORMAT_PLAINTEXT;
char *fs_resp_exchange = NULL, *fs_resp_key = NULL;
amqp_maybe_release_buffers(profile->conn_active->state);
timeout.tv_usec = 500 * 1000;
res = amqp_consume_message(profile->conn_active->state, &envelope, &timeout, 0);
if (res.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION) {
if (res.library_error == AMQP_STATUS_UNEXPECTED_STATE) {
/* Unexpected frame. Discard it then continue */
amqp_frame_t decoded_frame;
amqp_simple_wait_frame(profile->conn_active->state, &decoded_frame);
}
if (res.library_error == AMQP_STATUS_SOCKET_ERROR) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "A socket error occurred. Tearing down and reconnecting\n");
break;
}
if (res.library_error == AMQP_STATUS_CONNECTION_CLOSED) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "AMQP connection was closed. Tearing down and reconnecting\n");
break;
}
if (res.library_error == AMQP_STATUS_TCP_ERROR) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "A TCP error occurred. Tearing down and reconnecting\n");
break;
}
if (res.library_error == AMQP_STATUS_TIMEOUT) {
// nop
}
/* Try consuming again */
continue;
}
if (res.reply_type != AMQP_RESPONSE_NORMAL) {
break;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Delivery:%u, exchange:%.*s routingkey:%.*s\n",
(unsigned) envelope.delivery_tag, (int) envelope.exchange.len, (char *) envelope.exchange.bytes,
(int) envelope.routing_key.len, (char *) envelope.routing_key.bytes);
if (envelope.message.properties._flags & AMQP_BASIC_CONTENT_TYPE_FLAG) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Content-type: %.*s\n",
(int) envelope.message.properties.content_type.len, (char *) envelope.message.properties.content_type.bytes);
if (strncasecmp("text/plain", envelope.message.properties.content_type.bytes, strlen("text/plain")) == 0) {
commandFormat = COMMAND_FORMAT_PLAINTEXT;
} else {
commandFormat = COMMAND_FORMAT_UNKNOWN;
}
}
if (envelope.message.properties.headers.num_entries) {
int x = 0;
for ( x = 0; x < envelope.message.properties.headers.num_entries; x++) {
char *header_key = (char *)envelope.message.properties.headers.entries[x].key.bytes;
char *header_value = (char *)envelope.message.properties.headers.entries[x].value.value.bytes.bytes;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "AMQP message custom header key[%s] value[%s]\n", header_key, header_value);
if ( !strncmp(header_key, "x-fs-api-resp-exchange", 22)) {
fs_resp_exchange = header_value;
} else if (!strncmp(header_key, "x-fs-api-resp-key", 17)) {
fs_resp_key = header_value;
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Ignoring unrecognized event header [%s]\n", header_key);
}
}
}
if (commandFormat == COMMAND_FORMAT_PLAINTEXT) {
switch_stream_handle_t stream = { 0 }; /* Collects the command output */
/* Convert amqp bytes to c-string */
snprintf(command, sizeof(command), "%.*s", (int) envelope.message.body.len, (char *) envelope.message.body.bytes);
/* Execute the command */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Executing: %s\n", command);
SWITCH_STANDARD_STREAM(stream);
if ( fs_resp_exchange && fs_resp_key ) {
switch_status_t status = switch_console_execute(command, 0, &stream);
mod_amqp_command_response(profile, command, stream, fs_resp_exchange, fs_resp_key, status);
} else {
if (switch_console_execute(command, 0, &stream) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Remote command failed:\n%s\n", (char *) stream.data);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Remote command succeeded:\n%s\n", (char *) stream.data);
}
}
switch_safe_free(stream.data);
}
/* Tidy up */
amqp_destroy_envelope(&envelope);
}
amqp_bytes_free(queueName);
queueName.bytes = NULL;
mod_amqp_connection_close(profile->conn_active);
profile->conn_active = NULL;
if (profile->running) {
/* We'll reconnect, but sleep to avoid hammering resources */
switch_sleep(500);
}
}
/* Terminate the thread */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Command listener thread stopped\n");
switch_thread_exit(thread, SWITCH_STATUS_SUCCESS);
return NULL;
}
/* For Emacs:
* Local Variables:
* mode:c
* indent-tabs-mode:t
* tab-width:4
* c-basic-offset:4
* End:
* For VIM:
* vim:set softtabstop=4 shiftwidth=4 tabstop=4
*/
|
ty850454/S-S
|
ss-web/src/test/java/com/dreammakerteam/ss/ssweb/WebApplicationTests.java
|
<filename>ss-web/src/test/java/com/dreammakerteam/ss/ssweb/WebApplicationTests.java
package com.dreammakerteam.ss.ssweb;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class WebApplicationTests {
@Test
public void contextLoads() throws JsonProcessingException {
}
}
|
project-arlo/sonic-mgmt-framework
|
src/translib/igmp_snooping_test.go
|
<reponame>project-arlo/sonic-mgmt-framework<filename>src/translib/igmp_snooping_test.go
////////////////////////////////////////////////////////////////////////////////
// //
// Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or //
// its subsidiaries. //
// //
// 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 translib
import (
"errors"
"fmt"
"testing"
db "translib/db"
"os"
)
const (
CFG_L2MC_TABLE = "CFG_L2MC_TABLE"
CFG_L2MC_MROUTER_TABLE = "CFG_L2MC_MROUTER_TABLE"
CFG_L2MC_STATIC_GROUP_TABLE = "CFG_L2MC_STATIC_GROUP_TABLE"
CFG_L2MC_STATIC_MEMBER_TABLE = "CFG_L2MC_STATIC_MEMBER_TABLE"
APP_L2MC_MROUTER_TABLE = "APP_L2MC_MROUTER_TABLE"
APP_L2MC_MEMBER_TABLE = "APP_L2MC_MEMBER_TABLE"
)
func clearDb() {
fmt.Println("--------- Init IGMP Snooping Go test --------")
if err := clearIgmpSnoopingDataFromConfigDb(); err == nil {
fmt.Println("----- Removed All IGMP Snooping Data from Db -------")
createVlanInterface ()
} else {
fmt.Printf("Failed to remove All IGMP Snooping from Db: %v", err)
os.Exit(1) // Cancel any further tests.
}
}
func createVlanInterface () {
var createVlan string = "{\"openconfig-interfaces:config\": {\"name\": \"Vlan5\"}}"
Update(SetRequest{Path: "/openconfig-interfaces:interfaces/interface[name=Vlan5]/config", Payload: []byte(createVlan)})
etherMem := "{\"openconfig-vlan:config\": {\"interface-mode\": \"ACCESS\", \"access-vlan\": 5}}"
_, err := Update(SetRequest{Path: "/openconfig-interfaces:interfaces/interface[name=Ethernet8]/openconfig-if-ethernet:ethernet/openconfig-vlan:switched-vlan/config", Payload: []byte(etherMem)})
if err != nil {
fmt.Println("createVlanInterface - Error in configuring the vlan 5 - test - as member of the port Ethernet8 ==> error", err)
}
}
func TestIGMPSnoopingConfigPostDeleteGetAPIs(t *testing.T) {
clearDb()
//POST - config container
t.Run("POST - Config container", processSetRequest(igmpsIntfUrl, configNodeReq, "POST", false))
t.Run("Verify: POST - Config container", processGetRequest(configUrl, configNodeReq, false))
t.Run("Delete - Config container", processDeleteRequest(igmpsIntfUrl))
t.Run("Verify: Delete - Config container", processGetRequest(configUrl, "{\"openconfig-network-instance-deviation:config\":{\"name\":\"Vlan5\"}}", true))
//POST - mrouter
t.Run("POST - mrouter", processSetRequest(configUrl, mrouterReq, "POST", false))
t.Run("Verify: POST - mrouter", processGetRequest(mrouterUrl, mrouterReq, false))
t.Run("Delete - mrouterr", processDeleteRequest(mrouterUrl))
t.Run("Verify: Delete - mrouter", processGetRequest(mrouterUrl, "{}", true))
//POST - static-group
t.Run("POST - static group", processSetRequest(configUrl, staticGroupReq, "POST", false))
t.Run("Verify: POST - static group", processGetRequest(staticGrpUrl, staticGroupReq, false))
t.Run("Delete - static group", processDeleteRequest(staticGrpUrl))
t.Run("Verify: Delete - static group", processGetRequest(staticGrpUrl, "{}", true))
//POST - static-group only
t.Run("POST - static-group only", processSetRequest(configUrl, staticGroupOnlyReq, "POST", false))
t.Run("Verify: POST - static-group only", processGetRequest(staticGrpUrl, staticGroupOnlyReq, false))
t.Run("Delete - static-group only", processDeleteRequest(staticGrpUrl))
t.Run("Verify: Delete - static-group only", processGetRequest(staticGrpUrl, "{}", true))
//POST - static-group intf only
t.Run("POST - static group", processSetRequest(configUrl, staticGroupOnlyReq, "POST", false))
t.Run("Verify: POST - static group", processGetRequest(staticGrpUrl, staticGroupOnlyReq, false))
grpUrl := staticGrpUrl + "[group=1.2.3.4]"
t.Run("POST - static-group intf only", processSetRequest(grpUrl, staticGroupIntfReq, "POST", false))
t.Run("Verify: POST - static-group intf only", processGetRequest(grpUrl+"/outgoing-interface", staticGroupIntfReq, false))
t.Run("Delete - static-group intf only ", processDeleteRequest(grpUrl+"/outgoing-interface"))
t.Run("Verify: Delete - static-group intf only ", processGetRequest(grpUrl+"/outgoing-interface", "{}", true))
t.Run("Delete - static-group", processDeleteRequest(staticGrpUrl))
//DELETE - static-group intf delete only
t.Run("POST - static group", processSetRequest(configUrl, staticGroupReq, "POST", false))
t.Run("Verify: POST - static group", processGetRequest(staticGrpUrl, staticGroupReq, false))
t.Run("Delete - static-group intf delete only ", processDeleteRequest(grpUrl+"/outgoing-interface=Ethernet8"))
t.Run("Verify: Delete - static-group intf delete only ", processGetRequest(grpUrl+"/outgoing-interface=Ethernet8", "{}", true))
t.Run("Delete - static-group", processDeleteRequest(staticGrpUrl))
//POST - igmps enable
t.Run("POST - igmps enable ", processSetRequest(configUrl, igmpsEnableReq, "POST", false))
t.Run("Verify: POST - igmps enable ", processGetRequest(igmpsEnableUrl, igmpsEnableReq, false))
t.Run("Delete - igmps enable ", processDeleteRequest(igmpsEnableUrl))
t.Run("Verify: Delete - igmps enable ", processGetRequest(igmpsEnableUrl, "{\"openconfig-network-instance-deviation:enabled\":false}", false))
//POST - fast-leave
t.Run("POST - static group", processSetRequest(configUrl, fastLeaveReq, "POST", false))
t.Run("Verify: POST - fast-leave ", processGetRequest(fastLeaveUrl, fastLeaveReq, false))
t.Run("Delete - fast-leave ", processDeleteRequest(fastLeaveUrl))
t.Run("Verify: Delete - fast-leave ", processGetRequest(fastLeaveUrl, "{\"openconfig-network-instance-deviation:fast-leave\":false}", false))
//POST - querier
t.Run("POST - querier", processSetRequest(configUrl, querierReq, "POST", false))
t.Run("Verify: POST - querier", processGetRequest(querierUrl, querierReq, false))
t.Run("Delete - querier", processDeleteRequest(querierUrl))
t.Run("Verify: Delete - querier", processGetRequest(querierUrl, "{\"openconfig-network-instance-deviation:querier\":false}", false))
//POST - last-memeber
t.Run("POST - last-memeber ", processSetRequest(configUrl, lastMemReq, "POST", false))
t.Run("Verify: POST - last-memeber ", processGetRequest(lastMemUrl, lastMemReq, false))
t.Run("Delete - last-memeber ", processDeleteRequest(lastMemUrl))
t.Run("Verify: Delete - last-memeber ", processGetRequest(lastMemUrl, "{\"openconfig-network-instance-deviation:last-member-query-interval\":0}", false))
//POST - version
t.Run("POST - version", processSetRequest(configUrl, versionReq, "POST", false))
t.Run("Verify: POST - version", processGetRequest(versionUrl, versionReq, false))
t.Run("Delete - version", processDeleteRequest(versionUrl))
t.Run("Verify: Delete - version", processGetRequest(versionUrl, "{\"openconfig-network-instance-deviation:version\":0}", false))
//POST - query-max-response
t.Run("POST - query-max-response ", processSetRequest(configUrl, qryMaxTimeReq, "POST", false))
t.Run("Verify: POST - query-max-response ", processGetRequest(maxRespTimenUrl, qryMaxTimeReq, false))
t.Run("Delete - query-max-response ", processDeleteRequest(maxRespTimenUrl))
t.Run("Verify: Delete - query-max-response ", processGetRequest(maxRespTimenUrl, "{\"openconfig-network-instance-deviation:query-max-response-time\":0}", false))
//POST - query-interval
t.Run("POST - query-interval ", processSetRequest(configUrl, qryIntvlReq, "POST", false))
t.Run("Verify: POST - query-interval ", processGetRequest(qryIntvlUrl, qryIntvlReq, false))
t.Run("Delete - query-interval ", processDeleteRequest(qryIntvlUrl))
t.Run("Verify: Delete - query-interval", processGetRequest(qryIntvlUrl, "{\"openconfig-network-instance-deviation:query-interval\":0}", false))
}
func TestIGMPSnoopingConfigPatchDeleteGetAPIs(t *testing.T) {
clearDb()
//PATCH - config container
t.Run("PATCH - Config container", processSetRequest(configUrl, configNodeReq, "PATCH", false))
t.Run("Verify: PATCH - Config container", processGetRequest(configUrl, configNodeReq, false))
t.Run("Delete - Config container", processDeleteRequest(igmpsIntfUrl))
t.Run("Verify: Delete - Config container", processGetRequest(configUrl, "{\"openconfig-network-instance-deviation:config\":{\"name\":\"Vlan5\"}}", true))
//PATCH - mrouter
t.Run("PATCH - mrouter", processSetRequest(mrouterUrl, mrouterReq, "PATCH", false))
t.Run("Verify: PATCH - mrouter", processGetRequest(mrouterUrl, mrouterReq, false))
t.Run("Delete - mrouterr", processDeleteRequest(mrouterUrl))
t.Run("Verify: Delete - mrouter", processGetRequest(mrouterUrl, "{}", true))
//PATCH - static-group
t.Run("PATCH - static group", processSetRequest(staticGrpUrl, staticGroupReq, "PATCH", false))
t.Run("Verify: PATCH - static group", processGetRequest(staticGrpUrl, staticGroupReq, false))
t.Run("Delete - static group", processDeleteRequest(staticGrpUrl))
t.Run("Verify: Delete - static group", processGetRequest(staticGrpUrl, "{}", true))
//PATCH - static-group only
t.Run("PATCH - static-group only", processSetRequest(staticGrpUrl, staticGroupOnlyReq, "PATCH", false))
t.Run("Verify: PATCH - static-group only", processGetRequest(staticGrpUrl, staticGroupOnlyReq, false))
t.Run("Delete - static-group only", processDeleteRequest(staticGrpUrl))
t.Run("Verify: Delete - static-group only", processGetRequest(staticGrpUrl, "", true))
//PATCH - static-group intf only
t.Run("PATCH - PATCH group", processSetRequest(staticGrpUrl, staticGroupOnlyReq, "PATCH", false))
t.Run("Verify: PATCH - group", processGetRequest(staticGrpUrl, staticGroupOnlyReq, false))
grpUrl := staticGrpUrl + "[group=1.2.3.4]"
t.Run("PATCH - static-group intf only", processSetRequest(grpUrl+"/outgoing-interface", staticGroupIntfReq, "PATCH", false))
t.Run("Verify: PATCH - static-group intf only", processGetRequest(grpUrl+"/outgoing-interface", staticGroupIntfReq, false))
t.Run("Delete - static-group intf only ", processDeleteRequest(grpUrl+"/outgoing-interface"))
t.Run("Verify: Delete - static-group intf only ", processGetRequest(grpUrl+"/outgoing-interface", "", true))
t.Run("Delete - static-group", processDeleteRequest(staticGrpUrl))
//PATCH - igmps enable
t.Run("PATCH - igmps enable ", processSetRequest(igmpsEnableUrl, igmpsEnableReq, "PATCH", false))
t.Run("Verify: PATCH - igmps enable ", processGetRequest(igmpsEnableUrl, igmpsEnableReq, false))
t.Run("Delete - igmps enable ", processDeleteRequest(igmpsEnableUrl))
t.Run("Verify: Delete - igmps enable ", processGetRequest(igmpsEnableUrl, "{\"openconfig-network-instance-deviation:enabled\":false}", false))
//PATCH - fast-leave
t.Run("PATCH - fast-leave ", processSetRequest(fastLeaveUrl, fastLeaveReq, "PATCH", false))
t.Run("Verify: PATCH - fast-leave ", processGetRequest(fastLeaveUrl, fastLeaveReq, false))
t.Run("Delete - fast-leave ", processDeleteRequest(fastLeaveUrl))
t.Run("Verify: Delete - fast-leave ", processGetRequest(fastLeaveUrl, "{\"openconfig-network-instance-deviation:fast-leave\":false}", false))
//PATCH - querier
t.Run("PATCH - querier", processSetRequest(querierUrl, querierReq, "PATCH", false))
t.Run("Verify: PATCH - querier", processGetRequest(querierUrl, querierReq, false))
t.Run("Delete - querier", processDeleteRequest(querierUrl))
t.Run("Verify: Delete - querier", processGetRequest(querierUrl, "{\"openconfig-network-instance-deviation:querier\":false}", false))
//PATCH - last-memeber
t.Run("PATCH - last-memeber ", processSetRequest(lastMemUrl, lastMemReq, "PATCH", false))
t.Run("Verify: PATCH - last-memeber ", processGetRequest(lastMemUrl, lastMemReq, false))
t.Run("Delete - last-memeber ", processDeleteRequest(lastMemUrl))
t.Run("Verify: Delete - last-memeber ", processGetRequest(lastMemUrl, "{\"openconfig-network-instance-deviation:last-member-query-interval\":0}", false))
//PATCH - version
t.Run("PATCH - version", processSetRequest(versionUrl, versionReq, "PATCH", false))
t.Run("Verify: PATCH - version", processGetRequest(versionUrl, versionReq, false))
t.Run("Delete - version", processDeleteRequest(versionUrl))
t.Run("Verify: Delete - version", processGetRequest(versionUrl, "{\"openconfig-network-instance-deviation:version\":0}", false))
//PATCH - query-max-response
t.Run("PATCH - query-max-response ", processSetRequest(maxRespTimenUrl, qryMaxTimeReq, "PATCH", false))
t.Run("Verify: PATCH - query-max-response ", processGetRequest(maxRespTimenUrl, qryMaxTimeReq, false))
t.Run("Delete - query-max-response ", processDeleteRequest(maxRespTimenUrl))
t.Run("Verify: Delete - query-max-response ", processGetRequest(maxRespTimenUrl, "{\"openconfig-network-instance-deviation:query-max-response-time\":0}", false))
//PATCH - query-interval
t.Run("PATCH - query-interval ", processSetRequest(qryIntvlUrl, qryIntvlReq, "PATCH", false))
t.Run("Verify: PATCH - query-interval ", processGetRequest(qryIntvlUrl, qryIntvlReq, false))
t.Run("Delete - query-interval ", processDeleteRequest(qryIntvlUrl))
t.Run("Verify: Delete - query-interval", processGetRequest(qryIntvlUrl, "{\"openconfig-network-instance-deviation:query-interval\":0}", false))
}
func TestIGMPSnoopingConfigPutDeleteGetAPIs(t *testing.T) {
clearDb()
//PUT - config container
t.Run("PUT - Config container", processSetRequest(configUrl, configNodeReq, "PUT", false))
t.Run("Verify: PUT - Config container", processGetRequest(configUrl, configNodeReq, false))
t.Run("Delete - Config container", processDeleteRequest(igmpsIntfUrl))
t.Run("Verify: Delete - Config container", processGetRequest(configUrl, "{\"openconfig-network-instance-deviation:config\":{\"name\":\"Vlan5\"}}", true))
//PUT - mrouter
t.Run("PUT - mrouter", processSetRequest(mrouterUrl, mrouterReq, "PUT", false))
t.Run("Verify: PUT - mrouter", processGetRequest(mrouterUrl, mrouterReq, false))
t.Run("Delete - mrouterr", processDeleteRequest(mrouterUrl))
t.Run("Verify: Delete - mrouter", processGetRequest(mrouterUrl, "{}", true))
//PUT - static-group
t.Run("PUT - static group", processSetRequest(staticGrpUrl, staticGroupReq, "PUT", false))
t.Run("Verify: PUT - static group", processGetRequest(staticGrpUrl, staticGroupReq, false))
t.Run("Delete - static group", processDeleteRequest(staticGrpUrl))
t.Run("Verify: Delete - static group", processGetRequest(staticGrpUrl, "{}", true))
//PUT - static-group only
t.Run("PUT - static-group only", processSetRequest(staticGrpUrl, staticGroupOnlyReq, "PUT", false))
t.Run("Verify: PUT - static-group only", processGetRequest(staticGrpUrl, staticGroupOnlyReq, false))
t.Run("Delete - static-group only", processDeleteRequest(staticGrpUrl))
t.Run("Verify: Delete - static-group only", processGetRequest(staticGrpUrl, "", true))
//PUT - static-group intf only
t.Run("PUT - PUT static-group intf only", processSetRequest(staticGrpUrl, staticGroupOnlyReq, "PUT", false))
t.Run("Verify: PUT - static-group intf only", processGetRequest(staticGrpUrl, staticGroupOnlyReq, false))
grpUrl := staticGrpUrl + "[group=1.2.3.4]"
t.Run("PUT - static-group intf only", processSetRequest(grpUrl+"/outgoing-interface", staticGroupIntfReq, "PUT", false))
t.Run("Verify: PUT - static-group intf only", processGetRequest(grpUrl+"/outgoing-interface", staticGroupIntfReq, false))
t.Run("Delete - static-group intf only ", processDeleteRequest(grpUrl+"/outgoing-interface"))
t.Run("Verify: Delete - static-group intf only ", processGetRequest(grpUrl+"/outgoing-interface", "", true))
t.Run("Delete - static-group", processDeleteRequest(staticGrpUrl))
//PUT - igmps enable
t.Run("PUT - igmps enable ", processSetRequest(igmpsEnableUrl, igmpsEnableReq, "PUT", false))
t.Run("Verify: PUT - igmps enable ", processGetRequest(igmpsEnableUrl, igmpsEnableReq, false))
t.Run("Delete - igmps enable ", processDeleteRequest(igmpsEnableUrl))
t.Run("Verify: Delete - igmps enable ", processGetRequest(igmpsEnableUrl, "{\"openconfig-network-instance-deviation:enabled\":false}", false))
//PUT - fast-leave
t.Run("PUT - fast-leave ", processSetRequest(fastLeaveUrl, fastLeaveReq, "PUT", false))
t.Run("Verify: PUT - fast-leave ", processGetRequest(fastLeaveUrl, fastLeaveReq, false))
t.Run("Delete - fast-leave ", processDeleteRequest(fastLeaveUrl))
t.Run("Verify: Delete - fast-leave ", processGetRequest(fastLeaveUrl, "{\"openconfig-network-instance-deviation:fast-leave\":false}", false))
//PUT - querier
t.Run("PUT - querier", processSetRequest(querierUrl, querierReq, "PUT", false))
t.Run("Verify: PUT - querier", processGetRequest(querierUrl, querierReq, false))
t.Run("Delete - querier", processDeleteRequest(querierUrl))
t.Run("Verify: Delete - querier", processGetRequest(querierUrl, "{\"openconfig-network-instance-deviation:querier\":false}", false))
//PUT - last-memeber
t.Run("PUT - last-memeber ", processSetRequest(lastMemUrl, lastMemReq, "PUT", false))
t.Run("Verify: PUT - last-memeber ", processGetRequest(lastMemUrl, lastMemReq, false))
t.Run("Delete - last-memeber ", processDeleteRequest(lastMemUrl))
t.Run("Verify: Delete - last-memeber ", processGetRequest(lastMemUrl, "{\"openconfig-network-instance-deviation:last-member-query-interval\":0}", false))
//PUT - version
t.Run("PUT - version", processSetRequest(versionUrl, versionReq, "PUT", false))
t.Run("Verify: PUT - version", processGetRequest(versionUrl, versionReq, false))
t.Run("Delete - version", processDeleteRequest(versionUrl))
t.Run("Verify: Delete - version", processGetRequest(versionUrl, "{\"openconfig-network-instance-deviation:version\":0}", false))
//PUT - query-max-response
t.Run("PUT - query-max-response ", processSetRequest(maxRespTimenUrl, qryMaxTimeReq, "PUT", false))
t.Run("Verify: PUT - query-max-response ", processGetRequest(maxRespTimenUrl, qryMaxTimeReq, false))
t.Run("Delete - query-max-response ", processDeleteRequest(maxRespTimenUrl))
t.Run("Verify: Delete - query-max-response ", processGetRequest(maxRespTimenUrl, "{\"openconfig-network-instance-deviation:query-max-response-time\":0}", false))
//PUT - query-interval
t.Run("PUT - query-interval ", processSetRequest(qryIntvlUrl, qryIntvlReq, "PUT", false))
t.Run("Verify: PUT - query-interval ", processGetRequest(qryIntvlUrl, qryIntvlReq, false))
t.Run("Delete - query-interval ", processDeleteRequest(qryIntvlUrl))
t.Run("Verify: Delete - query-interval", processGetRequest(qryIntvlUrl, "{\"openconfig-network-instance-deviation:query-interval\":0}", false))
}
func TestIGMPSnoopingConfigNegativeAPIs(t *testing.T) {
clearDb()
var lastMemNegReq string = "{\"last-member-query-interval\":30000}"
var versionNegReq string = "{\"version\":10}"
var qryMaxTimeNegReq string = "{\"query-max-response-time\":11000}"
var qryIntvlNegReq string = "{\"query-interval\":126000}"
//PATCH - last-memeber
t.Run("PATCH - last-memeber ", processSetRequest(lastMemUrl, lastMemNegReq, "PATCH", true))
t.Run("Verify: PATCH - last-memeber ", processGetRequest(lastMemUrl, "{\"openconfig-network-instance-deviation:last-member-query-interval\":0}", false))
//PATCH - version
t.Run("PATCH - version", processSetRequest(versionUrl, versionNegReq, "PATCH", true))
t.Run("Verify: PATCH - version", processGetRequest(versionUrl, "{\"openconfig-network-instance-deviation:version\":0}", false))
//PATCH - query-max-response
t.Run("PATCH - query-max-response ", processSetRequest(maxRespTimenUrl, qryMaxTimeNegReq, "PATCH", true))
t.Run("Verify: PATCH - query-max-response ", processGetRequest(maxRespTimenUrl, "{\"openconfig-network-instance-deviation:query-max-response-time\":0}", false))
//PATCH - query-interval
t.Run("PATCH - query-interval ", processSetRequest(qryIntvlUrl, qryIntvlNegReq, "PATCH", true))
t.Run("Verify: PATCH - query-interval ", processGetRequest(qryIntvlUrl, "{\"openconfig-network-instance-deviation:query-interval\":0}", false))
t.Run("Verify: config container", processGetRequest(configUrl, "{\"openconfig-network-instance-deviation:config\":{\"name\":\"Vlan5\"}}", false))
}
func TestIGMPSnoopingStateGetAPIs(t *testing.T) {
clearDb()
// patch igmp snooping config.
t.Run("PATCH - Config container", processSetRequest(configUrl, configNodeReq, "PATCH", false))
t.Run("Verify: PATCH - Config container", processGetRequest(configUrl, configNodeReq, false))
//GET - state container
t.Run("Verify: GET - state container", processGetRequest(stateUrl, "{\"openconfig-network-instance-deviation:state\":{\"enabled\":true,\"fast-leave\":true,\"last-member-query-interval\":1001,\"mrouter-interface\":[\"Ethernet8\"],\"name\":\"Vlan5\",\"querier\":true,\"query-interval\":126,\"query-max-response-time\":11,\"version\":3}}", false))
//GET - state mrouter
//t.Run("Verify: GET - state mrouter", processGetRequest(mrouterStateUrl, mrouterReq, false))
//GET - state static-group
//t.Run("Verify: GET - state static-group ", processGetRequest(staticGrpStateUrl, staticGroupReq, false))
//GET - state static-group with keys
//t.Run("Verify: GET - state static-group with keys ", processGetRequest(staticGrpStateUrl+"=1.2.3.4,255.0.0.0", staticGroupReq, false))
//GET - state static-group intf
//t.Run("Verify: GET - state static-group intf only", processGetRequest(staticGrpStateUrl+"=1.2.3.4,255.0.0.0/outgoing-interface", staticGroupIntfReq, false))
//GET - state static-group intf with value
//t.Run("Verify: GET - state static-group intf only", processGetRequest(staticGrpStateUrl+"=1.2.3.4,255.0.0.0/outgoing-interface=Ethernet8", staticGroupIntfReq, false))
//GET - state igmp enable
t.Run("Verify: GET - state state container", processGetRequest(igmpsEnableStateUrl, igmpsEnableReq, false))
//GET - fast-leave
t.Run("Verify: GET - state mrouter", processGetRequest(fastLeaveStateUrl, fastLeaveReq, false))
//GET - querier
t.Run("Verify: GET - state querier", processGetRequest(querierStateUrl, querierReq, false))
//GET - last-memeber
t.Run("Verify: GET - state last-memeber ", processGetRequest(lastMemStateUrl, lastMemReq, false))
//GET - version
t.Run("Verify: GET - state version", processGetRequest(versionStateUrl, versionReq, false))
//GET - query-max-response
t.Run("Verify: GET - state query-max-response ", processGetRequest(maxRespTimenStateUrl, qryMaxTimeReq, false))
//GET - query-interval
t.Run("Verify: GET - state query-interval ", processGetRequest(qryIntvlStateUrl, qryIntvlReq, false))
}
func clearIgmpSnoopingDataFromConfigDb() error {
var err error
cgf_l2mc_tbl_ts := db.TableSpec{Name: "CFG_L2MC_TABLE"}
cgf_l2mc_mrouter_tbl_ts := db.TableSpec{Name: "CFG_L2MC_MROUTER_TABLE"}
cgf_l2mc_static_grp_tbl_ts := db.TableSpec{Name: "CFG_L2MC_STATIC_GROUP_TABLE"}
cgf_l2mc_static_mem_tbl_ts := db.TableSpec{Name: "CFG_L2MC_STATIC_MEMBER_TABLE"}
d := getConfigDb()
if d == nil {
err = errors.New("Failed to connect to config Db")
return err
}
if err = d.DeleteTable(&cgf_l2mc_tbl_ts); err != nil {
err = errors.New("Failed to delete CFG_L2MC_TABLE Table")
return err
}
if err = d.DeleteTable(&cgf_l2mc_mrouter_tbl_ts); err != nil {
err = errors.New("Failed to delete CFG_L2MC_MROUTER_TABLE Table")
return err
}
if err = d.DeleteTable(&cgf_l2mc_static_grp_tbl_ts); err != nil {
err = errors.New("Failed to delete CFG_L2MC_STATIC_GROUP_TABLE Table")
return err
}
if err = d.DeleteTable(&cgf_l2mc_static_mem_tbl_ts); err != nil {
err = errors.New("Failed to delete CFG_L2MC_STATIC_MEMBER_TABLE Table")
return err
}
return err
}
//config-URL
var igmpsIntfUrl string = "/openconfig-network-instance:network-instances/network-instance[name=default]/protocols/protocol[identifier=IGMP_SNOOPING][name=IGMP-SNOOPING]/openconfig-network-instance-deviation:igmp-snooping/interfaces/interface[name=Vlan5]"
var configUrl string = igmpsIntfUrl+"/config"
var mrouterUrl string = configUrl+"/mrouter-interface"
var staticGrpUrl string = configUrl+"/static-multicast-group"
var igmpsEnableUrl string = configUrl+"/enabled"
var fastLeaveUrl string = configUrl+"/fast-leave"
var querierUrl string = configUrl+"/querier"
var lastMemUrl string = configUrl+"/last-member-query-interval"
var versionUrl string = configUrl+"/version"
var maxRespTimenUrl string = configUrl+"/query-max-response-time"
var qryIntvlUrl string = configUrl+"/query-interval"
//state-URL
var stateUrl string = igmpsIntfUrl+"/state"
var mrouterStateUrl string = stateUrl+"/mrouter-interface"
var staticGrpStateUrl string = stateUrl+"/static-multicast-group"
var igmpsEnableStateUrl string = stateUrl+"/enabled"
var fastLeaveStateUrl string = stateUrl+"/fast-leave"
var querierStateUrl string = stateUrl+"/querier"
var lastMemStateUrl string = stateUrl+"/last-member-query-interval"
var versionStateUrl string = stateUrl+"/version"
var maxRespTimenStateUrl string = stateUrl+"/query-max-response-time"
var qryIntvlStateUrl string = stateUrl+"/query-interval"
//JSON data
var configNodeReq string = "{\"openconfig-network-instance-deviation:config\":{\"enabled\":true,\"fast-leave\":true,\"last-member-query-interval\":1001,\"mrouter-interface\":[\"Ethernet8\"],\"name\":\"Vlan5\",\"querier\":true,\"query-interval\":126,\"query-max-response-time\":11,\"static-multicast-group\":[{\"group\":\"1.2.3.4\",\"outgoing-interface\":[\"Ethernet8\"]}],\"version\":3}}"
var mrouterReq string = "{\"openconfig-network-instance-deviation:mrouter-interface\":[\"Ethernet8\"]}"
var staticGroupReq string = "{\"openconfig-network-instance-deviation:static-multicast-group\":[{\"group\":\"1.2.3.4\",\"outgoing-interface\":[\"Ethernet8\"]}]}"
var staticGroupOnlyReq string = "{\"openconfig-network-instance-deviation:static-multicast-group\":[{\"group\":\"1.2.3.4\"}]}"
var staticGroupIntfReq string = "{\"openconfig-network-instance-deviation:outgoing-interface\":[\"Ethernet8\"]}"
var igmpsEnableReq string = "{\"openconfig-network-instance-deviation:enabled\":true}"
var querierReq string = "{\"openconfig-network-instance-deviation:querier\":true}"
var fastLeaveReq string = "{\"openconfig-network-instance-deviation:fast-leave\":true}"
var lastMemReq string = "{\"openconfig-network-instance-deviation:last-member-query-interval\":1001}"
var versionReq string = "{\"openconfig-network-instance-deviation:version\":3}"
var qryMaxTimeReq string = "{\"openconfig-network-instance-deviation:query-max-response-time\":11}"
var qryIntvlReq string = "{\"openconfig-network-instance-deviation:query-interval\":126}"
|
lechium/tvOS145Headers
|
usr/libexec/identityservicesd/IDSRestoreMonitor.h
|
//
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
@class IMTimer, NSMapTable;
@interface IDSRestoreMonitor : NSObject
{
CDUnknownBlockType _timerBlock; // 8 = 0x8
IMTimer *_restoreTimer; // 16 = 0x10
NSMapTable *_actionByTarget; // 24 = 0x18
}
+ (id)sharedInstance; // IMP=0x00000001005cb584
- (void).cxx_destruct; // IMP=0x00000001005cbd60
@property(retain, nonatomic) NSMapTable *actionByTarget; // @synthesize actionByTarget=_actionByTarget;
@property(retain, nonatomic) IMTimer *restoreTimer; // @synthesize restoreTimer=_restoreTimer;
@property(copy, nonatomic) CDUnknownBlockType timerBlock; // @synthesize timerBlock=_timerBlock;
- (void)_timerFired; // IMP=0x00000001005cba50
- (void)removeTarget:(id)arg1; // IMP=0x00000001005cb9a4
- (void)addTarget:(id)arg1 actionBlock:(CDUnknownBlockType)arg2; // IMP=0x00000001005cb87c
- (_Bool)hasActionForTarget:(id)arg1; // IMP=0x00000001005cb7f8
- (id)initWithTimerBlock:(CDUnknownBlockType)arg1; // IMP=0x00000001005cb700
@end
|
bonkydog/webhack
|
spec/lib/mulitplex_spec.rb
|
<gh_stars>1-10
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Multiplex do
class Adapter
include Multiplex
end
before do
@coming_down = FakeFile.new
@coming_up = FakeFile.new
@going_down = FakeFile.new
@going_up = FakeFile.new
[@coming_down, @coming_up, @going_down, @going_up].each {|s| stub(s).sync=(anything)}
@adapter = Adapter.new
@adapter.max_buffer_size = 4
end
describe "io" do
before do
@stream = FakeFile.new
stub(@stream).sysread(1) {[?X.to_i]}.subject
stub(@stream).sysread(@adapter.max_buffer_size) {"Xyzzy"}.subject
stub(@stream).syswrite
@buffer = []
end
describe "#read_if_ready" do
context "when stream is ready to be read" do
before do
@stream.ready = true
end
context "when buffer is not full" do
before do
@adapter.read_if_ready(@stream, @buffer)
end
it "should read a character from the stream" do
@stream.should have_received.sysread(1)
end
it "should append the character read from the stream to the buffer" do
@buffer.first.should == ?X
end
it "should mark the stream unready" do
@stream.should_not be_ready
end
end
context "when buffer is full" do
before do
@buffer = [?f, ?u, ?l, ?l]
@adapter.read_if_ready(@stream, @buffer)
end
it "should not change the buffer" do
@buffer == []
end
it "should not attempt to read from the stream" do
@stream.should_not have_received.sysread(anything)
end
end
end
context "when stream is not ready to be read" do
before do
@adapter.read_if_ready(@stream, @buffer)
end
it "should not change the buffer" do
@buffer == []
end
it "should not attempt to read from the stream" do
@stream.should_not have_received.sysread(anything)
end
end
end
describe "#read_string_if_ready" do
context "when stream is ready to be read" do
before do
@stream.ready = true
@result = @adapter.read_string_if_ready(@stream)
end
it "should try to read a bunch of characters from the stream" do
@stream.should have_received.sysread(@adapter.max_buffer_size)
end
it "should return the read characters as a string" do
@result.should == "Xyzzy"
end
it "should mark the stream unready" do
@stream.should_not be_ready
end
end
context "when stream is not ready to be read" do
before do
@stream.ready = false
@result = @adapter.read_string_if_ready(@stream)
end
it "should not attempt to read from the stream" do
@stream.should_not have_received.sysread(anything)
end
it "should return nil" do
@result.should be_nil
end
end
end
describe "#write_if_ready" do
context "when the buffer has characters" do
before do
@buffer = [?x, ?y, ?z, ?z, ?y]
end
context "when stream is ready to be written" do
before do
@stream.ready = true
@adapter.write_if_ready(@stream, @buffer)
end
it "should remove the character from the front of the buffer" do
@buffer.should == [?y, ?z, ?z, ?y]
end
it "should write the character at the front of the buffer to the stream" do
@stream.should have_received.syswrite('x')
end
it "should mark the stream unready" do
@stream.should_not be_ready
end
end
context "when stream is not ready to write" do
before do
@buffer = [?x, ?y, ?z, ?z, ?y]
@adapter.write_if_ready(@stream, @buffer)
end
it "should not change the buffer" do
@buffer == []
end
it "should not attempt to write to the stream" do
@stream.should_not have_received.syswrite(anything)
end
end
end
context "when the buffer is empty" do
before do
@stream.ready = true
@adapter.write_if_ready(@stream, @buffer)
end
it "should not change the buffer" do
@buffer == []
end
it "should not attempt to write to the stream" do
@stream.should_not have_received.syswrite(anything)
end
end
end
describe "#select_readable" do
context "when a stream is ready" do
before do
stub(IO).select([@coming_up, @coming_down], nil, nil, 1) {[[@coming_up], [], []]} # timeout should be 1 second
@adapter.select_readable([@coming_up, @coming_down])
end
it "should return mark the readable streams ready" do
@coming_up.should be_ready
end
it "should return not mark the unreadable streams ready" do
@coming_down.should_not be_ready
end
end
context "when no stream is ready" do
before do
stub(IO).select([@coming_up, @coming_down], nil, nil, 1) {nil} # timeout should be 1 second
@adapter.select_readable([@coming_up, @coming_down])
end
it "should return not mark the unreadable streams ready" do
@coming_up.should_not be_ready
@coming_down.should_not be_ready
end
end
end
describe "#select_writable" do
context "when a stream is ready" do
before do
stub(IO).select(nil, [@going_up, @going_down], nil, 0) {[[], [@going_up], []]} # timeout should be 0 seconds
@adapter.select_writable([@going_up, @going_down])
end
it "should return mark the writable streams ready" do
@going_up.should be_ready
end
it "should return not mark the unwritable streams ready" do
@going_down.should_not be_ready
end
end
context "when no stream is ready" do
before do
stub(IO).select(nil, [@going_up, @going_down], nil, 0) {nil} # timeout should be 0 seconds
@adapter.select_writable([@going_up, @going_down])
end
it "should return not mark the unwritable streams ready" do
@going_up.should_not be_ready
@going_down.should_not be_ready
end
end
end
end
end
|
pradeepkumarcm-egov/DIGIT-Dev
|
core-services/libraries/enc-client/src/main/java/org/egov/encryption/producer/Producer.java
|
package org.egov.encryption.producer;
import org.egov.tracer.kafka.CustomKafkaTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Producer {
@Autowired
private CustomKafkaTemplate<String, Object> kafkaTemplate;
public void push(String topic, String key, Object data) {
kafkaTemplate.send(topic, key, data);
}
}
|
georgianapopescu/Redmine
|
ruby/lib/ruby/gems/2.3.0/gems/roadie-rails-1.1.1/spec/support/have_no_styling_matcher.rb
|
RSpec::Matchers.define :have_no_styling do
chain(:at_selector) { |selector| @selector = selector }
match { |document|
@selector ||= 'body > *:first'
styles_at_selector(document).empty?
}
description {
"have no styles at selector #{@selector.inspect}"
}
failure_message { |document|
"expected no styles at #{@selector.inspect} but had:\n#{styles_at_selector(document)}"
}
failure_message_when_negated {
"expected #{@selector.inspect} to have styles"
}
def styles_at_selector(document)
expect(document).to have_selector(@selector)
document.at_css(@selector)['style'] || ""
end
end
|
laraharrow/looker-role-explorer-extension
|
node_modules/@looker/components/dist/esm/utils/useToggle.js
|
import { useState } from 'react';
export function useToggle(initialValue) {
if (initialValue === void 0) { initialValue = false; }
var _a = useState(initialValue), value = _a[0], setValue = _a[1];
var setOn = function () { return setValue(true); };
var setOff = function () { return setValue(false); };
var toggle = function () { return setValue(!value); };
return { setOff: setOff, setOn: setOn, toggle: toggle, value: value };
}
//# sourceMappingURL=useToggle.js.map
|
rackeric/rack
|
commands/serverscommands/instancecommands/rebuild_test.go
|
package instancecommands
import (
"flag"
"fmt"
"net/http"
"testing"
"github.com/rackspace/rack/handler"
"github.com/rackspace/rack/internal/github.com/codegangsta/cli"
"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig"
"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/rackspace/compute/v2/servers"
th "github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/testhelper"
"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/testhelper/client"
)
func TestRebuildContext(t *testing.T) {
cmd := &commandRebuild{
Ctx: &handler.Context{},
}
expected := cmd.Ctx
actual := cmd.Context()
th.AssertDeepEquals(t, expected, actual)
}
func TestRebuildKeys(t *testing.T) {
cmd := &commandRebuild{}
expected := keysRebuild
actual := cmd.Keys()
th.AssertDeepEquals(t, expected, actual)
}
func TestRebuildServiceClientType(t *testing.T) {
cmd := &commandRebuild{}
expected := serviceClientType
actual := cmd.ServiceClientType()
th.AssertEquals(t, expected, actual)
}
func TestRebuildHandleFlags(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/servers/detail", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, `{"servers":[{"ID":"server1","Name":"server1Name"}]}`)
})
app := cli.NewApp()
flagset := flag.NewFlagSet("flags", 1)
flagset.String("id", "", "")
flagset.String("image-id", "", "")
flagset.String("admin-pass", "", "")
flagset.String("ipv4", "", "")
flagset.String("ipv6", "", "")
flagset.String("metadata", "", "")
flagset.String("rename", "", "")
flagset.Set("id", "server1")
flagset.Set("image-id", "123456789")
flagset.Set("admin-pass", "<PASSWORD>")
flagset.Set("ipv4", "172.16.17.32")
flagset.Set("metadata", "img=bar,flavor=foo")
flagset.Set("rename", "server1Rename")
c := cli.NewContext(app, flagset, nil)
cmd := &commandRebuild{
Ctx: &handler.Context{
CLIContext: c,
},
}
expected := &handler.Resource{
Params: ¶msRebuild{
opts: &servers.RebuildOpts{
ImageID: "123456789",
AdminPass: "<PASSWORD>",
AccessIPv4: "172.16.17.32",
Metadata: map[string]string{
"img": "bar",
"flavor": "foo",
},
Name: "server1Rename",
},
serverID: "server1",
},
}
actual := &handler.Resource{}
err := cmd.HandleFlags(actual)
th.AssertNoErr(t, err)
th.AssertDeepEquals(t, *expected.Params.(*paramsRebuild).opts, *actual.Params.(*paramsRebuild).opts)
}
func TestRebuildExecute(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
th.Mux.HandleFunc("/servers/server1/action", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, `{"server":{}}`)
})
cmd := &commandRebuild{
Ctx: &handler.Context{
ServiceClient: client.ServiceClient(),
},
}
actual := &handler.Resource{
Params: ¶msRebuild{
serverID: "server1",
opts: &servers.RebuildOpts{
Name: "server1Rename",
ImageID: "123456789",
AdminPass: "<PASSWORD>",
DiskConfig: diskconfig.Auto,
},
},
}
cmd.Execute(actual)
th.AssertNoErr(t, actual.Err)
}
|
kenone/mindy
|
src/components/Icons/cross.js
|
<gh_stars>0
import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faTimes } from '@fortawesome/free-solid-svg-icons'
const Cross = () => {
return <FontAwesomeIcon icon={faTimes} />
}
export default Cross
|
aryanmaurya1/ArvernOS
|
docs/search/functions_12.js
|
<gh_stars>10-100
var searchData=
[
['udp_5freceive_5fpacket_0',['udp_receive_packet',['../udp_8h.html#a1e9dad20351b1ebb8b51196d2563c591',1,'udp.c']]],
['udp_5fsend_5fpacket_1',['udp_send_packet',['../udp_8h.html#ac78d90d0d505eb6b507d0cf93c7499fb',1,'udp.c']]],
['unmap_2',['unmap',['../paging_8h.html#a2556847794baa9bcb9be757f7f67f6b4',1,'paging.c']]],
['unmap_5fmultiple_3',['unmap_multiple',['../paging_8h.html#aaf4d9db68debae8e51bab96105966d07',1,'paging.c']]]
];
|
xmar/pythran
|
third_party/boost/simd/arch/common/simd/function/shift_left.hpp
|
//==================================================================================================
/**
Copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SHIFT_LEFT_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SHIFT_LEFT_HPP_INCLUDED
#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/detail/assert_utils.hpp>
#include <boost/simd/detail/overload.hpp>
#include <boost/simd/detail/brigand.hpp>
#include <boost/simd/detail/traits.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
namespace boost { namespace simd { namespace ext
{
namespace bs = boost::simd;
namespace bd = boost::dispatch;
BOOST_DISPATCH_OVERLOAD_IF( shift_left_
, (typename A0, typename A1, typename X)
, (detail::is_native<X>)
, bd::cpu_
, bs::pack_<bd::floating_<A0>,X>
, bd::scalar_<bd::fundamental_<A1>>
)
{
BOOST_FORCEINLINE A0 operator()(const A0& a0, const A1& a1) const BOOST_NOEXCEPT
{
BOOST_ASSERT_MSG(assert_good_shift<A0>(a1), "shift_left: a shift is out of range");
return bitwise_cast<A0> ( shift_left( bitwise_cast<bd::as_integer_t<A0, signed>>(a0)
, bd::as_integer_t<A0>(a1)
)
);
}
};
} } }
#endif
|
TopEngineer0926/360platform
|
src/views/WebAppManager/Owners/OwnerEdit.js
|
<filename>src/views/WebAppManager/Owners/OwnerEdit.js
import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import { Avatar } from '@material-ui/core';
import MySelect from '../../../components/MySelect';
import MyButton from 'components/MyButton';
import Badge from '@material-ui/core/Badge';
import EditOutlinedIcon from '@material-ui/icons/EditOutlined';
import authService from '../../../services/authService.js';
import AddCircleOutlineIcon from '@material-ui/icons/AddCircleOutline';
import { Checkbox } from '@material-ui/core';
import IdCard from 'components/IdCard';
import { EditOwnerStyles as useStyles } from './useStyles';
import CircularProgress from '@material-ui/core/CircularProgress';
import { ToastsContainer, ToastsContainerPosition, ToastsStore } from 'react-toasts';
import AdminService, { ManagerService as Service } from '../../../services/api.js';
import RemoveCircleOutlineIcon from '@material-ui/icons/RemoveCircleOutline';
import DeleteConfirmDialog from 'components/DeleteConfirmDialog';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import MuiPhoneNumber from 'material-ui-phone-number';
import useGlobal from'Global/global';
const ManagerService = new Service();
const validEmailRegex = RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);
const fileTypes = [
"image/apng",
"image/bmp",
"image/gif",
"image/jpeg",
"image/pjpeg",
"image/png",
"image/svg+xml",
"image/tiff",
"image/webp",
"image/x-icon"
];
function validFileType(file) {
return fileTypes.includes(file.type);
}
const OwnerEdit = (props) => {
const { history } = props;
const token = authService.getToken();
if (!token) {
window.location.replace("/login");
}
const [globalState, globalActions] = useGlobal();
const accessOwners = authService.getAccess('role_owners');
const [state, setState] = useState(false);
const classes = useStyles();
const titleList = ['', 'Mr', 'Mme', 'Mr et Mme', 'Société', 'Indivision', 'PACS'];
const en_titleList = ['', 'Mr', 'Mrs', 'Mr & Mrs', 'Company', 'Indivision', 'PACS']
const [companyID, setCompanyID] = useState(-1);
const [suspendState, setSuspendState] = useState('Suspendre le compte');
const [openDelete, setOpenDelete] = useState(false);
const [deleteId, setDeleteId] = useState(-1);
const [openDelete1, setOpenDelete1] = useState(false);
const [removeBranchID, setRemoveBranchID] = useState(-1);
const [building, setBuilding] = useState(['']);
const [buildings, setBuildings] = useState(0);
const [buildingList, setBuildingList] = useState([]);
const [buildingID, setBuildingID] = useState(-1);
const [postalCode, setPostalCode] = React.useState('');
const [visibleIndicator, setVisibleIndicator] = useState(false);
const [isSubAccount, setIsSubAccount] = useState(false);
const [isMemberCouncil, setIsMemberCouncil] = useState(false);
const [avatarurl, setAvatarUrl] = useState("");
const [avatar, setAvatar] = useState(null);
const [idcardurls, setIdcardUrls] = useState([]);
const [idcards, setIdcards] = useState([]);
const [ownerTitle, setOwnerTitle] = useState(0);
const [lastname, setLastName] = useState('');
const [firstname, setFirstName] = useState('');
const [lastname1, setLastName1] = useState('');
const [firstname1, setFirstName1] = useState('');
const [email, setEmail] = useState('');
const [phonenumber, setPhoneNumber] = useState('');
const [address, setAddress] = useState('');
const [city, setCity] = useState('');
const [apartNumber, setApartNumber] = useState([]);
const [companyName, setCompanyName] = useState('');
const [errorsBuildings, setErrorsBuildings] = useState('');
const [errorsOwnerTitle, setErrorsOwnerTitle] = useState('');
const [errorsLastname, setErrorsLastname] = useState('');
const [errorsFirstname, setErrorsFirstname] = useState('');
const [errorsLastname1, setErrorsLastname1] = useState('');
const [errorsFirstname1, setErrorsFirstname1] = useState('');
const [errorsEmail, setErrorsEmail] = useState('');
const [errorsPhonenumber, setErrorsPhonenumber] = useState('');
const [errorsAddress, setErrorsAddress] = useState('');
const [errorsCity, setErrorsCity] = useState('');
const [errorsCompanyName, setErrorsCompanyName] = useState('');
const [errorsLotsList, setErrorsLotsList] = useState('');
const [errorsLot, setErrorsLot] = useState('');
const [errorsPostalCode, setErrorsPostalCode] = React.useState('');
const [lotsList, setLotsList] = useState([]);
const [stateLots, setStateLots] = useState(false);
const [buildingVote, setBuildingVote] = useState([]);
const [stripeCustomerID, setStripeCustomerID] = useState('');
const [voteAmount, setVoteAmount] = useState(Array.from({ length: 100 }, () => Array.from({ length: buildingVote.length }, () => null)));
let voteLists = [];
const [count, setCount] = useState(0);
const handleClick = () => {
history.goBack();
};
const handleClickSave = () => {
let cnt = 0;
if (ownerTitle === 0) { setErrorsOwnerTitle('please enter owner title'); cnt++; }
else setErrorsOwnerTitle('');
if (ownerTitle === 4) {
if (companyName.length === 0) { setErrorsCompanyName('please enter company name'); cnt++; }
else setErrorsCompanyName('');
} else if (ownerTitle === 3 || ownerTitle === 6) {
if (lastname.length === 0) { setErrorsLastname('please enter owner last name'); cnt++; }
else setErrorsLastname('');
if (firstname.length === 0) { setErrorsFirstname('please enter owner first name'); cnt++; }
else setErrorsFirstname('');
if (lastname1.length === 0) { setErrorsLastname1('please enter owner last name'); cnt++; }
else setErrorsLastname1('');
if (firstname1.length === 0) { setErrorsFirstname1('please enter owner first name'); cnt++; }
else setErrorsFirstname1('');
}
else {
if (lastname.length === 0) { setErrorsLastname('please enter owner last name'); cnt++; }
else setErrorsLastname('');
if (firstname.length === 0) { setErrorsFirstname('please enter owner first name'); cnt++; }
else setErrorsFirstname('');
}
if (buildingID === -1) { setErrorsBuildings('please select buildings'); cnt++; }
else setErrorsBuildings('');
if (email.length === 0) { setErrorsEmail('please enter owner email'); cnt++; }
else setErrorsEmail('');
if (phonenumber.length === 0) { setErrorsPhonenumber('please enter owner phone number'); cnt++; }
else setErrorsPhonenumber('');
if (address.length === 0) { setErrorsAddress('please enter address'); cnt++; }
else setErrorsAddress('');
if (city.length === 0) { setErrorsCity('please enter city'); cnt++; }
else setErrorsCity('');
if (postalCode.length !== 5) { setErrorsPostalCode('please check postal code'); cnt++; }
else setErrorsPostalCode('');
if (isSubAccount === false) {
if (count === 0) { setErrorsLotsList('please add a Lot at least'); cnt++; }
else setErrorsLotsList('');
if (apartNumber.length === 0) { setErrorsLot('please input a Lot'); cnt++; }
else setErrorsLot('');
} else {
setErrorsLotsList('');
setErrorsLot('');
}
if (cnt === 0) {
updateOwner();
}
}
const handleLoadFront = (event) => {
if (event.target.files[0] !== undefined) {
if (validFileType(event.target.files[0])) {
if (event.target.files[0].size > 5 * 1048576) {
ToastsStore.warning('Image size should be low than 5 MB.');
} else {
setAvatar(event.target.files[0]);
setAvatarUrl(URL.createObjectURL(event.target.files[0]));
}
}
else {
ToastsStore.warning('Image format is not correct.');
}
}
}
const handleLoadIdcard = (event) => {
if (event.target.files[0] !== undefined) {
if (validFileType(event.target.files[0])) {
if (event.target.files[0].size > 5 * 1048576) {
ToastsStore.warning('Image size should be low than 5 MB.');
} else {
idcardurls.push(URL.createObjectURL(event.target.files[0]));
idcards.push(event.target.files[0])
setIdcards(idcards);
setIdcardUrls(idcardurls);
setState(!state);
}
}
else {
ToastsStore.warning('Image format is not correct.');
}
}
}
const handleClickCloseIdcard = (num) => {
delete idcardurls[num];
delete idcards[num];
// idcardurls.splice(num, 1);
// idcards.splice(num, 1);
setIdcards(idcards);
setIdcardUrls(idcardurls);
setState(!state);
}
const handleChangeApartNumber = (event, i) => {
let apartment = [...apartNumber];
apartment[i] = event.target.value;
setApartNumber(apartment);
}
const handleChangeVoteAmount = (event, i, j) => {
let voteamount = [...voteAmount];
voteamount[i][j] = +event.target.value;
setVoteAmount(voteamount);
}
const handleChangeIsSubAccount = (event) => {
setIsSubAccount(event.target.checked);
if (isSubAccount)
setIsMemberCouncil(!isSubAccount);
else
setIsMemberCouncil(isSubAccount);
}
const handleChangeIsMemberCouncil = (event) => {
setIsMemberCouncil(event.target.checked);
if (event.target.checked) {
setCount(0);
setVoteAmount(Array.from({ length: 100 }, () => Array.from({ length: buildingVote.length }, () => null)));
setApartNumber([]);
setLotsList([]);
setStateLots(!stateLots);
}
if (isMemberCouncil)
setIsSubAccount(!isMemberCouncil);
else
setIsSubAccount(isMemberCouncil);
}
const handleChangeOwnerTitle = (val) => {
setOwnerTitle(Number(val));
}
const handleChangeLastName = (event) => {
setLastName(event.target.value);
}
const handleChangeFirstName = (event) => {
setFirstName(event.target.value);
}
const handleChangeLastName1 = (event) => {
setLastName1(event.target.value);
}
const handleChangeFirstName1 = (event) => {
setFirstName1(event.target.value);
}
const handleChangeCompanyName = (event) => {
setCompanyName(event.target.value);
}
const handleChangeEmail = (event) => {
event.preventDefault();
let errorsMail =
validEmailRegex.test(event.target.value)
? ''
: 'Email is not valid!';
setEmail(event.target.value);
setErrorsEmail(errorsMail);
}
const handleChangePhoneNumber = (val) => {
setPhoneNumber(val);
}
const handleChangeAddress = (event) => {
setAddress(event.target.value);
}
const handleChangeCity = (event) => {
setCity(event.target.value);
}
const handleChangePostalCode = (event) => {
if (event.target.value[event.target.value.length - 1] === '.')
return;
if (Number.isInteger(Number(event.target.value))) {
if (event.target.value.length < 6)
setPostalCode(event.target.value);
}
}
const handleChangeBuildings = (val) => {
setBuildings(val);
setBuildingID(buildingList[val].buildingID);
};
const handleClickAddLots = (event) => {
setCount(count + 1);
lotsList.push(buildingVote);
setLotsList(lotsList);
setStateLots(!stateLots);
}
const handleClickRemoveLot = (num) => {
setOpenDelete1(true);
setRemoveBranchID(num);
}
useEffect(() => {
if (accessOwners !== 'denied') {
getCompanies();
}
}, [accessOwners]);
const getCompanies = () => {
setVisibleIndicator(true);
ManagerService.getCompanyListByUser()
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
const data = response.data.data;
localStorage.setItem("token", JSON.stringify(data.token));
data.companylist.map((item) => (
setCompanyID(item.companyID)
)
);
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
ToastsStore.error('Cant connect to the server!');
setVisibleIndicator(false);
}
);
}
useEffect(() => {
getBuildings();
console.log('companyID:', companyID);
}, [companyID])
const getBuildings = () => {
let params = new URLSearchParams(window.location.search);
const requestData = {
'companyID': companyID
}
setVisibleIndicator(true);
ManagerService.getBuildingListByCompany(requestData)
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
const data = response.data.data;
localStorage.setItem("token", JSON.stringify(data.token));
building.splice(0, building.length)
data.buildinglist.map((item) => (
building.push(item.name)
)
);
// buildingList.push(...data.buildinglist);
setBuildingList(...data.buildinglist);
setBuilding(building);
setBuildingID(params.get('buildingID'));
for (let i = 0; i < data.buildinglist.length; i++)
if (data.buildinglist[i].buildingID == params.get('buildingID')) {
setBuildings(i);
}
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
ToastsStore.error("Can't connect to the server!");
setVisibleIndicator(false);
}
);
}
useEffect(() => {
getBuilding();
console.log('buildingList:', buildingList);
}, [buildingList]);
const getBuilding = () => {
let params = new URLSearchParams(window.location.search);
setVisibleIndicator(true);
ManagerService.getBuilding(params.get('buildingID'))
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
buildingVote.splice(0, buildingVote.length)
const data = response.data.data;
localStorage.setItem("token", JSON.stringify(data.token));
const vote_list = data.vote_list;
vote_list.map((vote, i) =>
buildingVote.push(vote)
)
setBuildingVote(buildingVote);
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
ToastsStore.error("Can't connect to the server!");
setVisibleIndicator(false);
}
);
};
useEffect(() => {
getOwner()
console.log('buildingVote:', buildingVote);
}, [buildingVote])
const getVoteList = () => {
for (let i = 0; i < apartNumber.length; i++) {
let votes = [];
for (let j = 0; j < voteAmount[i].length; j++) {
const vote = {
'voteID': buildingVote[j].voteID,
'vote_amount': voteAmount[i][j]
}
votes.push(vote);
}
const voteList = {
'apartment_number': apartNumber[i],
'vote': votes
}
voteLists.push(voteList);
}
}
const updateOwner = () => {
let params = new URLSearchParams(window.location.search);
getVoteList();
let formdata = new FormData();
formdata.set('type', en_titleList[ownerTitle]);
formdata.set('email', email);
formdata.set('owner_role', isSubAccount ? 'subaccount' : isMemberCouncil ? 'member' : 'owner');
formdata.set('buildingID', buildingID);
formdata.set('firstname', firstname);
formdata.set('lastname', lastname);
formdata.set('firstname_1', firstname1);
formdata.set('lastname_1', lastname1);
formdata.set('owner_company_name', companyName);
formdata.set('address', address);
formdata.set('city', city);
formdata.set('code_postal', postalCode);
formdata.set('phone', phonenumber);
formdata.set('photo_url', avatar === null ? '' : avatar)
formdata.set('id_card_front', idcards[0] === null ? '' : idcards[0])
formdata.set('id_card_back', idcards[1] === null ? '' : idcards[1])
formdata.set('vote_value_list', JSON.stringify(voteLists));
formdata.set('stripe_customerID', stripeCustomerID);
setVisibleIndicator(true);
ManagerService.updateOwner(params.get('id'), formdata)
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
const data = response.data.data;
localStorage.setItem("token", JSON.stringify(data.token));
ToastsStore.success("Updated Successfully!");
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
ToastsStore.error("Can't connect to the server!");
setVisibleIndicator(false);
}
);
}
const getOwner = () => {
let params = new URLSearchParams(window.location.search);
var data = {};
data['ID'] = params.get('id');
data['buildingID'] = params.get('buildingID');
setVisibleIndicator(true);
ManagerService.getOwner(params.get('id'), data)
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
const data = response.data.data;
localStorage.setItem("token", JSON.stringify(data.token));
const ownerInfo = data.owner.ownerInfo;
const apartmentInfo = data.owner.apartment_info;
const amountInfo = data.owner.amount_info;
setOwnerTitle(en_titleList.indexOf(ownerInfo.usertype));
if (ownerInfo.usertype === 'Company') {
setCompanyName(ownerInfo.owner_company_name);
} else if (ownerInfo.usertype === 'Mr & Mrs' || ownerInfo.usertype === 'PACS') {
setFirstName(ownerInfo.firstname);
setLastName(ownerInfo.lastname);
setFirstName1(ownerInfo.firstname_1);
setLastName1(ownerInfo.lastname_1);
}
else {
setFirstName(ownerInfo.firstname);
setLastName(ownerInfo.lastname);
}
setEmail(ownerInfo.email);
setPhoneNumber(ownerInfo.phone);
setAddress(ownerInfo.address);
setCity(ownerInfo.city ? ownerInfo.city : '');
setPostalCode(ownerInfo.code_postal ? ownerInfo.code_postal : '');
setStripeCustomerID(ownerInfo.customerID ? ownerInfo.customerID : '');
if (ownerInfo.owner_role === 'subaccount') {
setIsSubAccount(true);
setIsMemberCouncil(false);
} else if (ownerInfo.owner_role === 'member') {
setIsMemberCouncil(true);
setIsSubAccount(false);
} else if (ownerInfo.owner_role === 'owner') {
setIsMemberCouncil(false);
setIsSubAccount(false);
}
setAvatarUrl(ownerInfo.photo_url);
if (ownerInfo.status === 'active') setSuspendState('Suspendre le compte');
else if (ownerInfo.status === 'inactive') setSuspendState('Restaurer le compte');
let urls = [];
let apartment = [...apartNumber];
let apartmentId = [];
if (!(ownerInfo.identity_card_front === null || ownerInfo.identity_card_front === '' || ownerInfo.identity_card_front === undefined))
urls.push(ownerInfo.identity_card_front);
if (!(ownerInfo.identity_card_back === null || ownerInfo.identity_card_back === '' || ownerInfo.identity_card_back === undefined))
urls.push(ownerInfo.identity_card_back);
setIdcardUrls(urls);
for (let i = 0; i < apartmentInfo.length; i++) {
apartment.push(apartmentInfo[i].apartment_number);
apartmentId.push(apartmentInfo[i].apartmentID);
}
lotsList.splice(0, lotsList.length);
for (let i = 0; i < apartmentId.length; i++) {
for (let j = 0; j < amountInfo.length; j++)
if (amountInfo[j].apartmentID === apartmentId[i]) {
voteAmount[i].push(amountInfo[j].amount);
}
setVoteAmount(voteAmount);
setApartNumber(apartment);
lotsList.push(buildingVote);
}
console.log('lotslist:', lotsList)
setLotsList(lotsList);
setCount(lotsList.length)
setStateLots(!stateLots);
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
ToastsStore.error("Can't connect to the server!");
setVisibleIndicator(false);
}
);
}
const handleClickLoginAsOwner = () => {
let params = new URLSearchParams(window.location.search);
var data = {
'userID' : params.get('id'),
};
setVisibleIndicator(true);
AdminService.loginAs(data)
.then(
response => {
setVisibleIndicator(false);
if (response.data.code !== 200) {
ToastsStore.error(response.data.message);
} else {
let profile = response.data.data.profile;
globalActions.setFirstName(profile.firstname);
globalActions.setLastName(profile.lastname);
globalActions.setAvatarUrl(profile.photo_url);
localStorage.clear();
localStorage.setItem("token", JSON.stringify(response.data.data.token));
localStorage.setItem("firstlogin", JSON.stringify("false"));
localStorage.setItem("usertype", JSON.stringify(profile.usertype));
localStorage.setItem("select", JSON.stringify(0));
localStorage.setItem("login_as", JSON.stringify(profile.firstname + ' ' + profile.lastname));
if (!(profile.identity_card_front === null || profile.identity_card_front === "" || profile.identity_card_front === undefined)) {
if(profile.owner_role === 'subaccount'){
localStorage.setItem("role_addons", JSON.stringify('edit'));
localStorage.setItem("role_assemblies", JSON.stringify('denied'));
localStorage.setItem("role_chat", JSON.stringify('edit'));
localStorage.setItem("role_events", JSON.stringify('edit'));
localStorage.setItem("role_incidents", JSON.stringify('edit'));
localStorage.setItem("role_payments", JSON.stringify('edit'));
localStorage.setItem("role_invoices", JSON.stringify('edit'));
localStorage.setItem("idcard_state", JSON.stringify('true'));
}else{
localStorage.setItem("role_addons", JSON.stringify('edit'));
localStorage.setItem("role_assemblies", JSON.stringify('edit'));
localStorage.setItem("role_chat", JSON.stringify('edit'));
localStorage.setItem("role_events", JSON.stringify('edit'));
localStorage.setItem("role_incidents", JSON.stringify('edit'));
localStorage.setItem("role_payments", JSON.stringify('edit'));
localStorage.setItem("role_invoices", JSON.stringify('edit'));
localStorage.setItem("idcard_state", JSON.stringify('true'));
}
} else {
localStorage.setItem("role_addons", JSON.stringify('denied'));
localStorage.setItem("role_assemblies", JSON.stringify('denied'));
localStorage.setItem("role_chat", JSON.stringify('denied'));
localStorage.setItem("role_events", JSON.stringify('denied'));
localStorage.setItem("role_incidents", JSON.stringify('denied'));
localStorage.setItem("role_payments", JSON.stringify('denied'));
localStorage.setItem("role_invoices", JSON.stringify('denied'));
localStorage.setItem("idcard_state", JSON.stringify('false'));
}
window.location.replace("/owner/dashboard");
}
},
error => {
setVisibleIndicator(false);
ToastsStore.error("Can't connect to the Server!");
}
);
}
const handleClickResetPassword = () => {
var data = {};
data['email'] = email;
setVisibleIndicator(true);
ManagerService.forgotPassword(data)
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
ToastsStore.success(response.data.message);
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
setVisibleIndicator(false);
ToastsStore.error("Can't connect to the Server!");
}
);
}
const handleClickSuspendRestore = () => {
let data = {
'status': suspendState === 'Restaurer le compte' ? 'active' : 'inactive'
};
let params = new URLSearchParams(window.location.search);
setVisibleIndicator(true);
ManagerService.setSuspendOwner(params.get('id'), data)
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
const data = response.data.data;
localStorage.setItem("token", JSON.stringify(data.token));
if (suspendState === 'Restaurer le compte')
setSuspendState('Suspendre le compte');
else if (suspendState === 'Suspendre le compte')
setSuspendState('Restaurer le compte');
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
ToastsStore.error("Can't connect to the server!");
setVisibleIndicator(false);
}
);
}
const handleCloseDelete = () => {
setOpenDelete(false);
};
const handleCloseDelete1 = () => {
setOpenDelete1(false);
};
const handleDelete1 = () => {
handleCloseDelete1();
setCount(count - 1);
delete lotsList[removeBranchID];
lotsList.splice(removeBranchID, 1);
let voteamount = [...voteAmount];
delete voteamount[removeBranchID];
voteamount.splice(removeBranchID, 1);
setVoteAmount(voteamount);
let apartment = [...apartNumber];
delete apartment[removeBranchID];
apartment.splice(removeBranchID, 1);
setApartNumber(apartment);
setLotsList(lotsList);
setStateLots(!stateLots);
}
const handleClickDeleteOwner = () => {
setOpenDelete(true);
}
const handleDelete = () => {
let params = new URLSearchParams(window.location.search);
handleCloseDelete();
setDeleteId(-1);
setVisibleIndicator(true);
let data = {
'status': 'trash'
}
ManagerService.deleteOwner(params.get('id'), data)
.then(
response => {
setVisibleIndicator(false);
switch (response.data.code) {
case 200:
const data = response.data.data;
localStorage.setItem("token", JSON.stringify(data.token));
ToastsStore.success("Deleted successfully!");
history.goBack();
break;
case 401:
authService.logout();
history.push('/login');
window.location.reload();
break;
default:
ToastsStore.error(response.data.message);
}
},
error => {
ToastsStore.error("Can't connect to the server!");
setVisibleIndicator(false);
}
);
}
return (
<div className={classes.root}>
{
visibleIndicator ? <div className={classes.div_indicator}> <CircularProgress className={classes.indicator} /> </div> : null
}
<div className={classes.title}>
<Grid item container justify="space-around" alignItems="center">
<Grid item xs={12} sm={6} container justify="flex-start" >
<Grid item>
<Typography variant="h2" className={classes.headerTitle}>
<b>{companyName.length !== 0 ? companyName : firstname + ' ' + lastname}</b>
</Typography>
</Grid>
</Grid>
<Grid item xs={12} sm={6} container justify="flex-end" >
</Grid>
</Grid>
</div>
<div className={classes.tool}>
<p onClick={handleClick} className={classes.backTitle}>< Retour à la liste des Copropriétaires</p>
</div>
<Grid container direction="column" >
<div className={classes.body}>
<Grid item container><p className={classes.headerTitle}><b>Informations</b></p></Grid>
<Grid item container justify="space-between" direction="row-reverse" spacing={2}>
<Grid item>
<Grid container direction="column" spacing={2}>
<Grid item container direction="row-reverse">
<Badge
overlap="circle"
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
right: -20,
top: 10,
border: '2px solid gray',
padding: '1px 4px',
}}
badgeContent={
<div>
<input className={classes.input} accept="image/*" type="file" id="img_front" onChange={handleLoadFront} disabled={(accessOwners === 'see' ? true : false)} />
<label htmlFor="img_front">
<EditOutlinedIcon className={classes.editAvatar} />
</label>
</div>}
>
<Avatar className={classes.size} alt={firstname + ' ' + lastname} src={avatarurl} />
</Badge>
</Grid>
<Grid item container direction="row-reverse">
<MyButton
name={"Se connecter en tant que"}
color={"1"}
onClick={handleClickLoginAsOwner}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
<Grid item container direction="row-reverse">
<MyButton
name={"Réinitialiser le mot de passe"}
bgColor={"#00C9FF"}
onClick={handleClickResetPassword}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
<Grid item container direction="row-reverse">
<MyButton
name={suspendState}
bgColor={"#00C9FF"}
onClick={handleClickSuspendRestore}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
<Grid item container direction="row-reverse">
<MyButton
name={"Supprimer le compte"}
bgColor={"#00C9FF"}
onClick={handleClickDeleteOwner}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
</Grid>
</Grid>
<Grid item>
<Grid container direction="column" spacing={5}>
<Grid item></Grid>
<Grid item container alignItems="center" spacing={2}>
<Grid item><p className={classes.itemTitle}>Civilité</p></Grid>
<Grid xs item container direction="column">
<MySelect
color="gray"
data={titleList}
onChangeSelect={handleChangeOwnerTitle}
value={ownerTitle}
disabled={(accessOwners === 'see' ? true : false)}
/>
{errorsOwnerTitle.length > 0 &&
<span className={classes.error}>{errorsOwnerTitle}</span>}
</Grid>
</Grid>
{
ownerTitle === 4 ?
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Cabinet Nom</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={companyName}
onChange={handleChangeCompanyName}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsCompanyName.length > 0 &&
<span className={classes.error}>{errorsCompanyName}</span>}
</Grid>
</Grid>
: ownerTitle === 3 || ownerTitle === 6 ?
<Grid item container direction="column" spacing={5}>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Nom</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={lastname}
onChange={handleChangeLastName}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsLastname.length > 0 &&
<span className={classes.error}>{errorsLastname}</span>}
</Grid>
</Grid>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Prénom</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={firstname}
onChange={handleChangeFirstName}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsFirstname.length > 0 &&
<span className={classes.error}>{errorsFirstname}</span>}
</Grid>
</Grid>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Nom</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={lastname1}
onChange={handleChangeLastName1}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsLastname1.length > 0 &&
<span className={classes.error}>{errorsLastname1}</span>}
</Grid>
</Grid>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Prénom</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={firstname1}
onChange={handleChangeFirstName1}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsFirstname1.length > 0 &&
<span className={classes.error}>{errorsFirstname1}</span>}
</Grid>
</Grid>
</Grid>
:
<Grid item container direction="column" spacing={5}>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Nom</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={lastname}
onChange={handleChangeLastName}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsLastname.length > 0 &&
<span className={classes.error}>{errorsLastname}</span>}
</Grid>
</Grid>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Prénom</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={firstname}
onChange={handleChangeFirstName}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsFirstname.length > 0 &&
<span className={classes.error}>{errorsFirstname}</span>}
</Grid>
</Grid>
</Grid>
}
<Grid item container alignItems="center" spacing={1}>
<Grid item ><p className={classes.itemTitle}>Email</p></Grid>
<Grid xs item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={email}
onChange={handleChangeEmail}
disabled={(accessOwners === 'see' ? true : false)}
fullWidth
/>
{errorsEmail.length > 0 &&
<span className={classes.error}>{errorsEmail}</span>}
</Grid>
</Grid>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Téléphone</p></Grid>
<Grid xs item container>
<MuiPhoneNumber
defaultCountry='fr'
className={classes.text}
variant="outlined"
value={phonenumber}
onChange={handleChangePhoneNumber}
disabled={(accessOwners === 'see' ? true : false)}
/>
{errorsPhonenumber.length > 0 &&
<span className={classes.error}>{errorsPhonenumber}</span>}
</Grid>
</Grid>
<Grid item></Grid>
</Grid>
</Grid>
</Grid>
<Grid item container spacing={5}>
<Grid item container ></Grid>
<Grid item container spacing={1} direction="column">
<Grid item><p className={classes.itemTitle}>Adresse</p></Grid>
<Grid item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={address}
onChange={handleChangeAddress}
multiline
disabled={(accessOwners === 'see' ? true : false)}
style={{width:'50%'}}
/>
{errorsAddress.length > 0 &&
<span className={classes.error}>{errorsAddress}</span>}
</Grid>
</Grid>
<Grid item container spacing={1} direction="column">
<Grid item><p className={classes.itemTitle}>Code postal</p></Grid>
<Grid item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={postalCode}
onChange={handleChangePostalCode}
disabled={(accessOwners === 'see' ? true : false)}
style={{width:'50%'}}
/>
{errorsPostalCode.length > 0 &&
<span className={classes.error}>{errorsPostalCode}</span>}
</Grid>
</Grid>
<Grid item container spacing={1} direction="column">
<Grid item><p className={classes.itemTitle}>Ville</p></Grid>
<Grid item container direction="column">
<TextField
className={classes.text}
variant="outlined"
value={city}
onChange={handleChangeCity}
disabled={(accessOwners === 'see' ? true : false)}
style={{width:'50%'}}
/>
{errorsCity.length > 0 &&
<span className={classes.error}>{errorsCity}</span>}
</Grid>
</Grid>
<Grid item container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Immeuble</p></Grid>
<Grid item container direction="column">
<MySelect
color="gray"
data={building}
onChangeSelect={handleChangeBuildings}
value={buildings}
disabled={true}
width="50%"
disabled={(accessOwners === 'see' ? true : false)}
/>
{errorsBuildings.length > 0 &&
<span className={classes.error}>{errorsBuildings}</span>}
</Grid>
</Grid>
<Grid xs={6} item container justify="space-between" direction="row">
<Grid item>
<Grid container alignItems="center" spacing={1}>
<Grid item ><p className={classes.itemTitle}>Sous-compte</p></Grid>
<Grid xs item container>
<Checkbox
checked={isSubAccount}
onChange={handleChangeIsSubAccount}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
</Grid>
</Grid>
<Grid item>
<Grid container alignItems="center" spacing={1}>
<Grid item><p className={classes.itemTitle}>Membre du Conseil Syndical</p></Grid>
<Grid xs item container>
<Checkbox
checked={isMemberCouncil}
onChange={handleChangeIsMemberCouncil}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
</Grid>
</Grid>
</Grid>
<Grid item container direction="column" spacing={2}>
<Grid item>
{
stateLots !== null ?
<Grid item container direction="column" spacing={5}>
{
lotsList.map((lot, i) => {
return (
<Grid key={i} item container alignItems="center" spacing={3}>
<Grid item>
<Grid item container direction="column" spacing={3}>
<Grid item container alignItems="center" spacing={2}>
<Grid item><p className={classes.itemTitle}>Lot</p></Grid>
<Grid xs item container>
<TextField
className={classes.text}
variant="outlined"
value={apartNumber[i] || ''}
onChange={(event) => handleChangeApartNumber(event, i)}
style={{ width: 100 }}
disabled={(accessOwners === 'see' ? true : false)}
/>
{errorsLot.length > 0 &&
<span className={classes.error}>{errorsLot}</span>}
</Grid>
</Grid>
<Grid item><p className={classes.itemTitle}>Clé de répartition du lot</p></Grid>
<Grid item container direction="column" spacing={2} >
{
lot.map((vote1, j) => {
return (
<Grid key={j} item container alignItems="center" spacing={2}>
<Grid item><p className={classes.itemTitle}>{vote1.vote_branch_name} - {vote1.description}</p></Grid>
<Grid item >
<TextField
className={classes.text}
variant="outlined"
value={voteAmount[i][j] || ""}
onChange={(event) => handleChangeVoteAmount(event, i, j)}
style={{ width: 100 }}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
<Grid item><p className={classes.itemTitle}>tantièmes</p></Grid>
</Grid>
)
})
}
</Grid>
</Grid>
</Grid>
<Grid item>
<RemoveCircleOutlineIcon
className={classes.minus}
onClick={accessOwners === 'see' ? null : () => handleClickRemoveLot(i)}
/>
</Grid>
</Grid>
)
})
}
</Grid>
: null
}
</Grid>
<Grid item style={{ marginTop: 10, marginBottom: 10 }}>
<Grid item>
<MyButton
name={"Ajouter un lot"}
bgColor="grey"
onClick={isSubAccount ? null : handleClickAddLots}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
{errorsLotsList.length > 0 &&
<span className={classes.error}>{errorsLotsList}</span>}
</Grid>
</Grid>
<Grid xs={12} item container direction="column" style={{ marginTop: 30 }}>
<p className={classes.itemTitle}>Pièce d'identité</p>
<Grid item container justify="flex-start">
<IdCard
onClose={handleClickCloseIdcard}
idcardurls={idcardurls}
disabled={(accessOwners === 'see' ? true : false)}
state={state}
type="first"
badge="first"
/>
<input className={classes.input} accept="image/*" type="file" id="img_idcard" onChange={handleLoadIdcard} disabled={(accessOwners === 'see' ? true : false)} />
<label htmlFor="img_idcard">
{
<div className={classes.img}>
<AddCircleOutlineIcon className={classes.plus} />
</div>
}
</label>
</Grid>
</Grid>
</Grid>
<Grid item container style={{ paddingTop: '50px', paddingBottom: '50px' }}>
<MyButton
name={"Sauvegarder"}
color={"1"}
onClick={handleClickSave}
disabled={(accessOwners === 'see' ? true : false)}
/>
</Grid>
</div>
</Grid>
<DeleteConfirmDialog
openDelete={openDelete}
handleCloseDelete={handleCloseDelete}
handleDelete={handleDelete}
account={'owner'}
/>
<Dialog
open={openDelete1}
onClose={handleCloseDelete1}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
Delete Vote Branch
</DialogTitle>
<DialogContent>
Êtes-vous sur de vouloir supprimer les informations du lot ?
</DialogContent>
<DialogActions>
<Button autoFocus onClick={handleCloseDelete1} color="primary">
Cancel
</Button>
<Button onClick={handleDelete1} color="primary">
Delete
</Button>
</DialogActions>
</Dialog>
<ToastsContainer store={ToastsStore} position={ToastsContainerPosition.TOP_RIGHT} />
</div>
);
};
export default withRouter(OwnerEdit);
|
srl295/icu
|
richedit/classes/src/com/ibm/richtext/textapps/TestMTextToString.java
|
/*
* (C) Copyright IBM Corp. 1998-2004. All Rights Reserved.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/
package com.ibm.richtext.textapps;
import com.ibm.richtext.styledtext.MConstText;
import java.io.File;
public final class TestMTextToString {
static final String COPYRIGHT =
"(C) Copyright IBM Corp. 1998-1999 - All Rights Reserved";
public static void main(String[] args) {
if (args.length != 2 || args[0].equals(args[1])) {
usage();
}
else {
boolean success = testMTextToString(args[0], args[1]);
System.out.println(success? "PASSED" : "FAILED");
}
}
private static void usage() {
System.out.println("Usage: TestMTextToString mtextFile stringFile");
System.out.println("Compares the characters in mtextFile to the");
System.out.println("String in stringFile.");
System.exit(0);
}
public static boolean testMTextToString(String mtextFile, String stringFile) {
boolean success = false;
File mtext = new File(mtextFile);
MConstText text = FileUtils.loadMText(mtext);
if (text != null) {
String str = StringToMText.loadString(new File(stringFile));
if (str != null) {
success = compareMTextToString(text, str);
}
else {
System.out.println("Couldn't load String.");
}
}
else {
System.out.println("Couldn't load MText.");
}
return success;
}
public static boolean compareMTextToString(MConstText text, String str) {
if (text.length() != str.length()) {
return false;
}
for (int i=str.length()-1; i >= 0; i--) {
if (text.at(i) != str.charAt(i)) {
return false;
}
}
return true;
}
}
|
OneFlying/searchweb
|
src/main/java/com/yf/dao/AdvertDao.java
|
package com.yf.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.yf.model.Advert;
import com.yf.utils.RowMapperUtil;
@Repository("advertDao")
public class AdvertDao extends DaoAdapter{
private static RowMapper<Advert> advertRowMapper;
static {
advertRowMapper = new RowMapper<Advert>() {
public Advert mapRow(ResultSet rs, int rowNum) throws SQLException {
// TODO Auto-generated method stub
return (Advert)RowMapperUtil.getRowMapper(Advert.class, rs, "");
}
};
}
/**
* 保存广告信息
* @param advert
*/
public int saveAdvert(Advert advert){
try {
String sql = "insert into advert values(?,?,?,?,?,?)";
return super.getJdbcTemplate().update(sql,advert.getId(),advert.getTitle(),advert.getDesc(),advert.getPrice(),advert.getLogourl(),advert.getAdurl());
} catch (Exception e) {
// TODO: handle exception
return 0;
}
}
public int update(Advert advert){
try {
//desc见反引号是因为与数据库关键字冲突了 转义下
String sql = "update advert set title=?,`desc`=?,price=?,logourl=?,adurl=? where id=?";
return super.getJdbcTemplate().update(sql,advert.getTitle(),advert.getDesc(),advert.getPrice(),advert.getLogourl(),advert.getAdurl(),advert.getId());
} catch (Exception e) {
// TODO: handle exception
return 0;
}
}
public int delete(final String []ids){
String sql = "delete from advert where id=?";
return super.getJdbcTemplate().batchUpdate(sql,new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
// TODO Auto-generated method stub
ps.setString(1, ids[i]);
}
public int getBatchSize() {
// TODO Auto-generated method stub
return ids.length;
}
}).length;
}
public List<Advert> pageAdvert(SearchEntity searchEntity){
try {
String sql = searchEntity.toSql();
String totalSql = searchEntity.toPageTotalSql();
int total = 0;
if(searchEntity.getPageTotalSearchValues().size() <=0){
total = super.getJdbcTemplate().queryForInt(totalSql);
}else{
total = super.getJdbcTemplate().queryForInt(totalSql,searchEntity.getPageTotalSearchValues().toArray());
}
searchEntity.setTotal(total);
return super.getJdbcTemplate().query(sql, searchEntity.getSearchValues().toArray(),advertRowMapper);
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
public List<Advert> getAdvertsByTitle(String title){
try {
String sql = "select * from advert where title like ? order by price desc";
return super.getJdbcTemplate().query(sql,advertRowMapper,"%"+title+"%");
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
|
MaximilianKorn/opencast
|
modules/common/src/main/java/org/opencastproject/mediapackage/MediaPackageSerializer.java
|
<filename>modules/common/src/main/java/org/opencastproject/mediapackage/MediaPackageSerializer.java<gh_stars>100-1000
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community 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://opensource.org/licenses/ecl2.txt
*
* 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.opencastproject.mediapackage;
import java.net.URI;
import java.net.URISyntaxException;
public interface MediaPackageSerializer {
/**
* This method is called every time a url is being written to a media package manifest. By implementing this method,
* serializers are able to store package elements in directories relative to some common root folder, thereby making
* it movable.
*
* @param uri
* the url to encode
* @return the encoded path
* @throws URISyntaxException
* if the resulting URI contains syntax errors
*/
URI encodeURI(URI uri) throws URISyntaxException;
/**
* This method is called every time a url is being read from a media package manifest. By implementing this method,
* serializers are able to redirect urls to local caches which might make sense when it comes to dealing with huge
* media files.
*
* @param path
* the original path from the manifest
* @return the resolved url
* @throws URISyntaxException
* if the path cannot be converted into a url
* @throws URISyntaxException
* if the resulting URI contains syntax errors
*/
URI decodeURI(URI path) throws URISyntaxException;
/**
* Identifies the serializer ranking number. The ranking is respected when multiple serializers are chained. When
* encoding an URI, the serializer with the highest ranking is used first. If an URI needs to be decoded, the ranking
* is used in the opposite direction.
*
* @return The service ranking number.
*/
int getRanking();
}
|
matsukei/shirasagi
|
app/models/ss/file.rb
|
<gh_stars>0
class SS::File
include SS::File::Model
end
|
diekhans/kent
|
src/hg/lib/knownToSuper.c
|
/* knownToSuper.c was originally generated by the autoSql program, which also
* generated knownToSuper.h and knownToSuper.sql. This module links the database and
* the RAM representation of objects. */
/* Copyright (C) 2014 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#include "common.h"
#include "linefile.h"
#include "dystring.h"
#include "jksql.h"
#include "knownToSuper.h"
void knownToSuperStaticLoad(char **row, struct knownToSuper *ret)
/* Load a row from knownToSuper table into ret. The contents of ret will
* be replaced at the next call to this function. */
{
ret->gene = row[0];
ret->superfamily = sqlSigned(row[1]);
ret->start = sqlSigned(row[2]);
ret->end = sqlSigned(row[3]);
ret->eVal = atof(row[4]);
}
struct knownToSuper *knownToSuperLoad(char **row)
/* Load a knownToSuper from row fetched with select * from knownToSuper
* from database. Dispose of this with knownToSuperFree(). */
{
struct knownToSuper *ret;
AllocVar(ret);
ret->gene = cloneString(row[0]);
ret->superfamily = sqlSigned(row[1]);
ret->start = sqlSigned(row[2]);
ret->end = sqlSigned(row[3]);
ret->eVal = atof(row[4]);
return ret;
}
struct knownToSuper *knownToSuperLoadAll(char *fileName)
/* Load all knownToSuper from a whitespace-separated file.
* Dispose of this with knownToSuperFreeList(). */
{
struct knownToSuper *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[5];
while (lineFileRow(lf, row))
{
el = knownToSuperLoad(row);
slAddHead(&list, el);
}
lineFileClose(&lf);
slReverse(&list);
return list;
}
struct knownToSuper *knownToSuperLoadAllByChar(char *fileName, char chopper)
/* Load all knownToSuper from a chopper separated file.
* Dispose of this with knownToSuperFreeList(). */
{
struct knownToSuper *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[5];
while (lineFileNextCharRow(lf, chopper, row, ArraySize(row)))
{
el = knownToSuperLoad(row);
slAddHead(&list, el);
}
lineFileClose(&lf);
slReverse(&list);
return list;
}
struct knownToSuper *knownToSuperCommaIn(char **pS, struct knownToSuper *ret)
/* Create a knownToSuper out of a comma separated string.
* This will fill in ret if non-null, otherwise will
* return a new knownToSuper */
{
char *s = *pS;
if (ret == NULL)
AllocVar(ret);
ret->gene = sqlStringComma(&s);
ret->superfamily = sqlSignedComma(&s);
ret->start = sqlSignedComma(&s);
ret->end = sqlSignedComma(&s);
ret->eVal = sqlFloatComma(&s);
*pS = s;
return ret;
}
void knownToSuperFree(struct knownToSuper **pEl)
/* Free a single dynamically allocated knownToSuper such as created
* with knownToSuperLoad(). */
{
struct knownToSuper *el;
if ((el = *pEl) == NULL) return;
freeMem(el->gene);
freez(pEl);
}
void knownToSuperFreeList(struct knownToSuper **pList)
/* Free a list of dynamically allocated knownToSuper's */
{
struct knownToSuper *el, *next;
for (el = *pList; el != NULL; el = next)
{
next = el->next;
knownToSuperFree(&el);
}
*pList = NULL;
}
void knownToSuperOutput(struct knownToSuper *el, FILE *f, char sep, char lastSep)
/* Print out knownToSuper. Separate fields with sep. Follow last field with lastSep. */
{
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->gene);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%d", el->superfamily);
fputc(sep,f);
fprintf(f, "%d", el->start);
fputc(sep,f);
fprintf(f, "%d", el->end);
fputc(sep,f);
fprintf(f, "%f", el->eVal);
fputc(lastSep,f);
}
/* -------------------------------- End autoSql Generated Code -------------------------------- */
|
maikelronnau/sistema_epti
|
Sistema EPTI/src/DAO/HistoricoComputadorDAO.java
|
package DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import modelo.HistoricoComputadorVO;
import persistencia.ConexaoBanco;
/**
* @author <NAME>
* @version 1.0
* @since 14/01/2015
*/
public class HistoricoComputadorDAO {
/**
* @author <NAME>
* @version 1.0
* @since 14/01/2015
* @param his Objeto com os dados a serem cadastrados
* @return ID da permissão cadastrada
* @throws SQLException Falha ao cadastrar histórico
*/
public long cadastrarHistoricoComputador(HistoricoComputadorVO his) throws SQLException {
//Conectando com o banco de dados:
Connection con = ConexaoBanco.getConnection();
//Fim da conexão com o banco de dados.
try {
//Variável para receber o comando SQL:
String sql;
//Atribuindo comando à variável:
sql = "insert into historicocomputador(idhistoricocomputador, dataentrada, horaentrada,"
+ "dataconclusao, horaconclusao, limpeza, backup, reparacaoso, instalacaoso, "
+ "substituicaohd, driverpack, trocadefonte, libreoffice, antivirus, navegadores, "
+ "java, adobereader, winrarflash, conversorespdf, firewallcentralseg, usuarios, "
+ "dominio, ultravnc, ativacaowindows, icones, historicocomputador) "
+ "values(null, now(), now(), null, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null)";
//Preparando insersão de dados:
PreparedStatement stat = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//Executando insersão:
stat.execute();
//Recebendo ID gerado:
ResultSet rs = stat.getGeneratedKeys();
//Preparando para receber o ID:
rs.next();
//Variável para receber o ID gerado:
long id = rs.getLong(1);
//Fechando conexão com o banco de dados:
stat.close();
//Retornando ID:
return id;
} catch (SQLException e) {
//Lançando erro:
throw new SQLException("Erro ao cadastrar hitórico!");
} finally {
//Fechando conexão:
con.close();
}//Fecha finally.
}//Fecha método cadastrarHistoricoComputador.
/**
* @author <NAME>
* @version 1.0
* @since 14/01/2015
* @param his Objeto com os dados a serem atualizados
* @throws SQLException Falha ao atualizar histórico
*/
public void atualizarHistoricoComputador(HistoricoComputadorVO his) throws SQLException {
//Conectando com o banco de dados:
Connection con = ConexaoBanco.getConnection();
//Fim da conexão com o banco de dados.
try {
//Variável para receber o comando SQL:
String sql;
//Atribuindo comando à variável:
sql = "update historicocomputador set dataentrada = ?, horaentrada = ?, dataconclusao = ?, "
+ "horaconclusao = ?, limpeza = ?, backup = ?, reparacaoso = ?, instalacaoso = ?, "
+ "substituicaohd = ?, driverpack = ?, trocadefonte = ?, libreoffice = ?, antivirus = ?, "
+ "navegadores = ?, java = ?, adobereader = ?, winrarflash = ?, conversorespdf = ?, "
+ "firewallcentralseg = ?, usuarios = ?, dominio = ?, ultravnc = ?, ativacaowindows = ?, "
+ "icones = ? where idhistoricocomputador = ?";
//Preparando insersão de dados:
PreparedStatement stat = con.prepareStatement(sql);
//Inserindo dados ao comando:
stat.setDate(1, his.getDataEntrada());
stat.setTime(2, his.getHoraEntrada());
stat.setDate(3, his.getDataConclusao());
stat.setTime(4, his.getHoraConclusao());
stat.setByte(5, his.getLimpeza());
stat.setByte(6, his.getBackup());
stat.setByte(7, his.getReparacaoso());
stat.setByte(8, his.getInstalacaoso());
stat.setByte(9, his.getSubstituicaoHd());
stat.setByte(10, his.getDriverPack());
stat.setByte(11, his.getTrocaDeFonte());
stat.setByte(12, his.getLibreOffice());
stat.setByte(13, his.getAntivirus());
stat.setByte(14, his.getNavegadores());
stat.setByte(15, his.getJava());
stat.setByte(16, his.getAdobereader());
stat.setByte(17, his.getWinrarFlash());
stat.setByte(18, his.getConversoresPdf());
stat.setByte(19, his.getFirewallCentralSeg());
stat.setByte(20, his.getUsuarios());
stat.setByte(21, his.getDominio());
stat.setByte(22, his.getUltravnc());
stat.setByte(23, his.getAtivacaoWindows());
stat.setByte(24, his.getIcones());
stat.setLong(25, his.getIdHistoricoComputador());
//Executando exclusão:
stat.executeUpdate();
//Fechando conexão com o banco de dados:
stat.close();
} catch (SQLException e) {
//Lançando erro:
throw new SQLException("Erro ao atualizar histórico!");
} finally {
//Fechando conexão com o banco de dados:
con.close();
}//Fecha finally.
}//Fecha método atualizarHistorico.
/**
* @author <NAME>
* @version 1.0
* @since 14/01/2015
* @param his Objeto com os dados a serem atualizado
* @throws SQLException Falha ao atualizar histórico
*/
public void atualizarHistorico(HistoricoComputadorVO his) throws SQLException {
//Conectando com o banco de dados:
Connection con = ConexaoBanco.getConnection();
//Fim da conexão com o banco de dados.
try {
//Variável para receber o comando SQL:
String sql;
//Atribuindo comando à variável:
sql = "update historicocomputador set historicocomputador = ? "
+ "where idhistoricocomputador = ?";
//Preparando insersão de dados:
PreparedStatement stat = con.prepareStatement(sql);
//Inserindo dados ao comando:
stat.setString(1, his.getHistoricoComputador());
stat.setLong(2, his.getIdHistoricoComputador());
//Executando exclusão:
stat.executeUpdate();
//Fechando conexão com o banco de dados:
stat.close();
} catch (SQLException e) {
//Lançando erro:
throw new SQLException("Erro ao atualizar histórico!");
} finally {
//Fechando conexão com o banco de dados:
con.close();
}//Fecha finally.
}//Fecha método atualizarHistorico.
/**
* @author <NAME>
* @since 15/01/2015
* @version 1.0
* @param idHistoricoComputador Variável com o ID do histórico a ser excluído
* @throws SQLException Falha ao excluir histórico
*/
public void excluirHistoricoComputador(long idHistoricoComputador) throws SQLException {
//Conectando com o banco de dados:
Connection con = ConexaoBanco.getConnection();
//Fim da conexão com o banco de dados.
try {
//Variável para receber o comando SQL:
String sql;
//Atribuindo comando à variável:
sql = "delete from historicocomputador where idhistorico = ?";
//Preparando insersão de dados:
PreparedStatement stat = con.prepareStatement(sql);
//Inserindo dados ao comando:
stat.setLong(1, idHistoricoComputador);
//Executando exclusão:
stat.execute();
//Fechando conexão com o banco de dados:
stat.close();
} catch (SQLException e) {
//Lançando erro:
throw new SQLException("Erro ao excluir histórico!");
} finally {
//Fechando conexão com o banco de dados:
con.close();
}//Fecha finally.
}//Fecha método excluirHistorico.
}//Fecha classe.
|
xujie3949/MGU2
|
src/components/split/Split.js
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import SplitJS from 'split.js';
import stores from 'Stores/stores';
import navinfo from 'navinfo';
export default class Split extends PureComponent {
static propTypes = {
children: PropTypes.node,
config: PropTypes.object,
onCreated: PropTypes.func,
};
static defaultProps = {
children: null,
config: null,
onCreated: null,
};
constructor(props) {
super(props);
this.split = null;
this.splitIds = null;
}
componentDidMount() {
this.updateSplit();
}
componentDidUpdate() {
this.updateSplit();
}
computeSplitIds(children) {
const ids = [];
children.forEach(item => {
if (!item.key) {
return;
}
ids.push(`#${item.key}`);
});
return ids;
}
destroySplit() {
if (!this.split) {
return;
}
this.split.destroy();
this.split = null;
}
updateSplit() {
const { children, config, onCreated } = this.props;
if (!children && !config) {
return;
}
if (!navinfo.common.Util.isArray(children)) {
return;
}
const splitIds = this.computeSplitIds(children);
this.split = SplitJS(splitIds, config);
if (onCreated) {
onCreated();
}
}
render() {
this.destroySplit();
const { children } = this.props;
return (
children
);
}
}
|
roytam1/wine-win31look
|
dlls/ole32/moniker.c
|
/*
* Monikers
*
* Copyright 1998 <NAME>
* Copyright 1999 <NAME>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <assert.h>
#include <stdarg.h>
#include <string.h>
#include "winerror.h"
#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "wtypes.h"
#include "wine/debug.h"
#include "ole2.h"
#include "compobj_private.h"
WINE_DEFAULT_DEBUG_CHANNEL(ole);
#define BLOCK_TAB_SIZE 20 /* represent the first size table and it's increment block size */
/* define the structure of the running object table elements */
typedef struct RunObject{
IUnknown* pObj; /* points on a running object*/
IMoniker* pmkObj; /* points on a moniker who identifies this object */
FILETIME lastModifObj;
DWORD identRegObj; /* registration key relative to this object */
DWORD regTypeObj; /* registration type : strong or weak */
}RunObject;
/* define the RunningObjectTableImpl structure */
typedef struct RunningObjectTableImpl{
ICOM_VFIELD(IRunningObjectTable);
ULONG ref;
RunObject* runObjTab; /* pointer to the first object in the table */
DWORD runObjTabSize; /* current table size */
DWORD runObjTabLastIndx; /* first free index element in the table. */
DWORD runObjTabRegister; /* registration key of the next registered object */
} RunningObjectTableImpl;
RunningObjectTableImpl* runningObjectTableInstance=0;
/* IRunningObjectTable prototype functions : */
/* IUnknown functions*/
static HRESULT WINAPI RunningObjectTableImpl_QueryInterface(IRunningObjectTable* iface,REFIID riid,void** ppvObject);
static ULONG WINAPI RunningObjectTableImpl_AddRef(IRunningObjectTable* iface);
static ULONG WINAPI RunningObjectTableImpl_Release(IRunningObjectTable* iface);
/* IRunningObjectTable functions */
static HRESULT WINAPI RunningObjectTableImpl_Register(IRunningObjectTable* iface, DWORD grfFlags,IUnknown* punkObject,IMoniker* pmkObjectName,DWORD* pdwRegister);
static HRESULT WINAPI RunningObjectTableImpl_Revoke(IRunningObjectTable* iface, DWORD dwRegister);
static HRESULT WINAPI RunningObjectTableImpl_IsRunning(IRunningObjectTable* iface, IMoniker* pmkObjectName);
static HRESULT WINAPI RunningObjectTableImpl_GetObject(IRunningObjectTable* iface, IMoniker* pmkObjectName,IUnknown** ppunkObject);
static HRESULT WINAPI RunningObjectTableImpl_NoteChangeTime(IRunningObjectTable* iface, DWORD dwRegister,FILETIME* pfiletime);
static HRESULT WINAPI RunningObjectTableImpl_GetTimeOfLastChange(IRunningObjectTable* iface, IMoniker* pmkObjectName,FILETIME* pfiletime);
static HRESULT WINAPI RunningObjectTableImpl_EnumRunning(IRunningObjectTable* iface, IEnumMoniker** ppenumMoniker);
/* Local functions*/
HRESULT WINAPI RunningObjectTableImpl_Initialize();
HRESULT WINAPI RunningObjectTableImpl_UnInitialize();
HRESULT WINAPI RunningObjectTableImpl_Destroy();
HRESULT WINAPI RunningObjectTableImpl_GetObjectIndex(RunningObjectTableImpl* This,DWORD identReg,IMoniker* pmk,DWORD *indx);
/* Virtual function table for the IRunningObjectTable class. */
static ICOM_VTABLE(IRunningObjectTable) VT_RunningObjectTableImpl =
{
ICOM_MSVTABLE_COMPAT_DummyRTTIVALUE
RunningObjectTableImpl_QueryInterface,
RunningObjectTableImpl_AddRef,
RunningObjectTableImpl_Release,
RunningObjectTableImpl_Register,
RunningObjectTableImpl_Revoke,
RunningObjectTableImpl_IsRunning,
RunningObjectTableImpl_GetObject,
RunningObjectTableImpl_NoteChangeTime,
RunningObjectTableImpl_GetTimeOfLastChange,
RunningObjectTableImpl_EnumRunning
};
/***********************************************************************
* RunningObjectTable_QueryInterface
*/
HRESULT WINAPI RunningObjectTableImpl_QueryInterface(IRunningObjectTable* iface,REFIID riid,void** ppvObject)
{
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p,%p,%p)\n",This,riid,ppvObject);
/* validate arguments */
if (This==0)
return CO_E_NOTINITIALIZED;
if (ppvObject==0)
return E_INVALIDARG;
*ppvObject = 0;
if (IsEqualIID(&IID_IUnknown, riid))
*ppvObject = (IRunningObjectTable*)This;
else
if (IsEqualIID(&IID_IRunningObjectTable, riid))
*ppvObject = (IRunningObjectTable*)This;
if ((*ppvObject)==0)
return E_NOINTERFACE;
RunningObjectTableImpl_AddRef(iface);
return S_OK;
}
/***********************************************************************
* RunningObjectTable_AddRef
*/
ULONG WINAPI RunningObjectTableImpl_AddRef(IRunningObjectTable* iface)
{
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p)\n",This);
return ++(This->ref);
}
/***********************************************************************
* RunningObjectTable_Initialize
*/
HRESULT WINAPI RunningObjectTableImpl_Destroy()
{
TRACE("()\n");
if (runningObjectTableInstance==NULL)
return E_INVALIDARG;
/* free the ROT table memory */
HeapFree(GetProcessHeap(),0,runningObjectTableInstance->runObjTab);
/* free the ROT structure memory */
HeapFree(GetProcessHeap(),0,runningObjectTableInstance);
return S_OK;
}
/***********************************************************************
* RunningObjectTable_Release
*/
ULONG WINAPI RunningObjectTableImpl_Release(IRunningObjectTable* iface)
{
DWORD i;
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p)\n",This);
This->ref--;
/* unitialize ROT structure if there's no more reference to it*/
if (This->ref==0){
/* release all registered objects */
for(i=0;i<This->runObjTabLastIndx;i++)
{
if (( This->runObjTab[i].regTypeObj & ROTFLAGS_REGISTRATIONKEEPSALIVE) != 0)
IUnknown_Release(This->runObjTab[i].pObj);
IMoniker_Release(This->runObjTab[i].pmkObj);
}
/* RunningObjectTable data structure will be not destroyed here ! the destruction will be done only
* when RunningObjectTableImpl_UnInitialize function is called
*/
/* there's no more elements in the table */
This->runObjTabRegister=0;
This->runObjTabLastIndx=0;
return 0;
}
return This->ref;
}
/***********************************************************************
* RunningObjectTable_Initialize
*/
HRESULT WINAPI RunningObjectTableImpl_Initialize()
{
TRACE("()\n");
/* create the unique instance of the RunningObjectTableImpl structure */
runningObjectTableInstance = HeapAlloc(GetProcessHeap(), 0, sizeof(RunningObjectTableImpl));
if (runningObjectTableInstance == 0)
return E_OUTOFMEMORY;
/* initialize the virtual table function */
runningObjectTableInstance->lpVtbl = &VT_RunningObjectTableImpl;
/* the initial reference is set to "1" ! because if set to "0" it will be not practis when */
/* the ROT referred many times not in the same time (all the objects in the ROT will */
/* be removed every time the ROT is removed ) */
runningObjectTableInstance->ref = 1;
/* allocate space memory for the table which contains all the running objects */
runningObjectTableInstance->runObjTab = HeapAlloc(GetProcessHeap(), 0, sizeof(RunObject[BLOCK_TAB_SIZE]));
if (runningObjectTableInstance->runObjTab == NULL)
return E_OUTOFMEMORY;
runningObjectTableInstance->runObjTabSize=BLOCK_TAB_SIZE;
runningObjectTableInstance->runObjTabRegister=1;
runningObjectTableInstance->runObjTabLastIndx=0;
return S_OK;
}
/***********************************************************************
* RunningObjectTable_UnInitialize
*/
HRESULT WINAPI RunningObjectTableImpl_UnInitialize()
{
TRACE("()\n");
if (runningObjectTableInstance==NULL)
return E_POINTER;
RunningObjectTableImpl_Release((IRunningObjectTable*)runningObjectTableInstance);
RunningObjectTableImpl_Destroy();
return S_OK;
}
/***********************************************************************
* RunningObjectTable_Register
*/
HRESULT WINAPI RunningObjectTableImpl_Register(IRunningObjectTable* iface,
DWORD grfFlags, /* Registration options */
IUnknown *punkObject, /* Pointer to the object being registered */
IMoniker *pmkObjectName, /* Pointer to the moniker of the object being registered */
DWORD *pdwRegister) /* Pointer to the value identifying the registration */
{
HRESULT res=S_OK;
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p,%ld,%p,%p,%p)\n",This,grfFlags,punkObject,pmkObjectName,pdwRegister);
/* there's only two types of register : strong and or weak registration (only one must be passed on parameter) */
if ( ( (grfFlags & ROTFLAGS_REGISTRATIONKEEPSALIVE) || !(grfFlags & ROTFLAGS_ALLOWANYCLIENT)) &&
(!(grfFlags & ROTFLAGS_REGISTRATIONKEEPSALIVE) || (grfFlags & ROTFLAGS_ALLOWANYCLIENT)) &&
(grfFlags) )
return E_INVALIDARG;
if (punkObject==NULL || pmkObjectName==NULL || pdwRegister==NULL)
return E_INVALIDARG;
/* verify if the object to be registered was registered before */
if (RunningObjectTableImpl_GetObjectIndex(This,-1,pmkObjectName,NULL)==S_OK)
res = MK_S_MONIKERALREADYREGISTERED;
/* put the new registered object in the first free element in the table */
This->runObjTab[This->runObjTabLastIndx].pObj = punkObject;
This->runObjTab[This->runObjTabLastIndx].pmkObj = pmkObjectName;
This->runObjTab[This->runObjTabLastIndx].regTypeObj = grfFlags;
This->runObjTab[This->runObjTabLastIndx].identRegObj = This->runObjTabRegister;
CoFileTimeNow(&(This->runObjTab[This->runObjTabLastIndx].lastModifObj));
/* gives a registration identifier to the registered object*/
(*pdwRegister)= This->runObjTabRegister;
if (This->runObjTabRegister == 0xFFFFFFFF){
FIXME("runObjTabRegister: %ld is out of data limite \n",This->runObjTabRegister);
return E_FAIL;
}
This->runObjTabRegister++;
This->runObjTabLastIndx++;
if (This->runObjTabLastIndx == This->runObjTabSize){ /* table is full ! so it must be resized */
This->runObjTabSize+=BLOCK_TAB_SIZE; /* newsize table */
This->runObjTab=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,This->runObjTab,
This->runObjTabSize * sizeof(RunObject));
if (!This->runObjTab)
return E_OUTOFMEMORY;
}
/* add a reference to the object in the strong registration case */
if ((grfFlags & ROTFLAGS_REGISTRATIONKEEPSALIVE) !=0 )
IUnknown_AddRef(punkObject);
IMoniker_AddRef(pmkObjectName);
return res;
}
/***********************************************************************
* RunningObjectTable_Revoke
*/
HRESULT WINAPI RunningObjectTableImpl_Revoke( IRunningObjectTable* iface,
DWORD dwRegister) /* Value identifying registration to be revoked*/
{
DWORD index,j;
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p,%ld)\n",This,dwRegister);
/* verify if the object to be revoked was registered before or not */
if (RunningObjectTableImpl_GetObjectIndex(This,dwRegister,NULL,&index)==S_FALSE)
return E_INVALIDARG;
/* release the object if it was registered with a strong registrantion option */
if ((This->runObjTab[index].regTypeObj & ROTFLAGS_REGISTRATIONKEEPSALIVE)!=0)
IUnknown_Release(This->runObjTab[index].pObj);
IMoniker_Release(This->runObjTab[index].pmkObj);
/* remove the object from the table */
for(j=index; j<This->runObjTabLastIndx-1; j++)
This->runObjTab[j]= This->runObjTab[j+1];
This->runObjTabLastIndx--;
return S_OK;
}
/***********************************************************************
* RunningObjectTable_IsRunning
*/
HRESULT WINAPI RunningObjectTableImpl_IsRunning( IRunningObjectTable* iface,
IMoniker *pmkObjectName) /* Pointer to the moniker of the object whose status is desired */
{
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p,%p)\n",This,pmkObjectName);
return RunningObjectTableImpl_GetObjectIndex(This,-1,pmkObjectName,NULL);
}
/***********************************************************************
* RunningObjectTable_GetObject
*/
HRESULT WINAPI RunningObjectTableImpl_GetObject( IRunningObjectTable* iface,
IMoniker *pmkObjectName,/* Pointer to the moniker on the object */
IUnknown **ppunkObject) /* Address of output variable that receives the IUnknown interface pointer */
{
DWORD index;
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p,%p,%p)\n",This,pmkObjectName,ppunkObject);
if (ppunkObject==NULL)
return E_POINTER;
*ppunkObject=0;
/* verify if the object was registered before or not */
if (RunningObjectTableImpl_GetObjectIndex(This,-1,pmkObjectName,&index)==S_FALSE)
return MK_E_UNAVAILABLE;
/* add a reference to the object then set output object argument */
IUnknown_AddRef(This->runObjTab[index].pObj);
*ppunkObject=This->runObjTab[index].pObj;
return S_OK;
}
/***********************************************************************
* RunningObjectTable_NoteChangeTime
*/
HRESULT WINAPI RunningObjectTableImpl_NoteChangeTime(IRunningObjectTable* iface,
DWORD dwRegister, /* Value identifying registration being updated */
FILETIME *pfiletime) /* Pointer to structure containing object's last change time */
{
DWORD index=-1;
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p,%ld,%p)\n",This,dwRegister,pfiletime);
/* verify if the object to be changed was registered before or not */
if (RunningObjectTableImpl_GetObjectIndex(This,dwRegister,NULL,&index)==S_FALSE)
return E_INVALIDARG;
/* set the new value of the last time change */
This->runObjTab[index].lastModifObj= (*pfiletime);
return S_OK;
}
/***********************************************************************
* RunningObjectTable_GetTimeOfLastChange
*/
HRESULT WINAPI RunningObjectTableImpl_GetTimeOfLastChange(IRunningObjectTable* iface,
IMoniker *pmkObjectName, /* Pointer to moniker on the object whose status is desired */
FILETIME *pfiletime) /* Pointer to structure that receives object's last change time */
{
DWORD index=-1;
ICOM_THIS(RunningObjectTableImpl,iface);
TRACE("(%p,%p,%p)\n",This,pmkObjectName,pfiletime);
if (pmkObjectName==NULL || pfiletime==NULL)
return E_INVALIDARG;
/* verify if the object was registered before or not */
if (RunningObjectTableImpl_GetObjectIndex(This,-1,pmkObjectName,&index)==S_FALSE)
return MK_E_UNAVAILABLE;
(*pfiletime)= This->runObjTab[index].lastModifObj;
return S_OK;
}
/***********************************************************************
* RunningObjectTable_EnumRunning
*/
HRESULT WINAPI RunningObjectTableImpl_EnumRunning(IRunningObjectTable* iface,
IEnumMoniker **ppenumMoniker) /* Address of output variable that receives the IEnumMoniker interface pointer */
{
FIXME("(%p,%p) needs the IEnumMoniker implementation \n",iface,ppenumMoniker);
return E_NOTIMPL;
}
/***********************************************************************
* GetObjectIndex
*/
HRESULT WINAPI RunningObjectTableImpl_GetObjectIndex(RunningObjectTableImpl* This,
DWORD identReg,
IMoniker* pmk,
DWORD *indx)
{
DWORD i;
TRACE("(%p,%ld,%p,%p)\n",This,identReg,pmk,indx);
if (pmk!=NULL)
/* search object identified by a moniker */
for(i=0 ; (i < This->runObjTabLastIndx) &&(!IMoniker_IsEqual(This->runObjTab[i].pmkObj,pmk)==S_OK);i++);
else
/* search object identified by a register identifier */
for(i=0;((i<This->runObjTabLastIndx)&&(This->runObjTab[i].identRegObj!=identReg));i++);
if (i==This->runObjTabLastIndx) return S_FALSE;
if (indx != NULL) *indx=i;
return S_OK;
}
/******************************************************************************
* GetRunningObjectTable (OLE2.30)
*/
HRESULT WINAPI GetRunningObjectTable16(DWORD reserved, LPRUNNINGOBJECTTABLE *pprot)
{
FIXME("(%ld,%p),stub!\n",reserved,pprot);
return E_NOTIMPL;
}
/***********************************************************************
* GetRunningObjectTable (OLE32.@)
*/
HRESULT WINAPI GetRunningObjectTable(DWORD reserved, LPRUNNINGOBJECTTABLE *pprot)
{
IID riid=IID_IRunningObjectTable;
HRESULT res;
TRACE("()\n");
if (reserved!=0)
return E_UNEXPECTED;
if(runningObjectTableInstance==NULL)
return CO_E_NOTINITIALIZED;
res = RunningObjectTableImpl_QueryInterface((IRunningObjectTable*)runningObjectTableInstance,&riid,(void**)pprot);
return res;
}
/******************************************************************************
* OleRun [OLE32.@]
*/
HRESULT WINAPI OleRun(LPUNKNOWN pUnknown)
{
IRunnableObject *runable;
ICOM_THIS(IRunnableObject,pUnknown);
LRESULT ret;
ret = IRunnableObject_QueryInterface(This,&IID_IRunnableObject,(LPVOID*)&runable);
if (ret)
return 0; /* Appears to return no error. */
ret = IRunnableObject_Run(runable,NULL);
IRunnableObject_Release(runable);
return ret;
}
/******************************************************************************
* MkParseDisplayName [OLE32.@]
*/
HRESULT WINAPI MkParseDisplayName(LPBC pbc, LPCOLESTR szUserName,
LPDWORD pchEaten, LPMONIKER *ppmk)
{
FIXME("(%p, %s, %p, %p): stub.\n", pbc, debugstr_w(szUserName), pchEaten, *ppmk);
if (!(IsValidInterface((LPUNKNOWN) pbc)))
return E_INVALIDARG;
return MK_E_SYNTAX;
}
/******************************************************************************
* CreateClassMoniker [OLE32.@]
*/
HRESULT WINAPI CreateClassMoniker(REFCLSID rclsid, IMoniker ** ppmk)
{
FIXME("%s\n", debugstr_guid( rclsid ));
if( ppmk )
*ppmk = NULL;
return E_NOTIMPL;
}
|
Matt-Hayes24/hivemq-community-edition
|
src/main/java/com/hivemq/codec/encoder/mqtt5/Mqtt5PublishEncoder.java
|
/*
* Copyright 2019-present HiveMQ GmbH
*
* 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.hivemq.codec.encoder.mqtt5;
import com.google.common.primitives.ImmutableIntArray;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.codec.encoder.MqttEncoder;
import com.hivemq.configuration.service.SecurityConfigurationService;
import com.hivemq.mqtt.message.MessageType;
import com.hivemq.mqtt.message.QoS;
import com.hivemq.mqtt.message.dropping.MessageDroppedService;
import com.hivemq.mqtt.message.mqtt5.Mqtt5UserProperties;
import com.hivemq.mqtt.message.publish.PUBLISH;
import io.netty.buffer.ByteBuf;
import javax.inject.Singleton;
import java.util.List;
import static com.hivemq.codec.encoder.mqtt5.Mqtt5MessageEncoderUtil.*;
import static com.hivemq.configuration.entity.mqtt.MqttConfigurationDefaults.MAX_EXPIRY_INTERVAL_DEFAULT;
import static com.hivemq.mqtt.message.mqtt5.MessageProperties.*;
/**
* @author <NAME>
* @author <NAME>
*/
@Singleton
public class Mqtt5PublishEncoder extends Mqtt5MessageWithUserPropertiesEncoder<PUBLISH> implements MqttEncoder<PUBLISH> {
private static final int FIXED_HEADER = MessageType.PUBLISH.ordinal() << 4;
public Mqtt5PublishEncoder(final @NotNull MessageDroppedService messageDroppedService,
final @NotNull SecurityConfigurationService securityConfigurationService) {
super(messageDroppedService, securityConfigurationService);
}
@Override
void encode(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
encodeFixedHeader(publish, out);
encodeVariableHeader(publish, out);
encodePayload(publish, out);
}
@Override
int calculateRemainingLengthWithoutProperties(@NotNull final PUBLISH publish) {
int remainingLength = 0;
remainingLength += MqttBinaryData.encodedLength(publish.getTopic());
//packetIdentifier
if (publish.getQoS() != QoS.AT_MOST_ONCE) {
remainingLength += 2;
}
final byte[] payload = publish.getPayload();
if (payload != null) {
remainingLength += payload.length;
}
return remainingLength;
}
@Override
int calculatePropertyLength(@NotNull final PUBLISH publish) {
int propertyLength = 0;
propertyLength += fixedPropertyLength(publish);
propertyLength += publish.getUserProperties().encodedLength();
final ImmutableIntArray subscriptionIdentifiers = publish.getSubscriptionIdentifiers();
if (subscriptionIdentifiers != null) {
for (int i = 0; i < subscriptionIdentifiers.length(); i++) {
propertyLength += variableByteIntegerPropertyEncodedLength(subscriptionIdentifiers.get(i));
}
}
return propertyLength;
}
@Override
@NotNull Mqtt5UserProperties getUserProperties(@NotNull final PUBLISH publish) {
return publish.getUserProperties();
}
private int fixedPropertyLength(@NotNull final PUBLISH publish) {
int propertyLength = 0;
propertyLength += intPropertyEncodedLength(publish.getMessageExpiryInterval(), MAX_EXPIRY_INTERVAL_DEFAULT);
propertyLength += nullablePropertyEncodedLength(publish.getPayloadFormatIndicator());
propertyLength += nullablePropertyEncodedLength(publish.getContentType());
propertyLength += nullablePropertyEncodedLength(publish.getResponseTopic());
propertyLength += nullablePropertyEncodedLength(publish.getCorrelationData());
return propertyLength;
}
private void encodeFixedHeader(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
int flags = 0;
if (publish.isDuplicateDelivery()) {
flags |= 0b1000;
}
flags |= publish.getQoS().ordinal() << 1;
if (publish.isRetain()) {
flags |= 0b0001;
}
out.writeByte(FIXED_HEADER | flags);
MqttVariableByteInteger.encode(publish.getRemainingLength(), out);
}
private void encodeVariableHeader(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
MqttBinaryData.encode(publish.getTopic(), out);
if (publish.getQoS() != QoS.AT_MOST_ONCE) {
out.writeShort(publish.getPacketIdentifier());
}
encodeProperties(publish, out);
}
private void encodeProperties(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
MqttVariableByteInteger.encode(publish.getPropertyLength(), out);
encodeFixedProperties(publish, out);
encodeOmissibleProperties(publish, out);
final ImmutableIntArray subscriptionIdentifiers = publish.getSubscriptionIdentifiers();
if (subscriptionIdentifiers != null) {
for (int i = 0; i < subscriptionIdentifiers.length(); i++) {
encodeVariableByteIntegerProperty(SUBSCRIPTION_IDENTIFIER, subscriptionIdentifiers.get(i), out);
}
}
}
private void encodeFixedProperties(@NotNull final PUBLISH publish, @NotNull final ByteBuf out) {
encodeIntProperty(MESSAGE_EXPIRY_INTERVAL, publish.getMessageExpiryInterval(), MAX_EXPIRY_INTERVAL_DEFAULT, out);
encodeNullableProperty(PAYLOAD_FORMAT_INDICATOR, publish.getPayloadFormatIndicator(), out);
encodeNullableProperty(CONTENT_TYPE, publish.getContentType(), out);
encodeNullableProperty(RESPONSE_TOPIC, publish.getResponseTopic(), out);
encodeNullableProperty(CORRELATION_DATA, publish.getCorrelationData(), out);
}
private void encodePayload(@NotNull final PUBLISH publish, @NotNull final ByteBuf out) {
final byte[] payload = publish.getPayload();
if ((payload != null)) {
out.writeBytes(payload);
}
}
}
|
d-amien-b/simple-getwordpress
|
Collections-a-installer/community-general-2.4.0/plugins/modules/cloud/opennebula/one_host.py
|
#!/usr/bin/python
#
# Copyright 2018 www.privaz.io Valletech AB
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
---
module: one_host
short_description: Manages OpenNebula Hosts
requirements:
- pyone
description:
- "Manages OpenNebula Hosts"
options:
name:
description:
- Hostname of the machine to manage.
required: true
type: str
state:
description:
- Takes the host to the desired lifecycle state.
- If C(absent) the host will be deleted from the cluster.
- If C(present) the host will be created in the cluster (includes C(enabled), C(disabled) and C(offline) states).
- If C(enabled) the host is fully operational.
- C(disabled), e.g. to perform maintenance operations.
- C(offline), host is totally offline.
choices:
- absent
- present
- enabled
- disabled
- offline
default: present
type: str
im_mad_name:
description:
- The name of the information manager, this values are taken from the oned.conf with the tag name IM_MAD (name)
default: kvm
type: str
vmm_mad_name:
description:
- The name of the virtual machine manager mad name, this values are taken from the oned.conf with the tag name VM_MAD (name)
default: kvm
type: str
cluster_id:
description:
- The cluster ID.
default: 0
type: int
cluster_name:
description:
- The cluster specified by name.
type: str
labels:
description:
- The labels for this host.
type: list
elements: str
template:
description:
- The template or attribute changes to merge into the host template.
aliases:
- attributes
type: dict
extends_documentation_fragment:
- community.general.opennebula
author:
- <NAME> (@rvalle)
'''
EXAMPLES = '''
- name: Create a new host in OpenNebula
community.general.one_host:
name: host1
cluster_id: 1
api_url: http://127.0.0.1:2633/RPC2
- name: Create a host and adjust its template
community.general.one_host:
name: host2
cluster_name: default
template:
LABELS:
- gold
- ssd
RESERVED_CPU: -100
'''
# TODO: pending setting guidelines on returned values
RETURN = '''
'''
# TODO: Documentation on valid state transitions is required to properly implement all valid cases
# TODO: To be coherent with CLI this module should also provide "flush" functionality
from ansible_collections.community.general.plugins.module_utils.opennebula import OpenNebulaModule
try:
from pyone import HOST_STATES, HOST_STATUS
except ImportError:
pass # handled at module utils
# Pseudo definitions...
HOST_ABSENT = -99 # the host is absent (special case defined by this module)
class HostModule(OpenNebulaModule):
def __init__(self):
argument_spec = dict(
name=dict(type='str', required=True),
state=dict(choices=['present', 'absent', 'enabled', 'disabled', 'offline'], default='present'),
im_mad_name=dict(type='str', default="kvm"),
vmm_mad_name=dict(type='str', default="kvm"),
cluster_id=dict(type='int', default=0),
cluster_name=dict(type='str'),
labels=dict(type='list', elements='str'),
template=dict(type='dict', aliases=['attributes']),
)
mutually_exclusive = [
['cluster_id', 'cluster_name']
]
OpenNebulaModule.__init__(self, argument_spec, mutually_exclusive=mutually_exclusive)
def allocate_host(self):
"""
Creates a host entry in OpenNebula
Returns: True on success, fails otherwise.
"""
if not self.one.host.allocate(self.get_parameter('name'),
self.get_parameter('vmm_mad_name'),
self.get_parameter('im_mad_name'),
self.get_parameter('cluster_id')):
self.fail(msg="could not allocate host")
else:
self.result['changed'] = True
return True
def wait_for_host_state(self, host, target_states):
"""
Utility method that waits for a host state.
Args:
host:
target_states:
"""
return self.wait_for_state('host',
lambda: self.one.host.info(host.ID).STATE,
lambda s: HOST_STATES(s).name, target_states,
invalid_states=[HOST_STATES.ERROR, HOST_STATES.MONITORING_ERROR])
def run(self, one, module, result):
# Get the list of hosts
host_name = self.get_parameter("name")
host = self.get_host_by_name(host_name)
# manage host state
desired_state = self.get_parameter('state')
if bool(host):
current_state = host.STATE
current_state_name = HOST_STATES(host.STATE).name
else:
current_state = HOST_ABSENT
current_state_name = "ABSENT"
# apply properties
if desired_state == 'present':
if current_state == HOST_ABSENT:
self.allocate_host()
host = self.get_host_by_name(host_name)
self.wait_for_host_state(host, [HOST_STATES.MONITORED])
elif current_state in [HOST_STATES.ERROR, HOST_STATES.MONITORING_ERROR]:
self.fail(msg="invalid host state %s" % current_state_name)
elif desired_state == 'enabled':
if current_state == HOST_ABSENT:
self.allocate_host()
host = self.get_host_by_name(host_name)
self.wait_for_host_state(host, [HOST_STATES.MONITORED])
elif current_state in [HOST_STATES.DISABLED, HOST_STATES.OFFLINE]:
if one.host.status(host.ID, HOST_STATUS.ENABLED):
self.wait_for_host_state(host, [HOST_STATES.MONITORED])
result['changed'] = True
else:
self.fail(msg="could not enable host")
elif current_state in [HOST_STATES.MONITORED]:
pass
else:
self.fail(msg="unknown host state %s, cowardly refusing to change state to enable" % current_state_name)
elif desired_state == 'disabled':
if current_state == HOST_ABSENT:
self.fail(msg='absent host cannot be put in disabled state')
elif current_state in [HOST_STATES.MONITORED, HOST_STATES.OFFLINE]:
if one.host.status(host.ID, HOST_STATUS.DISABLED):
self.wait_for_host_state(host, [HOST_STATES.DISABLED])
result['changed'] = True
else:
self.fail(msg="could not disable host")
elif current_state in [HOST_STATES.DISABLED]:
pass
else:
self.fail(msg="unknown host state %s, cowardly refusing to change state to disable" % current_state_name)
elif desired_state == 'offline':
if current_state == HOST_ABSENT:
self.fail(msg='absent host cannot be placed in offline state')
elif current_state in [HOST_STATES.MONITORED, HOST_STATES.DISABLED]:
if one.host.status(host.ID, HOST_STATUS.OFFLINE):
self.wait_for_host_state(host, [HOST_STATES.OFFLINE])
result['changed'] = True
else:
self.fail(msg="could not set host offline")
elif current_state in [HOST_STATES.OFFLINE]:
pass
else:
self.fail(msg="unknown host state %s, cowardly refusing to change state to offline" % current_state_name)
elif desired_state == 'absent':
if current_state != HOST_ABSENT:
if one.host.delete(host.ID):
result['changed'] = True
else:
self.fail(msg="could not delete host from cluster")
# if we reach this point we can assume that the host was taken to the desired state
if desired_state != "absent":
# manipulate or modify the template
desired_template_changes = self.get_parameter('template')
if desired_template_changes is None:
desired_template_changes = dict()
# complete the template with specific ansible parameters
if self.is_parameter('labels'):
desired_template_changes['LABELS'] = self.get_parameter('labels')
if self.requires_template_update(host.TEMPLATE, desired_template_changes):
# setup the root element so that pyone will generate XML instead of attribute vector
desired_template_changes = {"TEMPLATE": desired_template_changes}
if one.host.update(host.ID, desired_template_changes, 1): # merge the template
result['changed'] = True
else:
self.fail(msg="failed to update the host template")
# the cluster
if host.CLUSTER_ID != self.get_parameter('cluster_id'):
if one.cluster.addhost(self.get_parameter('cluster_id'), host.ID):
result['changed'] = True
else:
self.fail(msg="failed to update the host cluster")
# return
self.exit()
def main():
HostModule().run_module()
if __name__ == '__main__':
main()
|
Wexalian/jtrakt
|
src/main/java/com/wexalian/jtrakt/json/adapter/DayTypeAdapter.java
|
<reponame>Wexalian/jtrakt
package com.wexalian.jtrakt.json.adapter;
import com.google.gson.*;
import com.wexalian.jtrakt.endpoint.TraktAirsInfo;
import java.lang.reflect.Type;
public class DayTypeAdapter implements JsonSerializer<TraktAirsInfo.Day>, JsonDeserializer<TraktAirsInfo.Day> {
public static DayTypeAdapter INSTANCE = new DayTypeAdapter();
@Override
public TraktAirsInfo.Day deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return TraktAirsInfo.Day.fromValue(json.getAsString());
}
@Override
public JsonElement serialize(TraktAirsInfo.Day src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
|
wyriwyg/hadatac
|
app/org/hadatac/console/controllers/schema/EditingOptions.java
|
package org.hadatac.console.controllers.schema;
import play.mvc.Controller;
import play.mvc.Result;
//import views.html.schema.*;
//import controllers.AuthApplication;
import org.hadatac.console.models.OtMSparqlQueryResults;
import org.hadatac.entity.pojo.Entity;
import org.hadatac.entity.pojo.Attribute;
import org.hadatac.entity.pojo.Unit;
import org.hadatac.utils.Hierarchy;
public class EditingOptions extends Controller {
public Result entityOptions() {
return ok(org.hadatac.console.views.html.schema.entityOptions.render(getEntities()));
}
public Result postEntityOptions() {
return ok(org.hadatac.console.views.html.schema.entityOptions.render(getEntities()));
}
public static OtMSparqlQueryResults getEntities() {
Entity entity = new Entity();
String json = entity.getHierarchyJson();
OtMSparqlQueryResults entities = new OtMSparqlQueryResults(json);
return entities;
}
public static OtMSparqlQueryResults getAttributes() {
Attribute attribute = new Attribute();
String json = attribute.getHierarchyJson();
OtMSparqlQueryResults attributes = new OtMSparqlQueryResults(json);
return attributes;
}
public static OtMSparqlQueryResults getUnits() {
Unit unit = new Unit();
String json = unit.getHierarchyJson();
OtMSparqlQueryResults units = new OtMSparqlQueryResults(json);
return units;
}
public static OtMSparqlQueryResults getHierarchy(String className) {
Hierarchy hierarchy = new Hierarchy(className);
String json = hierarchy.getHierarchyJson();
//System.out.println("JSON results" + json);
OtMSparqlQueryResults hierarchies = new OtMSparqlQueryResults(json);
//System.out.println("tree results:" + hierarchies.treeResults);
return hierarchies;
}
}
|
jpardobl/django-thermostat
|
django_thermostat/pypelib/parsing/ParseEngine.py
|
<filename>django_thermostat/pypelib/parsing/ParseEngine.py
import os
import sys
import time
import uuid
'''
@author: msune,lbergesio,cbermudo,omoya
@organization: i2CAT, OFELIA FP7
ParseEngine
Implementes driver-based parsing mechanism for rules
'''
class ParseEngine():
#Drivers
_drivers = ["RegexParser"]
_defaultDriver = 'RegexParser'
#Fill with appropiate path
PATH_TO_DRIVERS="drivers"
def __init__(self):
raise Exception("Static class cannot be instanciated")
@staticmethod
def _getDriver(driverName=None):
if driverName == None or driverName not in ParseEngine._drivers:
#TODO: Try all drivers?
raise Exception("Cannot find parser")
elif driverName == "RegexParser":
path = '.' + ParseEngine.PATH_TO_DRIVERS + '.RegexParser'
exec('from ' + path + ' import RegexParser')
#from ParseEngine.PATH_TO_DRIVERS.RegexParser import RegexParser
return RegexParser
@staticmethod
def parseRule(string, driverName= _defaultDriver):
return ParseEngine._getDriver(driverName).parseRule(string)
@staticmethod
def craftRule(rule, driverName=None):
return ParseEngine._getDriver(driverName).craftRule(rule)
# This calls should not be here. Instead, use parseRule in the persistence drivers if required.
# @staticmethod
# def parseCondition(stringCond, driverName=None):
# return ParseEngine._getDriver(driverName)._parseCondition(stringCond)
#
# @staticmethod
# def craftCondition(condition, driverName=None):
# return ParseEngine._getDriver(driverName).craftCondition(condition)
|
AndreaMelle/OmniPreview
|
CCRiftPlugin/src/PrSDK/PrSDKVideoSegmentProperties.h
|
/*******************************************************************/
/* */
/* ADOBE CONFIDENTIAL */
/* _ _ _ _ _ _ _ _ _ _ _ _ _ */
/* */
/* Copyright 2008 Adobe Systems Incorporated */
/* All Rights Reserved. */
/* */
/* NOTICE: All information contained herein is, and remains the */
/* property of Adobe Systems Incorporated and its suppliers, if */
/* any. The intellectual and technical concepts contained */
/* herein are proprietary to Adobe Systems Incorporated and its */
/* suppliers and may be covered by U.S. and Foreign Patents, */
/* patents in process, and are protected by trade secret or */
/* copyright law. Dissemination of this information or */
/* reproduction of this material is strictly forbidden unless */
/* prior written permission is obtained from Adobe Systems */
/* Incorporated. */
/* */
/*******************************************************************/
// This file is part of the public Premiere SDK.
#ifndef PRSDKVIDEOSEGMENTPROPERTIES_H
#define PRSDKVIDEOSEGMENTPROPERTIES_H
#ifndef PRSDKTYPES_H
#include "PrSDKTypes.h"
#endif
/**
** This file contains all of the string definitions of properties that may be found in video segments.
** Each one is list by the node type it may show up in, and hs a description of its value type.
**
** No property is ever guaranteed to be present on a node.
*/
// MediaNode, int32
#define kVideoSegmentProperty_Media_ClipID "MediaNode::ClipID"
// MediaNode, string
#define kVideoSegmentProperty_Media_InstanceString "MediaNode::MediaInstanceString"
// MediaNode, string
#define kVideoSegmentProperty_Media_ImplementationID "MediaNode::ImplementationID"
// MediaNode, size_t
#define kVideoSegmentProperty_Media_StreamGroup "MediaNode::MediaStreamGroup"
// MediaNode, string
#define kVideoSegmentProperty_Media_StreamLabel "MediaNode::MediaStreamLabel"
// MediaNode, bool
#define kVideoSegmentProperty_Media_IsDraft "MediaNode::MediaIsDraft"
// MediaNode, binary data
#define kVideoSegmentProperty_Media_ModState "MediaNode::MediaModState"
// MediaNode, bool
#define kVideoSegmentProperty_Media_IsOffline "MediaNode::MediaIsOffline"
// MediaNode, bool
#define kVideoSegmentProperty_Media_IsPending "MediaNode::MediaIsPending"
// MediaNode, stringl
#define kVideoSegmentProperty_Media_CaptioningID "MediaNode::MediaCaptioningID"
// MediaNode, PrTime
#define kVideoSegmentProperty_Media_StreamFrameRate "MediaNode::StreamFrameRate"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamAlphaType "MediaNode::StreamAlphaType"
// MediaNode, bool
#define kVideoSegmentProperty_Media_StreamIgnoreAlpha "MediaNode::StreamIgnoreAlpha"
// MediaNode, bool
#define kVideoSegmentProperty_Media_StreamInvertAlpha "MediaNode::StreamInvertAlpha"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamAlphaMatteColor "MediaNode::StreamAlphaMatteColor"
// MediaNode, bool
#define kVideoSegmentProperty_Media_StreamRemovePulldown "MediaNode::StreamRemovePulldown"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamPixelAspectRatioNum "MediaNode::StreamPixelAspectRatioNum"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamFrameWidth "MediaNode::StreamFrameWidth"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamFrameHeight "MediaNode::StreamFrameHeight"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamPixelAspectRatioDen "MediaNode::StreamPixelAspectRatioDen"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamFieldType "MediaNode::StreamFieldType"
// MediaNode, binary data
#define kVideoSegmentProperty_Media_StreamOpaqueData "MediaNode::StreamOpaqueData"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamPullDownCadence "MediaNode::StreamPullDownCadence"
// MediaNode, int32
#define kVideoSegmentProperty_Media_StreamFrameVidSubType "MediaNode::StreamFrameVidSubType"
// MediaNode, bool
#define kVideoSegmentProperty_Media_StreamIsContinuousTime "MediaNode::kVideoSegmentProperty_Media_StreamIsContinuousTime"
// MediaNode, bool
#define kVideoSegmentProperty_Media_StreamIsRollCrawl "MediaNode::StreamIsRollCrawl"
// MediaNode, int32
#define kVideoSegmentProperty_Media_RollCrawlDuration "MediaNode::RollCrawlDuration"
// MediaNode, PrTime
#define kVideoSegmentProperty_Media_ContentStart "MediaNode::ContentStart"
// MediaNode, PrTime
#define kVideoSegmentProperty_Media_ContentEnd "MediaNode::ContentEnd"
// MediaNode, PrTime
#define kVideoSegmentProperty_Media_StartTimecodeOffset "MediaNode::StartTimecodeOffset"
// MediaNode, string
#define kVideoSegmentProperty_Media_NestedSequenceHash "MediaNode::NestedSequenceHash"
// MediaNode, int32
#define kVideoSegmentProperty_Media_SelectedMulticamTrackFromNestedSequence "MediaNode::SelectedMulticamTrack"
// MediaNode string
#define kVideoSegmentProperty_Media_MulticamCameraOrderFromNestedSequence "MediaNode::MulticamCameraOrder"
// MediaNode, int32
#define kVideoSegmentProperty_Media_SelectedMulticamTrackTimelineID "MediaNode::SelectedMulticamTrackTimelineID"
// MediaNode, int32
#define kVideoSegmentProperty_Media_NestedSequenceTimelineID "MediaNode::NestedSequenceTimelineID"
// MediaNode, bool
#define kVideoSegmentProperty_Media_TrackItemIsMuted "MediaNode::TrackItemIsMuted"
// MediaNode, float64
#define kVideoSegmentProperty_Media_ClipSpeed "MediaNode::ClipSpeed"
// MediaNode, bool
#define kVideoSegmentProperty_Media_ClipBackwards "MediaNode::ClipBackwards"
// MediaNode, bool
#define kVideoSegmentProperty_Media_StreamFrameBlend "MediaNode::StreamFrameBlend"
// MediaNode, bool
#define kVideoSegmentProperty_Media_ClipScaleToFrameSize "MediaNode::ClipScaleToFrameSize"
// MediaNode, int, optional see PrNodeScalePolicy
#define kVideoSegmentProperty_Media_ClipScaleToFramePolicy "MediaNode::ClipScaleToFramePolicy"
// MediaNode, bool
#define kVideoSegmentProperty_Media_StreamReverseFieldDominance "MediaNode::StreamReverseFieldDominance"
// MediaNode, bool
#define kVideoSegmentProperty_Media_DeinterlaceAlways "MediaNode::DeinterlaceAlways"
// MediaNode, bool
#define kVideoSegmentProperty_Media_RemoveFlicker "MediaNode::RemoveFlicker"
// MediaNode, bool
#define kVideoSegmentProperty_Media_InterlaceConsecutiveFrames "MediaNode::InterlaceConsecutiveFrames"
// MediaNode, string
#define kVideoSegmentProperty_Media_ColorProfileName "MediaNode::SelectedColorProfileName"
// MediaNode, binary data
#define kVideoSegmentProperty_Media_ColorProfileData "MediaNode::SelectedColorProfileData"
// MediaNode, int32 - positive values mean shift up, negative means shift down
#define kVideoSegmentProperty_Media_ScanlineOffsetToImproveVerticalCentering "MediaNode::ScanlineOffsetToImproveVerticalCentering"
// MediaNode, int64 - media in point in units of ticks in media time
#define kVideoSegmentProperty_Media_InPointMediaTimeAsTicks "MediaNode::InPointMediaTimeAsTicks"
// MediaNode, int64 - media out point in units of ticks in media time
#define kVideoSegmentProperty_Media_OutPointMediaTimeAsTicks "MediaNode::OutPointMediaTimeAsTicks"
// MediaNode, int32 - containing sequence field type
#define kVideoSegmentProperty_Media_SequenceFieldType "MediaNode::SequenceFieldType"
// MediaNode, int32 - containing sequence frame rate
#define kVideoSegmentProperty_Media_SequenceFrameRate "MediaNode::SequenceFrameRate"
// MediaNode, int32 - containing sequence width
#define kVideoSegmentProperty_Media_SequenceWidth "MediaNode::SequenceWidth"
// MediaNode, int32 - containing sequence height
#define kVideoSegmentProperty_Media_SequenceHeight "MediaNode::SequenceHeight"
// MediaNode, int32 - containing sequence pixel aspect ratio num
#define kVideoSegmentProperty_Media_SequencePixelAspectRatioNum "MediaNode::SequencePixelAspectRatioNum"
// MediaNode, int32 - containing sequence pixel aspect ratio den
#define kVideoSegmentProperty_Media_SequencePixelAspectRatioDen "MediaNode::SequencePixelAspectRatioDen"
// ClipNode, float64
#define kVideoSegmentProperty_Clip_ClipSpeed "ClipNode::ClipSpeed"
// ClipNode, bool
#define kVideoSegmentProperty_Clip_ClipBackwards "ClipNode::ClipBackwards"
// ClipNode, keyframe data
#define kVideoSegmentProperty_Clip_TimeRemapping "ClipNode::TimeRemapping"
// ClipNode, PrTime
#define kVideoSegmentProperty_Clip_FrameHoldAtTime "ClipNode::FrameHoldAtTime"
// ClipNode, bool
#define kVideoSegmentProperty_Clip_FrameHoldFilters "ClipNode::FrameHoldFilters"
// ClipNode, PrTime
#define kVideoSegmentProperty_Clip_GrowingDuration "ClipNode::GrowingDuration"
// ClipNode, bool
#define kVideoSegmentProperty_Clip_FrameHoldDeinterlace "ClipNode::FrameHoldDeinterlace"
// ClipNode, int32
#define kVideoSegmentProperty_Clip_TrackID "ClipNode::TrackID"
// ClipNode, int64 - the start of the track item in units of ticks in sequence time
#define kVideoSegmentProperty_Clip_TrackItemStartAsTicks "ClipNode::TrackItemStartAsTicks"
// ClipNode, int64 - the end of the track item in units of ticks in sequence time
#define kVideoSegmentProperty_Clip_TrackItemEndAsTicks "ClipNode::TrackItemEndAsTicks"
// ClipNode, int64 - the "effective" start of the track item, adjusted for transitions at the head, in units of ticks in sequence time
#define kVideoSegmentProperty_Clip_EffectiveTrackItemStartAsTicks "ClipNode::EffectiveTrackItemStartAsTicks"
// ClipNode, int64 - the "effective" start of the track item, adjusted for transitions at the tail, in units of ticks in sequence time
#define kVideoSegmentProperty_Clip_EffectiveTrackItemEndAsTicks "ClipNode::EffectiveTrackItemEndAsTicks"
// ClipNode, bool - only set if false
#define kVideoSegmentProperty_Clip_AllowLinearCompositing "ClipNode::AllowLinearCompositing"
// ClipNode, bool - only set if true
#define kVideoSegmentProperty_Clip_HasCaptions "ClipNode::HasCaptions"
// ClipNode, int64 - the untrimmed duration of the clip in ticks
#define kVideoSegmentProperty_Clip_UntrimmedDuration "ClipNode::UntrimmedDuration"
// MulticamNode, int32
#define kVideoSegmentProperty_Multicam_SelectedTrack "MulticamNode::SelectedTrack"
// MulticamNode, string
#define kVideoSegmentProperty_Multicam_CameraOrder "MulticamNode::CameraOrder"
// MulticamNode, bool
#define kVideoSegmentProperty_Multicam_ShowProgram "MulticamNode::ShowProgram"
// MulticamNode, bool
#define kVideoSegmentProperty_Multicam_Recording "MulticamNode::Recording"
// MulticamNode, bool
#define kVideoSegmentProperty_Multicam_IsNonMultiCam "MulticamNode::IsNonMultiCam"
// MulticamNode, bool
#define kVideoSegmentProperty_Multicam_UseTimeRemapping "MulticamNode::UseTimeRemapping"
// SolidColorNode, int32
#define kVideoSegmentProperty_SolidColor_Color "SolidColorNode::Color"
// EffectNode, string
#define kVideoSegmentProperty_Effect_FilterMatchName "EffectNode::FilterMatchName"
// EffectNode, binary data
#define kVideoSegmentProperty_Effect_FilterOpaqueData "EffectNode::FilterOpaqueData"
// EffectNode, keyframe data
#define kVideoSegmentProperty_Effect_FilterParams "EffectNode::FilterParams"
// EffectNode, PrTime
#define kVideoSegmentProperty_Effect_EffectDuration "EffectNode::EffectDuration"
// EffectNode, uint32
#define kVideoSegmentProperty_Effect_RuntimeInstanceID "EffectNode::RuntimeInstanceID"
// EffectNode, string
#define kVideoSegmentProperty_Effect_LayerInputHashes "EffectNode::LayerInputHashes"
// EffectNode, string
#define kVideoSegmentProperty_Effect_StreamLabel "EffectNode::StreamLabel"
// EffectNode, string
#define kVideoSegmentProperty_Effect_ClipName "EffectNode::ClipName"
// EffectNode, string
#define kVideoSegmentProperty_Effect_MasterClipName "EffectNode::MasterClipName"
// EffectNode, string
#define kVideoSegmentProperty_Effect_FileName "EffectNode::FileName"
// EffectNode, string
#define kVideoSegmentProperty_Effect_SourceTrackClipNameHashes "EffectNode::SourceTrackClipNameHashes"
// TransitionNode, string
#define kVideoSegmentProperty_Transition_TransitionMatchName "TransitionNode::TransitionMatchName"
// TransitionNode, binary data
#define kVideoSegmentProperty_Transition_TransitionOpaqueData "TransitionNode::TransitionOpaqueData"
// TransitionNode, fpoint32
#define kVideoSegmentProperty_Transition_TransitionStartPosition "TransitionNode::TransitionStartPosition"
// TransitionNode, fpoint32
#define kVideoSegmentProperty_Transition_TransitionEndPosition "TransitionNode::TransitionEndPosition"
// TransitionNode, fpoint32
#define kVideoSegmentProperty_Transition_TransitionCenterPosition "TransitionNode::TransitionCenterPosition"
// TransitionNode, float32
#define kVideoSegmentProperty_Transition_TransitionStartPercent "TransitionNode::TransitionStartPercent"
// TransitionNode, float32
#define kVideoSegmentProperty_Transition_TransitionEndPercent "TransitionNode::TransitionEndPercent"
// TransitionNode, float32
#define kVideoSegmentProperty_Transition_TransitionBorderWidth "TransitionNode::TransitionBorderWidth"
// TransitionNode, int32
#define kVideoSegmentProperty_Transition_TransitionBorderColor "TransitionNode::TransitionBorderColor"
// TransitionNode, bool
#define kVideoSegmentProperty_Transition_TransitionSwitchSources "TransitionNode::TransitionSwitchSources"
// TransitionNode, bool
#define kVideoSegmentProperty_Transition_TransitionReverse "TransitionNode::TransitionReverse"
// TransitionNode, int32
#define kVideoSegmentProperty_Transition_TransitionDirection "TransitionNode::TransitionDirection"
// TransitionNode, int32
#define kVideoSegmentProperty_Transition_TransitionAntiAliasQuality "TransitionNode::TransitionAntiAliasQuality"
// TransitionNode, PrTime
#define kVideoSegmentProperty_Transition_TransitionDuration "TransitionNode::TransitionDuration"
// TransitionNode, keyframe data
#define kVideoSegmentProperty_Transition_TransitionParams "TransitionNode::TransitionParams"
// TransitionNode, uint32
#define kVideoSegmentProperty_Transition_RuntimeInstanceID "TransitionNode::RuntimeInstanceID"
// AdjustmentNode, bool
#define kVideoSegmentProperty_Adjustment_AdjustmentMediaIsOpaque "AdjustmentNode::AdjustmentMediaIsOpaque"
// AdjustmentNode, bool
#define kVideoSegmentProperty_Adjustment_InvertAlpha "AdjustmentNode::InvertAlpha"
#endif
|
catarizea/medical-equipment-tracker
|
authentication/src/utils/testHelpers/user.js
|
<reponame>catarizea/medical-equipment-tracker
const { v4: uuidv4 } = require('uuid');
const models = require('../../models');
const { generateJwtToken, generateRefreshToken } = require('../../services');
const {
REFRESH_TOKEN_COOKIE,
REFRESH_TOKEN_COOKIE_OPTIONS,
} = require('../../constants/cookies');
const loadUsers = async () => {
const adminUser = await models.User.findOne({ where: { email: '<EMAIL>' } });
const defaultUser = await models.User.findOne({ where: { email: '<EMAIL>' } });
const tempUser = {
firstName: 'Stela',
lastName: 'Ciompo',
email: '<EMAIL>',
role: ['user'],
defaultRole: 'user',
isBlocked: false,
passwordHash: <PASSWORD>',
};
return {
login: async (user, withRefreshToken = false) => {
const jwtToken = generateJwtToken(user);
const jwtTokenExpiry = new Date(
new Date().getTime() +
process.env.AUTHENTICATION_JWT_TOKEN_EXPIRES * 60 * 1000
);
let refreshToken = null;
let cookie = null;
if (withRefreshToken) {
refreshToken = await generateRefreshToken(user, '127.0.0.1');
cookie = {
key: REFRESH_TOKEN_COOKIE,
value: refreshToken.token,
REFRESH_TOKEN_COOKIE_OPTIONS,
};
}
return {
jwtToken,
jwtTokenExpiry,
refreshToken,
cookie,
};
},
adminUser,
defaultUser,
tempUser,
updateBlocked: async (user, isBlocked = false) => {
await models.User.update(
{ isBlocked, role: user.role },
{ where: { id: user.id } }
);
},
createTemp: async (user) => {
user.id = uuidv4();
const createdUser = await models.User.create(user);
return createdUser;
},
destroyTemp: async (user) => {
await models.User.destroy({ where: { email: user.email } });
},
destroyRemovedUser: async (user) => {
await models.RemovedUser.destroy({ where: { email: user.email } });
},
};
};
module.exports = loadUsers;
|
muratartim/Equinox
|
src/equinox/task/ExportMultiplicationTables.java
|
<reponame>muratartim/Equinox
/*
* Copyright 2018 <NAME> (<EMAIL>).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package equinox.task;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import equinox.plugin.FileType;
import equinox.serverUtilities.Permission;
import equinox.task.InternalEquinoxTask.LongRunningTask;
import equinox.task.serializableTask.SerializableExportMultiplicationTables;
import equinox.utility.Utility;
import jxl.CellType;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
/**
* Class for export multiplication tables task.
*
* @author <NAME>
* @date Feb 19, 2016
* @time 12:43:58 PM
*/
public class ExportMultiplicationTables extends TemporaryFileCreatingTask<Void> implements LongRunningTask, SavableTask {
/** Attributes. */
private final String spectrumName_, pilotPointName_, program_, section_, mission_, issue_, delRef_, description_;
/** MUT files. */
private final List<File> mutFiles_;
/** Path to output ZIP file. */
private final File output_;
/**
* Creates export multiplication tables task.
*
* @param mutFiles
* Multiplication table files.
* @param spectrumName
* Spectrum name.
* @param pilotPointName
* Pilot point name.
* @param program
* A/C program.
* @param section
* A/C section.
* @param mission
* Fatigue mission.
* @param issue
* Multiplication table issue.
* @param delRef
* Delivery reference.
* @param description
* Description.
* @param output
* Path to output ZIP file.
*/
public ExportMultiplicationTables(List<File> mutFiles, String spectrumName, String pilotPointName, String program, String section, String mission, String issue, String delRef, String description, File output) {
mutFiles_ = mutFiles;
spectrumName_ = spectrumName;
pilotPointName_ = pilotPointName;
program_ = program;
section_ = section;
mission_ = mission;
issue_ = issue;
delRef_ = delRef;
description_ = description;
output_ = output;
}
@Override
public boolean canBeCancelled() {
return true;
}
@Override
public String getTaskTitle() {
return "Export multiplication tables";
}
@Override
public SerializableTask getSerializableTask() {
return new SerializableExportMultiplicationTables(mutFiles_, spectrumName_, pilotPointName_, program_, section_, mission_, issue_, delRef_, description_, output_);
}
@Override
protected Void call() throws Exception {
// check permission
checkPermission(Permission.EXPORT_LOADCASE_FACTOR_FILE);
// update progress info
updateTitle("Exporting multiplication tables to '" + output_.getName() + "'");
// create array to store input files
ArrayList<Path> inputFiles = new ArrayList<>();
// write info file
inputFiles.add(writeInfoFile());
// task cancelled
if (isCancelled())
return null;
// copy files to temporary folder
updateMessage("Copying multiplication tables to temporary directory...");
for (File mutFile : mutFiles_) {
inputFiles.add(Files.copy(mutFile.toPath(), getWorkingDirectory().resolve(mutFile.getName()), StandardCopyOption.REPLACE_EXISTING));
}
// task cancelled
if (isCancelled())
return null;
// zip exported files
updateMessage("Zipping exported files...");
Utility.zipFiles(inputFiles, output_, this);
// return
return null;
}
/**
* Writes out info XLS file to working directory.
*
* @return Path to info XLS file.
* @throws Exception
* If exception occurs during process.
*/
private Path writeInfoFile() throws Exception {
// update progress info
updateMessage("Writing info Excel file...");
// create info file
Path infoFile = getWorkingDirectory().resolve("Multiplication_Table_Info.xls");
// declare workbook
WritableWorkbook workbook = null;
try {
// create workbook
workbook = Workbook.createWorkbook(infoFile.toFile());
// create worksheet
WritableSheet sheet = workbook.createSheet("Multiplication Table Info", 0);
// write headers
writeHeaders(sheet);
// write info
for (int i = 0; i < mutFiles_.size(); i++) {
writeInfo(sheet, FileType.getNameWithoutExtension(mutFiles_.get(i).toPath()), i + 1);
}
// write data
workbook.write();
}
// close workbook
finally {
if (workbook != null) {
workbook.close();
}
}
// return info file
return infoFile;
}
/**
* Writes table info.
*
* @param sheet
* Worksheet.
* @param fileName
* Multiplication table file name.
* @param index
* Row index.
* @throws Exception
* If exception occurs during process.
*/
private void writeInfo(WritableSheet sheet, String fileName, int index) throws Exception {
// initialize column index
int column = 0;
// multiplication table name
sheet.addCell(new jxl.write.Label(column, index, fileName, getDataFormat(index, CellType.LABEL, false)));
column++;
// spectrum name
sheet.addCell(new jxl.write.Label(column, index, spectrumName_, getDataFormat(index, CellType.LABEL, false)));
column++;
// pilot point name
sheet.addCell(new jxl.write.Label(column, index, pilotPointName_, getDataFormat(index, CellType.LABEL, false)));
column++;
// A/C program
sheet.addCell(new jxl.write.Label(column, index, program_, getDataFormat(index, CellType.LABEL, false)));
column++;
// A/C section
sheet.addCell(new jxl.write.Label(column, index, section_, getDataFormat(index, CellType.LABEL, false)));
column++;
// fatigue mission
sheet.addCell(new jxl.write.Label(column, index, mission_, getDataFormat(index, CellType.LABEL, false)));
column++;
// issue
sheet.addCell(new jxl.write.Label(column, index, issue_, getDataFormat(index, CellType.LABEL, false)));
column++;
// delivery reference
String deliveryRef = delRef_ == null ? "DRAFT" : delRef_;
sheet.addCell(new jxl.write.Label(column, index, deliveryRef, getDataFormat(index, CellType.LABEL, false)));
column++;
// description
sheet.addCell(new jxl.write.Label(column, index, description_, getDataFormat(index, CellType.LABEL, false)));
}
/**
* Writes table headers.
*
* @param sheet
* Worksheet.
* @throws Exception
* If exception occurs during process.
*/
private static void writeHeaders(WritableSheet sheet) throws Exception {
// get header format
WritableCellFormat format = getHeaderFormat();
// initialize column index
int column = 0;
// multiplication table name
String header = "Multiplication Table Name";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// spectrum name
header = "Spectrum Name";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// pilot point name
header = "Pilot Point Name";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// A/C program
header = "A/C Program";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// A/C section
header = "A/C Section";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// fatigue mission
header = "Fatigue Mission";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// issue
header = "Multiplication Table Issue";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// delivery reference
header = "Delivery Reference";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
column++;
// description
header = "Description";
sheet.addCell(new jxl.write.Label(column, 0, header, format));
sheet.setColumnView(column, header.length());
}
/**
* Returns header format.
*
* @return Header format.
* @throws WriteException
* If exception occurs during process.
*/
private static WritableCellFormat getHeaderFormat() throws WriteException {
WritableFont cellFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
WritableCellFormat cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
cellFormat.setBackground(Colour.ORANGE);
return cellFormat;
}
/**
* Returns data format.
*
* @param rowIndex
* Row index.
* @param ct
* Cell type.
* @param isScientific
* True if scientific format.
* @return Data format.
* @throws WriteException
* If exception occurs during process.
*/
private static WritableCellFormat getDataFormat(int rowIndex, CellType ct, boolean isScientific) throws WriteException {
WritableCellFormat cellFormat = ct == CellType.NUMBER ? new WritableCellFormat(isScientific ? NumberFormats.EXPONENTIAL : NumberFormats.FLOAT) : new WritableCellFormat();
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
cellFormat.setBackground(rowIndex % 2 == 0 ? Colour.WHITE : Colour.VERY_LIGHT_YELLOW);
return cellFormat;
}
}
|
JessonYue/LeetCodeLearning
|
Array/yangliu/Solution_07_16.java
|
class Solution {
public boolean backspaceCompare(String S, String T) {
return build(S).equals(build(T));
}
public String build(String S) {
Stack<Character> ans = new Stack();
for (char c: S.toCharArray()) {
if (c != '#')
ans.push(c);
else if (!ans.empty())
ans.pop();
}
return String.valueOf(ans);
}
}
|
boveloco/Puc
|
Programacao 3D/Ray Trace/src/br/pucpr/raytracer/Vector3fOps.java
|
<reponame>boveloco/Puc
package br.pucpr.raytracer;
import org.joml.Vector3f;
public class Vector3fOps {
public static Vector3f add(Vector3f a, Vector3f b) {
return new Vector3f(a).add(b);
}
public static Vector3f sub(Vector3f a, Vector3f b) {
return new Vector3f(a).sub(b);
}
public static Vector3f mul(Vector3f v, float s) {
return new Vector3f(v).mul(s);
}
public static Vector3f mul(float s, Vector3f v) {
return new Vector3f(v).mul(s);
}
public static Vector3f mul(Vector3f a, Vector3f b) {
return new Vector3f(a).mul(b);
}
public static Vector3f reflect(Vector3f v, Vector3f n) {
return new Vector3f(v).reflect(n);
}
}
|
sravani-m/Web-Application-Security-Framework
|
tools/arachni/system/arachni-ui-web/app/models/setting.rb
|
class Setting < ActiveRecord::Base
serialize :scan_target_whitelist_patterns, Array
serialize :scan_target_blacklist_patterns, Array
serialize :scan_allowed_types, Array
serialize :profile_allowed_checks, Array
serialize :profile_allowed_plugins, Array
after_save :save_callback
SCAN_TYPES = Scan::TYPES + [:multi_instance]
def scan_target_whitelist_patterns=( string_or_hash )
super self.class.string_list_to_array( string_or_hash )
end
def scan_target_blacklist_patterns=( string_or_hash )
super self.class.string_list_to_array( string_or_hash )
end
def profile_allowed_plugins_with_info
profile_allowed_plugins.
inject( {} ) { |h, name| h[name] = ::FrameworkHelper.plugins[name]; h }
end
def profile_allowed_modules_with_info
profile_allowed_modules.
inject( {} ) { |h, name| h[name] = ::FrameworkHelper.checks[name]; h }
end
private
def save_callback
Time.zone = self.timezone
end
def self.string_list_to_array( string_or_array )
case string_or_array
when Array
string_or_array
else
string_or_array.to_s.split( /[\n\r]/ ).reject( &:empty? )
end
end
end
|
aquariumbio/trident
|
pydent/models/operation.py
|
"""Models related to operations and operation types."""
from pydent.base import ModelBase
from pydent.exceptions import AquariumModelError
from pydent.marshaller import add_schema
from pydent.models.crud_mixin import SaveMixin
from pydent.models.data_associations import DataAssociatorMixin
from pydent.models.field_value_mixins import FieldTypeInterface
from pydent.models.field_value_mixins import FieldValueInterface
from pydent.relationships import Function
from pydent.relationships import HasMany
from pydent.relationships import HasManyGeneric
from pydent.relationships import HasManyThrough
from pydent.relationships import HasOne
from pydent.relationships import HasOneFromMany
from pydent.relationships import Raw
from pydent.utils import filter_list
@add_schema
class Operation(FieldValueInterface, DataAssociatorMixin, ModelBase):
"""A Operation model."""
fields = dict(
field_values=HasMany(
"FieldValue", ref="parent_id", additional_args={"parent_class": "Operation"}
),
data_associations=HasManyGeneric(
"DataAssociation", additional_args={"parent_class": "Operation"}
),
operation_type=HasOne("OperationType"),
job_associations=HasMany("JobAssociation", "Operation"),
jobs=HasManyThrough("Job", "JobAssociation"),
plan_associations=HasMany("PlanAssociation", "Operation"),
plans=HasManyThrough("Plan", "PlanAssociation"),
status=Raw(default="planning"),
routing=Function("get_routing"),
user=HasOne("User"),
)
METATYPE = "operation_type"
def __init__(
self, operation_type_id=None, operation_type=None, status=None, x=0, y=0
):
super().__init__(
operation_type_id=operation_type_id,
operation_type=operation_type,
status=status,
field_values=None,
x=x,
y=y,
)
def get_routing(self):
routing_dict = {}
fvs = self.field_values
ot = self.operation_type
if ot is None:
return routing_dict
for ft in ot.field_types:
if ft.routing is not None:
routing_dict[ft.routing] = None
if fvs is not None:
for fv in self.field_values:
ft = self.safe_get_field_type(fv)
if ft.routing is not None:
routing_dict[ft.routing] = fv.sid
return routing_dict
@property
def successors(self):
successors = []
if self.outputs:
for output in self.outputs:
for s in output.successors:
successors.append(s.operation)
return successors
@property
def predecessors(self):
predecessors = []
if self.inputs:
for inputs in self.inputs:
for s in inputs.predecessors:
predecessors.append(s.operation)
return predecessors
def init_field_values(self):
"""Initialize the :class:`FieldValue` from the :class:`FieldType` of
the parent :class:`Operation` type."""
self.field_values = []
for field_type in self.get_metatype().field_types:
if not field_type.array:
self.new_field_value_from_field_type(field_type)
return self
def field_value_array(self, name, role):
"""Returns :class:`FieldValue` array with name and role."""
return filter_list(self.get_field_value_array(name, role))
def field_value(self, name, role):
"""Returns :class:`FieldValue` with name and role.
Return None if not found.
"""
if self.field_values:
fvs = self.field_value_array(name, role)
if len(fvs) == 0:
return None
if len(fvs) == 1:
return fvs[0]
msg = "More than one FieldValue found for the field value"
msg += (
" of operation {}.(id={}).{}.{}. Are you sure you didn't mean to "
"call 'field_value_array'?"
)
raise AquariumModelError(
msg.format(self.operation_type, self.id, role, name)
)
@property
def plan(self):
return self.plans[0]
def input_array(self, name):
return self.get_field_value_array(name, "input")
def output_array(self, name):
return self.get_field_value_array(name, "output")
def input(self, name):
"""Returns the input :class:`FieldValue` by name."""
return self.field_value(name, "input")
def output(self, name):
"""Returns the output :class:`FieldValue` by name."""
return self.field_value(name, "output")
def add_to_input_array(
self, name, sample=None, item=None, value=None, container=None
):
"""Creates and adds a new input :class:`FieldValue`. When setting
values to items/samples/containers, the item/sample/container must be
saved.
:param name: name of the FieldType/FieldValue
:type name: string
:param sample: an existing Sample
:type sample: Sample
:param item: an existing Item
:type item: Item
:param value: a string or number value
:type value: string|integer
:param container: an existing ObjectType
:type container: ObjectType
:return: the newly created FieldValue
:rtype: FieldValue
"""
return self.new_field_value(
name,
"input",
dict(sample=sample, item=item, value=value, container=container),
)
def add_to_output_array(
self, name, sample=None, item=None, value=None, container=None
):
"""Creates and adds a new output :class:`FieldValue`. When setting
values to items/samples/containers, the item/sample/container must be
saved.
:param name: name of the FieldType/FieldValue
:type name: string
:param sample: an existing Sample
:type sample: Sample
:param item: an existing Item
:type item: Item
:param value: a string or number value
:type value: string|integer
:param container: an existing ObjectType
:type container: ObjectType
:return: the newly created FieldValue
:rtype: FieldValue
"""
return self.new_field_value(
name,
"output",
dict(sample=sample, item=item, value=value, container=container),
)
@property
def inputs(self):
"""Return a list of all input :class:`FieldValues`"""
return [fv for fv in self.field_values if fv.role == "input"]
@property
def outputs(self):
"""Return a list of all output :class:`FieldValues`"""
return [fv for fv in self.field_values if fv.role == "output"]
def set_input(
self, name, sample=None, item=None, value=None, container=None, object_type=None
):
"""Sets a input :class:`FieldValue` to a value. When setting values to
items/samples/containers, the item/sample/container must be saved.
:param name: name of the FieldValue/FieldType
:type name: string
:param sample: an existing Sample
:type sample: Sample
:param item: an existing Item
:type item: Item
:param value: a string or number value
:type value: string|integer
:param container: an existing ObjectType
:type container: ObjectType
:return: the existing FieldValue modified
:rtype: FieldValue
"""
if object_type is None and container:
object_type = container
return self.set_field_value(
name,
"input",
dict(sample=sample, item=item, value=value, object_type=container),
)
def set_output(
self, name, sample=None, item=None, value=None, container=None, object_type=None
):
"""Sets a output :class:`FieldValue` to a value. When setting values to
items/samples/containers, the item/sample/container must be saved.
:param name: name of the FieldValue/FieldType
:type name: string
:param sample: an existing Sample
:type sample: Sample
:param item: an existing Item
:type item: Item
:param value: a string or number value
:type value: string|integer
:param container: an existing ObjectType
:type container: ObjectType
:return: the existing FieldValue modified
:rtype: FieldValue
"""
if object_type is None and container:
object_type = container
return self.set_field_value(
name,
"output",
dict(sample=sample, item=item, value=value, object_type=object_type),
)
def set_input_array(self, name, values):
"""Sets input :class:`FieldValue` array using values. Values should be
a list of dictionaries containing sample, item, container, or values
keys. When setting values to items/samples/containers, the
item/sample/container must be saved.
:param name: name of the FieldType/FieldValues being modified
:type name: string
:param values: list of dictionary of values to set
(e.g. [{"sample": mysample}, {"item": myitem}])
:type values: list
:return: the list of modified FieldValues
:rtype: list
"""
return self.set_field_value_array(name, "input", values)
def set_output_array(self, name, values):
"""Sets output :class:`FieldValue` array using values. Values should be
a list of dictionaries containing sample, item, container, or values
keys. When setting values to items/samples/containers, the
item/sample/container must be saved.
:param name: name of the FieldType/FieldValues being modified
:type name: string
:param values: list of dictionary of values to set
(e.g. [{"sample": mysample}, {"item": myitem}])
:type values: list
:return: the list of modified FieldValues
:rtype: list
"""
return self.set_field_value_array(name, "output", values)
def show(self, pre=""):
"""Print the operation nicely."""
print(pre + self.operation_type.name + " " + str(self.cost))
for field_value in self.field_values:
field_value.show(pre=pre + " ")
def __str__(self):
return self._to_str(operation_type_name=self.operation_type.name)
@add_schema
class OperationType(FieldTypeInterface, SaveMixin, ModelBase):
"""Represents an OperationType, which is the definition of a protocol in
Aquarium."""
fields = dict(
operations=HasMany("Operation", "OperationType"),
field_types=HasMany(
"FieldType",
ref="parent_id",
additional_args={"parent_class": "OperationType"},
),
codes=HasManyGeneric("Code"),
cost_model=HasOneFromMany(
"Code",
ref="parent_id",
additional_args={"parent_class": "OperationType", "name": "cost_model"},
),
documentation=HasOneFromMany(
"Code",
ref="parent_id",
additional_args={"parent_class": "OperationType", "name": "documentation"},
),
precondition=HasOneFromMany(
"Code",
ref="parent_id",
additional_args={"parent_class": "OperationType", "name": "precondition"},
),
protocol=HasOneFromMany(
"Code",
ref="parent_id",
additional_args={"parent_class": "OperationType", "name": "protocol"},
),
test=HasOneFromMany(
"Code",
ref="parent_id",
additional_args={"parent_class": "OperationType", "name": "test"},
),
)
def code(self, accessor):
if accessor in [
"protocol",
"precondition",
"documentation",
"cost_model",
"test",
]:
return getattr(self, accessor)
return None
def instance(self, xpos=0, ypos=0):
operation = self.session.Operation.new(
operation_type_id=self.id, status="planning", x=xpos, y=ypos
)
operation.operation_type = self
operation.init_field_values()
return operation
def field_type(self, name, role):
if self.field_types:
fts = filter_list(self.field_types, role=role, name=name)
if len(fts) > 0:
return fts[0]
def sample_type(self):
sample_types = []
for field_type in self.field_types:
for allowable_field_type in field_type.allowable_field_types:
sample_types.append(allowable_field_type.sample_type)
return sample_types
def object_type(self):
object_types = []
for field_type in self.field_types:
for allowable_field_type in field_type.allowable_field_types:
object_types.append(allowable_field_type.object_type)
return object_types
def output(self, name):
return self.field_type(name, "output")
def input(self, name):
return self.field_type(name, "input")
def save(self):
"""Saves the Operation Type to the Aquarium server.
Requires this Operation Type to be connected to a session.
"""
return self.reload(self.session.utils.create_operation_type(self))
def to_save_json(self):
op_data = self.dump(
include={
"field_types": {"allowable_field_types": {}},
"protocol": {},
"cost_model": {},
"documentation": {},
"precondition": {},
"test": {},
}
)
# Format 'sample_type' and 'object_type' keys for afts
for ft_d, ft in zip(op_data["field_types"], self.field_types):
for aft_d, aft in zip(
ft_d["allowable_field_types"], ft.allowable_field_types
):
aft_d["sample_type"] = {"name": aft.sample_type.name}
aft_d["object_type"] = {"name": aft.object_type.name}
return op_data
def _get_create_json(self):
return self.to_save_json()
def _get_update_json(self):
return self.to_save_json()
def __str__(self):
return self._to_str("id", "name", "category")
|
alexfradiani/AlxFx
|
project/src/fradiani/env/ABar.java
|
<reponame>alexfradiani/AlxFx
package fradiani.env;
import fradiani.env.TickServer.TF;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* Model of a Bar
*/
public class ABar {
public double high;
public double low;
public double open;
public double close;
public long start;
public long end;
/**
* offset a millisecond time to its closest exact timeframe value
*/
public static long truncMillisTF(long time, TF timeframe) {
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
gc.setTimeInMillis(time);
//truncate the time to the timeframe being used
switch (timeframe) {
case T_1MIN:
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
break;
case T_5MIN:
//round to 5-min timeframe
int min = gc.get(Calendar.MINUTE);
min = 5 * (int) (min / 5);
gc.set(Calendar.MINUTE, min);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
break;
case T_15MIN:
min = gc.get(Calendar.MINUTE);
min = 15 * (int) (min / 15);
gc.set(Calendar.MINUTE, min);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
break;
case T_30MIN:
min = gc.get(Calendar.MINUTE);
min = 30 * (int) (min / 30);
gc.set(Calendar.MINUTE, min);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
break;
case T_1HOUR:
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
break;
}
return gc.getTimeInMillis();
}
/**
* Get the value of a timeframe as millisecs e.g: T_1MIN is 60000 millisecs
*/
public static long tfAsMillis(TF timeframe) {
int coef = 0;
switch (timeframe) {
case T_1MIN:
coef = 1;
break;
case T_5MIN:
coef = 5;
break;
case T_15MIN:
coef = 15;
break;
case T_30MIN:
coef = 30;
break;
case T_1HOUR:
coef = 60;
break;
}
return coef * 60 * 1000;
}
}
|
sjamboro/kogito-runtimes
|
kogito-codegen-modules/kogito-codegen-openapi/src/main/java/org/kie/kogito/codegen/openapi/client/OpenApiUtils.java
|
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.codegen.openapi.client;
import org.kie.kogito.codegen.api.context.KogitoBuildContext;
import static java.util.Objects.requireNonNull;
public final class OpenApiUtils {
private OpenApiUtils() {
}
/**
* Abstraction of the user's project temporary location
*/
public static String getTempDirLocation(KogitoBuildContext context) {
return context.getAppPaths().getOutputTarget().toString();
}
public static void requireValidSpecURI(final OpenApiSpecDescriptor resource) {
requireNonNull(resource, "OpenApiSpecDescriptor can't be null");
requireNonNull(resource.getURI(), "URI in OpenApiSpecDescriptor is null");
if (resource.getURI().getPath().equals("")) {
throw new IllegalArgumentException("Invalid OpenAPI spec file path: " + resource);
}
}
}
|
alwin-george-bsl/asanti
|
src/test/java/com/brightsparklabs/asanti/mocks/model/schema/TestAsnSchema.java
|
<filename>src/test/java/com/brightsparklabs/asanti/mocks/model/schema/TestAsnSchema.java
/*
* Maintained by brightSPARK Labs.
* www.brightsparklabs.com
*
* Refer to LICENSE at repository root for license details.
*/
package com.brightsparklabs.asanti.mocks.model.schema;
import static org.mockito.Mockito.*;
import com.brightsparklabs.asanti.model.schema.AsnSchema;
import com.brightsparklabs.asanti.reader.AsnSchemaReader;
import com.google.common.io.CharSource;
/**
* Utility class for obtaining a test instance of {@link AsnSchema} which conform to the test ASN.1
* schema defined in the {@code README.md} file
*
* @author brightSPARK Labs
*/
public class TestAsnSchema {
// -------------------------------------------------------------------------
// CONSTANTS
// -------------------------------------------------------------------------
/** the example schema defined in the {@code README.md} file */
public static final String TEST_SCHEMA_TEXT =
new StringBuilder()
.append("Document-PDU\n")
.append(
" { joint-iso-itu-t internationalRA(23) set(42) set-vendors(9) example(99) modules(2) document(1) }\n")
.append("DEFINITIONS")
.append(" AUTOMATIC TAGS ::=")
.append("BEGIN")
.append("EXPORTS Header, Body;\n")
.append("IMPORTS")
.append(" People,")
.append(" Person")
.append(" FROM People-Protocol")
.append(
" { joint-iso-itu-t internationalRA(23) set(42) set-vendors(9) example(99) modules(2) people(2) };")
.append(" Document ::= SEQUENCE")
.append(" {\n")
.append(" header [1] Header,\n")
.append(" body [2] Body,\n")
.append(" footer [3] Footer,\n")
.append(" dueDate [4] Date-Due,\n")
.append(" version [5] SEQUENCE\n")
.append(" {\n")
.append(" majorVersion [0] INTEGER,\n")
.append(" minorVersion [1] INTEGER\n")
.append(" },\n")
.append(" description [6] SET\n")
.append(" {\n")
.append(" numberLines [0] INTEGER,\n")
.append(" summary [1] OCTET STRING\n")
.append(" } OPTIONAL,\n")
.append(" aliasHeader [7] OCTET STRING (CONTAINING Header)\n")
.append(" }\n")
.append(" Header ::= SEQUENCE\n")
.append(" {")
.append(" published [0] PublishedMetadata")
.append(" }\n")
.append(" Body ::= SEQUENCE")
.append(" {")
.append(" lastModified [0] ModificationMetadata,")
.append(" prefix [1] Section-Note OPTIONAL,")
.append(" content [2] Section-Main,\n")
.append(" suffix [3] Section-Note OPTIONAL")
.append(" }\n")
.append(" Footer ::= SET")
.append(" {")
.append(" authors [0] People")
.append(" }\n")
.append(" PublishedMetadata ::= SEQUENCE")
.append(" {")
.append(" date [1] GeneralizedTime,")
.append(" country [2] OCTET STRING OPTIONAL")
.append(" }\n")
.append(" ModificationMetadata ::= SEQUENCE")
.append(" {")
.append(" date [0] GeneralizedTime,")
.append(" modifiedBy [1] Person")
.append(" }\n")
.append(" Section-Note ::= SEQUENCE")
.append(" {")
.append(" text [1] OCTET STRING")
.append(" }\n")
.append(" Section-Main ::= SEQUENCE")
.append(" {")
.append(" text [1] UTF8String OPTIONAL,")
.append(" paragraphs [2] SEQUENCE OF Paragraph,")
.append(" sections [3] SET OF")
.append(" SET")
.append(" {")
.append(" number [1] INTEGER,")
.append(" text [2] OCTET STRING")
.append(" }")
.append(" }\n")
.append(" Paragraph ::= SEQUENCE")
.append(" {")
.append(" title [1] OCTET STRING,")
.append(" contributor [2] Person OPTIONAL,")
.append(" points [3] SEQUENCE OF OCTET STRING")
.append(" }\n")
.append(" References ::= SEQUENCE (SIZE (1..50)) OF")
.append(" SEQUENCE")
.append(" {")
.append(" title [1] OCTET STRING,")
.append(" url [2] OCTET STRING")
.append(" }\n")
.append(" Date-Due ::= INTEGER\n")
.append(" {")
.append(" tomorrow(0),\n")
.append(" three-day(1),\n")
.append(" week (2)\n")
.append(" } DEFAULT week\n")
.append("END")
.append("\n")
.append("People-Protocol\r\n\r\n")
.append(
"\t\t{ joint-iso-itu-t internationalRA(23) set(42) set-vendors(9) example(99) modules(2) people(2) }\r\n")
.append("DEFINITIONS\r\n")
.append(" AUTOMATIC TAGS ::=\r\n")
.append("BEGIN\r\n")
.append(" DefaultAge INTEGER ::= 45\r\n")
.append(" People ::= SET OF Person\r\n")
.append(" Person ::= SEQUENCE\r\n")
.append(" {\r\n")
.append(" firstName \t[1]\t VisibleString,\r\n")
.append(" lastName \t [2]\t OCTET STRING,\r\n")
.append(" title\t\t [3]\t ENUMERATED\r\n")
.append(" { mr, mrs, ms, dr, rev } OPTIONAL,\r\n")
.append(" gender \t \tGender OPTIONAL\r\n")
.append(" } \n")
.append(" Gender ::= ENUMERATED \r\n")
.append(" {")
.append(" male(0), \r\n")
.append(" female(1)\t\t\r\n")
.append(" }\r\n")
.append("END\r\n")
.toString();
// -------------------------------------------------------------------------
// INSTANCE VARIABLES
// -------------------------------------------------------------------------
/** singleton instance */
private static AsnSchema instance;
// -------------------------------------------------------------------------
// PUBLIC METHODS
// -------------------------------------------------------------------------
/**
* Returns a singleton instance of this class
*
* @return a singleton instance
*/
public static AsnSchema getInstance() throws Exception {
if (instance != null) {
return instance;
}
final CharSource schemaSource = CharSource.wrap(TEST_SCHEMA_TEXT);
instance = AsnSchemaReader.read(schemaSource);
return instance;
}
}
|
Nalhin/Leetcode
|
src/main/java/com/leetcode/arrays/medium/CombinationSum_39.java
|
<reponame>Nalhin/Leetcode
package com.leetcode.arrays.medium;
// Given an array of distinct integers candidates and a target integer target, re
// turn a list of all unique combinations of candidates where the chosen numbers su
// m to target. You may return the combinations in any order.
//
// The same number may be chosen from candidates an unlimited number of times. T
// wo combinations are unique if the frequency of at least one of the chosen number
// s is different.
//
//
// Example 1:
//
//
// Input: candidates = [2,3,6,7], target = 7
// Output: [[2,2,3],[7]]
// Explanation:
// 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple ti
// mes.
// 7 is a candidate, and 7 = 7.
// These are the only two combinations.
//
//
// Example 2:
//
//
// Input: candidates = [2,3,5], target = 8
// Output: [[2,2,2,2],[2,3,3],[3,5]]
//
//
// Example 3:
//
//
// Input: candidates = [2], target = 1
// Output: []
//
//
// Example 4:
//
//
// Input: candidates = [1], target = 1
// Output: [[1]]
//
//
// Example 5:
//
//
// Input: candidates = [1], target = 2
// Output: [[1,1]]
//
//
//
// Constraints:
//
//
// 1 <= candidates.length <= 30
// 1 <= candidates[i] <= 200
// All elements of candidates are distinct.
// 1 <= target <= 500
//
// Related Topics Array Backtracking
// 👍 4560 👎 129
// leetcode submit region begin(Prohibit modification and deletion)
import java.util.ArrayList;
import java.util.List;
public class CombinationSum_39 {
private final List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtrack(candidates, 0, new ArrayList<>(), target);
return result;
}
private void backtrack(int[] candidates, int start, List<Integer> curr, int remaining) {
if (remaining == 0) {
result.add(new ArrayList<>(curr));
} else if (remaining > 0) {
for (int i = start; i < candidates.length; i++) {
curr.add(candidates[i]);
backtrack(candidates, i, curr, remaining - candidates[i]);
curr.remove(curr.size() - 1);
}
}
}
}
/*
T - target
M - min value
O(n^((T/M) + 1)) Runtime: 3 ms, faster than 80.27% of Java online submissions for Combination Sum.
O(T/M) Memory Usage: 39.4 MB, less than 89.09% of Java online submissions for Combination Sum.
*/
// leetcode submit region end(Prohibit modification and deletion)
|
bibonev/PacmanPlusPlus
|
src/main/java/gamelogic/core/GameLogic.java
|
<filename>src/main/java/gamelogic/core/GameLogic.java
package main.java.gamelogic.core;
import main.java.event.Event;
import main.java.event.arguments.GameDisplayInvalidatedEventArgs;
import main.java.event.arguments.GameEndedEventArgs;
import main.java.event.arguments.LocalPlayerDespawnEventArgs;
import main.java.event.arguments.LocalPlayerSpawnEventArgs;
import main.java.event.arguments.ReadyToStartEventArgs;
import main.java.event.listener.DotsEatenChangedListener;
import main.java.event.listener.GameDisplayInvalidatedListener;
import main.java.event.listener.GameEndedListener;
import main.java.event.listener.LocalPlayerDespawnListener;
import main.java.event.listener.LocalPlayerSpawnListener;
import main.java.event.listener.ReadyToStartListener;
import main.java.gamelogic.domain.Game;
public abstract class GameLogic {
public static final int GAME_STEP_DURATION = 250;
private Game game;
private Event<GameDisplayInvalidatedListener, GameDisplayInvalidatedEventArgs> onGameDisplayInvalidated;
private Event<GameEndedListener, GameEndedEventArgs> onGameEnded;
private Event<LocalPlayerSpawnListener, LocalPlayerSpawnEventArgs> onLocalPlayerSpawn;
private Event<LocalPlayerDespawnListener, LocalPlayerDespawnEventArgs> onLocalPlayerDespawn;
private Event<ReadyToStartListener, ReadyToStartEventArgs> onReadyToStart;
private Event<DotsEatenChangedListener, Integer> onDotsEatenChanged;
public abstract void gameStep(int delay);
public Event<GameDisplayInvalidatedListener, GameDisplayInvalidatedEventArgs> getOnGameDisplayInvalidated() {
return onGameDisplayInvalidated;
}
public Event<GameEndedListener, GameEndedEventArgs> getOnGameEnded() {
return onGameEnded;
}
public Event<LocalPlayerSpawnListener, LocalPlayerSpawnEventArgs> getOnLocalPlayerSpawn() {
return onLocalPlayerSpawn;
}
public Event<LocalPlayerDespawnListener, LocalPlayerDespawnEventArgs> getOnLocalPlayerDespawn() {
return onLocalPlayerDespawn;
}
public Event<ReadyToStartListener, ReadyToStartEventArgs> getOnReadyToStart() {
return onReadyToStart;
}
public void readyToStart() {
getOnReadyToStart().fire(new ReadyToStartEventArgs(game, this));
}
public GameLogic(final Game game) {
this.game = game;
onReadyToStart = new Event<>((l, a) -> l.onReadyToStart(a));
onGameDisplayInvalidated = new Event<>((l, a) -> l.onGameDisplayInvalidated(a));
onGameEnded = new Event<>((l, a) -> l.onGameEnded(a));
onLocalPlayerSpawn = new Event<>((l, a) -> l.onLocalPlayerSpawn(a));
onLocalPlayerDespawn = new Event<>((l, a) -> l.onLocalPlayerDespawn(a));
}
}
|
antonmedv/year
|
packages/2005/05/07/index.js
|
<filename>packages/2005/05/07/index.js
module.exports = new Date(2005, 4, 7)
|
dc4cities/central-system
|
modules/escalation-manager/src/main/java/eu/dc4cities/controlsystem/modules/escalationmanager/PowerRenPercent.java
|
<filename>modules/escalation-manager/src/main/java/eu/dc4cities/controlsystem/modules/escalationmanager/PowerRenPercent.java
/*
* Copyright 2016 The DC4Cities author.
*
* 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 eu.dc4cities.controlsystem.modules.escalationmanager;
import org.jscience.physics.amount.Amount;
import javax.measure.quantity.Dimensionless;
import javax.measure.quantity.Power;
public class PowerRenPercent implements Comparable
{
private Amount<Power> power;
private Amount<Dimensionless> renPercent;
/**
*
*/
public PowerRenPercent() {
}
/**
* @param power
* @param renPercent
*/
public PowerRenPercent(Amount<Power> power, Amount<Dimensionless> renPercent) {
this.power = power;
this.renPercent = renPercent;
}
/**
* @return the power
*/
public Amount<Power> getPower() {
return power;
}
/**
* @param power the power to set
*/
public void setPower(Amount<Power> power) {
this.power = power;
}
/**
* @return the renPercent
*/
public Amount<Dimensionless> getRenPercent() {
return renPercent;
}
/**
* @param renPercent the renPercent to set
*/
public void setRenPercent(Amount<Dimensionless> renPercent) {
this.renPercent = renPercent;
}
@Override
public boolean equals(Object o)
{
if(o instanceof PowerRenPercent)
{
PowerRenPercent prp = (PowerRenPercent)o;
return this.renPercent.equals(prp.renPercent);
}
return false;
}
@Override
public int compareTo(Object o)
{
if(o instanceof PowerRenPercent)
{
PowerRenPercent prp = (PowerRenPercent)o;
return this.renPercent.compareTo(prp.renPercent);
}
return 0;
}
}
|
AresSys/AresOperator
|
metadata/annotations.go
|
<reponame>AresSys/AresOperator<gh_stars>1-10
package metadata
// AresQueue related
const (
// AresQueueAnnotationKey is the annotation key of Pod to identify
// which ares-queue it belongs to.
AresQueueAnnotationKey = GroupName + "/ares-queue"
// PreemptableAnnotationKey is the annotation key of Pod to determine
// if it is preemptable
PreemptableAnnotationKey = GroupName + "/preemptable"
// JobPriorityAnnotationKey is the annotation key of AresJob/PodGroup
// to indicate the priority of job
JobPriorityAnnotationKey = GroupName + "/job-priority"
)
// AresScheduler related
const (
// KubeMonopolizeNodesAnnotationKey is the annotation key of Pod to declare that
// it wants to monopolize nodes with other pods which have the same value of this annotation.
// KubeMonopolizeNodesAnnotationKey是Pod的annotation关键字,用以声明其想与含有同样value的一组Pod独占一组节点
KubeMonopolizeNodesAnnotationKey = "ares.io/monopolize-nodes"
)
|
cwx508489/react-template
|
src/routes/home/index.js
|
<reponame>cwx508489/react-template
import React from 'react';
import i18n from "i18n";
import HomePage from './HomePage';
import CONSTANTS from '../../constants';
export default {
path: `${CONSTANTS.ROUTE_HOME}`,
async action({next,render,context,params}){
context.setTitle(i18n.t('common:website'));
context.setCss("home");
context.setJs("home");
return <HomePage />;
}
};
|
mzlogin/LeetCode
|
algorithms/cpp/mylist.h
|
<filename>algorithms/cpp/mylist.h
#include <stdio.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createList(int* nums, int len) {
ListNode* head = NULL;
ListNode* tail = NULL;
for (int i = 0; i < len; i++) {
if (head == NULL) {
head = new ListNode(nums[i]);
tail = head;
} else {
tail->next = new ListNode(nums[i]);
tail = tail->next;
}
}
return head;
}
bool arrayEqualsList(int* nums, int len, ListNode* list) {
for (int i = 0; i < len; i++) {
if (list == NULL || list->val != nums[i]) {
return false;
}
list = list->next;
}
return true;
}
int getListValueAt(ListNode* root, int pos) {
for (int i = 0; i < pos; i++) {
root = root->next;
}
return root->val;
}
void printList(ListNode* list) {
if (list != NULL) {
ListNode* p = list;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
}
|
cisco-ie/cisco-proto
|
codegen/go/xr/62x/cisco_ios_xr_ipv4_bgp_oper/bgp/instances/instance/instance_standby/default_vrf/afs/af/advertised_path_xr/advertised_path/bgp_path_bag.pb.go
|
<filename>codegen/go/xr/62x/cisco_ios_xr_ipv4_bgp_oper/bgp/instances/instance/instance_standby/default_vrf/afs/af/advertised_path_xr/advertised_path/bgp_path_bag.pb.go
/*
Copyright 2019 Cisco Systems
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.
*/
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: bgp_path_bag.proto
package cisco_ios_xr_ipv4_bgp_oper_bgp_instances_instance_instance_standby_default_vrf_afs_af_advertised_path_xr_advertised_path
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// 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.ProtoPackageIsVersion3 // please upgrade the proto package
type BgpPathBag_KEYS struct {
InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3" json:"instance_name,omitempty"`
AfName string `protobuf:"bytes,2,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"`
Rd string `protobuf:"bytes,3,opt,name=rd,proto3" json:"rd,omitempty"`
Network string `protobuf:"bytes,4,opt,name=network,proto3" json:"network,omitempty"`
PrefixLength uint32 `protobuf:"varint,5,opt,name=prefix_length,json=prefixLength,proto3" json:"prefix_length,omitempty"`
NeighborAddress string `protobuf:"bytes,6,opt,name=neighbor_address,json=neighborAddress,proto3" json:"neighbor_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpPathBag_KEYS) Reset() { *m = BgpPathBag_KEYS{} }
func (m *BgpPathBag_KEYS) String() string { return proto.CompactTextString(m) }
func (*BgpPathBag_KEYS) ProtoMessage() {}
func (*BgpPathBag_KEYS) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{0}
}
func (m *BgpPathBag_KEYS) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpPathBag_KEYS.Unmarshal(m, b)
}
func (m *BgpPathBag_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpPathBag_KEYS.Marshal(b, m, deterministic)
}
func (m *BgpPathBag_KEYS) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpPathBag_KEYS.Merge(m, src)
}
func (m *BgpPathBag_KEYS) XXX_Size() int {
return xxx_messageInfo_BgpPathBag_KEYS.Size(m)
}
func (m *BgpPathBag_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_BgpPathBag_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_BgpPathBag_KEYS proto.InternalMessageInfo
func (m *BgpPathBag_KEYS) GetInstanceName() string {
if m != nil {
return m.InstanceName
}
return ""
}
func (m *BgpPathBag_KEYS) GetAfName() string {
if m != nil {
return m.AfName
}
return ""
}
func (m *BgpPathBag_KEYS) GetRd() string {
if m != nil {
return m.Rd
}
return ""
}
func (m *BgpPathBag_KEYS) GetNetwork() string {
if m != nil {
return m.Network
}
return ""
}
func (m *BgpPathBag_KEYS) GetPrefixLength() uint32 {
if m != nil {
return m.PrefixLength
}
return 0
}
func (m *BgpPathBag_KEYS) GetNeighborAddress() string {
if m != nil {
return m.NeighborAddress
}
return ""
}
type BgpL2VpnAddrT struct {
L2VpnAddress []uint32 `protobuf:"varint,1,rep,packed,name=l2vpn_address,json=l2vpnAddress,proto3" json:"l2vpn_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpL2VpnAddrT) Reset() { *m = BgpL2VpnAddrT{} }
func (m *BgpL2VpnAddrT) String() string { return proto.CompactTextString(m) }
func (*BgpL2VpnAddrT) ProtoMessage() {}
func (*BgpL2VpnAddrT) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{1}
}
func (m *BgpL2VpnAddrT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpL2VpnAddrT.Unmarshal(m, b)
}
func (m *BgpL2VpnAddrT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpL2VpnAddrT.Marshal(b, m, deterministic)
}
func (m *BgpL2VpnAddrT) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpL2VpnAddrT.Merge(m, src)
}
func (m *BgpL2VpnAddrT) XXX_Size() int {
return xxx_messageInfo_BgpL2VpnAddrT.Size(m)
}
func (m *BgpL2VpnAddrT) XXX_DiscardUnknown() {
xxx_messageInfo_BgpL2VpnAddrT.DiscardUnknown(m)
}
var xxx_messageInfo_BgpL2VpnAddrT proto.InternalMessageInfo
func (m *BgpL2VpnAddrT) GetL2VpnAddress() []uint32 {
if m != nil {
return m.L2VpnAddress
}
return nil
}
type BgpL2VpnMspwAddrT struct {
L2VpnAddress []uint32 `protobuf:"varint,1,rep,packed,name=l2vpn_address,json=l2vpnAddress,proto3" json:"l2vpn_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpL2VpnMspwAddrT) Reset() { *m = BgpL2VpnMspwAddrT{} }
func (m *BgpL2VpnMspwAddrT) String() string { return proto.CompactTextString(m) }
func (*BgpL2VpnMspwAddrT) ProtoMessage() {}
func (*BgpL2VpnMspwAddrT) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{2}
}
func (m *BgpL2VpnMspwAddrT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpL2VpnMspwAddrT.Unmarshal(m, b)
}
func (m *BgpL2VpnMspwAddrT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpL2VpnMspwAddrT.Marshal(b, m, deterministic)
}
func (m *BgpL2VpnMspwAddrT) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpL2VpnMspwAddrT.Merge(m, src)
}
func (m *BgpL2VpnMspwAddrT) XXX_Size() int {
return xxx_messageInfo_BgpL2VpnMspwAddrT.Size(m)
}
func (m *BgpL2VpnMspwAddrT) XXX_DiscardUnknown() {
xxx_messageInfo_BgpL2VpnMspwAddrT.DiscardUnknown(m)
}
var xxx_messageInfo_BgpL2VpnMspwAddrT proto.InternalMessageInfo
func (m *BgpL2VpnMspwAddrT) GetL2VpnAddress() []uint32 {
if m != nil {
return m.L2VpnAddress
}
return nil
}
type BgpIpv4SrpolicyAddrT struct {
Ipv4SrpolicyAddress []uint32 `protobuf:"varint,1,rep,packed,name=ipv4_srpolicy_address,json=ipv4SrpolicyAddress,proto3" json:"ipv4_srpolicy_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpIpv4SrpolicyAddrT) Reset() { *m = BgpIpv4SrpolicyAddrT{} }
func (m *BgpIpv4SrpolicyAddrT) String() string { return proto.CompactTextString(m) }
func (*BgpIpv4SrpolicyAddrT) ProtoMessage() {}
func (*BgpIpv4SrpolicyAddrT) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{3}
}
func (m *BgpIpv4SrpolicyAddrT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpIpv4SrpolicyAddrT.Unmarshal(m, b)
}
func (m *BgpIpv4SrpolicyAddrT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpIpv4SrpolicyAddrT.Marshal(b, m, deterministic)
}
func (m *BgpIpv4SrpolicyAddrT) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpIpv4SrpolicyAddrT.Merge(m, src)
}
func (m *BgpIpv4SrpolicyAddrT) XXX_Size() int {
return xxx_messageInfo_BgpIpv4SrpolicyAddrT.Size(m)
}
func (m *BgpIpv4SrpolicyAddrT) XXX_DiscardUnknown() {
xxx_messageInfo_BgpIpv4SrpolicyAddrT.DiscardUnknown(m)
}
var xxx_messageInfo_BgpIpv4SrpolicyAddrT proto.InternalMessageInfo
func (m *BgpIpv4SrpolicyAddrT) GetIpv4SrpolicyAddress() []uint32 {
if m != nil {
return m.Ipv4SrpolicyAddress
}
return nil
}
type BgpIpv6SrpolicyAddrT struct {
Ipv6SrpolicyAddress []uint32 `protobuf:"varint,1,rep,packed,name=ipv6_srpolicy_address,json=ipv6SrpolicyAddress,proto3" json:"ipv6_srpolicy_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpIpv6SrpolicyAddrT) Reset() { *m = BgpIpv6SrpolicyAddrT{} }
func (m *BgpIpv6SrpolicyAddrT) String() string { return proto.CompactTextString(m) }
func (*BgpIpv6SrpolicyAddrT) ProtoMessage() {}
func (*BgpIpv6SrpolicyAddrT) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{4}
}
func (m *BgpIpv6SrpolicyAddrT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpIpv6SrpolicyAddrT.Unmarshal(m, b)
}
func (m *BgpIpv6SrpolicyAddrT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpIpv6SrpolicyAddrT.Marshal(b, m, deterministic)
}
func (m *BgpIpv6SrpolicyAddrT) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpIpv6SrpolicyAddrT.Merge(m, src)
}
func (m *BgpIpv6SrpolicyAddrT) XXX_Size() int {
return xxx_messageInfo_BgpIpv6SrpolicyAddrT.Size(m)
}
func (m *BgpIpv6SrpolicyAddrT) XXX_DiscardUnknown() {
xxx_messageInfo_BgpIpv6SrpolicyAddrT.DiscardUnknown(m)
}
var xxx_messageInfo_BgpIpv6SrpolicyAddrT proto.InternalMessageInfo
func (m *BgpIpv6SrpolicyAddrT) GetIpv6SrpolicyAddress() []uint32 {
if m != nil {
return m.Ipv6SrpolicyAddress
}
return nil
}
type BgpAddrtype struct {
Afi string `protobuf:"bytes,1,opt,name=afi,proto3" json:"afi,omitempty"`
Ipv4Address string `protobuf:"bytes,2,opt,name=ipv4_address,json=ipv4Address,proto3" json:"ipv4_address,omitempty"`
Ipv4McastAddress string `protobuf:"bytes,3,opt,name=ipv4_mcast_address,json=ipv4McastAddress,proto3" json:"ipv4_mcast_address,omitempty"`
Ipv4LabelAddress string `protobuf:"bytes,4,opt,name=ipv4_label_address,json=ipv4LabelAddress,proto3" json:"ipv4_label_address,omitempty"`
Ipv4TunnelAddress string `protobuf:"bytes,5,opt,name=ipv4_tunnel_address,json=ipv4TunnelAddress,proto3" json:"ipv4_tunnel_address,omitempty"`
Ipv4MdtAddress string `protobuf:"bytes,6,opt,name=ipv4mdt_address,json=ipv4mdtAddress,proto3" json:"ipv4mdt_address,omitempty"`
Ipv4VpnAddress string `protobuf:"bytes,7,opt,name=ipv4vpn_address,json=ipv4vpnAddress,proto3" json:"ipv4vpn_address,omitempty"`
Ipv4VpnaMcastddress string `protobuf:"bytes,8,opt,name=ipv4vpna_mcastddress,json=ipv4vpnaMcastddress,proto3" json:"ipv4vpna_mcastddress,omitempty"`
Ipv6Address string `protobuf:"bytes,9,opt,name=ipv6_address,json=ipv6Address,proto3" json:"ipv6_address,omitempty"`
Ipv6McastAddress string `protobuf:"bytes,10,opt,name=ipv6_mcast_address,json=ipv6McastAddress,proto3" json:"ipv6_mcast_address,omitempty"`
Ipv6LabelAddress string `protobuf:"bytes,11,opt,name=ipv6_label_address,json=ipv6LabelAddress,proto3" json:"ipv6_label_address,omitempty"`
Ipv6VpnAddress string `protobuf:"bytes,12,opt,name=ipv6vpn_address,json=ipv6vpnAddress,proto3" json:"ipv6vpn_address,omitempty"`
Ipv6VpnMcastAddress string `protobuf:"bytes,13,opt,name=ipv6vpn_mcast_address,json=ipv6vpnMcastAddress,proto3" json:"ipv6vpn_mcast_address,omitempty"`
L2VpnvplsAddress *BgpL2VpnAddrT `protobuf:"bytes,14,opt,name=l2vpnvpls_address,json=l2vpnvplsAddress,proto3" json:"l2vpnvpls_address,omitempty"`
RtConstraintAddress string `protobuf:"bytes,15,opt,name=rt_constraint_address,json=rtConstraintAddress,proto3" json:"rt_constraint_address,omitempty"`
Ipv6MvpnAddress string `protobuf:"bytes,16,opt,name=ipv6mvpn_address,json=ipv6mvpnAddress,proto3" json:"ipv6mvpn_address,omitempty"`
Ipv4MvpnAddress string `protobuf:"bytes,17,opt,name=ipv4mvpn_address,json=ipv4mvpnAddress,proto3" json:"ipv4mvpn_address,omitempty"`
L2VpnEvpnAddress string `protobuf:"bytes,18,opt,name=l2vpn_evpn_address,json=l2vpnEvpnAddress,proto3" json:"l2vpn_evpn_address,omitempty"`
LsLsAddress string `protobuf:"bytes,19,opt,name=ls_ls_address,json=lsLsAddress,proto3" json:"ls_ls_address,omitempty"`
L2VpnMspwAddress *BgpL2VpnMspwAddrT `protobuf:"bytes,20,opt,name=l2vpn_mspw_address,json=l2vpnMspwAddress,proto3" json:"l2vpn_mspw_address,omitempty"`
Ipv4FlowspecAddress string `protobuf:"bytes,21,opt,name=ipv4_flowspec_address,json=ipv4FlowspecAddress,proto3" json:"ipv4_flowspec_address,omitempty"`
Ipv6FlowspecAddress string `protobuf:"bytes,22,opt,name=ipv6_flowspec_address,json=ipv6FlowspecAddress,proto3" json:"ipv6_flowspec_address,omitempty"`
Ipv4VpnFlowspecAddress string `protobuf:"bytes,23,opt,name=ipv4vpn_flowspec_address,json=ipv4vpnFlowspecAddress,proto3" json:"ipv4vpn_flowspec_address,omitempty"`
Ipv6VpnFlowspecAddress string `protobuf:"bytes,24,opt,name=ipv6vpn_flowspec_address,json=ipv6vpnFlowspecAddress,proto3" json:"ipv6vpn_flowspec_address,omitempty"`
Ipv4SrPolicyAddress *BgpIpv4SrpolicyAddrT `protobuf:"bytes,25,opt,name=ipv4sr_policy_address,json=ipv4srPolicyAddress,proto3" json:"ipv4sr_policy_address,omitempty"`
Ipv6SrPolicyAddress *BgpIpv6SrpolicyAddrT `protobuf:"bytes,26,opt,name=ipv6sr_policy_address,json=ipv6srPolicyAddress,proto3" json:"ipv6sr_policy_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpAddrtype) Reset() { *m = BgpAddrtype{} }
func (m *BgpAddrtype) String() string { return proto.CompactTextString(m) }
func (*BgpAddrtype) ProtoMessage() {}
func (*BgpAddrtype) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{5}
}
func (m *BgpAddrtype) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpAddrtype.Unmarshal(m, b)
}
func (m *BgpAddrtype) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpAddrtype.Marshal(b, m, deterministic)
}
func (m *BgpAddrtype) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpAddrtype.Merge(m, src)
}
func (m *BgpAddrtype) XXX_Size() int {
return xxx_messageInfo_BgpAddrtype.Size(m)
}
func (m *BgpAddrtype) XXX_DiscardUnknown() {
xxx_messageInfo_BgpAddrtype.DiscardUnknown(m)
}
var xxx_messageInfo_BgpAddrtype proto.InternalMessageInfo
func (m *BgpAddrtype) GetAfi() string {
if m != nil {
return m.Afi
}
return ""
}
func (m *BgpAddrtype) GetIpv4Address() string {
if m != nil {
return m.Ipv4Address
}
return ""
}
func (m *BgpAddrtype) GetIpv4McastAddress() string {
if m != nil {
return m.Ipv4McastAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4LabelAddress() string {
if m != nil {
return m.Ipv4LabelAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4TunnelAddress() string {
if m != nil {
return m.Ipv4TunnelAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4MdtAddress() string {
if m != nil {
return m.Ipv4MdtAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4VpnAddress() string {
if m != nil {
return m.Ipv4VpnAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4VpnaMcastddress() string {
if m != nil {
return m.Ipv4VpnaMcastddress
}
return ""
}
func (m *BgpAddrtype) GetIpv6Address() string {
if m != nil {
return m.Ipv6Address
}
return ""
}
func (m *BgpAddrtype) GetIpv6McastAddress() string {
if m != nil {
return m.Ipv6McastAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv6LabelAddress() string {
if m != nil {
return m.Ipv6LabelAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv6VpnAddress() string {
if m != nil {
return m.Ipv6VpnAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv6VpnMcastAddress() string {
if m != nil {
return m.Ipv6VpnMcastAddress
}
return ""
}
func (m *BgpAddrtype) GetL2VpnvplsAddress() *BgpL2VpnAddrT {
if m != nil {
return m.L2VpnvplsAddress
}
return nil
}
func (m *BgpAddrtype) GetRtConstraintAddress() string {
if m != nil {
return m.RtConstraintAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv6MvpnAddress() string {
if m != nil {
return m.Ipv6MvpnAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4MvpnAddress() string {
if m != nil {
return m.Ipv4MvpnAddress
}
return ""
}
func (m *BgpAddrtype) GetL2VpnEvpnAddress() string {
if m != nil {
return m.L2VpnEvpnAddress
}
return ""
}
func (m *BgpAddrtype) GetLsLsAddress() string {
if m != nil {
return m.LsLsAddress
}
return ""
}
func (m *BgpAddrtype) GetL2VpnMspwAddress() *BgpL2VpnMspwAddrT {
if m != nil {
return m.L2VpnMspwAddress
}
return nil
}
func (m *BgpAddrtype) GetIpv4FlowspecAddress() string {
if m != nil {
return m.Ipv4FlowspecAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv6FlowspecAddress() string {
if m != nil {
return m.Ipv6FlowspecAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4VpnFlowspecAddress() string {
if m != nil {
return m.Ipv4VpnFlowspecAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv6VpnFlowspecAddress() string {
if m != nil {
return m.Ipv6VpnFlowspecAddress
}
return ""
}
func (m *BgpAddrtype) GetIpv4SrPolicyAddress() *BgpIpv4SrpolicyAddrT {
if m != nil {
return m.Ipv4SrPolicyAddress
}
return nil
}
func (m *BgpAddrtype) GetIpv6SrPolicyAddress() *BgpIpv6SrpolicyAddrT {
if m != nil {
return m.Ipv6SrPolicyAddress
}
return nil
}
type BgpPrefixtype struct {
Prefix *BgpAddrtype `protobuf:"bytes,1,opt,name=prefix,proto3" json:"prefix,omitempty"`
PrefixLength uint32 `protobuf:"varint,2,opt,name=prefix_length,json=prefixLength,proto3" json:"prefix_length,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpPrefixtype) Reset() { *m = BgpPrefixtype{} }
func (m *BgpPrefixtype) String() string { return proto.CompactTextString(m) }
func (*BgpPrefixtype) ProtoMessage() {}
func (*BgpPrefixtype) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{6}
}
func (m *BgpPrefixtype) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpPrefixtype.Unmarshal(m, b)
}
func (m *BgpPrefixtype) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpPrefixtype.Marshal(b, m, deterministic)
}
func (m *BgpPrefixtype) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpPrefixtype.Merge(m, src)
}
func (m *BgpPrefixtype) XXX_Size() int {
return xxx_messageInfo_BgpPrefixtype.Size(m)
}
func (m *BgpPrefixtype) XXX_DiscardUnknown() {
xxx_messageInfo_BgpPrefixtype.DiscardUnknown(m)
}
var xxx_messageInfo_BgpPrefixtype proto.InternalMessageInfo
func (m *BgpPrefixtype) GetPrefix() *BgpAddrtype {
if m != nil {
return m.Prefix
}
return nil
}
func (m *BgpPrefixtype) GetPrefixLength() uint32 {
if m != nil {
return m.PrefixLength
}
return 0
}
type BgpTeTunnel struct {
TunnelType string `protobuf:"bytes,1,opt,name=tunnel_type,json=tunnelType,proto3" json:"tunnel_type,omitempty"`
TunnelName []uint32 `protobuf:"varint,2,rep,packed,name=tunnel_name,json=tunnelName,proto3" json:"tunnel_name,omitempty"`
HasTunnel bool `protobuf:"varint,3,opt,name=has_tunnel,json=hasTunnel,proto3" json:"has_tunnel,omitempty"`
IsTunnelUp bool `protobuf:"varint,4,opt,name=is_tunnel_up,json=isTunnelUp,proto3" json:"is_tunnel_up,omitempty"`
IsTunnelInfoStale bool `protobuf:"varint,5,opt,name=is_tunnel_info_stale,json=isTunnelInfoStale,proto3" json:"is_tunnel_info_stale,omitempty"`
IsTunnelRegistered bool `protobuf:"varint,6,opt,name=is_tunnel_registered,json=isTunnelRegistered,proto3" json:"is_tunnel_registered,omitempty"`
TunnelV6Required bool `protobuf:"varint,7,opt,name=tunnel_v6_required,json=tunnelV6Required,proto3" json:"tunnel_v6_required,omitempty"`
TunnelV6Enabled bool `protobuf:"varint,8,opt,name=tunnel_v6_enabled,json=tunnelV6Enabled,proto3" json:"tunnel_v6_enabled,omitempty"`
BindingLabel uint32 `protobuf:"varint,9,opt,name=binding_label,json=bindingLabel,proto3" json:"binding_label,omitempty"`
TunnelIfHandle uint32 `protobuf:"varint,10,opt,name=tunnel_if_handle,json=tunnelIfHandle,proto3" json:"tunnel_if_handle,omitempty"`
LastTunnelUpdate uint32 `protobuf:"varint,11,opt,name=last_tunnel_update,json=lastTunnelUpdate,proto3" json:"last_tunnel_update,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpTeTunnel) Reset() { *m = BgpTeTunnel{} }
func (m *BgpTeTunnel) String() string { return proto.CompactTextString(m) }
func (*BgpTeTunnel) ProtoMessage() {}
func (*BgpTeTunnel) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{7}
}
func (m *BgpTeTunnel) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpTeTunnel.Unmarshal(m, b)
}
func (m *BgpTeTunnel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpTeTunnel.Marshal(b, m, deterministic)
}
func (m *BgpTeTunnel) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpTeTunnel.Merge(m, src)
}
func (m *BgpTeTunnel) XXX_Size() int {
return xxx_messageInfo_BgpTeTunnel.Size(m)
}
func (m *BgpTeTunnel) XXX_DiscardUnknown() {
xxx_messageInfo_BgpTeTunnel.DiscardUnknown(m)
}
var xxx_messageInfo_BgpTeTunnel proto.InternalMessageInfo
func (m *BgpTeTunnel) GetTunnelType() string {
if m != nil {
return m.TunnelType
}
return ""
}
func (m *BgpTeTunnel) GetTunnelName() []uint32 {
if m != nil {
return m.TunnelName
}
return nil
}
func (m *BgpTeTunnel) GetHasTunnel() bool {
if m != nil {
return m.HasTunnel
}
return false
}
func (m *BgpTeTunnel) GetIsTunnelUp() bool {
if m != nil {
return m.IsTunnelUp
}
return false
}
func (m *BgpTeTunnel) GetIsTunnelInfoStale() bool {
if m != nil {
return m.IsTunnelInfoStale
}
return false
}
func (m *BgpTeTunnel) GetIsTunnelRegistered() bool {
if m != nil {
return m.IsTunnelRegistered
}
return false
}
func (m *BgpTeTunnel) GetTunnelV6Required() bool {
if m != nil {
return m.TunnelV6Required
}
return false
}
func (m *BgpTeTunnel) GetTunnelV6Enabled() bool {
if m != nil {
return m.TunnelV6Enabled
}
return false
}
func (m *BgpTeTunnel) GetBindingLabel() uint32 {
if m != nil {
return m.BindingLabel
}
return 0
}
func (m *BgpTeTunnel) GetTunnelIfHandle() uint32 {
if m != nil {
return m.TunnelIfHandle
}
return 0
}
func (m *BgpTeTunnel) GetLastTunnelUpdate() uint32 {
if m != nil {
return m.LastTunnelUpdate
}
return 0
}
type BgpL2VpnEvpnEsiT struct {
Esi []uint32 `protobuf:"varint,1,rep,packed,name=esi,proto3" json:"esi,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpL2VpnEvpnEsiT) Reset() { *m = BgpL2VpnEvpnEsiT{} }
func (m *BgpL2VpnEvpnEsiT) String() string { return proto.CompactTextString(m) }
func (*BgpL2VpnEvpnEsiT) ProtoMessage() {}
func (*BgpL2VpnEvpnEsiT) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{8}
}
func (m *BgpL2VpnEvpnEsiT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpL2VpnEvpnEsiT.Unmarshal(m, b)
}
func (m *BgpL2VpnEvpnEsiT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpL2VpnEvpnEsiT.Marshal(b, m, deterministic)
}
func (m *BgpL2VpnEvpnEsiT) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpL2VpnEvpnEsiT.Merge(m, src)
}
func (m *BgpL2VpnEvpnEsiT) XXX_Size() int {
return xxx_messageInfo_BgpL2VpnEvpnEsiT.Size(m)
}
func (m *BgpL2VpnEvpnEsiT) XXX_DiscardUnknown() {
xxx_messageInfo_BgpL2VpnEvpnEsiT.DiscardUnknown(m)
}
var xxx_messageInfo_BgpL2VpnEvpnEsiT proto.InternalMessageInfo
func (m *BgpL2VpnEvpnEsiT) GetEsi() []uint32 {
if m != nil {
return m.Esi
}
return nil
}
type BgpV4V6T struct {
Len string `protobuf:"bytes,1,opt,name=len,proto3" json:"len,omitempty"`
Ipv4Address string `protobuf:"bytes,2,opt,name=ipv4_address,json=ipv4Address,proto3" json:"ipv4_address,omitempty"`
Ipv6Address string `protobuf:"bytes,3,opt,name=ipv6_address,json=ipv6Address,proto3" json:"ipv6_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpV4V6T) Reset() { *m = BgpV4V6T{} }
func (m *BgpV4V6T) String() string { return proto.CompactTextString(m) }
func (*BgpV4V6T) ProtoMessage() {}
func (*BgpV4V6T) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{9}
}
func (m *BgpV4V6T) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpV4V6T.Unmarshal(m, b)
}
func (m *BgpV4V6T) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpV4V6T.Marshal(b, m, deterministic)
}
func (m *BgpV4V6T) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpV4V6T.Merge(m, src)
}
func (m *BgpV4V6T) XXX_Size() int {
return xxx_messageInfo_BgpV4V6T.Size(m)
}
func (m *BgpV4V6T) XXX_DiscardUnknown() {
xxx_messageInfo_BgpV4V6T.DiscardUnknown(m)
}
var xxx_messageInfo_BgpV4V6T proto.InternalMessageInfo
func (m *BgpV4V6T) GetLen() string {
if m != nil {
return m.Len
}
return ""
}
func (m *BgpV4V6T) GetIpv4Address() string {
if m != nil {
return m.Ipv4Address
}
return ""
}
func (m *BgpV4V6T) GetIpv6Address() string {
if m != nil {
return m.Ipv6Address
}
return ""
}
type BgpAdvinfoType_ struct {
IsNeighbor bool `protobuf:"varint,1,opt,name=is_neighbor,json=isNeighbor,proto3" json:"is_neighbor,omitempty"`
NeighborAddressXr *BgpAddrtype `protobuf:"bytes,2,opt,name=neighbor_address_xr,json=neighborAddressXr,proto3" json:"neighbor_address_xr,omitempty"`
UpdateGroupNumber uint32 `protobuf:"varint,3,opt,name=update_group_number,json=updateGroupNumber,proto3" json:"update_group_number,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpAdvinfoType_) Reset() { *m = BgpAdvinfoType_{} }
func (m *BgpAdvinfoType_) String() string { return proto.CompactTextString(m) }
func (*BgpAdvinfoType_) ProtoMessage() {}
func (*BgpAdvinfoType_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{10}
}
func (m *BgpAdvinfoType_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpAdvinfoType_.Unmarshal(m, b)
}
func (m *BgpAdvinfoType_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpAdvinfoType_.Marshal(b, m, deterministic)
}
func (m *BgpAdvinfoType_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpAdvinfoType_.Merge(m, src)
}
func (m *BgpAdvinfoType_) XXX_Size() int {
return xxx_messageInfo_BgpAdvinfoType_.Size(m)
}
func (m *BgpAdvinfoType_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpAdvinfoType_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpAdvinfoType_ proto.InternalMessageInfo
func (m *BgpAdvinfoType_) GetIsNeighbor() bool {
if m != nil {
return m.IsNeighbor
}
return false
}
func (m *BgpAdvinfoType_) GetNeighborAddressXr() *BgpAddrtype {
if m != nil {
return m.NeighborAddressXr
}
return nil
}
func (m *BgpAdvinfoType_) GetUpdateGroupNumber() uint32 {
if m != nil {
return m.UpdateGroupNumber
}
return 0
}
type BgpPath_ struct {
BgpPrefix *BgpPrefixtype `protobuf:"bytes,1,opt,name=bgp_prefix,json=bgpPrefix,proto3" json:"bgp_prefix,omitempty"`
NeighborAddressXr *BgpAddrtype `protobuf:"bytes,2,opt,name=neighbor_address_xr,json=neighborAddressXr,proto3" json:"neighbor_address_xr,omitempty"`
RouteType string `protobuf:"bytes,3,opt,name=route_type,json=routeType,proto3" json:"route_type,omitempty"`
IsPathValid bool `protobuf:"varint,4,opt,name=is_path_valid,json=isPathValid,proto3" json:"is_path_valid,omitempty"`
IsPathDamped bool `protobuf:"varint,5,opt,name=is_path_damped,json=isPathDamped,proto3" json:"is_path_damped,omitempty"`
IsPathHistoryHeld bool `protobuf:"varint,6,opt,name=is_path_history_held,json=isPathHistoryHeld,proto3" json:"is_path_history_held,omitempty"`
IsInternalPath bool `protobuf:"varint,7,opt,name=is_internal_path,json=isInternalPath,proto3" json:"is_internal_path,omitempty"`
IsBestPath bool `protobuf:"varint,8,opt,name=is_best_path,json=isBestPath,proto3" json:"is_best_path,omitempty"`
IsAsBest bool `protobuf:"varint,9,opt,name=is_as_best,json=isAsBest,proto3" json:"is_as_best,omitempty"`
IsSpkrAsBest bool `protobuf:"varint,10,opt,name=is_spkr_as_best,json=isSpkrAsBest,proto3" json:"is_spkr_as_best,omitempty"`
IsPartialBest bool `protobuf:"varint,11,opt,name=is_partial_best,json=isPartialBest,proto3" json:"is_partial_best,omitempty"`
IsAggregationSuppressed bool `protobuf:"varint,12,opt,name=is_aggregation_suppressed,json=isAggregationSuppressed,proto3" json:"is_aggregation_suppressed,omitempty"`
IsImportDampened bool `protobuf:"varint,13,opt,name=is_import_dampened,json=isImportDampened,proto3" json:"is_import_dampened,omitempty"`
IsImportSuspect bool `protobuf:"varint,14,opt,name=is_import_suspect,json=isImportSuspect,proto3" json:"is_import_suspect,omitempty"`
IsPathNotAdvertised bool `protobuf:"varint,15,opt,name=is_path_not_advertised,json=isPathNotAdvertised,proto3" json:"is_path_not_advertised,omitempty"`
IsPathNotAdvertisedToEbgPs bool `protobuf:"varint,16,opt,name=is_path_not_advertised_to_ebg_ps,json=isPathNotAdvertisedToEbgPs,proto3" json:"is_path_not_advertised_to_ebg_ps,omitempty"`
IsPathAdvertisedLocalAsOnly bool `protobuf:"varint,17,opt,name=is_path_advertised_local_as_only,json=isPathAdvertisedLocalAsOnly,proto3" json:"is_path_advertised_local_as_only,omitempty"`
IsPathFromRouteReflector bool `protobuf:"varint,18,opt,name=is_path_from_route_reflector,json=isPathFromRouteReflector,proto3" json:"is_path_from_route_reflector,omitempty"`
IsPathReceivedOnly bool `protobuf:"varint,19,opt,name=is_path_received_only,json=isPathReceivedOnly,proto3" json:"is_path_received_only,omitempty"`
IsReceivedPathNotModified bool `protobuf:"varint,20,opt,name=is_received_path_not_modified,json=isReceivedPathNotModified,proto3" json:"is_received_path_not_modified,omitempty"`
IsPathLocallySourced bool `protobuf:"varint,21,opt,name=is_path_locally_sourced,json=isPathLocallySourced,proto3" json:"is_path_locally_sourced,omitempty"`
IsPathLocalAggregate bool `protobuf:"varint,22,opt,name=is_path_local_aggregate,json=isPathLocalAggregate,proto3" json:"is_path_local_aggregate,omitempty"`
IsPathFromNetworkCommand bool `protobuf:"varint,23,opt,name=is_path_from_network_command,json=isPathFromNetworkCommand,proto3" json:"is_path_from_network_command,omitempty"`
IsPathFromRedistributeCommand bool `protobuf:"varint,24,opt,name=is_path_from_redistribute_command,json=isPathFromRedistributeCommand,proto3" json:"is_path_from_redistribute_command,omitempty"`
IsPathImported bool `protobuf:"varint,25,opt,name=is_path_imported,json=isPathImported,proto3" json:"is_path_imported,omitempty"`
IsPathReoriginated bool `protobuf:"varint,26,opt,name=is_path_reoriginated,json=isPathReoriginated,proto3" json:"is_path_reoriginated,omitempty"`
IsPathReoriginatedStitching bool `protobuf:"varint,27,opt,name=is_path_reoriginated_stitching,json=isPathReoriginatedStitching,proto3" json:"is_path_reoriginated_stitching,omitempty"`
IsPathVpnOnly bool `protobuf:"varint,28,opt,name=is_path_vpn_only,json=isPathVpnOnly,proto3" json:"is_path_vpn_only,omitempty"`
IsPathFromConfederationPeer bool `protobuf:"varint,29,opt,name=is_path_from_confederation_peer,json=isPathFromConfederationPeer,proto3" json:"is_path_from_confederation_peer,omitempty"`
IsPathSyncedWithIgp bool `protobuf:"varint,30,opt,name=is_path_synced_with_igp,json=isPathSyncedWithIgp,proto3" json:"is_path_synced_with_igp,omitempty"`
IsPathMultipath bool `protobuf:"varint,31,opt,name=is_path_multipath,json=isPathMultipath,proto3" json:"is_path_multipath,omitempty"`
IsPathImpCandidate bool `protobuf:"varint,32,opt,name=is_path_imp_candidate,json=isPathImpCandidate,proto3" json:"is_path_imp_candidate,omitempty"`
IsPathStale bool `protobuf:"varint,33,opt,name=is_path_stale,json=isPathStale,proto3" json:"is_path_stale,omitempty"`
IsPathLongLivedStale bool `protobuf:"varint,34,opt,name=is_path_long_lived_stale,json=isPathLongLivedStale,proto3" json:"is_path_long_lived_stale,omitempty"`
IsPathBackup bool `protobuf:"varint,35,opt,name=is_path_backup,json=isPathBackup,proto3" json:"is_path_backup,omitempty"`
IsPathBackupProtectMultipath bool `protobuf:"varint,36,opt,name=is_path_backup_protect_multipath,json=isPathBackupProtectMultipath,proto3" json:"is_path_backup_protect_multipath,omitempty"`
IsPathBestExternal bool `protobuf:"varint,37,opt,name=is_path_best_external,json=isPathBestExternal,proto3" json:"is_path_best_external,omitempty"`
IsPathAdditionalPath bool `protobuf:"varint,38,opt,name=is_path_additional_path,json=isPathAdditionalPath,proto3" json:"is_path_additional_path,omitempty"`
IsPathNexthopDiscarded bool `protobuf:"varint,39,opt,name=is_path_nexthop_discarded,json=isPathNexthopDiscarded,proto3" json:"is_path_nexthop_discarded,omitempty"`
NextHop *BgpAddrtype `protobuf:"bytes,40,opt,name=next_hop,json=nextHop,proto3" json:"next_hop,omitempty"`
NhTunnel *BgpTeTunnel `protobuf:"bytes,41,opt,name=nh_tunnel,json=nhTunnel,proto3" json:"nh_tunnel,omitempty"`
HasRcvdLabel bool `protobuf:"varint,42,opt,name=has_rcvd_label,json=hasRcvdLabel,proto3" json:"has_rcvd_label,omitempty"`
RcvdLabel uint32 `protobuf:"varint,43,opt,name=rcvd_label,json=rcvdLabel,proto3" json:"rcvd_label,omitempty"`
HasLocalNetLabel bool `protobuf:"varint,44,opt,name=has_local_net_label,json=hasLocalNetLabel,proto3" json:"has_local_net_label,omitempty"`
LocalLabel uint32 `protobuf:"varint,45,opt,name=local_label,json=localLabel,proto3" json:"local_label,omitempty"`
IgpMetric uint32 `protobuf:"varint,46,opt,name=igp_metric,json=igpMetric,proto3" json:"igp_metric,omitempty"`
PathWeight uint32 `protobuf:"varint,47,opt,name=path_weight,json=pathWeight,proto3" json:"path_weight,omitempty"`
NeighborRouterId string `protobuf:"bytes,48,opt,name=neighbor_router_id,json=neighborRouterId,proto3" json:"neighbor_router_id,omitempty"`
HasMdtGroupAddr bool `protobuf:"varint,49,opt,name=has_mdt_group_addr,json=hasMdtGroupAddr,proto3" json:"has_mdt_group_addr,omitempty"`
MdtGroupAddr *BgpAddrtype `protobuf:"bytes,50,opt,name=mdt_group_addr,json=mdtGroupAddr,proto3" json:"mdt_group_addr,omitempty"`
L2VpnSize uint32 `protobuf:"varint,51,opt,name=l2vpn_size,json=l2vpnSize,proto3" json:"l2vpn_size,omitempty"`
HasEsi bool `protobuf:"varint,52,opt,name=has_esi,json=hasEsi,proto3" json:"has_esi,omitempty"`
L2VpnEvpnEsi *BgpL2VpnEvpnEsiT `protobuf:"bytes,53,opt,name=l2vpn_evpn_esi,json=l2vpnEvpnEsi,proto3" json:"l2vpn_evpn_esi,omitempty"`
HasGwAddr bool `protobuf:"varint,54,opt,name=has_gw_addr,json=hasGwAddr,proto3" json:"has_gw_addr,omitempty"`
GwAddr *BgpV4V6T `protobuf:"bytes,55,opt,name=gw_addr,json=gwAddr,proto3" json:"gw_addr,omitempty"`
HasNhAddr bool `protobuf:"varint,56,opt,name=has_nh_addr,json=hasNhAddr,proto3" json:"has_nh_addr,omitempty"`
NhAddr *BgpV4V6T `protobuf:"bytes,57,opt,name=nh_addr,json=nhAddr,proto3" json:"nh_addr,omitempty"`
HasSecondLabel bool `protobuf:"varint,58,opt,name=has_second_label,json=hasSecondLabel,proto3" json:"has_second_label,omitempty"`
SecondLabel uint32 `protobuf:"varint,59,opt,name=second_label,json=secondLabel,proto3" json:"second_label,omitempty"`
L2VpnCircuitStatusValue []uint32 `protobuf:"varint,60,rep,packed,name=l2vpn_circuit_status_value,json=l2vpnCircuitStatusValue,proto3" json:"l2vpn_circuit_status_value,omitempty"`
PathFlapCount uint32 `protobuf:"varint,61,opt,name=path_flap_count,json=pathFlapCount,proto3" json:"path_flap_count,omitempty"`
SecondsSinceFirstFlap uint32 `protobuf:"varint,62,opt,name=seconds_since_first_flap,json=secondsSinceFirstFlap,proto3" json:"seconds_since_first_flap,omitempty"`
TimeToUnsuppress uint32 `protobuf:"varint,63,opt,name=time_to_unsuppress,json=timeToUnsuppress,proto3" json:"time_to_unsuppress,omitempty"`
DampenPenalty uint32 `protobuf:"varint,64,opt,name=dampen_penalty,json=dampenPenalty,proto3" json:"dampen_penalty,omitempty"`
HalflifeTime uint32 `protobuf:"varint,65,opt,name=halflife_time,json=halflifeTime,proto3" json:"halflife_time,omitempty"`
SuppressPenalty uint32 `protobuf:"varint,66,opt,name=suppress_penalty,json=suppressPenalty,proto3" json:"suppress_penalty,omitempty"`
ReuseValue uint32 `protobuf:"varint,67,opt,name=reuse_value,json=reuseValue,proto3" json:"reuse_value,omitempty"`
MaximumSuppressTime uint32 `protobuf:"varint,68,opt,name=maximum_suppress_time,json=maximumSuppressTime,proto3" json:"maximum_suppress_time,omitempty"`
BestPathCompStage string `protobuf:"bytes,69,opt,name=best_path_comp_stage,json=bestPathCompStage,proto3" json:"best_path_comp_stage,omitempty"`
BestPathCompWinner *BgpAddrtype `protobuf:"bytes,70,opt,name=best_path_comp_winner,json=bestPathCompWinner,proto3" json:"best_path_comp_winner,omitempty"`
BestPathIdCompWinner uint32 `protobuf:"varint,71,opt,name=best_path_id_comp_winner,json=bestPathIdCompWinner,proto3" json:"best_path_id_comp_winner,omitempty"`
PathFlags uint64 `protobuf:"varint,72,opt,name=path_flags,json=pathFlags,proto3" json:"path_flags,omitempty"`
PathImportFlags uint32 `protobuf:"varint,73,opt,name=path_import_flags,json=pathImportFlags,proto3" json:"path_import_flags,omitempty"`
BestPathId uint32 `protobuf:"varint,74,opt,name=best_path_id,json=bestPathId,proto3" json:"best_path_id,omitempty"`
LocalPathId uint32 `protobuf:"varint,75,opt,name=local_path_id,json=localPathId,proto3" json:"local_path_id,omitempty"`
RcvdPathId uint32 `protobuf:"varint,76,opt,name=rcvd_path_id,json=rcvdPathId,proto3" json:"rcvd_path_id,omitempty"`
PathTableVersion uint32 `protobuf:"varint,77,opt,name=path_table_version,json=pathTableVersion,proto3" json:"path_table_version,omitempty"`
LocalPeersAdvertisedTo []*BgpAdvinfoType_ `protobuf:"bytes,78,rep,name=local_peers_advertised_to,json=localPeersAdvertisedTo,proto3" json:"local_peers_advertised_to,omitempty"`
PePeersAdvertisedTo []*BgpAdvinfoType_ `protobuf:"bytes,79,rep,name=pe_peers_advertised_to,json=pePeersAdvertisedTo,proto3" json:"pe_peers_advertised_to,omitempty"`
BestPathOrrBitfield []*BgpAdvinfoType_ `protobuf:"bytes,80,rep,name=best_path_orr_bitfield,json=bestPathOrrBitfield,proto3" json:"best_path_orr_bitfield,omitempty"`
AddPathOrrBitfield []*BgpAdvinfoType_ `protobuf:"bytes,81,rep,name=add_path_orr_bitfield,json=addPathOrrBitfield,proto3" json:"add_path_orr_bitfield,omitempty"`
AdvertisedtoPe bool `protobuf:"varint,82,opt,name=advertisedto_pe,json=advertisedtoPe,proto3" json:"advertisedto_pe,omitempty"`
RibFailed bool `protobuf:"varint,83,opt,name=rib_failed,json=ribFailed,proto3" json:"rib_failed,omitempty"`
SnRpkiOriginAsValidity uint32 `protobuf:"varint,84,opt,name=sn_rpki_origin_as_validity,json=snRpkiOriginAsValidity,proto3" json:"sn_rpki_origin_as_validity,omitempty"`
ShowRpkiOriginAsValidity bool `protobuf:"varint,85,opt,name=show_rpki_origin_as_validity,json=showRpkiOriginAsValidity,proto3" json:"show_rpki_origin_as_validity,omitempty"`
IbgpSignaledValidity bool `protobuf:"varint,86,opt,name=ibgp_signaled_validity,json=ibgpSignaledValidity,proto3" json:"ibgp_signaled_validity,omitempty"`
RpkiOriginAsValidationDisabled bool `protobuf:"varint,87,opt,name=rpki_origin_as_validation_disabled,json=rpkiOriginAsValidationDisabled,proto3" json:"rpki_origin_as_validation_disabled,omitempty"`
AcceptOwnPath bool `protobuf:"varint,88,opt,name=accept_own_path,json=acceptOwnPath,proto3" json:"accept_own_path,omitempty"`
AcceptOwnSelfOriginatedPAth bool `protobuf:"varint,89,opt,name=accept_own_self_originated_p_ath,json=acceptOwnSelfOriginatedPAth,proto3" json:"accept_own_self_originated_p_ath,omitempty"`
AigpMetric uint64 `protobuf:"varint,90,opt,name=aigp_metric,json=aigpMetric,proto3" json:"aigp_metric,omitempty"`
MvpnSfsPath bool `protobuf:"varint,91,opt,name=mvpn_sfs_path,json=mvpnSfsPath,proto3" json:"mvpn_sfs_path,omitempty"`
FspecInvalidPath bool `protobuf:"varint,92,opt,name=fspec_invalid_path,json=fspecInvalidPath,proto3" json:"fspec_invalid_path,omitempty"`
HasMvpnNbrAddr bool `protobuf:"varint,93,opt,name=has_mvpn_nbr_addr,json=hasMvpnNbrAddr,proto3" json:"has_mvpn_nbr_addr,omitempty"`
MvpnNbrAddr *BgpAddrtype `protobuf:"bytes,94,opt,name=mvpn_nbr_addr,json=mvpnNbrAddr,proto3" json:"mvpn_nbr_addr,omitempty"`
HasMvpnNexthopAddr bool `protobuf:"varint,95,opt,name=has_mvpn_nexthop_addr,json=hasMvpnNexthopAddr,proto3" json:"has_mvpn_nexthop_addr,omitempty"`
MvpnNexthopAddr *BgpAddrtype `protobuf:"bytes,96,opt,name=mvpn_nexthop_addr,json=mvpnNexthopAddr,proto3" json:"mvpn_nexthop_addr,omitempty"`
HasMvpnPmsi bool `protobuf:"varint,97,opt,name=has_mvpn_pmsi,json=hasMvpnPmsi,proto3" json:"has_mvpn_pmsi,omitempty"`
MvpnPmsiType uint32 `protobuf:"varint,98,opt,name=mvpn_pmsi_type,json=mvpnPmsiType,proto3" json:"mvpn_pmsi_type,omitempty"`
MvpnPmsiFlags uint32 `protobuf:"varint,99,opt,name=mvpn_pmsi_flags,json=mvpnPmsiFlags,proto3" json:"mvpn_pmsi_flags,omitempty"`
MvpnPmsiLabel uint32 `protobuf:"varint,100,opt,name=mvpn_pmsi_label,json=mvpnPmsiLabel,proto3" json:"mvpn_pmsi_label,omitempty"`
MvpnPmsiValue []uint32 `protobuf:"varint,101,rep,packed,name=mvpn_pmsi_value,json=mvpnPmsiValue,proto3" json:"mvpn_pmsi_value,omitempty"`
HasMvpnExtcomm bool `protobuf:"varint,102,opt,name=has_mvpn_extcomm,json=hasMvpnExtcomm,proto3" json:"has_mvpn_extcomm,omitempty"`
ExtendedCommunity []uint32 `protobuf:"varint,103,rep,packed,name=extended_community,json=extendedCommunity,proto3" json:"extended_community,omitempty"`
MvpnPathFlags uint32 `protobuf:"varint,104,opt,name=mvpn_path_flags,json=mvpnPathFlags,proto3" json:"mvpn_path_flags,omitempty"`
LocalNh bool `protobuf:"varint,105,opt,name=local_nh,json=localNh,proto3" json:"local_nh,omitempty"`
RtSetLimitEnabled bool `protobuf:"varint,106,opt,name=rt_set_limit_enabled,json=rtSetLimitEnabled,proto3" json:"rt_set_limit_enabled,omitempty"`
PathRtSetId uint32 `protobuf:"varint,107,opt,name=path_rt_set_id,json=pathRtSetId,proto3" json:"path_rt_set_id,omitempty"`
PathRtSetRouteCount uint32 `protobuf:"varint,108,opt,name=path_rt_set_route_count,json=pathRtSetRouteCount,proto3" json:"path_rt_set_route_count,omitempty"`
IsPathAfInstallEligible bool `protobuf:"varint,109,opt,name=is_path_af_install_eligible,json=isPathAfInstallEligible,proto3" json:"is_path_af_install_eligible,omitempty"`
IsPermanentPath bool `protobuf:"varint,110,opt,name=is_permanent_path,json=isPermanentPath,proto3" json:"is_permanent_path,omitempty"`
GracefulShutdown bool `protobuf:"varint,111,opt,name=graceful_shutdown,json=gracefulShutdown,proto3" json:"graceful_shutdown,omitempty"`
LabeledUnicastSafiPath bool `protobuf:"varint,112,opt,name=labeled_unicast_safi_path,json=labeledUnicastSafiPath,proto3" json:"labeled_unicast_safi_path,omitempty"`
VpnPathFlags uint32 `protobuf:"varint,113,opt,name=vpn_path_flags,json=vpnPathFlags,proto3" json:"vpn_path_flags,omitempty"`
HasVpnNexthopAddr bool `protobuf:"varint,114,opt,name=has_vpn_nexthop_addr,json=hasVpnNexthopAddr,proto3" json:"has_vpn_nexthop_addr,omitempty"`
VpnNexthopAddr *BgpAddrtype `protobuf:"bytes,115,opt,name=vpn_nexthop_addr,json=vpnNexthopAddr,proto3" json:"vpn_nexthop_addr,omitempty"`
IsOrigSrcRdPresent bool `protobuf:"varint,116,opt,name=is_orig_src_rd_present,json=isOrigSrcRdPresent,proto3" json:"is_orig_src_rd_present,omitempty"`
AfName string `protobuf:"bytes,117,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"`
RouteDistinguisher string `protobuf:"bytes,118,opt,name=route_distinguisher,json=routeDistinguisher,proto3" json:"route_distinguisher,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpPath_) Reset() { *m = BgpPath_{} }
func (m *BgpPath_) String() string { return proto.CompactTextString(m) }
func (*BgpPath_) ProtoMessage() {}
func (*BgpPath_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{11}
}
func (m *BgpPath_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpPath_.Unmarshal(m, b)
}
func (m *BgpPath_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpPath_.Marshal(b, m, deterministic)
}
func (m *BgpPath_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpPath_.Merge(m, src)
}
func (m *BgpPath_) XXX_Size() int {
return xxx_messageInfo_BgpPath_.Size(m)
}
func (m *BgpPath_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpPath_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpPath_ proto.InternalMessageInfo
func (m *BgpPath_) GetBgpPrefix() *BgpPrefixtype {
if m != nil {
return m.BgpPrefix
}
return nil
}
func (m *BgpPath_) GetNeighborAddressXr() *BgpAddrtype {
if m != nil {
return m.NeighborAddressXr
}
return nil
}
func (m *BgpPath_) GetRouteType() string {
if m != nil {
return m.RouteType
}
return ""
}
func (m *BgpPath_) GetIsPathValid() bool {
if m != nil {
return m.IsPathValid
}
return false
}
func (m *BgpPath_) GetIsPathDamped() bool {
if m != nil {
return m.IsPathDamped
}
return false
}
func (m *BgpPath_) GetIsPathHistoryHeld() bool {
if m != nil {
return m.IsPathHistoryHeld
}
return false
}
func (m *BgpPath_) GetIsInternalPath() bool {
if m != nil {
return m.IsInternalPath
}
return false
}
func (m *BgpPath_) GetIsBestPath() bool {
if m != nil {
return m.IsBestPath
}
return false
}
func (m *BgpPath_) GetIsAsBest() bool {
if m != nil {
return m.IsAsBest
}
return false
}
func (m *BgpPath_) GetIsSpkrAsBest() bool {
if m != nil {
return m.IsSpkrAsBest
}
return false
}
func (m *BgpPath_) GetIsPartialBest() bool {
if m != nil {
return m.IsPartialBest
}
return false
}
func (m *BgpPath_) GetIsAggregationSuppressed() bool {
if m != nil {
return m.IsAggregationSuppressed
}
return false
}
func (m *BgpPath_) GetIsImportDampened() bool {
if m != nil {
return m.IsImportDampened
}
return false
}
func (m *BgpPath_) GetIsImportSuspect() bool {
if m != nil {
return m.IsImportSuspect
}
return false
}
func (m *BgpPath_) GetIsPathNotAdvertised() bool {
if m != nil {
return m.IsPathNotAdvertised
}
return false
}
func (m *BgpPath_) GetIsPathNotAdvertisedToEbgPs() bool {
if m != nil {
return m.IsPathNotAdvertisedToEbgPs
}
return false
}
func (m *BgpPath_) GetIsPathAdvertisedLocalAsOnly() bool {
if m != nil {
return m.IsPathAdvertisedLocalAsOnly
}
return false
}
func (m *BgpPath_) GetIsPathFromRouteReflector() bool {
if m != nil {
return m.IsPathFromRouteReflector
}
return false
}
func (m *BgpPath_) GetIsPathReceivedOnly() bool {
if m != nil {
return m.IsPathReceivedOnly
}
return false
}
func (m *BgpPath_) GetIsReceivedPathNotModified() bool {
if m != nil {
return m.IsReceivedPathNotModified
}
return false
}
func (m *BgpPath_) GetIsPathLocallySourced() bool {
if m != nil {
return m.IsPathLocallySourced
}
return false
}
func (m *BgpPath_) GetIsPathLocalAggregate() bool {
if m != nil {
return m.IsPathLocalAggregate
}
return false
}
func (m *BgpPath_) GetIsPathFromNetworkCommand() bool {
if m != nil {
return m.IsPathFromNetworkCommand
}
return false
}
func (m *BgpPath_) GetIsPathFromRedistributeCommand() bool {
if m != nil {
return m.IsPathFromRedistributeCommand
}
return false
}
func (m *BgpPath_) GetIsPathImported() bool {
if m != nil {
return m.IsPathImported
}
return false
}
func (m *BgpPath_) GetIsPathReoriginated() bool {
if m != nil {
return m.IsPathReoriginated
}
return false
}
func (m *BgpPath_) GetIsPathReoriginatedStitching() bool {
if m != nil {
return m.IsPathReoriginatedStitching
}
return false
}
func (m *BgpPath_) GetIsPathVpnOnly() bool {
if m != nil {
return m.IsPathVpnOnly
}
return false
}
func (m *BgpPath_) GetIsPathFromConfederationPeer() bool {
if m != nil {
return m.IsPathFromConfederationPeer
}
return false
}
func (m *BgpPath_) GetIsPathSyncedWithIgp() bool {
if m != nil {
return m.IsPathSyncedWithIgp
}
return false
}
func (m *BgpPath_) GetIsPathMultipath() bool {
if m != nil {
return m.IsPathMultipath
}
return false
}
func (m *BgpPath_) GetIsPathImpCandidate() bool {
if m != nil {
return m.IsPathImpCandidate
}
return false
}
func (m *BgpPath_) GetIsPathStale() bool {
if m != nil {
return m.IsPathStale
}
return false
}
func (m *BgpPath_) GetIsPathLongLivedStale() bool {
if m != nil {
return m.IsPathLongLivedStale
}
return false
}
func (m *BgpPath_) GetIsPathBackup() bool {
if m != nil {
return m.IsPathBackup
}
return false
}
func (m *BgpPath_) GetIsPathBackupProtectMultipath() bool {
if m != nil {
return m.IsPathBackupProtectMultipath
}
return false
}
func (m *BgpPath_) GetIsPathBestExternal() bool {
if m != nil {
return m.IsPathBestExternal
}
return false
}
func (m *BgpPath_) GetIsPathAdditionalPath() bool {
if m != nil {
return m.IsPathAdditionalPath
}
return false
}
func (m *BgpPath_) GetIsPathNexthopDiscarded() bool {
if m != nil {
return m.IsPathNexthopDiscarded
}
return false
}
func (m *BgpPath_) GetNextHop() *BgpAddrtype {
if m != nil {
return m.NextHop
}
return nil
}
func (m *BgpPath_) GetNhTunnel() *BgpTeTunnel {
if m != nil {
return m.NhTunnel
}
return nil
}
func (m *BgpPath_) GetHasRcvdLabel() bool {
if m != nil {
return m.HasRcvdLabel
}
return false
}
func (m *BgpPath_) GetRcvdLabel() uint32 {
if m != nil {
return m.RcvdLabel
}
return 0
}
func (m *BgpPath_) GetHasLocalNetLabel() bool {
if m != nil {
return m.HasLocalNetLabel
}
return false
}
func (m *BgpPath_) GetLocalLabel() uint32 {
if m != nil {
return m.LocalLabel
}
return 0
}
func (m *BgpPath_) GetIgpMetric() uint32 {
if m != nil {
return m.IgpMetric
}
return 0
}
func (m *BgpPath_) GetPathWeight() uint32 {
if m != nil {
return m.PathWeight
}
return 0
}
func (m *BgpPath_) GetNeighborRouterId() string {
if m != nil {
return m.NeighborRouterId
}
return ""
}
func (m *BgpPath_) GetHasMdtGroupAddr() bool {
if m != nil {
return m.HasMdtGroupAddr
}
return false
}
func (m *BgpPath_) GetMdtGroupAddr() *BgpAddrtype {
if m != nil {
return m.MdtGroupAddr
}
return nil
}
func (m *BgpPath_) GetL2VpnSize() uint32 {
if m != nil {
return m.L2VpnSize
}
return 0
}
func (m *BgpPath_) GetHasEsi() bool {
if m != nil {
return m.HasEsi
}
return false
}
func (m *BgpPath_) GetL2VpnEvpnEsi() *BgpL2VpnEvpnEsiT {
if m != nil {
return m.L2VpnEvpnEsi
}
return nil
}
func (m *BgpPath_) GetHasGwAddr() bool {
if m != nil {
return m.HasGwAddr
}
return false
}
func (m *BgpPath_) GetGwAddr() *BgpV4V6T {
if m != nil {
return m.GwAddr
}
return nil
}
func (m *BgpPath_) GetHasNhAddr() bool {
if m != nil {
return m.HasNhAddr
}
return false
}
func (m *BgpPath_) GetNhAddr() *BgpV4V6T {
if m != nil {
return m.NhAddr
}
return nil
}
func (m *BgpPath_) GetHasSecondLabel() bool {
if m != nil {
return m.HasSecondLabel
}
return false
}
func (m *BgpPath_) GetSecondLabel() uint32 {
if m != nil {
return m.SecondLabel
}
return 0
}
func (m *BgpPath_) GetL2VpnCircuitStatusValue() []uint32 {
if m != nil {
return m.L2VpnCircuitStatusValue
}
return nil
}
func (m *BgpPath_) GetPathFlapCount() uint32 {
if m != nil {
return m.PathFlapCount
}
return 0
}
func (m *BgpPath_) GetSecondsSinceFirstFlap() uint32 {
if m != nil {
return m.SecondsSinceFirstFlap
}
return 0
}
func (m *BgpPath_) GetTimeToUnsuppress() uint32 {
if m != nil {
return m.TimeToUnsuppress
}
return 0
}
func (m *BgpPath_) GetDampenPenalty() uint32 {
if m != nil {
return m.DampenPenalty
}
return 0
}
func (m *BgpPath_) GetHalflifeTime() uint32 {
if m != nil {
return m.HalflifeTime
}
return 0
}
func (m *BgpPath_) GetSuppressPenalty() uint32 {
if m != nil {
return m.SuppressPenalty
}
return 0
}
func (m *BgpPath_) GetReuseValue() uint32 {
if m != nil {
return m.ReuseValue
}
return 0
}
func (m *BgpPath_) GetMaximumSuppressTime() uint32 {
if m != nil {
return m.MaximumSuppressTime
}
return 0
}
func (m *BgpPath_) GetBestPathCompStage() string {
if m != nil {
return m.BestPathCompStage
}
return ""
}
func (m *BgpPath_) GetBestPathCompWinner() *BgpAddrtype {
if m != nil {
return m.BestPathCompWinner
}
return nil
}
func (m *BgpPath_) GetBestPathIdCompWinner() uint32 {
if m != nil {
return m.BestPathIdCompWinner
}
return 0
}
func (m *BgpPath_) GetPathFlags() uint64 {
if m != nil {
return m.PathFlags
}
return 0
}
func (m *BgpPath_) GetPathImportFlags() uint32 {
if m != nil {
return m.PathImportFlags
}
return 0
}
func (m *BgpPath_) GetBestPathId() uint32 {
if m != nil {
return m.BestPathId
}
return 0
}
func (m *BgpPath_) GetLocalPathId() uint32 {
if m != nil {
return m.LocalPathId
}
return 0
}
func (m *BgpPath_) GetRcvdPathId() uint32 {
if m != nil {
return m.RcvdPathId
}
return 0
}
func (m *BgpPath_) GetPathTableVersion() uint32 {
if m != nil {
return m.PathTableVersion
}
return 0
}
func (m *BgpPath_) GetLocalPeersAdvertisedTo() []*BgpAdvinfoType_ {
if m != nil {
return m.LocalPeersAdvertisedTo
}
return nil
}
func (m *BgpPath_) GetPePeersAdvertisedTo() []*BgpAdvinfoType_ {
if m != nil {
return m.PePeersAdvertisedTo
}
return nil
}
func (m *BgpPath_) GetBestPathOrrBitfield() []*BgpAdvinfoType_ {
if m != nil {
return m.BestPathOrrBitfield
}
return nil
}
func (m *BgpPath_) GetAddPathOrrBitfield() []*BgpAdvinfoType_ {
if m != nil {
return m.AddPathOrrBitfield
}
return nil
}
func (m *BgpPath_) GetAdvertisedtoPe() bool {
if m != nil {
return m.AdvertisedtoPe
}
return false
}
func (m *BgpPath_) GetRibFailed() bool {
if m != nil {
return m.RibFailed
}
return false
}
func (m *BgpPath_) GetSnRpkiOriginAsValidity() uint32 {
if m != nil {
return m.SnRpkiOriginAsValidity
}
return 0
}
func (m *BgpPath_) GetShowRpkiOriginAsValidity() bool {
if m != nil {
return m.ShowRpkiOriginAsValidity
}
return false
}
func (m *BgpPath_) GetIbgpSignaledValidity() bool {
if m != nil {
return m.IbgpSignaledValidity
}
return false
}
func (m *BgpPath_) GetRpkiOriginAsValidationDisabled() bool {
if m != nil {
return m.RpkiOriginAsValidationDisabled
}
return false
}
func (m *BgpPath_) GetAcceptOwnPath() bool {
if m != nil {
return m.AcceptOwnPath
}
return false
}
func (m *BgpPath_) GetAcceptOwnSelfOriginatedPAth() bool {
if m != nil {
return m.AcceptOwnSelfOriginatedPAth
}
return false
}
func (m *BgpPath_) GetAigpMetric() uint64 {
if m != nil {
return m.AigpMetric
}
return 0
}
func (m *BgpPath_) GetMvpnSfsPath() bool {
if m != nil {
return m.MvpnSfsPath
}
return false
}
func (m *BgpPath_) GetFspecInvalidPath() bool {
if m != nil {
return m.FspecInvalidPath
}
return false
}
func (m *BgpPath_) GetHasMvpnNbrAddr() bool {
if m != nil {
return m.HasMvpnNbrAddr
}
return false
}
func (m *BgpPath_) GetMvpnNbrAddr() *BgpAddrtype {
if m != nil {
return m.MvpnNbrAddr
}
return nil
}
func (m *BgpPath_) GetHasMvpnNexthopAddr() bool {
if m != nil {
return m.HasMvpnNexthopAddr
}
return false
}
func (m *BgpPath_) GetMvpnNexthopAddr() *BgpAddrtype {
if m != nil {
return m.MvpnNexthopAddr
}
return nil
}
func (m *BgpPath_) GetHasMvpnPmsi() bool {
if m != nil {
return m.HasMvpnPmsi
}
return false
}
func (m *BgpPath_) GetMvpnPmsiType() uint32 {
if m != nil {
return m.MvpnPmsiType
}
return 0
}
func (m *BgpPath_) GetMvpnPmsiFlags() uint32 {
if m != nil {
return m.MvpnPmsiFlags
}
return 0
}
func (m *BgpPath_) GetMvpnPmsiLabel() uint32 {
if m != nil {
return m.MvpnPmsiLabel
}
return 0
}
func (m *BgpPath_) GetMvpnPmsiValue() []uint32 {
if m != nil {
return m.MvpnPmsiValue
}
return nil
}
func (m *BgpPath_) GetHasMvpnExtcomm() bool {
if m != nil {
return m.HasMvpnExtcomm
}
return false
}
func (m *BgpPath_) GetExtendedCommunity() []uint32 {
if m != nil {
return m.ExtendedCommunity
}
return nil
}
func (m *BgpPath_) GetMvpnPathFlags() uint32 {
if m != nil {
return m.MvpnPathFlags
}
return 0
}
func (m *BgpPath_) GetLocalNh() bool {
if m != nil {
return m.LocalNh
}
return false
}
func (m *BgpPath_) GetRtSetLimitEnabled() bool {
if m != nil {
return m.RtSetLimitEnabled
}
return false
}
func (m *BgpPath_) GetPathRtSetId() uint32 {
if m != nil {
return m.PathRtSetId
}
return 0
}
func (m *BgpPath_) GetPathRtSetRouteCount() uint32 {
if m != nil {
return m.PathRtSetRouteCount
}
return 0
}
func (m *BgpPath_) GetIsPathAfInstallEligible() bool {
if m != nil {
return m.IsPathAfInstallEligible
}
return false
}
func (m *BgpPath_) GetIsPermanentPath() bool {
if m != nil {
return m.IsPermanentPath
}
return false
}
func (m *BgpPath_) GetGracefulShutdown() bool {
if m != nil {
return m.GracefulShutdown
}
return false
}
func (m *BgpPath_) GetLabeledUnicastSafiPath() bool {
if m != nil {
return m.LabeledUnicastSafiPath
}
return false
}
func (m *BgpPath_) GetVpnPathFlags() uint32 {
if m != nil {
return m.VpnPathFlags
}
return 0
}
func (m *BgpPath_) GetHasVpnNexthopAddr() bool {
if m != nil {
return m.HasVpnNexthopAddr
}
return false
}
func (m *BgpPath_) GetVpnNexthopAddr() *BgpAddrtype {
if m != nil {
return m.VpnNexthopAddr
}
return nil
}
func (m *BgpPath_) GetIsOrigSrcRdPresent() bool {
if m != nil {
return m.IsOrigSrcRdPresent
}
return false
}
func (m *BgpPath_) GetAfName() string {
if m != nil {
return m.AfName
}
return ""
}
func (m *BgpPath_) GetRouteDistinguisher() string {
if m != nil {
return m.RouteDistinguisher
}
return ""
}
type BgpPedistlblEntry_ struct {
PeAddress string `protobuf:"bytes,1,opt,name=pe_address,json=peAddress,proto3" json:"pe_address,omitempty"`
Label uint32 `protobuf:"varint,2,opt,name=label,proto3" json:"label,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpPedistlblEntry_) Reset() { *m = BgpPedistlblEntry_{} }
func (m *BgpPedistlblEntry_) String() string { return proto.CompactTextString(m) }
func (*BgpPedistlblEntry_) ProtoMessage() {}
func (*BgpPedistlblEntry_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{12}
}
func (m *BgpPedistlblEntry_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpPedistlblEntry_.Unmarshal(m, b)
}
func (m *BgpPedistlblEntry_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpPedistlblEntry_.Marshal(b, m, deterministic)
}
func (m *BgpPedistlblEntry_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpPedistlblEntry_.Merge(m, src)
}
func (m *BgpPedistlblEntry_) XXX_Size() int {
return xxx_messageInfo_BgpPedistlblEntry_.Size(m)
}
func (m *BgpPedistlblEntry_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpPedistlblEntry_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpPedistlblEntry_ proto.InternalMessageInfo
func (m *BgpPedistlblEntry_) GetPeAddress() string {
if m != nil {
return m.PeAddress
}
return ""
}
func (m *BgpPedistlblEntry_) GetLabel() uint32 {
if m != nil {
return m.Label
}
return 0
}
type BgpBindingSidT struct {
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
Label uint32 `protobuf:"varint,2,opt,name=label,proto3" json:"label,omitempty"`
Ipv6Address string `protobuf:"bytes,3,opt,name=ipv6_address,json=ipv6Address,proto3" json:"ipv6_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpBindingSidT) Reset() { *m = BgpBindingSidT{} }
func (m *BgpBindingSidT) String() string { return proto.CompactTextString(m) }
func (*BgpBindingSidT) ProtoMessage() {}
func (*BgpBindingSidT) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{13}
}
func (m *BgpBindingSidT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpBindingSidT.Unmarshal(m, b)
}
func (m *BgpBindingSidT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpBindingSidT.Marshal(b, m, deterministic)
}
func (m *BgpBindingSidT) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpBindingSidT.Merge(m, src)
}
func (m *BgpBindingSidT) XXX_Size() int {
return xxx_messageInfo_BgpBindingSidT.Size(m)
}
func (m *BgpBindingSidT) XXX_DiscardUnknown() {
xxx_messageInfo_BgpBindingSidT.DiscardUnknown(m)
}
var xxx_messageInfo_BgpBindingSidT proto.InternalMessageInfo
func (m *BgpBindingSidT) GetType() string {
if m != nil {
return m.Type
}
return ""
}
func (m *BgpBindingSidT) GetLabel() uint32 {
if m != nil {
return m.Label
}
return 0
}
func (m *BgpBindingSidT) GetIpv6Address() string {
if m != nil {
return m.Ipv6Address
}
return ""
}
type SrSid_ struct {
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
Label uint32 `protobuf:"varint,2,opt,name=label,proto3" json:"label,omitempty"`
Ipv4Address string `protobuf:"bytes,3,opt,name=ipv4_address,json=ipv4Address,proto3" json:"ipv4_address,omitempty"`
Ipv6Address string `protobuf:"bytes,4,opt,name=ipv6_address,json=ipv6Address,proto3" json:"ipv6_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SrSid_) Reset() { *m = SrSid_{} }
func (m *SrSid_) String() string { return proto.CompactTextString(m) }
func (*SrSid_) ProtoMessage() {}
func (*SrSid_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{14}
}
func (m *SrSid_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SrSid_.Unmarshal(m, b)
}
func (m *SrSid_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SrSid_.Marshal(b, m, deterministic)
}
func (m *SrSid_) XXX_Merge(src proto.Message) {
xxx_messageInfo_SrSid_.Merge(m, src)
}
func (m *SrSid_) XXX_Size() int {
return xxx_messageInfo_SrSid_.Size(m)
}
func (m *SrSid_) XXX_DiscardUnknown() {
xxx_messageInfo_SrSid_.DiscardUnknown(m)
}
var xxx_messageInfo_SrSid_ proto.InternalMessageInfo
func (m *SrSid_) GetType() string {
if m != nil {
return m.Type
}
return ""
}
func (m *SrSid_) GetLabel() uint32 {
if m != nil {
return m.Label
}
return 0
}
func (m *SrSid_) GetIpv4Address() string {
if m != nil {
return m.Ipv4Address
}
return ""
}
func (m *SrSid_) GetIpv6Address() string {
if m != nil {
return m.Ipv6Address
}
return ""
}
type SrExppath_ struct {
Weight uint32 `protobuf:"varint,1,opt,name=weight,proto3" json:"weight,omitempty"`
Segment []*SrSid_ `protobuf:"bytes,2,rep,name=segment,proto3" json:"segment,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SrExppath_) Reset() { *m = SrExppath_{} }
func (m *SrExppath_) String() string { return proto.CompactTextString(m) }
func (*SrExppath_) ProtoMessage() {}
func (*SrExppath_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{15}
}
func (m *SrExppath_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SrExppath_.Unmarshal(m, b)
}
func (m *SrExppath_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SrExppath_.Marshal(b, m, deterministic)
}
func (m *SrExppath_) XXX_Merge(src proto.Message) {
xxx_messageInfo_SrExppath_.Merge(m, src)
}
func (m *SrExppath_) XXX_Size() int {
return xxx_messageInfo_SrExppath_.Size(m)
}
func (m *SrExppath_) XXX_DiscardUnknown() {
xxx_messageInfo_SrExppath_.DiscardUnknown(m)
}
var xxx_messageInfo_SrExppath_ proto.InternalMessageInfo
func (m *SrExppath_) GetWeight() uint32 {
if m != nil {
return m.Weight
}
return 0
}
func (m *SrExppath_) GetSegment() []*SrSid_ {
if m != nil {
return m.Segment
}
return nil
}
type BgpSrpolicyEntry_ struct {
TunnelEncapType uint32 `protobuf:"varint,1,opt,name=tunnel_encap_type,json=tunnelEncapType,proto3" json:"tunnel_encap_type,omitempty"`
BindingSid *BgpBindingSidT `protobuf:"bytes,2,opt,name=binding_sid,json=bindingSid,proto3" json:"binding_sid,omitempty"`
AllocatedBindingSid *BgpBindingSidT `protobuf:"bytes,3,opt,name=allocated_binding_sid,json=allocatedBindingSid,proto3" json:"allocated_binding_sid,omitempty"`
Preference uint32 `protobuf:"varint,4,opt,name=preference,proto3" json:"preference,omitempty"`
State bool `protobuf:"varint,5,opt,name=state,proto3" json:"state,omitempty"`
RequestState string `protobuf:"bytes,6,opt,name=request_state,json=requestState,proto3" json:"request_state,omitempty"`
SegmentList []*SrExppath_ `protobuf:"bytes,7,rep,name=segment_list,json=segmentList,proto3" json:"segment_list,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpSrpolicyEntry_) Reset() { *m = BgpSrpolicyEntry_{} }
func (m *BgpSrpolicyEntry_) String() string { return proto.CompactTextString(m) }
func (*BgpSrpolicyEntry_) ProtoMessage() {}
func (*BgpSrpolicyEntry_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{16}
}
func (m *BgpSrpolicyEntry_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpSrpolicyEntry_.Unmarshal(m, b)
}
func (m *BgpSrpolicyEntry_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpSrpolicyEntry_.Marshal(b, m, deterministic)
}
func (m *BgpSrpolicyEntry_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpSrpolicyEntry_.Merge(m, src)
}
func (m *BgpSrpolicyEntry_) XXX_Size() int {
return xxx_messageInfo_BgpSrpolicyEntry_.Size(m)
}
func (m *BgpSrpolicyEntry_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpSrpolicyEntry_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpSrpolicyEntry_ proto.InternalMessageInfo
func (m *BgpSrpolicyEntry_) GetTunnelEncapType() uint32 {
if m != nil {
return m.TunnelEncapType
}
return 0
}
func (m *BgpSrpolicyEntry_) GetBindingSid() *BgpBindingSidT {
if m != nil {
return m.BindingSid
}
return nil
}
func (m *BgpSrpolicyEntry_) GetAllocatedBindingSid() *BgpBindingSidT {
if m != nil {
return m.AllocatedBindingSid
}
return nil
}
func (m *BgpSrpolicyEntry_) GetPreference() uint32 {
if m != nil {
return m.Preference
}
return 0
}
func (m *BgpSrpolicyEntry_) GetState() bool {
if m != nil {
return m.State
}
return false
}
func (m *BgpSrpolicyEntry_) GetRequestState() string {
if m != nil {
return m.RequestState
}
return ""
}
func (m *BgpSrpolicyEntry_) GetSegmentList() []*SrExppath_ {
if m != nil {
return m.SegmentList
}
return nil
}
type BgpTunencapEntry_ struct {
SrPolicy *BgpSrpolicyEntry_ `protobuf:"bytes,1,opt,name=sr_policy,json=srPolicy,proto3" json:"sr_policy,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpTunencapEntry_) Reset() { *m = BgpTunencapEntry_{} }
func (m *BgpTunencapEntry_) String() string { return proto.CompactTextString(m) }
func (*BgpTunencapEntry_) ProtoMessage() {}
func (*BgpTunencapEntry_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{17}
}
func (m *BgpTunencapEntry_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpTunencapEntry_.Unmarshal(m, b)
}
func (m *BgpTunencapEntry_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpTunencapEntry_.Marshal(b, m, deterministic)
}
func (m *BgpTunencapEntry_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpTunencapEntry_.Merge(m, src)
}
func (m *BgpTunencapEntry_) XXX_Size() int {
return xxx_messageInfo_BgpTunencapEntry_.Size(m)
}
func (m *BgpTunencapEntry_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpTunencapEntry_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpTunencapEntry_ proto.InternalMessageInfo
func (m *BgpTunencapEntry_) GetSrPolicy() *BgpSrpolicyEntry_ {
if m != nil {
return m.SrPolicy
}
return nil
}
type BgpCommonAttrEntry_ struct {
IsMetricPresent bool `protobuf:"varint,1,opt,name=is_metric_present,json=isMetricPresent,proto3" json:"is_metric_present,omitempty"`
IsLocalPrefPresent bool `protobuf:"varint,2,opt,name=is_local_pref_present,json=isLocalPrefPresent,proto3" json:"is_local_pref_present,omitempty"`
IsAtomicAggregatePresent bool `protobuf:"varint,3,opt,name=is_atomic_aggregate_present,json=isAtomicAggregatePresent,proto3" json:"is_atomic_aggregate_present,omitempty"`
IsAggregatorPresent bool `protobuf:"varint,4,opt,name=is_aggregator_present,json=isAggregatorPresent,proto3" json:"is_aggregator_present,omitempty"`
IsOriginPresent bool `protobuf:"varint,5,opt,name=is_origin_present,json=isOriginPresent,proto3" json:"is_origin_present,omitempty"`
IsAsPathPresent bool `protobuf:"varint,6,opt,name=is_as_path_present,json=isAsPathPresent,proto3" json:"is_as_path_present,omitempty"`
IsCommunityPresent bool `protobuf:"varint,7,opt,name=is_community_present,json=isCommunityPresent,proto3" json:"is_community_present,omitempty"`
IsExtendedCommunityPresent bool `protobuf:"varint,8,opt,name=is_extended_community_present,json=isExtendedCommunityPresent,proto3" json:"is_extended_community_present,omitempty"`
IsSsaPresent bool `protobuf:"varint,9,opt,name=is_ssa_present,json=isSsaPresent,proto3" json:"is_ssa_present,omitempty"`
IsConnectorPresent bool `protobuf:"varint,10,opt,name=is_connector_present,json=isConnectorPresent,proto3" json:"is_connector_present,omitempty"`
IsPmsiPresent bool `protobuf:"varint,11,opt,name=is_pmsi_present,json=isPmsiPresent,proto3" json:"is_pmsi_present,omitempty"`
IsPppmpPresent bool `protobuf:"varint,12,opt,name=is_pppmp_present,json=isPppmpPresent,proto3" json:"is_pppmp_present,omitempty"`
IsAigpPresent bool `protobuf:"varint,13,opt,name=is_aigp_present,json=isAigpPresent,proto3" json:"is_aigp_present,omitempty"`
IsPeDistinguisherLabelPresent bool `protobuf:"varint,14,opt,name=is_pe_distinguisher_label_present,json=isPeDistinguisherLabelPresent,proto3" json:"is_pe_distinguisher_label_present,omitempty"`
IsLsAttributePresent bool `protobuf:"varint,15,opt,name=is_ls_attribute_present,json=isLsAttributePresent,proto3" json:"is_ls_attribute_present,omitempty"`
IsLabelIndexPresent bool `protobuf:"varint,16,opt,name=is_label_index_present,json=isLabelIndexPresent,proto3" json:"is_label_index_present,omitempty"`
NeighborAs uint32 `protobuf:"varint,17,opt,name=neighbor_as,json=neighborAs,proto3" json:"neighbor_as,omitempty"`
AggregatorAs uint32 `protobuf:"varint,18,opt,name=aggregator_as,json=aggregatorAs,proto3" json:"aggregator_as,omitempty"`
AggregatorAddress string `protobuf:"bytes,19,opt,name=aggregator_address,json=aggregatorAddress,proto3" json:"aggregator_address,omitempty"`
Metric uint32 `protobuf:"varint,20,opt,name=metric,proto3" json:"metric,omitempty"`
LocalPreference uint32 `protobuf:"varint,21,opt,name=local_preference,json=localPreference,proto3" json:"local_preference,omitempty"`
Origin uint32 `protobuf:"varint,22,opt,name=origin,proto3" json:"origin,omitempty"`
AsPath string `protobuf:"bytes,23,opt,name=as_path,json=asPath,proto3" json:"as_path,omitempty"`
Community []uint32 `protobuf:"varint,24,rep,packed,name=community,proto3" json:"community,omitempty"`
ExtendedCommunityFlags uint32 `protobuf:"varint,25,opt,name=extended_community_flags,json=extendedCommunityFlags,proto3" json:"extended_community_flags,omitempty"`
ExtendedCommunity []uint32 `protobuf:"varint,26,rep,packed,name=extended_community,json=extendedCommunity,proto3" json:"extended_community,omitempty"`
UnknownAttribute []uint32 `protobuf:"varint,27,rep,packed,name=unknown_attribute,json=unknownAttribute,proto3" json:"unknown_attribute,omitempty"`
Cluster []uint32 `protobuf:"varint,28,rep,packed,name=cluster,proto3" json:"cluster,omitempty"`
Originator string `protobuf:"bytes,29,opt,name=originator,proto3" json:"originator,omitempty"`
L2Tpv3SessionId uint32 `protobuf:"varint,30,opt,name=l2tpv3_session_id,json=l2tpv3SessionId,proto3" json:"l2tpv3_session_id,omitempty"`
L2Tpv3Cookie []uint32 `protobuf:"varint,31,rep,packed,name=l2tpv3_cookie,json=l2tpv3Cookie,proto3" json:"l2tpv3_cookie,omitempty"`
ConnectorType uint32 `protobuf:"varint,32,opt,name=connector_type,json=connectorType,proto3" json:"connector_type,omitempty"`
ConnectorValue []uint32 `protobuf:"varint,33,rep,packed,name=connector_value,json=connectorValue,proto3" json:"connector_value,omitempty"`
AigpMetricValue uint64 `protobuf:"varint,34,opt,name=aigp_metric_value,json=aigpMetricValue,proto3" json:"aigp_metric_value,omitempty"`
PmsiType uint32 `protobuf:"varint,35,opt,name=pmsi_type,json=pmsiType,proto3" json:"pmsi_type,omitempty"`
PmsiFlags uint32 `protobuf:"varint,36,opt,name=pmsi_flags,json=pmsiFlags,proto3" json:"pmsi_flags,omitempty"`
PmsiLabel uint32 `protobuf:"varint,37,opt,name=pmsi_label,json=pmsiLabel,proto3" json:"pmsi_label,omitempty"`
PmsiValue []uint32 `protobuf:"varint,38,rep,packed,name=pmsi_value,json=pmsiValue,proto3" json:"pmsi_value,omitempty"`
PpmPvalue uint32 `protobuf:"varint,39,opt,name=ppm_pvalue,json=ppmPvalue,proto3" json:"ppm_pvalue,omitempty"`
PeDistinguisherLabel []*BgpPedistlblEntry_ `protobuf:"bytes,40,rep,name=pe_distinguisher_label,json=peDistinguisherLabel,proto3" json:"pe_distinguisher_label,omitempty"`
LsAttr []uint32 `protobuf:"varint,41,rep,packed,name=ls_attr,json=lsAttr,proto3" json:"ls_attr,omitempty"`
LabelIndexAttr []uint32 `protobuf:"varint,42,rep,packed,name=label_index_attr,json=labelIndexAttr,proto3" json:"label_index_attr,omitempty"`
TunnelEncap *BgpTunencapEntry_ `protobuf:"bytes,43,opt,name=tunnel_encap,json=tunnelEncap,proto3" json:"tunnel_encap,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpCommonAttrEntry_) Reset() { *m = BgpCommonAttrEntry_{} }
func (m *BgpCommonAttrEntry_) String() string { return proto.CompactTextString(m) }
func (*BgpCommonAttrEntry_) ProtoMessage() {}
func (*BgpCommonAttrEntry_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{18}
}
func (m *BgpCommonAttrEntry_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpCommonAttrEntry_.Unmarshal(m, b)
}
func (m *BgpCommonAttrEntry_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpCommonAttrEntry_.Marshal(b, m, deterministic)
}
func (m *BgpCommonAttrEntry_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpCommonAttrEntry_.Merge(m, src)
}
func (m *BgpCommonAttrEntry_) XXX_Size() int {
return xxx_messageInfo_BgpCommonAttrEntry_.Size(m)
}
func (m *BgpCommonAttrEntry_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpCommonAttrEntry_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpCommonAttrEntry_ proto.InternalMessageInfo
func (m *BgpCommonAttrEntry_) GetIsMetricPresent() bool {
if m != nil {
return m.IsMetricPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsLocalPrefPresent() bool {
if m != nil {
return m.IsLocalPrefPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsAtomicAggregatePresent() bool {
if m != nil {
return m.IsAtomicAggregatePresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsAggregatorPresent() bool {
if m != nil {
return m.IsAggregatorPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsOriginPresent() bool {
if m != nil {
return m.IsOriginPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsAsPathPresent() bool {
if m != nil {
return m.IsAsPathPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsCommunityPresent() bool {
if m != nil {
return m.IsCommunityPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsExtendedCommunityPresent() bool {
if m != nil {
return m.IsExtendedCommunityPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsSsaPresent() bool {
if m != nil {
return m.IsSsaPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsConnectorPresent() bool {
if m != nil {
return m.IsConnectorPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsPmsiPresent() bool {
if m != nil {
return m.IsPmsiPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsPppmpPresent() bool {
if m != nil {
return m.IsPppmpPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsAigpPresent() bool {
if m != nil {
return m.IsAigpPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsPeDistinguisherLabelPresent() bool {
if m != nil {
return m.IsPeDistinguisherLabelPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsLsAttributePresent() bool {
if m != nil {
return m.IsLsAttributePresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetIsLabelIndexPresent() bool {
if m != nil {
return m.IsLabelIndexPresent
}
return false
}
func (m *BgpCommonAttrEntry_) GetNeighborAs() uint32 {
if m != nil {
return m.NeighborAs
}
return 0
}
func (m *BgpCommonAttrEntry_) GetAggregatorAs() uint32 {
if m != nil {
return m.AggregatorAs
}
return 0
}
func (m *BgpCommonAttrEntry_) GetAggregatorAddress() string {
if m != nil {
return m.AggregatorAddress
}
return ""
}
func (m *BgpCommonAttrEntry_) GetMetric() uint32 {
if m != nil {
return m.Metric
}
return 0
}
func (m *BgpCommonAttrEntry_) GetLocalPreference() uint32 {
if m != nil {
return m.LocalPreference
}
return 0
}
func (m *BgpCommonAttrEntry_) GetOrigin() uint32 {
if m != nil {
return m.Origin
}
return 0
}
func (m *BgpCommonAttrEntry_) GetAsPath() string {
if m != nil {
return m.AsPath
}
return ""
}
func (m *BgpCommonAttrEntry_) GetCommunity() []uint32 {
if m != nil {
return m.Community
}
return nil
}
func (m *BgpCommonAttrEntry_) GetExtendedCommunityFlags() uint32 {
if m != nil {
return m.ExtendedCommunityFlags
}
return 0
}
func (m *BgpCommonAttrEntry_) GetExtendedCommunity() []uint32 {
if m != nil {
return m.ExtendedCommunity
}
return nil
}
func (m *BgpCommonAttrEntry_) GetUnknownAttribute() []uint32 {
if m != nil {
return m.UnknownAttribute
}
return nil
}
func (m *BgpCommonAttrEntry_) GetCluster() []uint32 {
if m != nil {
return m.Cluster
}
return nil
}
func (m *BgpCommonAttrEntry_) GetOriginator() string {
if m != nil {
return m.Originator
}
return ""
}
func (m *BgpCommonAttrEntry_) GetL2Tpv3SessionId() uint32 {
if m != nil {
return m.L2Tpv3SessionId
}
return 0
}
func (m *BgpCommonAttrEntry_) GetL2Tpv3Cookie() []uint32 {
if m != nil {
return m.L2Tpv3Cookie
}
return nil
}
func (m *BgpCommonAttrEntry_) GetConnectorType() uint32 {
if m != nil {
return m.ConnectorType
}
return 0
}
func (m *BgpCommonAttrEntry_) GetConnectorValue() []uint32 {
if m != nil {
return m.ConnectorValue
}
return nil
}
func (m *BgpCommonAttrEntry_) GetAigpMetricValue() uint64 {
if m != nil {
return m.AigpMetricValue
}
return 0
}
func (m *BgpCommonAttrEntry_) GetPmsiType() uint32 {
if m != nil {
return m.PmsiType
}
return 0
}
func (m *BgpCommonAttrEntry_) GetPmsiFlags() uint32 {
if m != nil {
return m.PmsiFlags
}
return 0
}
func (m *BgpCommonAttrEntry_) GetPmsiLabel() uint32 {
if m != nil {
return m.PmsiLabel
}
return 0
}
func (m *BgpCommonAttrEntry_) GetPmsiValue() []uint32 {
if m != nil {
return m.PmsiValue
}
return nil
}
func (m *BgpCommonAttrEntry_) GetPpmPvalue() uint32 {
if m != nil {
return m.PpmPvalue
}
return 0
}
func (m *BgpCommonAttrEntry_) GetPeDistinguisherLabel() []*BgpPedistlblEntry_ {
if m != nil {
return m.PeDistinguisherLabel
}
return nil
}
func (m *BgpCommonAttrEntry_) GetLsAttr() []uint32 {
if m != nil {
return m.LsAttr
}
return nil
}
func (m *BgpCommonAttrEntry_) GetLabelIndexAttr() []uint32 {
if m != nil {
return m.LabelIndexAttr
}
return nil
}
func (m *BgpCommonAttrEntry_) GetTunnelEncap() *BgpTunencapEntry_ {
if m != nil {
return m.TunnelEncap
}
return nil
}
type BgpAttrRnhAddrT struct {
Len string `protobuf:"bytes,1,opt,name=len,proto3" json:"len,omitempty"`
Ipv4Address string `protobuf:"bytes,2,opt,name=ipv4_address,json=ipv4Address,proto3" json:"ipv4_address,omitempty"`
Ipv6Address string `protobuf:"bytes,3,opt,name=ipv6_address,json=ipv6Address,proto3" json:"ipv6_address,omitempty"`
MacAddress string `protobuf:"bytes,4,opt,name=mac_address,json=macAddress,proto3" json:"mac_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpAttrRnhAddrT) Reset() { *m = BgpAttrRnhAddrT{} }
func (m *BgpAttrRnhAddrT) String() string { return proto.CompactTextString(m) }
func (*BgpAttrRnhAddrT) ProtoMessage() {}
func (*BgpAttrRnhAddrT) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{19}
}
func (m *BgpAttrRnhAddrT) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpAttrRnhAddrT.Unmarshal(m, b)
}
func (m *BgpAttrRnhAddrT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpAttrRnhAddrT.Marshal(b, m, deterministic)
}
func (m *BgpAttrRnhAddrT) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpAttrRnhAddrT.Merge(m, src)
}
func (m *BgpAttrRnhAddrT) XXX_Size() int {
return xxx_messageInfo_BgpAttrRnhAddrT.Size(m)
}
func (m *BgpAttrRnhAddrT) XXX_DiscardUnknown() {
xxx_messageInfo_BgpAttrRnhAddrT.DiscardUnknown(m)
}
var xxx_messageInfo_BgpAttrRnhAddrT proto.InternalMessageInfo
func (m *BgpAttrRnhAddrT) GetLen() string {
if m != nil {
return m.Len
}
return ""
}
func (m *BgpAttrRnhAddrT) GetIpv4Address() string {
if m != nil {
return m.Ipv4Address
}
return ""
}
func (m *BgpAttrRnhAddrT) GetIpv6Address() string {
if m != nil {
return m.Ipv6Address
}
return ""
}
func (m *BgpAttrRnhAddrT) GetMacAddress() string {
if m != nil {
return m.MacAddress
}
return ""
}
type BgpAttr_ struct {
IsAsPath2Byte bool `protobuf:"varint,1,opt,name=is_as_path2_byte,json=isAsPath2Byte,proto3" json:"is_as_path2_byte,omitempty"`
IsApplicationGatewayPresent bool `protobuf:"varint,2,opt,name=is_application_gateway_present,json=isApplicationGatewayPresent,proto3" json:"is_application_gateway_present,omitempty"`
IsAttrSetPresent bool `protobuf:"varint,3,opt,name=is_attr_set_present,json=isAttrSetPresent,proto3" json:"is_attr_set_present,omitempty"`
SetAigpInboundIgp bool `protobuf:"varint,4,opt,name=set_aigp_inbound_igp,json=setAigpInboundIgp,proto3" json:"set_aigp_inbound_igp,omitempty"`
SetAigpInboundMetric bool `protobuf:"varint,5,opt,name=set_aigp_inbound_metric,json=setAigpInboundMetric,proto3" json:"set_aigp_inbound_metric,omitempty"`
IsRnhPresent bool `protobuf:"varint,6,opt,name=is_rnh_present,json=isRnhPresent,proto3" json:"is_rnh_present,omitempty"`
IsRibrnhPresent bool `protobuf:"varint,7,opt,name=is_ribrnh_present,json=isRibrnhPresent,proto3" json:"is_ribrnh_present,omitempty"`
AttributeKeyNumber uint32 `protobuf:"varint,8,opt,name=attribute_key_number,json=attributeKeyNumber,proto3" json:"attribute_key_number,omitempty"`
AttributeReuseIdConfig bool `protobuf:"varint,9,opt,name=attribute_reuse_id_config,json=attributeReuseIdConfig,proto3" json:"attribute_reuse_id_config,omitempty"`
AttributeReuseIdMaxId uint32 `protobuf:"varint,10,opt,name=attribute_reuse_id_max_id,json=attributeReuseIdMaxId,proto3" json:"attribute_reuse_id_max_id,omitempty"`
AttributeReuseIdNode uint32 `protobuf:"varint,11,opt,name=attribute_reuse_id_node,json=attributeReuseIdNode,proto3" json:"attribute_reuse_id_node,omitempty"`
AttributeReuseIdCurrent uint32 `protobuf:"varint,12,opt,name=attribute_reuse_id_current,json=attributeReuseIdCurrent,proto3" json:"attribute_reuse_id_current,omitempty"`
AttributeReuseIdKeys uint32 `protobuf:"varint,13,opt,name=attribute_reuse_id_keys,json=attributeReuseIdKeys,proto3" json:"attribute_reuse_id_keys,omitempty"`
AttributeReuseIdRecoverSec uint32 `protobuf:"varint,14,opt,name=attribute_reuse_id_recover_sec,json=attributeReuseIdRecoverSec,proto3" json:"attribute_reuse_id_recover_sec,omitempty"`
VpnDistinguisher uint32 `protobuf:"varint,15,opt,name=vpn_distinguisher,json=vpnDistinguisher,proto3" json:"vpn_distinguisher,omitempty"`
CommonAttributes *BgpCommonAttrEntry_ `protobuf:"bytes,16,opt,name=common_attributes,json=commonAttributes,proto3" json:"common_attributes,omitempty"`
AttrSet *BgpCommonAttrEntry_ `protobuf:"bytes,17,opt,name=attr_set,json=attrSet,proto3" json:"attr_set,omitempty"`
RnhType uint32 `protobuf:"varint,18,opt,name=rnh_type,json=rnhType,proto3" json:"rnh_type,omitempty"`
RnhLen uint32 `protobuf:"varint,19,opt,name=rnh_len,json=rnhLen,proto3" json:"rnh_len,omitempty"`
RnhAddrLen uint32 `protobuf:"varint,20,opt,name=rnh_addr_len,json=rnhAddrLen,proto3" json:"rnh_addr_len,omitempty"`
RnhAddr *BgpAttrRnhAddrT `protobuf:"bytes,21,opt,name=rnh_addr,json=rnhAddr,proto3" json:"rnh_addr,omitempty"`
RibrnhTable uint32 `protobuf:"varint,22,opt,name=ribrnh_table,json=ribrnhTable,proto3" json:"ribrnh_table,omitempty"`
RibrnhMac string `protobuf:"bytes,23,opt,name=ribrnh_mac,json=ribrnhMac,proto3" json:"ribrnh_mac,omitempty"`
RibrnhIp *BgpAddrtype `protobuf:"bytes,24,opt,name=ribrnh_ip,json=ribrnhIp,proto3" json:"ribrnh_ip,omitempty"`
RibrnhipTable uint32 `protobuf:"varint,25,opt,name=ribrnhip_table,json=ribrnhipTable,proto3" json:"ribrnhip_table,omitempty"`
RibrnhVni uint32 `protobuf:"varint,26,opt,name=ribrnh_vni,json=ribrnhVni,proto3" json:"ribrnh_vni,omitempty"`
RibrnhEncap uint32 `protobuf:"varint,27,opt,name=ribrnh_encap,json=ribrnhEncap,proto3" json:"ribrnh_encap,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpAttr_) Reset() { *m = BgpAttr_{} }
func (m *BgpAttr_) String() string { return proto.CompactTextString(m) }
func (*BgpAttr_) ProtoMessage() {}
func (*BgpAttr_) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{20}
}
func (m *BgpAttr_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpAttr_.Unmarshal(m, b)
}
func (m *BgpAttr_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpAttr_.Marshal(b, m, deterministic)
}
func (m *BgpAttr_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpAttr_.Merge(m, src)
}
func (m *BgpAttr_) XXX_Size() int {
return xxx_messageInfo_BgpAttr_.Size(m)
}
func (m *BgpAttr_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpAttr_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpAttr_ proto.InternalMessageInfo
func (m *BgpAttr_) GetIsAsPath2Byte() bool {
if m != nil {
return m.IsAsPath2Byte
}
return false
}
func (m *BgpAttr_) GetIsApplicationGatewayPresent() bool {
if m != nil {
return m.IsApplicationGatewayPresent
}
return false
}
func (m *BgpAttr_) GetIsAttrSetPresent() bool {
if m != nil {
return m.IsAttrSetPresent
}
return false
}
func (m *BgpAttr_) GetSetAigpInboundIgp() bool {
if m != nil {
return m.SetAigpInboundIgp
}
return false
}
func (m *BgpAttr_) GetSetAigpInboundMetric() bool {
if m != nil {
return m.SetAigpInboundMetric
}
return false
}
func (m *BgpAttr_) GetIsRnhPresent() bool {
if m != nil {
return m.IsRnhPresent
}
return false
}
func (m *BgpAttr_) GetIsRibrnhPresent() bool {
if m != nil {
return m.IsRibrnhPresent
}
return false
}
func (m *BgpAttr_) GetAttributeKeyNumber() uint32 {
if m != nil {
return m.AttributeKeyNumber
}
return 0
}
func (m *BgpAttr_) GetAttributeReuseIdConfig() bool {
if m != nil {
return m.AttributeReuseIdConfig
}
return false
}
func (m *BgpAttr_) GetAttributeReuseIdMaxId() uint32 {
if m != nil {
return m.AttributeReuseIdMaxId
}
return 0
}
func (m *BgpAttr_) GetAttributeReuseIdNode() uint32 {
if m != nil {
return m.AttributeReuseIdNode
}
return 0
}
func (m *BgpAttr_) GetAttributeReuseIdCurrent() uint32 {
if m != nil {
return m.AttributeReuseIdCurrent
}
return 0
}
func (m *BgpAttr_) GetAttributeReuseIdKeys() uint32 {
if m != nil {
return m.AttributeReuseIdKeys
}
return 0
}
func (m *BgpAttr_) GetAttributeReuseIdRecoverSec() uint32 {
if m != nil {
return m.AttributeReuseIdRecoverSec
}
return 0
}
func (m *BgpAttr_) GetVpnDistinguisher() uint32 {
if m != nil {
return m.VpnDistinguisher
}
return 0
}
func (m *BgpAttr_) GetCommonAttributes() *BgpCommonAttrEntry_ {
if m != nil {
return m.CommonAttributes
}
return nil
}
func (m *BgpAttr_) GetAttrSet() *BgpCommonAttrEntry_ {
if m != nil {
return m.AttrSet
}
return nil
}
func (m *BgpAttr_) GetRnhType() uint32 {
if m != nil {
return m.RnhType
}
return 0
}
func (m *BgpAttr_) GetRnhLen() uint32 {
if m != nil {
return m.RnhLen
}
return 0
}
func (m *BgpAttr_) GetRnhAddrLen() uint32 {
if m != nil {
return m.RnhAddrLen
}
return 0
}
func (m *BgpAttr_) GetRnhAddr() *BgpAttrRnhAddrT {
if m != nil {
return m.RnhAddr
}
return nil
}
func (m *BgpAttr_) GetRibrnhTable() uint32 {
if m != nil {
return m.RibrnhTable
}
return 0
}
func (m *BgpAttr_) GetRibrnhMac() string {
if m != nil {
return m.RibrnhMac
}
return ""
}
func (m *BgpAttr_) GetRibrnhIp() *BgpAddrtype {
if m != nil {
return m.RibrnhIp
}
return nil
}
func (m *BgpAttr_) GetRibrnhipTable() uint32 {
if m != nil {
return m.RibrnhipTable
}
return 0
}
func (m *BgpAttr_) GetRibrnhVni() uint32 {
if m != nil {
return m.RibrnhVni
}
return 0
}
func (m *BgpAttr_) GetRibrnhEncap() uint32 {
if m != nil {
return m.RibrnhEncap
}
return 0
}
type BgpPathBag struct {
NoPath bool `protobuf:"varint,50,opt,name=no_path,json=noPath,proto3" json:"no_path,omitempty"`
AfName string `protobuf:"bytes,51,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"`
NeighborAddressXr *BgpAddrtype `protobuf:"bytes,52,opt,name=neighbor_address_xr,json=neighborAddressXr,proto3" json:"neighbor_address_xr,omitempty"`
ProcessInstanceId uint32 `protobuf:"varint,53,opt,name=process_instance_id,json=processInstanceId,proto3" json:"process_instance_id,omitempty"`
LabelOor bool `protobuf:"varint,54,opt,name=label_oor,json=labelOor,proto3" json:"label_oor,omitempty"`
LabelOOrVersion uint32 `protobuf:"varint,55,opt,name=label_o_or_version,json=labelOOrVersion,proto3" json:"label_o_or_version,omitempty"`
LabelFail bool `protobuf:"varint,56,opt,name=label_fail,json=labelFail,proto3" json:"label_fail,omitempty"`
PathInformation *BgpPath_ `protobuf:"bytes,57,opt,name=path_information,json=pathInformation,proto3" json:"path_information,omitempty"`
AttributesAfterPolicyIn *BgpAttr_ `protobuf:"bytes,58,opt,name=attributes_after_policy_in,json=attributesAfterPolicyIn,proto3" json:"attributes_after_policy_in,omitempty"`
RouteDistinguisher string `protobuf:"bytes,59,opt,name=route_distinguisher,json=routeDistinguisher,proto3" json:"route_distinguisher,omitempty"`
SourceRouteDistinguisher string `protobuf:"bytes,60,opt,name=source_route_distinguisher,json=sourceRouteDistinguisher,proto3" json:"source_route_distinguisher,omitempty"`
PrefixVersion uint32 `protobuf:"varint,61,opt,name=prefix_version,json=prefixVersion,proto3" json:"prefix_version,omitempty"`
VrfName string `protobuf:"bytes,62,opt,name=vrf_name,json=vrfName,proto3" json:"vrf_name,omitempty"`
SourceVrfName string `protobuf:"bytes,63,opt,name=source_vrf_name,json=sourceVrfName,proto3" json:"source_vrf_name,omitempty"`
SrcafName string `protobuf:"bytes,64,opt,name=srcaf_name,json=srcafName,proto3" json:"srcaf_name,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpPathBag) Reset() { *m = BgpPathBag{} }
func (m *BgpPathBag) String() string { return proto.CompactTextString(m) }
func (*BgpPathBag) ProtoMessage() {}
func (*BgpPathBag) Descriptor() ([]byte, []int) {
return fileDescriptor_bb29889f75ad586c, []int{21}
}
func (m *BgpPathBag) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpPathBag.Unmarshal(m, b)
}
func (m *BgpPathBag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpPathBag.Marshal(b, m, deterministic)
}
func (m *BgpPathBag) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpPathBag.Merge(m, src)
}
func (m *BgpPathBag) XXX_Size() int {
return xxx_messageInfo_BgpPathBag.Size(m)
}
func (m *BgpPathBag) XXX_DiscardUnknown() {
xxx_messageInfo_BgpPathBag.DiscardUnknown(m)
}
var xxx_messageInfo_BgpPathBag proto.InternalMessageInfo
func (m *BgpPathBag) GetNoPath() bool {
if m != nil {
return m.NoPath
}
return false
}
func (m *BgpPathBag) GetAfName() string {
if m != nil {
return m.AfName
}
return ""
}
func (m *BgpPathBag) GetNeighborAddressXr() *BgpAddrtype {
if m != nil {
return m.NeighborAddressXr
}
return nil
}
func (m *BgpPathBag) GetProcessInstanceId() uint32 {
if m != nil {
return m.ProcessInstanceId
}
return 0
}
func (m *BgpPathBag) GetLabelOor() bool {
if m != nil {
return m.LabelOor
}
return false
}
func (m *BgpPathBag) GetLabelOOrVersion() uint32 {
if m != nil {
return m.LabelOOrVersion
}
return 0
}
func (m *BgpPathBag) GetLabelFail() bool {
if m != nil {
return m.LabelFail
}
return false
}
func (m *BgpPathBag) GetPathInformation() *BgpPath_ {
if m != nil {
return m.PathInformation
}
return nil
}
func (m *BgpPathBag) GetAttributesAfterPolicyIn() *BgpAttr_ {
if m != nil {
return m.AttributesAfterPolicyIn
}
return nil
}
func (m *BgpPathBag) GetRouteDistinguisher() string {
if m != nil {
return m.RouteDistinguisher
}
return ""
}
func (m *BgpPathBag) GetSourceRouteDistinguisher() string {
if m != nil {
return m.SourceRouteDistinguisher
}
return ""
}
func (m *BgpPathBag) GetPrefixVersion() uint32 {
if m != nil {
return m.PrefixVersion
}
return 0
}
func (m *BgpPathBag) GetVrfName() string {
if m != nil {
return m.VrfName
}
return ""
}
func (m *BgpPathBag) GetSourceVrfName() string {
if m != nil {
return m.SourceVrfName
}
return ""
}
func (m *BgpPathBag) GetSrcafName() string {
if m != nil {
return m.SrcafName
}
return ""
}
func init() {
proto.RegisterType((*BgpPathBag_KEYS)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_path_bag_KEYS")
proto.RegisterType((*BgpL2VpnAddrT)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_l2vpn_addr_t")
proto.RegisterType((*BgpL2VpnMspwAddrT)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_l2vpn_mspw_addr_t")
proto.RegisterType((*BgpIpv4SrpolicyAddrT)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_ipv4_srpolicy_addr_t")
proto.RegisterType((*BgpIpv6SrpolicyAddrT)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_ipv6_srpolicy_addr_t")
proto.RegisterType((*BgpAddrtype)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_addrtype")
proto.RegisterType((*BgpPrefixtype)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_prefixtype")
proto.RegisterType((*BgpTeTunnel)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_te_tunnel")
proto.RegisterType((*BgpL2VpnEvpnEsiT)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_l2vpn_evpn_esi_t")
proto.RegisterType((*BgpV4V6T)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_v4_v6_t")
proto.RegisterType((*BgpAdvinfoType_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_advinfo_type_")
proto.RegisterType((*BgpPath_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_path_")
proto.RegisterType((*BgpPedistlblEntry_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_pedistlbl_entry_")
proto.RegisterType((*BgpBindingSidT)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_binding_sid_t")
proto.RegisterType((*SrSid_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.sr_sid_")
proto.RegisterType((*SrExppath_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.sr_exppath_")
proto.RegisterType((*BgpSrpolicyEntry_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_srpolicy_entry_")
proto.RegisterType((*BgpTunencapEntry_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_tunencap_entry_")
proto.RegisterType((*BgpCommonAttrEntry_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_common_attr_entry_")
proto.RegisterType((*BgpAttrRnhAddrT)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_attr_rnh_addr_t")
proto.RegisterType((*BgpAttr_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_attr_")
proto.RegisterType((*BgpPathBag)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_standby.default_vrf.afs.af.advertised_path_xr.advertised_path.bgp_path_bag")
}
func init() { proto.RegisterFile("bgp_path_bag.proto", fileDescriptor_bb29889f75ad586c) }
var fileDescriptor_bb29889f75ad586c = []byte{
// 5119 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x5c, 0x5b, 0x6f, 0x1c, 0xc9,
0x75, 0x46, 0x4b, 0x5a, 0x72, 0x58, 0xe4, 0xf0, 0xd2, 0xbc, 0xa8, 0x75, 0xa7, 0x66, 0x57, 0x2b,
0x69, 0x2f, 0x94, 0x97, 0x4b, 0x73, 0xaf, 0x5e, 0x2f, 0x45, 0x51, 0xab, 0xf1, 0x92, 0x14, 0xd3,
0xa3, 0xd5, 0xda, 0xb9, 0xb5, 0x7b, 0xba, 0x6b, 0x66, 0x2a, 0xec, 0xae, 0xee, 0xad, 0xaa, 0x19,
0x92, 0x7e, 0x33, 0x02, 0x27, 0x41, 0x82, 0x38, 0x41, 0x9e, 0x83, 0x18, 0x08, 0x12, 0x20, 0x86,
0x6d, 0x04, 0x46, 0x10, 0x24, 0x48, 0x02, 0x27, 0x46, 0x12, 0xf8, 0x21, 0x79, 0xcf, 0x6f, 0xc8,
0x3f, 0xc8, 0x63, 0x50, 0xe7, 0x54, 0x75, 0xf7, 0x0c, 0x47, 0x81, 0xfd, 0x10, 0x90, 0x7e, 0x58,
0x2c, 0xfb, 0x9c, 0xef, 0xd4, 0xbd, 0xce, 0xf9, 0x4e, 0x55, 0x8d, 0x88, 0xdb, 0xee, 0xe6, 0x41,
0x1e, 0xaa, 0x5e, 0xd0, 0x0e, 0xbb, 0x6b, 0xb9, 0xc8, 0x54, 0xe6, 0x1e, 0x47, 0x4c, 0x46, 0x59,
0xc0, 0x32, 0x19, 0x1c, 0x8b, 0x80, 0xe5, 0x83, 0x8d, 0x40, 0xa3, 0xb2, 0x9c, 0x8a, 0xb5, 0x76,
0x37, 0x5f, 0x63, 0x5c, 0xaa, 0x90, 0x47, 0x54, 0x16, 0x7f, 0x15, 0x7f, 0x04, 0xfa, 0x7f, 0x71,
0xfb, 0x64, 0x2d, 0xa6, 0x9d, 0xb0, 0x9f, 0xa8, 0x60, 0x20, 0x3a, 0x6b, 0x61, 0x47, 0xae, 0x85,
0x9d, 0xb5, 0x30, 0x1e, 0x50, 0xa1, 0x98, 0xa4, 0x31, 0x56, 0x78, 0x2c, 0x46, 0x45, 0x8d, 0xff,
0x70, 0xc8, 0x42, 0xb5, 0x41, 0xc1, 0xa7, 0x3b, 0xdf, 0x68, 0xb9, 0x2f, 0x93, 0x7a, 0x51, 0x3e,
0x0f, 0x53, 0xea, 0x39, 0xab, 0xce, 0xbd, 0x29, 0x7f, 0xc6, 0x0a, 0xf7, 0xc3, 0x94, 0xba, 0x97,
0xc9, 0x64, 0xd8, 0x41, 0xf5, 0x05, 0x50, 0x4f, 0x84, 0x1d, 0x50, 0xcc, 0x92, 0x0b, 0x22, 0xf6,
0x2e, 0x82, 0xec, 0x82, 0x88, 0x5d, 0x8f, 0x4c, 0x72, 0xaa, 0x8e, 0x32, 0x71, 0xe8, 0x5d, 0x02,
0xa1, 0xfd, 0xd4, 0xf5, 0xe4, 0x82, 0x76, 0xd8, 0x71, 0x90, 0x50, 0xde, 0x55, 0x3d, 0xef, 0xa5,
0x55, 0xe7, 0x5e, 0xdd, 0x9f, 0x41, 0xe1, 0x2e, 0xc8, 0xdc, 0xfb, 0x64, 0x9e, 0x53, 0xd6, 0xed,
0xb5, 0x33, 0x11, 0x84, 0x71, 0x2c, 0xa8, 0x94, 0xde, 0x04, 0x94, 0x33, 0x67, 0xe5, 0x5b, 0x28,
0x6e, 0xbc, 0x43, 0xe6, 0x75, 0x67, 0x92, 0xf5, 0x41, 0xce, 0x01, 0x1b, 0x28, 0x5d, 0x47, 0xf9,
0xad, 0x6d, 0x9d, 0xd5, 0x8b, 0xba, 0x0e, 0x10, 0x5a, 0xc3, 0x0f, 0xc9, 0x72, 0x69, 0x98, 0xca,
0xfc, 0xe8, 0x17, 0xb2, 0xde, 0x27, 0x9e, 0xb6, 0x86, 0x79, 0x93, 0x22, 0xcf, 0x12, 0x16, 0x9d,
0xd8, 0x02, 0xd6, 0xc9, 0xf2, 0x69, 0x79, 0x59, 0xd0, 0xa2, 0x56, 0xb6, 0x8c, 0xee, 0x74, 0x79,
0x9b, 0x2f, 0x28, 0x6f, 0xf3, 0xff, 0x2a, 0x6f, 0x73, 0xb4, 0xbc, 0xff, 0xa9, 0x93, 0x19, 0x5d,
0xa0, 0x86, 0xaa, 0x93, 0x9c, 0xba, 0xf3, 0xe4, 0x62, 0xd8, 0x61, 0x66, 0x56, 0xf5, 0x9f, 0xee,
0x6d, 0x32, 0x03, 0xcd, 0xb4, 0xa5, 0xe1, 0x8c, 0x4e, 0x6b, 0x99, 0x29, 0xc5, 0x7d, 0x83, 0xb8,
0x00, 0x49, 0xa3, 0x50, 0xaa, 0x02, 0x88, 0xd3, 0x3c, 0xaf, 0x35, 0x7b, 0x5a, 0x31, 0x8a, 0x4e,
0xc2, 0x36, 0x4d, 0x0a, 0xf4, 0xa5, 0x12, 0xbd, 0xab, 0x15, 0x16, 0xbd, 0x46, 0x60, 0x20, 0x02,
0xd5, 0xe7, 0xbc, 0x02, 0x7f, 0x09, 0xe0, 0x0b, 0x5a, 0xf5, 0x0c, 0x34, 0x16, 0x7f, 0x97, 0xcc,
0x69, 0x61, 0x1a, 0xab, 0x91, 0x25, 0x31, 0x6b, 0xc4, 0x23, 0xc0, 0xea, 0x0c, 0x4e, 0x96, 0xc0,
0x72, 0x0e, 0xdd, 0xb7, 0xc8, 0x92, 0x91, 0x84, 0xd8, 0x43, 0x83, 0xae, 0x01, 0x7a, 0xd1, 0xea,
0xf6, 0x4a, 0x95, 0x19, 0xb3, 0xcd, 0xa2, 0xe0, 0xa9, 0x62, 0xcc, 0x36, 0x87, 0x47, 0x61, 0x73,
0x64, 0xcc, 0x48, 0x31, 0x0a, 0x9b, 0x63, 0xc6, 0x6c, 0x73, 0x64, 0xcc, 0xa6, 0x4b, 0xf4, 0xd0,
0x98, 0x61, 0xd7, 0x36, 0xab, 0x5d, 0x9b, 0x29, 0xba, 0xb6, 0x59, 0xe9, 0x9a, 0x59, 0x32, 0xb0,
0xb4, 0x87, 0xda, 0x51, 0x2f, 0xfa, 0xa6, 0x95, 0x43, 0x4d, 0xf9, 0x7b, 0x87, 0x2c, 0xc0, 0x1a,
0x1f, 0xe4, 0x89, 0x2c, 0x0c, 0x66, 0x57, 0x9d, 0x7b, 0xd3, 0xeb, 0xbf, 0xef, 0xac, 0x9d, 0x95,
0xbf, 0x5a, 0x1b, 0xdd, 0xde, 0xfe, 0x7c, 0xd1, 0xca, 0x4a, 0x77, 0x85, 0x0a, 0xa2, 0x8c, 0x4b,
0x25, 0x42, 0xc6, 0xcb, 0xee, 0xce, 0x61, 0x77, 0x85, 0xda, 0x2e, 0x74, 0xd6, 0xe6, 0x3e, 0x81,
0xf1, 0x4d, 0xab, 0x83, 0x39, 0x8f, 0x3e, 0xc6, 0xca, 0x87, 0xa1, 0x1b, 0x43, 0xd0, 0x85, 0x02,
0xba, 0x51, 0x85, 0xbe, 0x41, 0x5c, 0x6c, 0x2b, 0xad, 0x82, 0x5d, 0x9c, 0x4f, 0xd0, 0xec, 0x54,
0xd0, 0x0d, 0x52, 0x4f, 0x64, 0x50, 0x19, 0xed, 0x45, 0x5c, 0x4f, 0x89, 0xdc, 0x2d, 0xfa, 0xf6,
0x13, 0xc7, 0x16, 0x59, 0x38, 0x29, 0x8d, 0x5c, 0x82, 0x79, 0xf9, 0xa3, 0x73, 0x31, 0x2f, 0x15,
0xef, 0x69, 0x3a, 0xb9, 0x27, 0xf3, 0xa3, 0xe1, 0xb5, 0xb8, 0x11, 0x74, 0x92, 0xec, 0x48, 0xe6,
0x34, 0x2a, 0xba, 0xb0, 0x5c, 0xee, 0xb3, 0xc7, 0x46, 0x37, 0xb2, 0x7e, 0x4f, 0xdb, 0xac, 0x94,
0xeb, 0x77, 0xd4, 0xe6, 0x5d, 0xe2, 0xd9, 0x7d, 0x7f, 0xca, 0xec, 0x32, 0x98, 0xad, 0x18, 0xfd,
0x78, 0xcb, 0xcd, 0xb1, 0x96, 0x5e, 0x61, 0xb9, 0x39, 0xc6, 0xf2, 0x67, 0x0e, 0x76, 0x4e, 0x8a,
0x60, 0xc4, 0x37, 0x5f, 0x81, 0xf9, 0xf9, 0x93, 0x33, 0x9e, 0x9f, 0x71, 0xf1, 0x09, 0x47, 0x5c,
0x8a, 0x83, 0x6a, 0xc0, 0xb0, 0x3d, 0xd9, 0x3c, 0xdd, 0x93, 0xab, 0xe7, 0xa5, 0x27, 0x9b, 0x63,
0x7b, 0xb2, 0x39, 0xd2, 0x93, 0xc6, 0x7f, 0x39, 0x64, 0x16, 0xf8, 0x0d, 0x30, 0x0a, 0x08, 0x7e,
0xdf, 0x73, 0xc8, 0x04, 0x7e, 0x42, 0x00, 0x9c, 0x5e, 0xff, 0x9d, 0x33, 0xee, 0x8d, 0x0d, 0xcb,
0xbe, 0x69, 0xd6, 0x69, 0x5a, 0x74, 0xe1, 0x34, 0x2d, 0x6a, 0xfc, 0xe7, 0x45, 0x52, 0xd7, 0xd6,
0x8a, 0x9a, 0xa8, 0xe9, 0xde, 0x22, 0xd3, 0x26, 0x7e, 0xea, 0xd2, 0x4c, 0x74, 0x27, 0x28, 0x7a,
0xa6, 0x7b, 0x5e, 0x02, 0x0c, 0x6b, 0xd3, 0x8c, 0xc1, 0x00, 0x80, 0xb9, 0xdd, 0x20, 0xa4, 0x17,
0x4a, 0x53, 0x1e, 0x84, 0xf6, 0x9a, 0x3f, 0xd5, 0x0b, 0x25, 0x06, 0x5f, 0x77, 0x95, 0xcc, 0x30,
0xab, 0x0d, 0xfa, 0x39, 0x44, 0xf3, 0x9a, 0x4f, 0x98, 0xd1, 0x7f, 0x96, 0xbb, 0x0f, 0xc8, 0x52,
0x89, 0x60, 0xbc, 0x93, 0xe9, 0xe1, 0x49, 0x28, 0x04, 0xf2, 0x9a, 0xbf, 0x60, 0x91, 0x4d, 0xde,
0xc9, 0x5a, 0x5a, 0xe1, 0x7e, 0xa9, 0x6a, 0x20, 0x68, 0x97, 0x49, 0x45, 0x05, 0x8d, 0x21, 0x9a,
0xd7, 0x7c, 0xd7, 0x1a, 0xf8, 0x85, 0x46, 0x3b, 0x55, 0x03, 0x1f, 0x6c, 0x06, 0x82, 0x7e, 0xd1,
0x67, 0x1a, 0x3f, 0x09, 0xf8, 0x79, 0xd4, 0x3c, 0xdf, 0xf4, 0x8d, 0xdc, 0x7d, 0x8d, 0x2c, 0x94,
0x68, 0xca, 0xc3, 0x76, 0x42, 0x63, 0x88, 0xe9, 0x35, 0x7f, 0xce, 0x82, 0x77, 0x50, 0xac, 0x87,
0xbd, 0xcd, 0x78, 0xcc, 0x78, 0x17, 0x23, 0x30, 0x04, 0xf4, 0xba, 0x3f, 0x63, 0x84, 0x10, 0x7c,
0xdd, 0x7b, 0x64, 0xde, 0x76, 0xaf, 0x13, 0xf4, 0x42, 0x1e, 0x27, 0x14, 0xe2, 0x79, 0xdd, 0x9f,
0x45, 0x79, 0xb3, 0xf3, 0x04, 0xa4, 0xe0, 0xfd, 0x75, 0xb4, 0x2d, 0xc6, 0x2b, 0x0e, 0x15, 0x85,
0x68, 0x5e, 0xf7, 0xe7, 0xb5, 0xc6, 0x8e, 0x9a, 0x96, 0x37, 0xee, 0x91, 0xa5, 0xd2, 0x87, 0x42,
0xbc, 0xa0, 0x92, 0x05, 0x4a, 0x53, 0x35, 0x2a, 0x99, 0x61, 0x77, 0xfa, 0xcf, 0x06, 0x25, 0xd3,
0x1a, 0x39, 0xd8, 0xd0, 0x5d, 0x02, 0x40, 0x42, 0xb9, 0xe5, 0x72, 0x09, 0xe5, 0x3f, 0x0f, 0x97,
0x1b, 0xa5, 0x2e, 0x17, 0x4f, 0x51, 0x97, 0xc6, 0x9f, 0x5d, 0xc0, 0xcc, 0x20, 0x8c, 0x07, 0x30,
0x91, 0x7a, 0x4d, 0x05, 0x7a, 0x09, 0x31, 0x19, 0x58, 0xde, 0x0d, 0xb5, 0xc2, 0x0a, 0xd8, 0x37,
0x12, 0xf7, 0xef, 0x1c, 0xb2, 0x38, 0x4a, 0xd7, 0x83, 0x63, 0x01, 0x8d, 0x38, 0x47, 0x5b, 0x6d,
0x61, 0x24, 0x75, 0xf8, 0xba, 0xd0, 0x1c, 0x14, 0xe7, 0x28, 0xe8, 0x8a, 0xac, 0x9f, 0x07, 0xbc,
0x9f, 0xb6, 0xa9, 0x80, 0xa1, 0xa9, 0xfb, 0x0b, 0xa8, 0xfa, 0x44, 0x6b, 0xf6, 0x41, 0xd1, 0xf8,
0xe1, 0x07, 0x64, 0xaa, 0x48, 0x9d, 0xdc, 0xbf, 0x72, 0x08, 0x29, 0x1d, 0x8d, 0xf1, 0x2c, 0xbf,
0x77, 0xc6, 0xdd, 0x2d, 0xbd, 0x9e, 0xaf, 0x9b, 0x7a, 0x80, 0xee, 0xe5, 0x97, 0x77, 0x8a, 0x6e,
0x10, 0x22, 0xb2, 0xbe, 0xf6, 0x78, 0xda, 0xc1, 0xe1, 0xa2, 0x9d, 0x02, 0x09, 0xf8, 0xb7, 0x06,
0xa9, 0x33, 0x89, 0x85, 0x0f, 0xc2, 0x84, 0xc5, 0xc6, 0x41, 0x4d, 0x33, 0x79, 0x10, 0xaa, 0xde,
0x73, 0x2d, 0x72, 0x5f, 0x21, 0xb3, 0x16, 0x13, 0x87, 0x69, 0x4e, 0x63, 0xe3, 0x9b, 0x66, 0x10,
0xf4, 0x08, 0x64, 0xc6, 0x8f, 0x01, 0xaa, 0xc7, 0xa4, 0xca, 0xc4, 0x49, 0xd0, 0xa3, 0x89, 0x75,
0x4b, 0x0b, 0x88, 0x7d, 0x82, 0x9a, 0x27, 0x34, 0x89, 0xb5, 0x5b, 0x60, 0x32, 0x60, 0x5c, 0x51,
0xc1, 0xc3, 0x04, 0x2c, 0x8d, 0x4f, 0x9a, 0x65, 0xb2, 0x69, 0xc4, 0xda, 0xc8, 0x38, 0xd1, 0x36,
0x95, 0x0a, 0x51, 0x35, 0xbb, 0x85, 0x1e, 0x52, 0xa9, 0x00, 0x71, 0x9d, 0x10, 0x26, 0x83, 0x10,
0x41, 0xe0, 0x84, 0x6a, 0x7e, 0x8d, 0xc9, 0x2d, 0x40, 0xb8, 0x77, 0xc8, 0x1c, 0x93, 0x81, 0xcc,
0x0f, 0x45, 0x01, 0x21, 0xb6, 0x07, 0xad, 0xfc, 0x50, 0x18, 0xd8, 0xab, 0x00, 0xcb, 0x43, 0xa1,
0x58, 0x98, 0x20, 0x6c, 0x1a, 0x60, 0x75, 0xdd, 0x78, 0x90, 0x02, 0xee, 0x7d, 0x72, 0x45, 0x57,
0xd6, 0xed, 0x0a, 0xda, 0x0d, 0x15, 0xcb, 0x78, 0x20, 0xfb, 0x79, 0xae, 0xc7, 0x9b, 0xc6, 0x90,
0x4f, 0xd4, 0xfc, 0xcb, 0x4c, 0x6e, 0x95, 0xfa, 0x56, 0xa1, 0x86, 0x7c, 0x45, 0x06, 0x2c, 0xcd,
0x33, 0xa1, 0x70, 0x34, 0x39, 0x8d, 0x21, 0xab, 0xa8, 0xf9, 0xf3, 0x4c, 0x36, 0x41, 0xf1, 0xc8,
0xc8, 0xb5, 0x2b, 0x2e, 0xd1, 0xb2, 0xaf, 0x99, 0x93, 0x82, 0x8c, 0xa2, 0xe6, 0xcf, 0x59, 0x70,
0x0b, 0xc5, 0xee, 0xdb, 0x64, 0xc5, 0x8e, 0x3f, 0xcf, 0x34, 0x83, 0xb7, 0xeb, 0x04, 0x48, 0x7c,
0xcd, 0x5f, 0xc4, 0x19, 0xd8, 0xcf, 0xd4, 0x56, 0xa1, 0x72, 0x1f, 0x91, 0xd5, 0xf1, 0x46, 0x81,
0xca, 0x02, 0xda, 0xee, 0x06, 0x39, 0x92, 0xfa, 0x9a, 0x7f, 0x75, 0x8c, 0xf9, 0xb3, 0x6c, 0xa7,
0xdd, 0x3d, 0x90, 0xee, 0x4e, 0x59, 0x4a, 0xa5, 0x84, 0x24, 0x8b, 0xc2, 0x44, 0x0f, 0x78, 0xc6,
0x93, 0x13, 0xe0, 0xfb, 0x35, 0xff, 0x1a, 0x96, 0x52, 0x16, 0xb1, 0xab, 0x41, 0x5b, 0xf2, 0x29,
0x4f, 0x4e, 0xdc, 0x8f, 0xc8, 0x75, 0x5b, 0x4c, 0x47, 0x64, 0x69, 0x80, 0xeb, 0x56, 0xd0, 0x4e,
0x42, 0x23, 0x95, 0x09, 0xc8, 0x02, 0x6a, 0xbe, 0x87, 0x45, 0x3c, 0x16, 0x59, 0xea, 0x6b, 0x80,
0x6f, 0xf5, 0xee, 0x5b, 0x64, 0xd9, 0xda, 0x0b, 0x1a, 0x51, 0x36, 0xa0, 0x31, 0xd6, 0xbd, 0x68,
0x23, 0xa3, 0x36, 0xf4, 0x8d, 0x0a, 0xaa, 0xfc, 0x98, 0xdc, 0x60, 0xb2, 0x44, 0x17, 0x03, 0x91,
0x66, 0x31, 0xeb, 0x30, 0x1a, 0x43, 0x9a, 0x50, 0xf3, 0xaf, 0x30, 0x69, 0xcd, 0xcc, 0x20, 0xec,
0x19, 0x80, 0xfb, 0x65, 0x72, 0xd9, 0x56, 0x0a, 0x1d, 0x4e, 0x4e, 0x02, 0x99, 0xf5, 0x45, 0x44,
0x63, 0xe0, 0xe7, 0x35, 0x7f, 0x09, 0xab, 0xdd, 0x45, 0x65, 0x0b, 0x75, 0xa7, 0xcc, 0x8a, 0xe5,
0x44, 0x81, 0xa2, 0x0f, 0x9b, 0xd9, 0xa5, 0x44, 0x4f, 0x0d, 0x91, 0x39, 0x15, 0x0a, 0xa2, 0x2c,
0x4d, 0x43, 0x1e, 0x03, 0x4f, 0x1f, 0x1a, 0xa2, 0x7d, 0x04, 0x6c, 0xa3, 0xde, 0x7d, 0x42, 0x6e,
0x0f, 0x0f, 0x31, 0x8d, 0x99, 0x54, 0x82, 0xb5, 0xf5, 0x48, 0xdb, 0x42, 0x3c, 0x28, 0xe4, 0x46,
0x65, 0x9c, 0x2b, 0x28, 0x5b, 0x12, 0xee, 0x5e, 0x28, 0x09, 0xd7, 0x27, 0x8d, 0x81, 0xb3, 0xc3,
0xee, 0xd5, 0x86, 0x4d, 0x23, 0x35, 0x7c, 0xc5, 0x4c, 0x4b, 0x26, 0x58, 0x97, 0xf1, 0x50, 0xa3,
0xaf, 0x0e, 0xcf, 0x4a, 0xa9, 0x71, 0xb7, 0xc9, 0xcd, 0x71, 0x16, 0x81, 0x54, 0x4c, 0x45, 0x3d,
0xc6, 0xbb, 0xde, 0xb5, 0xea, 0x6a, 0xaa, 0xda, 0xb6, 0x2c, 0xc4, 0xbd, 0x5b, 0x36, 0x50, 0x53,
0x03, 0x58, 0x08, 0xd7, 0xcb, 0xed, 0xac, 0x7a, 0xcf, 0x73, 0x0e, 0x6b, 0xe0, 0x11, 0xb9, 0x35,
0x34, 0x26, 0x51, 0xc6, 0x3b, 0x34, 0xa6, 0x02, 0xb7, 0x76, 0x4e, 0xa9, 0xf0, 0x6e, 0x54, 0xab,
0xd3, 0x23, 0xb2, 0x5d, 0xc5, 0x1c, 0x50, 0x2a, 0xdc, 0x8d, 0x72, 0x42, 0xe5, 0x09, 0x8f, 0x68,
0x1c, 0x1c, 0x31, 0x3d, 0x36, 0xdd, 0xdc, 0xbb, 0x59, 0xdd, 0x7f, 0x2d, 0x50, 0x7e, 0xce, 0x54,
0xaf, 0xd9, 0xcd, 0xcd, 0x06, 0x07, 0xab, 0xb4, 0x9f, 0x28, 0x06, 0xee, 0xed, 0x96, 0xdd, 0xe0,
0x1a, 0xbf, 0x67, 0xc5, 0xd5, 0xe5, 0xcd, 0xd2, 0x3c, 0x88, 0x42, 0x1e, 0x33, 0xe0, 0x47, 0xab,
0xd5, 0x81, 0x6c, 0xa6, 0xf9, 0xb6, 0xd5, 0x54, 0xbd, 0x3b, 0x92, 0xca, 0xdb, 0x55, 0xef, 0x8e,
0x74, 0x72, 0x93, 0x78, 0xe5, 0x4a, 0xd4, 0x3c, 0x0e, 0x76, 0x02, 0xc2, 0x1b, 0xc3, 0x4b, 0x91,
0x77, 0x77, 0xb5, 0x12, 0xed, 0x2a, 0x51, 0xa1, 0x1d, 0x46, 0x87, 0xfd, 0xdc, 0x7b, 0xb9, 0x1a,
0x15, 0x1e, 0x82, 0xcc, 0x7d, 0x5c, 0xba, 0x06, 0x44, 0x05, 0xb9, 0xc8, 0x14, 0x8d, 0x54, 0xa5,
0xbf, 0xaf, 0x80, 0xdd, 0xf5, 0xaa, 0xdd, 0x01, 0x82, 0xc6, 0x76, 0x1e, 0xe2, 0x00, 0x3d, 0xc6,
0xf8, 0xe0, 0xdd, 0xa9, 0x76, 0x5e, 0xbb, 0xe7, 0x1d, 0xa3, 0xa9, 0x6e, 0xb1, 0x30, 0x8e, 0x99,
0x9e, 0x29, 0x1b, 0x66, 0x5e, 0xad, 0xf6, 0x6b, 0xab, 0x50, 0x42, 0x28, 0x79, 0x0f, 0xbc, 0x3b,
0x7a, 0x02, 0x7a, 0xac, 0x7a, 0x59, 0x1e, 0xc4, 0x4c, 0x46, 0xa1, 0x88, 0x69, 0xec, 0xdd, 0x05,
0xc3, 0x15, 0xe3, 0x0b, 0x51, 0xfd, 0xc8, 0x6a, 0xdd, 0x3f, 0x77, 0x48, 0x4d, 0xdb, 0x04, 0xbd,
0x2c, 0xf7, 0xee, 0x9d, 0x2f, 0x6a, 0x30, 0xa9, 0x1b, 0xf6, 0x24, 0xcb, 0xdd, 0xbf, 0x74, 0xc8,
0x14, 0xef, 0xd9, 0x84, 0xe5, 0x3e, 0xb4, 0xf2, 0x77, 0xcf, 0xb8, 0x95, 0x45, 0x42, 0xe6, 0xd7,
0x78, 0xcf, 0x64, 0x4e, 0xaf, 0x90, 0x59, 0x9d, 0x58, 0x89, 0x68, 0x10, 0x9b, 0xdc, 0xe2, 0x35,
0x5c, 0x5f, 0xbd, 0x50, 0xfa, 0xd1, 0x20, 0xc6, 0xdc, 0x42, 0xd3, 0x9b, 0x12, 0xf1, 0x3a, 0x10,
0xcf, 0x29, 0x51, 0xa8, 0xdf, 0x24, 0x8b, 0xba, 0x10, 0x74, 0xb1, 0x9c, 0x2a, 0x83, 0x7b, 0x03,
0xe3, 0x6d, 0x2f, 0x94, 0xe0, 0x5f, 0xf7, 0xa9, 0x42, 0xf8, 0x2d, 0x32, 0x8d, 0x50, 0x84, 0xbd,
0x09, 0xc5, 0x11, 0x10, 0x15, 0xd5, 0xb1, 0x6e, 0x1e, 0xa4, 0x54, 0x09, 0x16, 0x79, 0x6b, 0x58,
0x1d, 0xeb, 0xe6, 0x7b, 0x20, 0xd0, 0xf6, 0xd0, 0xcd, 0x23, 0x4d, 0xc3, 0x94, 0xf7, 0x00, 0xed,
0xb5, 0xe8, 0x73, 0x90, 0xe8, 0xf0, 0x5f, 0xd0, 0x48, 0x08, 0x6f, 0x22, 0x60, 0xb1, 0xf7, 0x25,
0x3c, 0xde, 0xb2, 0x1a, 0x08, 0x6b, 0xa2, 0x19, 0xbb, 0xaf, 0x13, 0x57, 0xb7, 0x3e, 0x8d, 0x95,
0xe1, 0xd7, 0x7a, 0x36, 0xbd, 0xb7, 0xd0, 0x3d, 0xf4, 0x42, 0xb9, 0x17, 0x2b, 0x60, 0xd7, 0x9a,
0xed, 0xb9, 0x3f, 0x72, 0xc8, 0xec, 0x08, 0x72, 0xfd, 0x7c, 0x2d, 0xc1, 0x99, 0xb4, 0xda, 0xde,
0x1b, 0x84, 0x60, 0xe6, 0x26, 0xd9, 0xb7, 0xa8, 0xf7, 0x36, 0x0e, 0x25, 0x48, 0x5a, 0xec, 0x5b,
0x70, 0x55, 0xa2, 0xfb, 0xae, 0x13, 0xb9, 0x0d, 0xe8, 0xf0, 0x44, 0x2f, 0x94, 0x3b, 0x92, 0xb9,
0x7f, 0xeb, 0x90, 0xd9, 0xe1, 0x94, 0xcf, 0xfb, 0x32, 0xf4, 0xf3, 0xbb, 0xe7, 0xe2, 0x2c, 0xaf,
0xcc, 0x43, 0xcd, 0x8d, 0xc7, 0x8e, 0xfe, 0x4f, 0x32, 0xf7, 0x26, 0x99, 0xd6, 0x1d, 0xea, 0xe2,
0x49, 0x9f, 0xb7, 0x59, 0x9c, 0x14, 0x7c, 0x02, 0x27, 0x7d, 0xee, 0xf7, 0x1c, 0x32, 0x69, 0x95,
0xef, 0x40, 0x87, 0xbe, 0x73, 0xc6, 0x1d, 0x32, 0xe9, 0xb2, 0x3f, 0xd1, 0xc5, 0x16, 0x9a, 0x1e,
0xf0, 0x1e, 0x36, 0xf2, 0xdd, 0xa2, 0x07, 0xfb, 0xbd, 0xa2, 0x07, 0x56, 0xf9, 0xde, 0xf9, 0xea,
0x01, 0xc7, 0x16, 0xde, 0x23, 0x7a, 0xcf, 0x07, 0x92, 0x46, 0x19, 0xb7, 0x3e, 0xe3, 0x7d, 0x24,
0x2d, 0xbd, 0x50, 0xb6, 0x40, 0x8c, 0x1b, 0xfd, 0x36, 0x99, 0x19, 0x42, 0x7d, 0x00, 0xeb, 0x73,
0x5a, 0x56, 0x20, 0x1f, 0x90, 0xab, 0x38, 0xe5, 0x11, 0x13, 0x51, 0x9f, 0x29, 0xdd, 0x5e, 0xd5,
0x97, 0x3a, 0x8f, 0xea, 0x53, 0xef, 0x43, 0x38, 0x7d, 0xb8, 0x0c, 0x88, 0x6d, 0x04, 0xb4, 0x40,
0xff, 0x5c, 0xab, 0x75, 0xae, 0x81, 0x8c, 0x23, 0x09, 0xf3, 0x20, 0xca, 0xfa, 0x5c, 0x79, 0x5f,
0x81, 0x2a, 0xea, 0x5a, 0xfc, 0x38, 0x09, 0xf3, 0x6d, 0x2d, 0x74, 0xdf, 0x21, 0x1e, 0xd6, 0x29,
0x03, 0xc9, 0xf4, 0xa0, 0x74, 0x98, 0x90, 0x0a, 0xcc, 0xbc, 0x8f, 0xc0, 0x60, 0xd9, 0xe8, 0x5b,
0x5a, 0xfd, 0x58, 0x6b, 0xb5, 0x35, 0x9c, 0xf9, 0xb0, 0x94, 0x6a, 0x1e, 0xdf, 0xe7, 0x36, 0x3f,
0xf1, 0xbe, 0x8a, 0x47, 0x29, 0x5a, 0xf3, 0x2c, 0xfb, 0xac, 0x90, 0xbb, 0x77, 0xc8, 0x2c, 0x26,
0x23, 0x41, 0x4e, 0x79, 0x98, 0xa8, 0x13, 0xef, 0x63, 0x6c, 0x0d, 0x4a, 0x0f, 0x50, 0xe8, 0xbe,
0x4c, 0xea, 0xbd, 0x30, 0xe9, 0x24, 0xac, 0x43, 0x03, 0x5d, 0x86, 0xb7, 0x85, 0xc7, 0x3d, 0x56,
0xf8, 0x8c, 0xa5, 0xd4, 0xbd, 0x4f, 0xe6, 0x6d, 0xb9, 0x45, 0x69, 0x0f, 0x01, 0x37, 0x67, 0xe5,
0xb6, 0xbc, 0x5b, 0x64, 0x5a, 0xd0, 0xbe, 0xa4, 0x66, 0xcc, 0xb6, 0xd1, 0x5f, 0x82, 0x08, 0x87,
0x69, 0x9d, 0x2c, 0xa7, 0xe1, 0x31, 0x4b, 0xfb, 0x69, 0x91, 0x63, 0x61, 0xc5, 0x8f, 0x00, 0xba,
0x68, 0x94, 0x36, 0xc1, 0x82, 0xfa, 0x1f, 0x90, 0xa5, 0x22, 0x55, 0xd4, 0x9c, 0x36, 0xd7, 0x13,
0xd3, 0xa5, 0xde, 0x0e, 0xde, 0x8c, 0xb5, 0x4d, 0xce, 0xb8, 0x9d, 0xa5, 0x79, 0x4b, 0x2b, 0xdc,
0x7f, 0x70, 0xc8, 0xf2, 0x88, 0xc5, 0x11, 0xe3, 0x9c, 0x0a, 0xef, 0xf1, 0xf9, 0x72, 0xa0, 0x6e,
0xb5, 0xed, 0x9f, 0x43, 0x13, 0x35, 0x7d, 0x2b, 0xdb, 0xce, 0xe2, 0xa1, 0xe6, 0x7f, 0x02, 0x83,
0xb4, 0x64, 0xad, 0x9a, 0x71, 0xc5, 0xee, 0x06, 0x21, 0x76, 0x01, 0x76, 0xa5, 0xf7, 0x64, 0xd5,
0xb9, 0x77, 0xc9, 0x9f, 0x32, 0x6b, 0xaf, 0x2b, 0x35, 0x31, 0xad, 0x70, 0x7b, 0x83, 0x6a, 0xe2,
0x2c, 0xe6, 0x05, 0xbb, 0x47, 0xec, 0x2a, 0x99, 0xa9, 0x36, 0xc1, 0xfb, 0x1a, 0x4e, 0x63, 0x59,
0x2d, 0xdc, 0xd3, 0x40, 0x5c, 0xb5, 0x90, 0x4f, 0x71, 0x3b, 0x81, 0xd0, 0x60, 0x56, 0xc9, 0x0c,
0x44, 0x72, 0x0b, 0xd9, 0x35, 0x8b, 0x21, 0x1a, 0xc4, 0x06, 0xf1, 0x06, 0x71, 0x41, 0xa9, 0xc2,
0x76, 0x42, 0x83, 0x01, 0x15, 0x92, 0x65, 0xdc, 0xdb, 0xc3, 0x25, 0xad, 0x35, 0xcf, 0xb4, 0xe2,
0x39, 0xca, 0xdd, 0x9f, 0x39, 0xe4, 0x8a, 0xa9, 0x94, 0x52, 0x21, 0x87, 0x73, 0x5b, 0x6f, 0x7f,
0xf5, 0xe2, 0xbd, 0xe9, 0xf5, 0x3f, 0x38, 0xf3, 0x99, 0xad, 0x1c, 0x14, 0xfa, 0x2b, 0x38, 0x1c,
0xba, 0xb5, 0xd5, 0x1c, 0xdb, 0xfd, 0xa9, 0x43, 0x56, 0x72, 0x3a, 0xb6, 0x1b, 0x4f, 0xcf, 0x61,
0x37, 0x16, 0x73, 0x3a, 0xbe, 0x0f, 0xe5, 0x22, 0xc9, 0x84, 0x08, 0xda, 0x4c, 0x75, 0x18, 0x4d,
0x62, 0xef, 0xe0, 0x3c, 0xf6, 0xc1, 0x2e, 0xde, 0xa7, 0x42, 0x3c, 0x34, 0x0d, 0x75, 0xff, 0xd9,
0x21, 0xcb, 0x61, 0x1c, 0x8f, 0xe9, 0xc2, 0xaf, 0x9c, 0xc3, 0x2e, 0xb8, 0x61, 0x1c, 0x8f, 0xf6,
0xe0, 0x2e, 0x99, 0x2b, 0x0d, 0x55, 0x16, 0xe4, 0xd4, 0xf3, 0x31, 0xfc, 0x55, 0xc5, 0x07, 0x70,
0xab, 0x21, 0x58, 0x3b, 0xe8, 0x84, 0x2c, 0xa1, 0xb1, 0xd7, 0xc2, 0x48, 0x2f, 0x58, 0xfb, 0x31,
0x08, 0xdc, 0xf7, 0xc9, 0x55, 0xc9, 0x03, 0x91, 0x1f, 0xb2, 0x00, 0x53, 0xef, 0x20, 0x94, 0x78,
0x7e, 0xc8, 0xd4, 0x89, 0xf7, 0x0c, 0x76, 0xe4, 0x8a, 0xe4, 0x7e, 0x7e, 0xc8, 0x9e, 0x82, 0x7e,
0x4b, 0x3e, 0x37, 0x5a, 0xf7, 0x23, 0x72, 0x5d, 0xf6, 0xb2, 0xa3, 0x17, 0x5a, 0x7f, 0x86, 0x47,
0x18, 0x1a, 0x33, 0xd6, 0x7e, 0x83, 0xac, 0x30, 0xdd, 0x5b, 0xc9, 0xba, 0x3c, 0x4c, 0x68, 0x5c,
0x5a, 0x3e, 0x37, 0x59, 0x5d, 0xbb, 0x9b, 0xb7, 0x8c, 0xb2, 0xb0, 0xfa, 0x1a, 0x69, 0x8c, 0xab,
0x10, 0x73, 0xfc, 0x98, 0x49, 0xbc, 0xe5, 0xf8, 0x1c, 0x4a, 0xb8, 0x29, 0x46, 0xeb, 0x05, 0xd8,
0x23, 0x83, 0xd2, 0xb1, 0x3b, 0x8c, 0x22, 0x9a, 0xab, 0x20, 0x3b, 0xe2, 0x98, 0x50, 0x7e, 0x1d,
0x0f, 0x16, 0x50, 0xfc, 0xf4, 0x88, 0x43, 0x26, 0xb9, 0x43, 0x56, 0x2b, 0x38, 0x49, 0x93, 0x4e,
0x50, 0x39, 0xcc, 0xc8, 0x03, 0x6d, 0xf8, 0x0d, 0x3c, 0x59, 0x28, 0x0c, 0x5b, 0x34, 0xe9, 0x3c,
0x2d, 0x40, 0x07, 0x5b, 0xaa, 0xa7, 0x83, 0x64, 0x58, 0x49, 0x3a, 0x7e, 0x15, 0x5c, 0x35, 0x09,
0xcb, 0xac, 0xa3, 0x41, 0xea, 0x70, 0xb5, 0x2e, 0x3b, 0x98, 0xb7, 0x7a, 0xbf, 0x86, 0x59, 0xbe,
0x16, 0xb6, 0x3a, 0x90, 0xaa, 0x6a, 0xdf, 0xd9, 0x81, 0x7b, 0x59, 0xc6, 0xa1, 0xe3, 0x08, 0xfc,
0x75, 0xcc, 0x83, 0x40, 0xd3, 0x44, 0x05, 0xa0, 0xef, 0x93, 0x05, 0x48, 0x3c, 0x74, 0xa9, 0xbc,
0x8d, 0x27, 0xde, 0xde, 0x6f, 0x14, 0x44, 0x69, 0x6f, 0x90, 0xf3, 0xfd, 0x36, 0x1c, 0x32, 0xbb,
0x3f, 0x70, 0x4c, 0xed, 0x05, 0xee, 0x37, 0xcf, 0x57, 0xd0, 0x84, 0x61, 0xb0, 0xad, 0x7d, 0x8b,
0x2c, 0x97, 0x1d, 0x33, 0xd9, 0x3d, 0x34, 0x3a, 0xc0, 0x63, 0x04, 0xdb, 0x39, 0x54, 0x81, 0xc9,
0xdf, 0x38, 0x64, 0xe1, 0x34, 0xfe, 0x9b, 0xe7, 0xab, 0x93, 0x73, 0xe9, 0x48, 0xab, 0x1b, 0x9a,
0xa9, 0x99, 0x8e, 0xe6, 0xa9, 0x64, 0x5e, 0x88, 0x6b, 0xc2, 0x74, 0xf0, 0x20, 0x95, 0x4c, 0x67,
0xd8, 0x85, 0x1e, 0xaf, 0x07, 0xda, 0x48, 0xe7, 0x52, 0x83, 0x80, 0x1b, 0x82, 0x57, 0xc9, 0x5c,
0x89, 0x42, 0x1e, 0x10, 0x21, 0x37, 0xb4, 0x30, 0x64, 0x01, 0x43, 0x38, 0x24, 0xcd, 0xf1, 0x30,
0x0e, 0x69, 0xf3, 0x10, 0x0e, 0x79, 0x1f, 0x05, 0xae, 0x5c, 0xe0, 0x90, 0xfa, 0x19, 0xae, 0x0e,
0x58, 0x7a, 0xac, 0xa2, 0x2c, 0x4d, 0xbd, 0xce, 0xd0, 0x12, 0xdc, 0x41, 0xa9, 0xfb, 0x26, 0x71,
0xe9, 0xb1, 0xa2, 0x3c, 0xa6, 0x40, 0x7f, 0xd2, 0x3e, 0xd7, 0xde, 0xa0, 0x0b, 0x85, 0x2e, 0x58,
0xcd, 0xb6, 0x55, 0x94, 0x0d, 0x28, 0xe9, 0x4f, 0xaf, 0xd2, 0xd0, 0x82, 0x02, 0x5d, 0x21, 0x35,
0x73, 0x6e, 0xd0, 0xf3, 0x18, 0x54, 0x3c, 0x09, 0xdf, 0xfb, 0x3d, 0x4d, 0x31, 0x85, 0x0a, 0x24,
0x55, 0x41, 0xc2, 0x52, 0xa6, 0x8a, 0x5b, 0xd2, 0xdf, 0xc2, 0xbb, 0x0e, 0xa1, 0x5a, 0x54, 0xed,
0x6a, 0x4d, 0x79, 0x4f, 0x3a, 0x8b, 0xc7, 0x99, 0x68, 0xc5, 0x62, 0xef, 0x10, 0x19, 0x90, 0x96,
0xfa, 0x1a, 0xde, 0x8c, 0xdd, 0x0d, 0x72, 0xb9, 0x0a, 0xc2, 0xe3, 0x6f, 0xcc, 0x0d, 0x12, 0xa4,
0xbb, 0x05, 0x1a, 0x8e, 0x08, 0x30, 0x43, 0xf8, 0x90, 0x5c, 0x2b, 0x8e, 0xb9, 0x3a, 0x01, 0x2c,
0xae, 0x24, 0x09, 0x68, 0xc2, 0xba, 0xac, 0x9d, 0x50, 0x2f, 0xb5, 0xf7, 0x11, 0x70, 0xd4, 0xd5,
0x69, 0xa2, 0x7e, 0xc7, 0xa8, 0xed, 0x01, 0x24, 0x15, 0x69, 0xc8, 0x29, 0x37, 0xf7, 0x2b, 0xbc,
0x38, 0x80, 0xb4, 0x72, 0xf0, 0x0a, 0xaf, 0x93, 0x85, 0xae, 0x08, 0x23, 0xda, 0xe9, 0x27, 0x81,
0xec, 0xf5, 0x55, 0x9c, 0x1d, 0x71, 0x2f, 0x43, 0x17, 0x62, 0x15, 0x2d, 0x23, 0x77, 0xdf, 0x23,
0x57, 0x60, 0x11, 0xd0, 0x38, 0xe8, 0x73, 0x06, 0x6f, 0xa8, 0x64, 0xd8, 0x61, 0x58, 0x41, 0x8e,
0xc7, 0x68, 0x06, 0xf0, 0x19, 0xea, 0x5b, 0x61, 0x87, 0x41, 0x3d, 0xaf, 0x90, 0xd9, 0x91, 0xf9,
0xf9, 0x02, 0xd7, 0xe5, 0xd0, 0xf4, 0x3c, 0x20, 0x4b, 0x7a, 0x7d, 0x9c, 0xda, 0x99, 0x02, 0xe7,
0xa0, 0x17, 0xca, 0xe7, 0xc3, 0x5b, 0xe2, 0xc7, 0x0e, 0x99, 0x3f, 0x85, 0x96, 0xe7, 0x6b, 0x1f,
0xcf, 0x8e, 0x6c, 0xe3, 0x75, 0xb8, 0xd4, 0xd1, 0x51, 0x23, 0x90, 0x22, 0x0a, 0x44, 0x1c, 0xe8,
0x3c, 0x87, 0x72, 0xe5, 0x29, 0x7b, 0xee, 0xa9, 0xa3, 0x45, 0x4b, 0x44, 0x7e, 0x7c, 0x80, 0x9a,
0xea, 0x23, 0xd3, 0xfe, 0xd0, 0x23, 0xd3, 0x07, 0x64, 0x11, 0xd7, 0x54, 0xcc, 0xa4, 0x62, 0xbc,
0xdb, 0x67, 0xb2, 0x47, 0x85, 0x37, 0x00, 0x90, 0x0b, 0xaa, 0x47, 0x55, 0x4d, 0xe3, 0x53, 0xbc,
0x60, 0xcf, 0xe1, 0xf8, 0x3f, 0x69, 0x27, 0x01, 0xe5, 0x4a, 0x9c, 0x04, 0x90, 0x3b, 0xd0, 0xca,
0x2b, 0x4a, 0xb8, 0x53, 0xcc, 0xa9, 0xbd, 0x29, 0x5f, 0x22, 0x2f, 0xe1, 0xfe, 0xc7, 0x37, 0x18,
0xf8, 0xd1, 0xf8, 0x26, 0xde, 0x8d, 0xdb, 0xe7, 0x02, 0x92, 0xc5, 0x81, 0x72, 0x5d, 0x72, 0xa9,
0xf2, 0xf0, 0x02, 0xfe, 0x1e, 0x6f, 0xfe, 0xf3, 0x5c, 0xbf, 0x9f, 0x90, 0x49, 0x29, 0xa0, 0xe0,
0x5f, 0xb8, 0xdc, 0x8d, 0x31, 0xe5, 0xbe, 0xf0, 0xe6, 0xff, 0xd2, 0xe9, 0xaa, 0xff, 0xcd, 0x21,
0xd3, 0x52, 0x04, 0xf4, 0x38, 0xc7, 0xab, 0xed, 0x15, 0x32, 0x61, 0xce, 0x00, 0x1d, 0xa8, 0xcc,
0x7c, 0xb9, 0x7f, 0xea, 0x90, 0x49, 0x49, 0xbb, 0xa9, 0x9e, 0xc1, 0x0b, 0x40, 0x1a, 0xbf, 0x7d,
0x86, 0x4b, 0xcf, 0x8c, 0x96, 0x6f, 0x9b, 0xd4, 0xf8, 0xc7, 0x97, 0xc8, 0x22, 0x70, 0x2b, 0xfb,
0x4e, 0xc8, 0x4c, 0x78, 0xf9, 0x24, 0x84, 0xf2, 0x28, 0xcc, 0xcb, 0xc7, 0x32, 0x75, 0xfb, 0x24,
0x64, 0x47, 0xcb, 0x21, 0x5e, 0xfc, 0xc8, 0x21, 0xd3, 0x95, 0x49, 0x36, 0x57, 0xe4, 0x67, 0xcd,
0x8d, 0x87, 0x96, 0x9d, 0x4f, 0xcc, 0x67, 0x8b, 0xc5, 0xee, 0xbf, 0x68, 0x56, 0x9f, 0x68, 0xcf,
0xae, 0x59, 0x59, 0xb5, 0xe5, 0x17, 0xcf, 0x61, 0xcb, 0x17, 0x8b, 0xa6, 0x3e, 0x2c, 0xbb, 0x70,
0x93, 0x90, 0x5c, 0xd0, 0x0e, 0x15, 0x94, 0x47, 0x14, 0x96, 0x67, 0xdd, 0xaf, 0x48, 0xf4, 0xca,
0x97, 0x2a, 0x54, 0xf6, 0x4d, 0x11, 0x7e, 0xb8, 0x2f, 0x93, 0xba, 0xa0, 0x5f, 0xf4, 0x75, 0x52,
0x86, 0x5a, 0x7c, 0x0e, 0x3c, 0x63, 0x84, 0x2d, 0x00, 0x7d, 0xdf, 0x21, 0x33, 0x66, 0x75, 0x04,
0x09, 0x93, 0xca, 0x9b, 0x84, 0x55, 0xfb, 0x9d, 0xb3, 0x5d, 0xb5, 0x76, 0x9f, 0xf9, 0xd3, 0xa6,
0x6d, 0xbb, 0x4c, 0xaa, 0xc6, 0xbf, 0x3a, 0xb8, 0x7a, 0x55, 0x9f, 0xe3, 0x32, 0x35, 0xab, 0xf7,
0x07, 0x0e, 0x99, 0x2a, 0x9e, 0xe5, 0x99, 0x67, 0x26, 0x7f, 0x78, 0xc6, 0xb3, 0x3a, 0xb2, 0xc3,
0xfc, 0x9a, 0x7d, 0x85, 0xd7, 0xf8, 0xa7, 0x79, 0xb2, 0xa2, 0x11, 0x9a, 0xc9, 0x64, 0x3c, 0x08,
0x95, 0x12, 0x95, 0x6d, 0xc8, 0xa4, 0xc9, 0x03, 0x8a, 0x40, 0xe0, 0xd8, 0x60, 0x8d, 0xd9, 0x80,
0x8d, 0x02, 0x78, 0x61, 0x66, 0x0e, 0x40, 0x04, 0xed, 0x14, 0xf8, 0x0b, 0x36, 0x70, 0xc0, 0xd5,
0xc7, 0x81, 0xa0, 0x1d, 0x6b, 0xf2, 0x15, 0x60, 0x12, 0xa1, 0xca, 0x52, 0x16, 0x95, 0xf7, 0xd1,
0x85, 0xe1, 0x45, 0x7b, 0xb7, 0xbc, 0x05, 0x88, 0xe2, 0x52, 0xda, 0x9a, 0xaf, 0x43, 0x8d, 0xd6,
0x2e, 0x13, 0x85, 0xe1, 0x25, 0x7b, 0xff, 0xb9, 0x55, 0xe8, 0xac, 0x0d, 0xf6, 0xc8, 0x24, 0x65,
0x16, 0xff, 0x92, 0xed, 0x11, 0x26, 0x42, 0x16, 0xfb, 0x3a, 0x3c, 0x9d, 0x08, 0x0d, 0xd7, 0xb1,
0xe0, 0x09, 0x0b, 0xde, 0x02, 0x86, 0x63, 0xc1, 0x78, 0xe9, 0x5c, 0xb0, 0xc1, 0x02, 0x3e, 0x69,
0x7b, 0x5f, 0xf0, 0x41, 0x6b, 0xb1, 0x05, 0x4f, 0x01, 0x4e, 0x13, 0xc9, 0xc2, 0xb4, 0x66, 0xdf,
0x41, 0xec, 0x8c, 0x52, 0x4a, 0x5b, 0x04, 0x5e, 0x89, 0x4a, 0x19, 0x16, 0x36, 0x53, 0xc5, 0x33,
0x13, 0x19, 0x8e, 0x36, 0x8d, 0x73, 0x78, 0xb6, 0x50, 0x60, 0x49, 0xd9, 0x34, 0xa3, 0xb2, 0x16,
0xe6, 0x61, 0x8a, 0x26, 0xcc, 0x16, 0x5c, 0x3e, 0x4c, 0x49, 0x25, 0xb3, 0x38, 0x73, 0x27, 0x9f,
0xe7, 0x69, 0x5e, 0x00, 0x67, 0x8a, 0x3b, 0x79, 0x2d, 0x1e, 0x2e, 0x11, 0xd2, 0x4a, 0x0b, 0xac,
0xdb, 0x12, 0xb7, 0x58, 0xb7, 0xc0, 0x99, 0xf7, 0x02, 0x23, 0x94, 0xc1, 0xbc, 0xb6, 0xb7, 0x96,
0xb3, 0xc5, 0x7b, 0x81, 0x61, 0xfe, 0x00, 0x7c, 0xdf, 0x96, 0x84, 0xb7, 0xb1, 0x89, 0x84, 0x05,
0x8d, 0xef, 0x0d, 0xac, 0xfd, 0x9c, 0xbd, 0x8d, 0xdd, 0x95, 0x5b, 0x56, 0x69, 0xcd, 0xf0, 0x55,
0x0b, 0xd6, 0xc7, 0x78, 0x4c, 0x8f, 0x0b, 0xab, 0x79, 0xbb, 0xaa, 0xa0, 0x9a, 0xa6, 0xd6, 0x59,
0xa3, 0x5b, 0x64, 0xba, 0x7c, 0xac, 0x85, 0x4f, 0xcd, 0xeb, 0x3e, 0x29, 0xde, 0x46, 0x49, 0xed,
0xfa, 0x2a, 0xeb, 0x34, 0xc4, 0x07, 0xe6, 0x75, 0x7f, 0xa6, 0x14, 0x6e, 0x49, 0x9d, 0x56, 0x54,
0x41, 0x43, 0x2f, 0xcc, 0x17, 0x2a, 0x48, 0xc3, 0x12, 0x56, 0xc8, 0x84, 0xc9, 0xd0, 0x97, 0x30,
0xe4, 0xe3, 0x97, 0x7b, 0x9f, 0xcc, 0x97, 0xbb, 0xd0, 0xb8, 0xe8, 0x65, 0x0c, 0x9d, 0x89, 0xdd,
0x81, 0xc6, 0x4f, 0xaf, 0x90, 0x09, 0xdc, 0x0a, 0xf0, 0x06, 0xa4, 0xee, 0x9b, 0x2f, 0x60, 0x74,
0x26, 0xb5, 0xbf, 0x6c, 0x18, 0x9d, 0x34, 0xcf, 0x9e, 0xa6, 0xca, 0x84, 0xc7, 0x83, 0x84, 0xa7,
0x14, 0xb8, 0xef, 0x12, 0x6f, 0xcc, 0x72, 0x46, 0x46, 0x7d, 0x05, 0xcf, 0x68, 0x4e, 0x65, 0x47,
0xc8, 0xad, 0xc7, 0x67, 0x54, 0x57, 0x5f, 0x94, 0x51, 0xbd, 0x4e, 0x16, 0xfa, 0xfc, 0x90, 0x67,
0x47, 0xbc, 0x9c, 0x5d, 0xef, 0x1a, 0xa0, 0xe7, 0x8d, 0xa2, 0x98, 0x58, 0xd7, 0x23, 0x93, 0x51,
0xd2, 0x97, 0x8a, 0x0a, 0xef, 0x3a, 0x40, 0xec, 0xa7, 0x0e, 0x63, 0xf6, 0x7c, 0x24, 0xc3, 0x37,
0x17, 0x53, 0x7e, 0x45, 0xa2, 0x9d, 0x45, 0xb2, 0xae, 0xf2, 0xc1, 0xdb, 0x81, 0xa4, 0x52, 0xb2,
0x8c, 0xeb, 0x3c, 0xea, 0xa6, 0x19, 0x4a, 0x50, 0xb4, 0x50, 0xde, 0x8c, 0xf1, 0x47, 0x48, 0x80,
0x8d, 0xb2, 0xec, 0x90, 0x51, 0xef, 0x96, 0xfd, 0x11, 0x92, 0x16, 0x6e, 0x83, 0xcc, 0xbd, 0x43,
0x66, 0xcb, 0x6d, 0x08, 0x9c, 0x66, 0x15, 0x13, 0xc1, 0x42, 0x0a, 0x8c, 0xe6, 0x2e, 0x99, 0x2b,
0x61, 0x98, 0xb1, 0xde, 0x86, 0xd2, 0x4a, 0x6b, 0x4c, 0x59, 0x5f, 0x23, 0x0b, 0x95, 0x93, 0x1a,
0x03, 0x6d, 0xc0, 0x79, 0xcd, 0x5c, 0x79, 0x5e, 0x83, 0xd8, 0x6b, 0x64, 0xaa, 0xcc, 0xbb, 0x5f,
0x86, 0x6a, 0x6b, 0xb9, 0xcd, 0xb9, 0x35, 0xc1, 0x2e, 0xd3, 0xed, 0x57, 0xf0, 0x6e, 0x34, 0x2f,
0x52, 0x6d, 0xab, 0x46, 0x3a, 0x7b, 0xa7, 0x54, 0x17, 0x97, 0xd4, 0x95, 0xe4, 0xfa, 0x55, 0x5c,
0x16, 0x79, 0x91, 0x58, 0x6b, 0x75, 0x9e, 0x06, 0x39, 0xaa, 0xef, 0x1a, 0xeb, 0x3c, 0x3d, 0x00,
0x81, 0xfb, 0xef, 0x78, 0xda, 0x3c, 0x66, 0xc3, 0x7b, 0xf7, 0x20, 0xf6, 0x9f, 0xf5, 0x3d, 0xeb,
0x68, 0x3a, 0xe2, 0x2f, 0xe5, 0x63, 0xfc, 0x8e, 0xde, 0x34, 0xc6, 0xdb, 0x78, 0xf7, 0x61, 0x08,
0x26, 0x12, 0x70, 0x2f, 0xda, 0x4b, 0x56, 0xfd, 0x09, 0x20, 0x5e, 0xc3, 0xf9, 0x4c, 0x0a, 0x57,
0x02, 0xc8, 0x1f, 0x3b, 0x64, 0xa6, 0xca, 0x7b, 0xe1, 0x7d, 0xc1, 0xd9, 0x73, 0x87, 0x11, 0x7e,
0xe3, 0x4f, 0x57, 0x28, 0x78, 0xe3, 0xbb, 0x86, 0x04, 0x01, 0x6f, 0x10, 0xe6, 0x3a, 0xf6, 0xff,
0xef, 0xcd, 0xb3, 0xf6, 0xb5, 0x69, 0x18, 0x8d, 0xe4, 0x46, 0x24, 0x0d, 0xed, 0x4f, 0x3c, 0x1a,
0xff, 0x5d, 0xc7, 0x37, 0xbf, 0xd0, 0x20, 0xf3, 0x2a, 0xcb, 0x78, 0xb3, 0xf5, 0xa0, 0x7d, 0xa2,
0xa8, 0x61, 0x30, 0x75, 0x1b, 0xc2, 0xd7, 0x1f, 0x9e, 0x28, 0x6a, 0xde, 0x80, 0x85, 0x79, 0x9e,
0xb0, 0x08, 0x4f, 0x69, 0x35, 0xd7, 0x38, 0x0a, 0x4f, 0x46, 0x88, 0xcc, 0x35, 0x26, 0xb7, 0x4a,
0xd0, 0x27, 0x88, 0xb1, 0x81, 0xe0, 0x4d, 0xb2, 0xc8, 0x70, 0x0d, 0xc0, 0x89, 0xca, 0x30, 0x93,
0x99, 0x67, 0xb0, 0x1e, 0x5a, 0x54, 0x59, 0xf8, 0x03, 0xb2, 0xa4, 0x61, 0xb0, 0x87, 0x19, 0x6f,
0x67, 0x7d, 0x1e, 0xc3, 0x03, 0x2e, 0x24, 0x30, 0x0b, 0x92, 0x2a, 0x1d, 0x1b, 0x9b, 0xa8, 0x69,
0x76, 0x73, 0x1d, 0xd4, 0x4e, 0x19, 0x98, 0x20, 0x80, 0x24, 0x66, 0x69, 0xd8, 0xc6, 0x1c, 0xd8,
0x22, 0x4f, 0xd0, 0x93, 0x33, 0xcc, 0x62, 0x66, 0x98, 0xf4, 0x79, 0x6f, 0x98, 0x1b, 0x09, 0xd6,
0xae, 0x02, 0x27, 0x2d, 0xdd, 0xf1, 0x41, 0x5e, 0xe1, 0x14, 0x65, 0x5c, 0x3d, 0xa4, 0x27, 0xf6,
0x25, 0x76, 0x0d, 0x76, 0xb7, 0x5b, 0xe8, 0x3e, 0xa5, 0x27, 0xf8, 0x14, 0xdb, 0x7d, 0x8f, 0x5c,
0x29, 0x2d, 0xf0, 0x12, 0x16, 0x6e, 0x0f, 0x79, 0x87, 0x75, 0x0d, 0x6d, 0x59, 0x29, 0x00, 0xbe,
0xd6, 0x37, 0xe3, 0x6d, 0xd0, 0xba, 0xef, 0x8e, 0x35, 0x4d, 0xc3, 0x63, 0xed, 0x8f, 0xf1, 0x61,
0xff, 0xf2, 0xa8, 0xe9, 0x5e, 0x78, 0xdc, 0x84, 0x57, 0x8f, 0x63, 0x2c, 0x79, 0x16, 0xdb, 0x47,
0xfe, 0x4b, 0xa3, 0x76, 0xfb, 0x59, 0x4c, 0xdd, 0x0f, 0xc8, 0xd5, 0x71, 0x6d, 0xed, 0x0b, 0x61,
0x19, 0x4e, 0xdd, 0xbf, 0x7c, 0xaa, 0xb1, 0xa8, 0x7e, 0x41, 0x9d, 0x87, 0xf4, 0x04, 0x7f, 0xcc,
0x37, 0xa6, 0xce, 0x4f, 0xe9, 0x89, 0x74, 0x1f, 0x92, 0x9b, 0x63, 0xcc, 0x04, 0x8d, 0xb2, 0x01,
0xd5, 0xab, 0x29, 0x02, 0xda, 0x53, 0xf7, 0xaf, 0x8e, 0x5a, 0xfb, 0x08, 0x69, 0xd1, 0x48, 0xc7,
0xc5, 0x41, 0xce, 0x47, 0x8e, 0x5b, 0xe6, 0xf0, 0xbe, 0x72, 0x90, 0xf3, 0x21, 0xa7, 0xe5, 0xfe,
0xc4, 0x21, 0x0b, 0x15, 0xce, 0x0f, 0x45, 0xe2, 0xe3, 0xdb, 0xe9, 0xf5, 0x3f, 0x3e, 0x63, 0x8f,
0x73, 0x3a, 0x17, 0xf1, 0xe7, 0x51, 0x56, 0xc4, 0x75, 0xe9, 0xfe, 0xd0, 0x21, 0x35, 0xbb, 0xd5,
0x80, 0x73, 0x9d, 0xcb, 0x76, 0x4f, 0x86, 0xb8, 0xe7, 0xdd, 0x2b, 0xa4, 0xa6, 0x37, 0x16, 0xc4,
0x5f, 0xa4, 0x7f, 0x93, 0x82, 0xf7, 0x20, 0xfc, 0x5e, 0x26, 0xfa, 0xcf, 0x40, 0xfb, 0xcb, 0x45,
0x24, 0x62, 0x82, 0xf7, 0x76, 0x29, 0x87, 0x3b, 0x6a, 0xeb, 0x52, 0xb5, 0x76, 0xc9, 0xdc, 0x51,
0xe3, 0xf3, 0x12, 0x8d, 0xf8, 0xbe, 0x83, 0xc5, 0xc2, 0xe1, 0xe2, 0xf2, 0xb9, 0x08, 0x17, 0x23,
0x91, 0x00, 0xba, 0x09, 0x87, 0x8b, 0xb7, 0xc9, 0x8c, 0xf1, 0x2e, 0x70, 0xa3, 0x6e, 0x48, 0xe7,
0x34, 0xca, 0xe0, 0x2e, 0xdd, 0xdc, 0x03, 0x6a, 0x48, 0x1a, 0x46, 0x86, 0x7c, 0x4e, 0xa1, 0x64,
0x2f, 0x8c, 0xdc, 0xbf, 0x70, 0x88, 0xf9, 0x0a, 0x58, 0x0e, 0xef, 0x86, 0xcf, 0xd1, 0x59, 0x6a,
0x0d, 0x5b, 0xd6, 0xcc, 0x35, 0xcf, 0xc3, 0xbf, 0x59, 0x6e, 0xba, 0x8a, 0xf4, 0xb7, 0x6e, 0xa5,
0xa3, 0x9d, 0x1d, 0x70, 0x06, 0xcf, 0x93, 0xeb, 0xb6, 0xb3, 0xcf, 0x39, 0xab, 0x0c, 0x17, 0x92,
0x81, 0x6b, 0xd5, 0xe1, 0xc2, 0xe0, 0xfb, 0xed, 0x1a, 0xfe, 0x6a, 0xdc, 0xfe, 0xd3, 0x00, 0x7a,
0x25, 0xf1, 0x0c, 0x99, 0xfb, 0x3a, 0xbe, 0x62, 0xe3, 0x19, 0x30, 0xf7, 0xca, 0x21, 0xed, 0xdb,
0x43, 0x87, 0xb4, 0x2f, 0xfa, 0xa5, 0xc9, 0xc6, 0x2f, 0xc3, 0x8f, 0x81, 0x72, 0x91, 0x45, 0xba,
0xbd, 0x45, 0x8d, 0x2c, 0x86, 0xc7, 0x79, 0x75, 0x7f, 0xc1, 0xa8, 0x9a, 0x46, 0xd3, 0x8c, 0x35,
0x03, 0x46, 0x1e, 0x96, 0x65, 0xf6, 0x39, 0x5c, 0x0d, 0x04, 0x4f, 0x33, 0xa1, 0x93, 0x7d, 0xa3,
0x0c, 0x34, 0xe9, 0x36, 0x6f, 0x3d, 0xde, 0x31, 0x64, 0x1f, 0x50, 0x4f, 0x85, 0x7d, 0xea, 0x71,
0x83, 0x10, 0x04, 0x77, 0x42, 0x96, 0xd8, 0x77, 0x69, 0x20, 0x79, 0x1c, 0xb2, 0xc4, 0xfd, 0x6b,
0x87, 0xcc, 0xe3, 0xab, 0x12, 0xde, 0xc9, 0x44, 0x0a, 0x44, 0xc1, 0x3c, 0x50, 0xfb, 0xed, 0xb3,
0xe6, 0xb2, 0x70, 0x8a, 0x85, 0x2f, 0x6a, 0xca, 0xc6, 0xb9, 0x3f, 0x75, 0x2a, 0x11, 0x4f, 0x06,
0x61, 0x47, 0xd1, 0xe2, 0x67, 0xa5, 0x8c, 0xc3, 0x93, 0xb5, 0xb3, 0x6f, 0x3b, 0xf8, 0x95, 0x4a,
0xdc, 0x95, 0x5b, 0xba, 0x99, 0x78, 0x8a, 0xd5, 0xe4, 0x2f, 0xba, 0x6d, 0xf8, 0xe0, 0x45, 0xb7,
0x0d, 0xee, 0x87, 0xe4, 0x2a, 0xfe, 0x72, 0x22, 0x18, 0x67, 0xf7, 0x21, 0xd8, 0x79, 0x88, 0xf0,
0x4f, 0x5b, 0xdf, 0x21, 0xb3, 0xe6, 0x07, 0xa0, 0x76, 0xb1, 0xd8, 0xf7, 0x74, 0x20, 0xb5, 0x4b,
0xe5, 0x0a, 0xa9, 0x0d, 0x84, 0xd9, 0x78, 0x1f, 0xe1, 0xbf, 0xac, 0x31, 0x10, 0xb8, 0xf3, 0x5e,
0x25, 0x73, 0xa6, 0xfe, 0x02, 0xf1, 0x55, 0x40, 0xd4, 0x51, 0xfc, 0xdc, 0xe0, 0x6e, 0x10, 0x22,
0x45, 0x64, 0x77, 0xef, 0xc7, 0xe8, 0x13, 0x41, 0xa2, 0xd5, 0xed, 0x09, 0xf8, 0xf7, 0x49, 0xde,
0xfe, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb7, 0x69, 0x72, 0x8d, 0xb5, 0x44, 0x00, 0x00,
}
|
gridgentoo/ServiceFabricAzure
|
src/prod/src/Hosting2/Deactivator.cpp
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
using namespace Hosting2;
using namespace Management;
StringLiteral const TraceType("Deactivator");
// ********************************************************************************************************************
// Deactivator::ServicePackageInstanceReplicaCountEntry Implementation
//
class Deactivator::ServicePackageInstanceReplicaCountEntry :
private TextTraceComponent<TraceTaskCodes::Hosting>
{
public:
ServicePackageInstanceReplicaCountEntry(
ServicePackageInstanceIdentifier const & servicePackageInstanceId, wstring const & traceId)
: id_(servicePackageInstanceId),
servicePackageUsageCount_(0),
closing_(false),
servicePackageSequenceNumber_(0),
continuousDeactivationFailureCount_(0),
servicePackageInstanceUnusedSince_(DateTime::Now()),
traceId_(traceId),
entryLock_()
{
}
public:
ErrorCode IncrementUsageCount(Deactivator & deactivator)
{
bool shouldCancelDeactivation = false;
uint64 sequenceNumber = 0;
{
AcquireWriteLock writeLock(entryLock_);
if(closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
sequenceNumber = ++this->servicePackageSequenceNumber_;
if(++this->servicePackageUsageCount_ == 1)
{
shouldCancelDeactivation = true;
continuousDeactivationFailureCount_ = 0;
this->servicePackageInstanceUnusedSince_ = DateTime::MaxValue;
}
WriteInfo(
TraceType,
traceId_,
"IncrementUsageCount: {0}. ShouldCancelDeactivation={1}",
this->ToString(),
shouldCancelDeactivation);
}
if(shouldCancelDeactivation)
{
deactivator.CancelServicePackageInstanceDeactivation(this->id_, sequenceNumber);
}
return ErrorCode(ErrorCodeValue::Success);
}
void DecrementUsageCount(Deactivator & deactivator)
{
bool shouldScheduleDeactivation = false;
uint64 sequenceNumber = 0;
{
AcquireWriteLock writeLock(entryLock_);
ASSERT_IF(closing_, "Decrement call cannot be called in closing state. The usage count is already 0. {0}", this->ToString());
ASSERT_IF(
this->servicePackageUsageCount_ - 1 < 0,
"DecrementUsageCount: UsageCount cannot be negative. ServicePackage={0}", id_);
sequenceNumber = ++this->servicePackageSequenceNumber_;
if(--this->servicePackageUsageCount_ == 0)
{
shouldScheduleDeactivation = true;
this->servicePackageInstanceUnusedSince_ = DateTime::Now();
}
WriteInfo(
TraceType,
traceId_,
"DecrementUsageCount: {0}. ShouldScheduleDeactivation={1}",
this->ToString(),
shouldScheduleDeactivation);
}
if(shouldScheduleDeactivation)
{
this->ScheduleServicePackageInstanceDeactivation(deactivator, sequenceNumber);
}
}
LONG GetUsageCount()
{
{
AcquireReadLock readLock(entryLock_);
return this->servicePackageUsageCount_;
}
}
ErrorCode ScheduleDeactivationIfNotUsed(Deactivator & deactivator, bool & isDeactivationScheduled)
{
uint64 sequenceNumber = 0;
{
AcquireReadLock readLock(entryLock_);
if(closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
if(this->servicePackageUsageCount_ == 0 &&
this->GetDeactivationGraceInterval() != TimeSpan::MaxValue)
{
sequenceNumber = this->servicePackageSequenceNumber_;
isDeactivationScheduled = true;
}
else
{
isDeactivationScheduled = false;
}
WriteInfo(
TraceType,
traceId_,
"ScheduleDeactivationIfNotUsed: {0}, IsDeactivationScheduled={1}",
this->ToString(),
isDeactivationScheduled);
}
if(isDeactivationScheduled)
{
this->ScheduleServicePackageInstanceDeactivation(deactivator, sequenceNumber);
}
return ErrorCode(ErrorCodeValue::Success);
}
bool OnDeactivateIfNotUsed(uint64 const sequenceNumber)
{
AcquireWriteLock writeLock(entryLock_);
if(closing_) { return false; }
WriteInfo(
TraceType,
traceId_,
"OnDeactivateIfNotUsed: {0}, IncomingSequenceNumber={1}",
this->ToString(),
sequenceNumber);
if(this->servicePackageSequenceNumber_ == sequenceNumber && this->servicePackageUsageCount_ == 0)
{
this->closing_ = true;
return true;
}
return false;
}
void ScheduleDeactivationIfNotUsedSince(DateTime lowerBound, Deactivator & deactivator)
{
bool shouldScheduleDeactivation = false;
uint64 sequenceNumber = 0;
{
AcquireReadLock readLock(entryLock_);
if(this->closing_) { return; }
if(this->servicePackageUsageCount_ == 0 && this->servicePackageInstanceUnusedSince_.Ticks <= lowerBound.Ticks)
{
shouldScheduleDeactivation = true;
sequenceNumber = this->servicePackageSequenceNumber_;
}
WriteNoise(
TraceType,
traceId_,
"ScheduleDeactivationIfNotUsedSince: ServicePackage={0}, ServicePackageUsageCount={1}, LowerBound={2}, shouldScheduleDeactivation={3}.",
this->id_,
this->servicePackageUsageCount_,
lowerBound,
shouldScheduleDeactivation);
}
if(shouldScheduleDeactivation)
{
this->ScheduleServicePackageInstanceDeactivation(deactivator, sequenceNumber);
}
}
void ScheduleServicePackageInstanceDeactivation(
Deactivator & deactivator,
uint64 sequenceNumber)
{
auto dueTime = GetDeactivationGraceInterval();
deactivator.ScheduleServicePackageInstanceDeactivation(
this->id_,
sequenceNumber,
dueTime);
}
void OnDeactivationFailed(Deactivator & deactivator)
{
uint64 sequenceNumber = 0;
int64 failureCount = 0;
{
AcquireWriteLock writeLock(entryLock_);
ASSERT_IFNOT(closing_, "Attempted to deactivate a ServicePackage without marking it for closing");
closing_ = false;
sequenceNumber = this->servicePackageSequenceNumber_;
failureCount = ++continuousDeactivationFailureCount_;
WriteInfo(
TraceType,
traceId_,
"OnDeactivationFailed: {0}. ContinuousDeactivationFailureCount={1}",
this->ToString(),
this->continuousDeactivationFailureCount_);
}
auto deactivationGraceInterval = HostingConfig::GetConfig().DeactivationGraceInterval;
auto deactivationMaxRetryInterval = HostingConfig::GetConfig().DeactivationMaxRetryInterval;
auto retryTime = TimeSpan::FromMilliseconds((double)failureCount * deactivationGraceInterval.TotalMilliseconds());
if (retryTime.Ticks > deactivationMaxRetryInterval.Ticks)
{
retryTime = deactivationMaxRetryInterval;
}
WriteInfo(
TraceType,
traceId_,
"OnDeactivationFailed: {0}. Scheduled To Run after={1} milliseconds",
this->ToString(),
retryTime.TotalMilliseconds());
deactivator.ScheduleServicePackageInstanceDeactivation(this->id_, sequenceNumber, retryTime);
}
TimeSpan GetDeactivationGraceInterval()
{
return (id_.ActivationContext.IsExclusive ?
HostingConfig::GetConfig().ExclusiveModeDeactivationGraceInterval :
HostingConfig::GetConfig().DeactivationGraceInterval);
}
bool IsClosing()
{
AcquireReadLock readLock(entryLock_);
return closing_;
}
wstring ToString()
{
return wformatString(
"ServicePackageInstanceReplicaCountEntry: ServicePackageInstanceId={0}, UsageCount={1}, SequenceNumber={2}",
this->id_,
this->servicePackageUsageCount_,
this->servicePackageSequenceNumber_);
}
private:
ServicePackageInstanceIdentifier const id_;
wstring const traceId_;
RwLock entryLock_;
/* These members should always be accessed under lock */
bool closing_;
LONG servicePackageUsageCount_;
DateTime servicePackageInstanceUnusedSince_;
uint64 servicePackageSequenceNumber_;
int64 continuousDeactivationFailureCount_;
};
// ********************************************************************************************************************
// Deactivator::ApplicationReplicaCountEntry Implementation
//
class Deactivator::ApplicationReplicaCountEntry : private TextTraceComponent<TraceTaskCodes::Hosting>
{
public:
ApplicationReplicaCountEntry(ApplicationIdentifier const & applicationId, wstring const & traceId)
: id_(applicationId),
traceId_(traceId),
closing_(false),
applicationUsageCount_(0),
applicationSequenceNumber_(0),
applicationUnusedSince_(DateTime::Now())
{
}
ErrorCode EnsureServicePackageInstanceEntry(ServicePackageInstanceIdentifier const & servicePackageInstanceId)
{
AcquireWriteLock writeLock(entryLock_);
if (closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
auto iter = servicePackageInstancesMap_.find(servicePackageInstanceId);
if (iter != servicePackageInstancesMap_.end())
{
if(iter->second->IsClosing())
{
return ErrorCode(ErrorCodeValue::InvalidState);
}
}
else
{
servicePackageInstancesMap_.insert(make_pair(servicePackageInstanceId, make_shared<ServicePackageInstanceReplicaCountEntry>(servicePackageInstanceId, traceId_)));
WriteInfo(
TraceType,
traceId_,
"EnsureServicePackage: New entry with ServicePackage={0} inserted.",
servicePackageInstanceId);
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode IncrementUsageCount(ServicePackageInstanceIdentifier const & servicePackageInstanceId, Deactivator & deactivator)
{
Deactivator::ServicePackageInstanceReplicaCountEntrySPtr ServicePackageInstanceReplicaCountEntry;
ErrorCode error = GetServicePackageEntry(servicePackageInstanceId, ServicePackageInstanceReplicaCountEntry);
if(error.IsSuccess())
{
error = ServicePackageInstanceReplicaCountEntry->IncrementUsageCount(deactivator);
if(error.IsSuccess())
{
// If increment on ServicePackage is successful, increment application UsageCount
bool shouldCancelDeactivation = false;
uint64 sequenceNumber = 0;
{
// If ServicePackage increment passes and if application is in closing state,
// return InvalidState. Application deactivation always succeeds, hence the application
// entry will be remove
AcquireWriteLock writeLock(entryLock_);
if(closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
sequenceNumber = ++this->applicationSequenceNumber_;
if(++this->applicationUsageCount_ == 1)
{
shouldCancelDeactivation = true;
this->applicationUnusedSince_ = DateTime::MaxValue;
}
}
if(shouldCancelDeactivation)
{
deactivator.CancelApplicationDeactivation(this->id_, sequenceNumber);
}
}
}
return error;
}
ErrorCode DecrementUsageCount(ServicePackageInstanceIdentifier const & servicePackageInstanceId, Deactivator & deactivator)
{
Deactivator::ServicePackageInstanceReplicaCountEntrySPtr servicePackageReplicaCountEntry;
ErrorCode error = GetServicePackageEntry(servicePackageInstanceId, servicePackageReplicaCountEntry);
if(error.IsSuccess())
{
{
AcquireWriteLock writeLock(entryLock_);
if(closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
++this->applicationSequenceNumber_;
if(--this->applicationUsageCount_ == 0)
{
this->applicationUnusedSince_ = DateTime::Now();
// We are not scheduling deactivation of the applicaiton here.
// When the last ServicePackage is successfully deactivated,
// we will schedule application deactivation.
}
}
servicePackageReplicaCountEntry->DecrementUsageCount(deactivator);
}
return error;
}
ErrorCode ScheduleDeactivationIfNotUsed(ServicePackageInstanceIdentifier const & servicePackageInstanceId, Deactivator & deactivator, bool & isDeactivationScheduled)
{
Deactivator::ServicePackageInstanceReplicaCountEntrySPtr servicePackageReplicaCountEntry;
ErrorCode error = GetServicePackageEntry(servicePackageInstanceId, servicePackageReplicaCountEntry);
if(error.IsSuccess())
{
return servicePackageReplicaCountEntry->ScheduleDeactivationIfNotUsed(deactivator, isDeactivationScheduled);
}
return error;
}
ErrorCode ScheduleDeactivationIfNotUsed(Deactivator & deactivator, bool & isDeactivationScheduled)
{
uint64 sequenceNumber = 0;
{
AcquireReadLock readLock(entryLock_);
if(this->closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
if(this->applicationUsageCount_ == 0 &&
HostingConfig::GetConfig().DeactivationGraceInterval != TimeSpan::MaxValue)
{
isDeactivationScheduled = true;
sequenceNumber = this->applicationSequenceNumber_;
}
else
{
isDeactivationScheduled = false;
}
WriteInfo(
TraceType,
traceId_,
"ScheduleDeactivationIfNotUsed: Application={0}, ApplicationUsageCount={1}, IsDeactivationScheduled={2}.",
this->id_,
this->applicationUsageCount_,
isDeactivationScheduled);
}
if(isDeactivationScheduled)
{
deactivator.ScheduleApplicationDeactivation(this->id_, sequenceNumber);
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode ScheduleDeactivationIfNotUsedSince(DateTime lowerBound, Deactivator & deactivator)
{
bool shouldScheduleApplicationDeactivation = false;
uint64 sequenceNumber = 0;
map<ServicePackageInstanceIdentifier, Deactivator::ServicePackageInstanceReplicaCountEntrySPtr> map;
{
AcquireReadLock readLock(entryLock_);
if(this->closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
if(this->applicationUsageCount_ == 0 &&
this->applicationUnusedSince_.Ticks <= lowerBound.Ticks)
{
shouldScheduleApplicationDeactivation = true;
sequenceNumber = this->applicationSequenceNumber_;
}
else
{
map = servicePackageInstancesMap_;
}
WriteNoise(
TraceType,
traceId_,
"ScheduleDeactivationIfNotUsedSince: Application={0}, ApplicationUsageCount={1}, LowerBound={2}, shouldScheduleApplicationDeactivation={3}.",
this->id_,
this->applicationUsageCount_,
lowerBound,
shouldScheduleApplicationDeactivation);
}
if(shouldScheduleApplicationDeactivation)
{
deactivator.ScheduleApplicationDeactivation(this->id_, sequenceNumber);
}
else
{
for(auto iter = map.begin(); iter != map.end(); ++iter)
{
iter->second->ScheduleDeactivationIfNotUsedSince(lowerBound, deactivator);
}
}
return ErrorCode(ErrorCodeValue::Success);
}
bool OnDeactivateIfNotUsed(ServicePackageInstanceIdentifier const & servicePackageInstanceId, uint64 const servicePackageSequenceNumber)
{
Deactivator::ServicePackageInstanceReplicaCountEntrySPtr servicePackageReplicaCountEntry;
ErrorCode error = GetServicePackageEntry(servicePackageInstanceId, servicePackageReplicaCountEntry);
if(error.IsSuccess())
{
return servicePackageReplicaCountEntry->OnDeactivateIfNotUsed(servicePackageSequenceNumber);
}
return false;
}
bool OnDeactivateIfNotUsed(uint64 const applicationSequenceNumber)
{
bool isNotUsed = false;
{
AcquireWriteLock writeLock(entryLock_);
if(closing_) { return false; }
if(this->applicationUsageCount_ == 0 && applicationSequenceNumber == this->applicationSequenceNumber_)
{
closing_ = true;
isNotUsed = true;
}
WriteInfo(
TraceType,
traceId_,
"OnDeactivateIfNotUsed: IsNotUsed={0}, Closing={1}, Application={2}, ApplicationUsageCount={3}.",
isNotUsed,
closing_,
id_,
this->applicationUsageCount_);
}
return isNotUsed;
}
void OnDeactivationFailed(ServicePackageInstanceIdentifier const & servicePackageInstanceId, Deactivator & deactivator)
{
Deactivator::ServicePackageInstanceReplicaCountEntrySPtr servicePackageReplicaCountEntry;
ErrorCode error = GetServicePackageEntry(servicePackageInstanceId, servicePackageReplicaCountEntry);
if(error.IsSuccess())
{
servicePackageReplicaCountEntry->OnDeactivationFailed(deactivator);
}
}
void OnDeactivationSuccess(ServicePackageInstanceIdentifier const & servicePackageInstanceId, Deactivator & deactivator)
{
bool shouldScheduleApplicationDeactivation = false;
uint64 sequenceNumber = 0;
{
AcquireWriteLock writeLock(entryLock_);
if (closing_) { return; }
auto iter = servicePackageInstancesMap_.find(servicePackageInstanceId);
if (iter != servicePackageInstancesMap_.end())
{
ASSERT_IFNOT(iter->second->IsClosing(), "Deactivating a ServicePackage without marking it for closing.");
servicePackageInstancesMap_.erase(iter);
WriteInfo(
TraceType,
traceId_,
"OnDeactivationSuccess: Entry with ServicePackage={0} removed. Remaining ServicePackage count:{1}.",
servicePackageInstanceId,
servicePackageInstancesMap_.size());
// If the last ServicePackage is deactivated, schedule the application for deactivation
if(servicePackageInstancesMap_.empty())
{
ASSERT_IF(this->applicationUsageCount_ != 0, "If there are no ServicePackages, the UsageCount has to be 0.");
shouldScheduleApplicationDeactivation = true;
sequenceNumber = this->applicationSequenceNumber_;
}
}
}
if(shouldScheduleApplicationDeactivation)
{
deactivator.ScheduleApplicationDeactivation(this->id_, sequenceNumber);
}
}
bool DoesServicePackageInstanceEntryExists(ServicePackageInstanceIdentifier const & servicePackageInstanceId, __out LONG & servicePackageReplicaCount)
{
Deactivator::ServicePackageInstanceReplicaCountEntrySPtr servicePackageReplicaCountEntry;
ErrorCode error = GetServicePackageEntry(servicePackageInstanceId, servicePackageReplicaCountEntry);
if(error.IsSuccess())
{
servicePackageReplicaCount = servicePackageReplicaCountEntry->GetUsageCount();
}
return error.IsSuccess();
}
void GetServicePackageInstanceEntries(
ServicePackageIdentifier const & servicePackageId,
__out vector<ServicePackageInstanceIdentifier> & servicePackageInstances)
{
{
AcquireReadLock readLock(entryLock_);
if (closing_)
{
WriteNoise(
TraceType,
traceId_,
"GetServicePackageInstanceEntries: Looking for ServicePackage={0}. ApplicationReplicaCountEntry is closing.",
servicePackageId);
return;
}
for (auto const & packageInstanceEntry : servicePackageInstancesMap_)
{
if (packageInstanceEntry.first.IsActivationOf(servicePackageId))
{
servicePackageInstances.push_back(packageInstanceEntry.first);
}
}
}
WriteNoise(
TraceType,
traceId_,
"GetServicePackageInstanceEntries: Looking for ServicePackage={0}. Number of instances found={1}",
servicePackageId,
servicePackageInstances.size());
}
LONG GetUsageCount()
{
AcquireReadLock readLock(entryLock_);
return applicationUsageCount_;
}
bool IsClosing()
{
AcquireReadLock readLock(entryLock_);
return closing_;
}
private:
ErrorCode GetServicePackageEntry(ServicePackageInstanceIdentifier const & servicePackageInstanceId, Deactivator::ServicePackageInstanceReplicaCountEntrySPtr & servicePackageEntrySPtr)
{
bool entryFound = false;
{
AcquireReadLock readLock(entryLock_);
if (closing_) { return ErrorCode(ErrorCodeValue::InvalidState); }
auto iter = servicePackageInstancesMap_.find(servicePackageInstanceId);
if (iter != servicePackageInstancesMap_.end())
{
servicePackageEntrySPtr = iter->second;
entryFound = true;
}
}
WriteNoise(
TraceType,
traceId_,
"GetServicePackageEntry: Looking for ServicePackage={0}. Entry Found={1}",
servicePackageInstanceId,
entryFound);
return entryFound ? ErrorCode(ErrorCodeValue::Success) : ErrorCode(ErrorCodeValue::NotFound);
}
private:
ApplicationIdentifier const id_;
wstring const traceId_;
RwLock entryLock_;
/* These members should always be accessed under lock */
bool closing_;
LONG applicationUsageCount_;
DateTime applicationUnusedSince_;
uint64 applicationSequenceNumber_;
map<ServicePackageInstanceIdentifier, Deactivator::ServicePackageInstanceReplicaCountEntrySPtr> servicePackageInstancesMap_;
};
// ********************************************************************************************************************
// Deactivator::DeactivationEntry Implementation
//
template <class TIdentifier>
class Deactivator::DeactivationEntry
{
DENY_COPY(DeactivationEntry)
public:
DeactivationEntry(TIdentifier const & id, uint64 const sequenceNumber, TimerSPtr const & timer)
: Id(id), SequenceNumber(sequenceNumber), DeactivationTimer(timer)
{
}
virtual ~DeactivationEntry()
{
if (DeactivationTimer)
{
DeactivationTimer->Cancel();
}
}
public:
TIdentifier const Id;
uint64 const SequenceNumber;
TimerSPtr const DeactivationTimer;
};
template class Deactivator::DeactivationEntry<ServicePackageInstanceIdentifier>;
template class Deactivator::DeactivationEntry<ApplicationIdentifier>;
// ********************************************************************************************************************
// Deactivator::DeactivationQueue Implementation
//
template <class TIdentifier>
class Deactivator::DeactivationQueue : Common::TextTraceComponent<Common::TraceTaskCodes::Hosting>
{
DENY_COPY(DeactivationQueue)
public:
DeactivationQueue(wstring const & traceId)
: map_(),
lock_(),
isClosed_(false),
traceId_(traceId)
{
}
virtual ~DeactivationQueue()
{
}
// add deactivation entry to the queue
ErrorCode Add(shared_ptr<Deactivator::DeactivationEntry<TIdentifier>> const & entry)
{
{
AcquireWriteLock lock(lock_);
if (isClosed_) { return ErrorCode(ErrorCodeValue::ObjectClosed); }
auto iter = map_.find(entry->Id);
if (iter != map_.end())
{
if(iter->second->SequenceNumber < entry->SequenceNumber)
{
WriteNoise(
TraceType,
traceId_,
"An entry with SequenceNumber={0} was found and removed. Add DeactivationEntry SequenceNumber={1}. A new DeactivationEntry will be added. Id={2}",
iter->second->SequenceNumber,
entry->SequenceNumber,
entry->Id);
map_.erase(iter);
}
else
{
WriteNoise(
TraceType,
traceId_,
"An entry with SequenceNumber={0} is already present. Add DeactivationEntry SequenceNumber={1}. Id={2}",
iter->second->SequenceNumber,
entry->SequenceNumber,
entry->Id);
return ErrorCode(ErrorCodeValue::AlreadyExists);
}
}
map_.insert(make_pair(entry->Id, entry));
return ErrorCode(ErrorCodeValue::Success);
}
}
// remove the deactivation entry from the queue, if the instance id is same or lower
ErrorCode Remove(
TIdentifier const & id,
uint64 const sequenceNumber,
__out shared_ptr<Deactivator::DeactivationEntry<TIdentifier>> & entry)
{
{
AcquireWriteLock lock(lock_);
if (isClosed_) { return ErrorCode(ErrorCodeValue::ObjectClosed); }
auto iter = map_.find(id);
if (iter != map_.end())
{
if(iter->second->SequenceNumber <= sequenceNumber)
{
WriteNoise(
TraceType,
traceId_,
"An entry with SequenceNumber={0} was found and removed. Remove DeactivatorEntry SequenceNumber={1}. Id={2}",
iter->second->SequenceNumber,
sequenceNumber,
id);
entry = iter->second;
map_.erase(iter);
return ErrorCode(ErrorCodeValue::Success);
}
else
{
WriteNoise(
TraceType,
traceId_,
"An entry with SequenceNumber={0} was found but not removed. Remove DeactivatorEntry SequenceNumber={1}. Id={2}",
iter->second->SequenceNumber,
sequenceNumber,
id);
}
}
return ErrorCode(ErrorCodeValue::NotFound);
}
}
void Close()
{
{
AcquireWriteLock lock(lock_);
if (!isClosed_)
{
isClosed_ = true;
map_.clear();
}
}
}
private:
map<TIdentifier, shared_ptr<Deactivator::DeactivationEntry<TIdentifier>>> map_;
RwLock lock_;
bool isClosed_;
wstring const traceId_;
};
template class Deactivator::DeactivationQueue<ServicePackageInstanceIdentifier>;
template class Deactivator::DeactivationQueue<ApplicationIdentifier>;
// ********************************************************************************************************************
// Deactivator Implementation
//
Deactivator::Deactivator(ComponentRoot const & root, __in ApplicationManager & appManager)
: RootedObject(root),
appManager_(appManager),
pendingServicePackageDeactivations_(),
pendingApplicationDeactivations_(),
unusedApplicationScanTimer_(),
random_((int)SequenceNumber::GetNext())
{
auto pendingServicePackageDeactivations = make_unique<DeactivationQueue<ServicePackageInstanceIdentifier>>(root.TraceId);
auto pendingApplicationDeactivations = make_unique<DeactivationQueue<ApplicationIdentifier>>(root.TraceId);
pendingServicePackageDeactivations_ = move(pendingServicePackageDeactivations);
pendingApplicationDeactivations_ = move(pendingApplicationDeactivations);
}
Deactivator::~Deactivator()
{
}
ErrorCode Deactivator::OnOpen()
{
auto deactivationScanInterval = HostingConfig::GetConfig().DeactivationScanInterval;
if (deactivationScanInterval != TimeSpan::MaxValue)
{
auto root = Root.CreateComponentRoot();
unusedApplicationScanTimer_ = Timer::Create("Hosting.ScanForUnusedApplications", [this, root](TimerSPtr const &) { this->ScanForUnusedApplications(); }, false);
unusedApplicationScanTimer_->Change(deactivationScanInterval, deactivationScanInterval);
}
return ErrorCode(ErrorCodeValue::Success);
}
ErrorCode Deactivator::OnClose()
{
pendingServicePackageDeactivations_->Close();
pendingApplicationDeactivations_->Close();
if (unusedApplicationScanTimer_)
{
unusedApplicationScanTimer_->Cancel();
}
{
AcquireWriteLock lock(this->mapLock_);
this->applicationMap_.clear();
}
return ErrorCode(ErrorCodeValue::Success);
}
void Deactivator::OnAbort()
{
pendingServicePackageDeactivations_->Close();
pendingApplicationDeactivations_->Close();
if (unusedApplicationScanTimer_)
{
unusedApplicationScanTimer_->Cancel();
}
{
AcquireWriteLock writeLock(this->mapLock_);
this->applicationMap_.clear();
}
}
/***************************** ServicePackage Deactivation ********************************/
void Deactivator::ScheduleServicePackageInstanceDeactivation(
ServicePackageInstanceIdentifier const & servicePackageInstanceId,
uint64 const sequenceNumber,
TimeSpan deactivationGraceInterval)
{
if(deactivationGraceInterval == TimeSpan::MaxValue)
{
WriteInfo(
TraceType,
Root.TraceId,
"ServicePackage={0}, SequenceNumber={1} is not scheduled for deactivation since DeactivationGraceInterval is TimeSpan::MaxValue.",
servicePackageInstanceId,
sequenceNumber);
return;
}
if(HostingConfig::GetConfig().EnableProcessDebugging && appManager_.IsCodePackageLockFilePresent(servicePackageInstanceId))
{
WriteInfo(
TraceType,
Root.TraceId,
"ServicePackage={0}, SequenceNumber={1} is not scheduled for deactivation since ProcessDebugging is enabled and CodePackage lock file was found on one or more code packages.",
servicePackageInstanceId,
sequenceNumber);
return;
}
else
{
WriteInfo(
TraceType,
Root.TraceId,
"ServicePackage={0}, SequenceNumber={1} is not used. Scheduling it for deactivation.",
servicePackageInstanceId,
sequenceNumber);
auto root = this->Root.CreateComponentRoot();
auto deactivationTimer = Timer::Create(
"Hosting.Deactivation1",
[root, this, servicePackageInstanceId, sequenceNumber](TimerSPtr const & timer)
{ this->OnServicePackageInstanceDeactivationCallback(timer, servicePackageInstanceId, sequenceNumber); });
auto deactivationEntry = make_shared<ServicePackageInstanceDeactivationEntry>(servicePackageInstanceId, sequenceNumber, deactivationTimer);
auto error = this->pendingServicePackageDeactivations_->Add(deactivationEntry);
if (!error.IsSuccess())
{
WriteTrace(
error.IsError(ErrorCodeValue::AlreadyExists) ? LogLevel::Noise : LogLevel::Warning,
TraceType,
Root.TraceId,
"Failed to schedule deactivation of ServicePackage={0}, SequenceNumber={1}, ErrorCode={2}",
servicePackageInstanceId,
sequenceNumber,
error);
return;
}
else
{
deactivationTimer->Change(deactivationGraceInterval);
}
}
}
void Deactivator::CancelServicePackageInstanceDeactivation(ServicePackageInstanceIdentifier const & servicePackageInstanceId, uint64 const sequenceNumber)
{
ServicePackageInstanceDeactivationEntrySPtr entry;
auto error = pendingServicePackageDeactivations_->Remove(servicePackageInstanceId, sequenceNumber, entry);
if (error.IsSuccess())
{
entry->DeactivationTimer->Cancel();
WriteInfo(
TraceType,
Root.TraceId,
"Deactivation of ServicePackage={0} is canceled. SequenceNumber={1}",
servicePackageInstanceId,
sequenceNumber);
return;
}
}
ErrorCode Deactivator::EnsureServicePackageInstanceEntry(ServicePackageInstanceIdentifier const & servicePackageInstanceId)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
return applicationReplicaCountEntry->EnsureServicePackageInstanceEntry(servicePackageInstanceId);
}
return error;
}
ErrorCode Deactivator::IncrementUsageCount(ServicePackageInstanceIdentifier const & servicePackageInstanceId)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
return applicationReplicaCountEntry->IncrementUsageCount(servicePackageInstanceId, *this);
}
return error;
}
ErrorCode Deactivator::DecrementUsageCount(ServicePackageInstanceIdentifier const & servicePackageInstanceId)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
return applicationReplicaCountEntry->DecrementUsageCount(servicePackageInstanceId, *this);
}
return error;
}
ErrorCode Deactivator::ScheduleDeactivationIfNotUsed(ServicePackageInstanceIdentifier const & servicePackageInstanceId, __out bool & isDeactivationScheduled)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
return applicationReplicaCountEntry->ScheduleDeactivationIfNotUsed(servicePackageInstanceId, *this, isDeactivationScheduled);
}
return error;
}
bool Deactivator::OnDeactivateIfNotUsed(ServicePackageInstanceIdentifier const & servicePackageInstanceId, uint64 const sequenceNumber)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
return applicationReplicaCountEntry->OnDeactivateIfNotUsed(servicePackageInstanceId, sequenceNumber);
}
return false;
}
void Deactivator::OnDeactivationSuccess(ServicePackageInstanceIdentifier const & servicePackageInstanceId)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
applicationReplicaCountEntry->OnDeactivationSuccess(servicePackageInstanceId, *this);
}
}
void Deactivator::OnDeactivationFailed(ServicePackageInstanceIdentifier const & servicePackageInstanceId)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
applicationReplicaCountEntry->OnDeactivationFailed(servicePackageInstanceId, *this);
}
}
void Deactivator::OnServicePackageInstanceDeactivationCallback(
TimerSPtr const & timer,
ServicePackageInstanceIdentifier const & servicePackageInstanceId,
uint64 const sequenceNumber)
{
ASSERT_IF(timer == nullptr, "OnServicePackageDeactivationCallback: Timer cannot be null");
timer->Cancel();
ServicePackageInstanceDeactivationEntrySPtr removed;
this->pendingServicePackageDeactivations_->Remove(servicePackageInstanceId, sequenceNumber, removed).ReadValue();
WriteNoise(
TraceType,
Root.TraceId,
"OnServicePackageDeactivationCallback: ServicePackage={0}, SequenceNumber={1}",
servicePackageInstanceId,
sequenceNumber);
if(this->OnDeactivateIfNotUsed(servicePackageInstanceId, sequenceNumber))
{
this->appManager_.DeactivateServicePackageInstance(servicePackageInstanceId);
}
}
bool Deactivator::IsUsed(ServicePackageInstanceIdentifier const & servicePackageInstanceId)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageInstanceId.ApplicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
LONG servicePackageReplicaCount;
if(applicationReplicaCountEntry->DoesServicePackageInstanceEntryExists(servicePackageInstanceId, servicePackageReplicaCount) && servicePackageReplicaCount > 0)
{
return true;
}
}
return false;
}
bool Deactivator::IsUsed(ApplicationIdentifier const & applicationId)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(applicationId, applicationReplicaCountEntry);
if(error.IsSuccess() && applicationReplicaCountEntry->GetUsageCount() > 0)
{
return true;
}
return false;
}
void Deactivator::GetServicePackageInstanceEntries(
ServicePackageIdentifier const & servicePackageId,
__out vector<ServicePackageInstanceIdentifier> & servicePackageInstances)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(servicePackageId.ApplicationId, applicationReplicaCountEntry);
if (error.IsSuccess())
{
applicationReplicaCountEntry->GetServicePackageInstanceEntries(servicePackageId, servicePackageInstances);
}
}
/****************************** Application Deactivation *********************************/
ErrorCode Deactivator::EnsureApplicationEntry(ApplicationIdentifier const & applicationId)
{
if (this->State.Value != FabricComponentState::Opened)
{
return ErrorCode(ErrorCodeValue::InvalidState);
}
{
AcquireWriteLock writeLock(mapLock_);
auto iter = applicationMap_.find(applicationId);
if (iter != applicationMap_.end())
{
if(iter->second->IsClosing())
{
return ErrorCode(ErrorCodeValue::InvalidState);
}
}
else
{
applicationMap_.insert(make_pair(applicationId, make_shared<ApplicationReplicaCountEntry>(applicationId, Root.TraceId)));
WriteInfo(
TraceType,
Root.TraceId,
"EnsureApplication: New entry with Application={0} inserted.",
applicationId);
}
}
return ErrorCode(ErrorCodeValue::Success);
}
void Deactivator::ScanForUnusedApplications()
{
if (this->State.Value != FabricComponentState::Opened)
{
return;
}
DateTime lowerBound = DateTime::Now().SubtractWithMaxValueCheck(HostingConfig::GetConfig().DeactivationScanInterval);
WriteNoise(
TraceType,
Root.TraceId,
"Scanning for applications that are unused since {0}",
lowerBound);
map<ServiceModel::ApplicationIdentifier, ApplicationReplicaCountEntrySPtr> tempApplicationMap;
{
AcquireReadLock readLock(mapLock_);
tempApplicationMap = this->applicationMap_;
}
for(auto iter = tempApplicationMap.begin(); iter != tempApplicationMap.end(); ++iter)
{
iter->second->ScheduleDeactivationIfNotUsedSince(lowerBound, *this);
}
}
ErrorCode Deactivator::ScheduleDeactivationIfNotUsed(ApplicationIdentifier const & applicationId, __out bool & isDeactivationScheduled)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(applicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
return applicationReplicaCountEntry->ScheduleDeactivationIfNotUsed(*this, isDeactivationScheduled);
}
return error;
}
ErrorCode Deactivator::GetApplicationEntry(ServiceModel::ApplicationIdentifier const & applicationId, ApplicationReplicaCountEntrySPtr & applicationReplicaCountEntry)
{
if (this->State.Value != FabricComponentState::Opened)
{
return ErrorCode(ErrorCodeValue::InvalidState);
}
bool entryFound = false;
{
AcquireReadLock readLock(mapLock_);
auto iter = applicationMap_.find(applicationId);
if (iter != applicationMap_.end())
{
applicationReplicaCountEntry = iter->second;
entryFound = true;
}
}
if(entryFound)
{
WriteNoise(
TraceType,
Root.TraceId,
"GetApplicationEntry: Looking for Application={0}. EntryFound={1}, UsageCount={2}",
applicationId,
entryFound,
applicationReplicaCountEntry->GetUsageCount());
return ErrorCode(ErrorCodeValue::Success);
}
else
{
WriteNoise(
TraceType,
Root.TraceId,
"GetApplicationEntry: Application={0} entry is not found.",
applicationId);
return ErrorCode(ErrorCodeValue::NotFound);
}
}
void Deactivator::ScheduleApplicationDeactivation(
ApplicationIdentifier const & applicationId,
uint64 const applicationSequenceNumber)
{
auto deactivationGraceInterval = HostingConfig::GetConfig().DeactivationGraceInterval;
if(deactivationGraceInterval == TimeSpan::MaxValue)
{
WriteInfo(
TraceType,
Root.TraceId,
"Application={0}, SequenceNumber={1} is not scheduled for deactivation since DeactivationGraceInterval is TimeSpan::MaxValue.",
applicationId,
applicationSequenceNumber);
return;
}
else
{
WriteInfo(
TraceType,
Root.TraceId,
"Application={0}, SequenceNumber={1} is not used. Scheduling it for deactivation.",
applicationId,
applicationSequenceNumber);
auto root = this->Root.CreateComponentRoot();
auto deactivationTimer = Timer::Create(
"Hosting.Deactivation2",
[root, this, applicationId, applicationSequenceNumber](TimerSPtr const & timer)
{ this->OnApplicationDeactivationCallback(timer, applicationId, applicationSequenceNumber); });
auto deactivationEntry = make_shared<ApplicationDeactivationEntry>(applicationId, applicationSequenceNumber, deactivationTimer);
auto error = this->pendingApplicationDeactivations_->Add(deactivationEntry);
if (!error.IsSuccess())
{
WriteTrace(
error.IsError(ErrorCodeValue::AlreadyExists) ? LogLevel::Noise : LogLevel::Warning,
TraceType,
Root.TraceId,
"Failed to schedule deactivation of Application={0}, SequenceNumber={1}, ErrorCode={2}",
applicationId,
applicationSequenceNumber,
error);
return;
}
else
{
deactivationTimer->Change(deactivationGraceInterval);
}
}
}
void Deactivator::CancelApplicationDeactivation(ApplicationIdentifier const & applicationId, uint64 const applicationSequenceNumber)
{
ApplicationDeactivationEntrySPtr entry;
auto error = pendingApplicationDeactivations_->Remove(applicationId, applicationSequenceNumber, entry);
if (error.IsSuccess())
{
entry->DeactivationTimer->Cancel();
WriteInfo(
TraceType,
Root.TraceId,
"Deactivation of Application={0} is canceled. SequenceNumber={1}",
applicationId,
applicationSequenceNumber);
return;
}
}
bool Deactivator::OnDeactivateIfNotUsed(ApplicationIdentifier const & applicationId, uint64 const applicationSequenceNumber)
{
ApplicationReplicaCountEntrySPtr applicationReplicaCountEntry;
ErrorCode error = this->GetApplicationEntry(applicationId, applicationReplicaCountEntry);
if(error.IsSuccess())
{
return applicationReplicaCountEntry->OnDeactivateIfNotUsed(applicationSequenceNumber);
}
return false;
}
void Deactivator::OnDeactivationSuccess(ServiceModel::ApplicationIdentifier const & applicationId)
{
if (this->State.Value != FabricComponentState::Opened)
{
return;
}
{
AcquireWriteLock writeLock(mapLock_);
auto iter = applicationMap_.find(applicationId);
if (iter != applicationMap_.end())
{
ASSERT_IFNOT(iter->second->IsClosing(), "Deactivated an Application without marking it for closing");
applicationMap_.erase(iter);
WriteNoise(
TraceType,
Root.TraceId,
"OnDeactivationSuccess: Entry with Application={0} removed.",
applicationId);
}
}
}
void Deactivator::OnApplicationDeactivationCallback(
TimerSPtr const & timer,
ApplicationIdentifier const & applicationId,
uint64 const applicationSequenceNumber)
{
ASSERT_IF(timer == nullptr, "OnApplicationDeactivationCallback: Timer cannot be null");
timer->Cancel();
ApplicationDeactivationEntrySPtr removed;
this->pendingApplicationDeactivations_->Remove(applicationId, applicationSequenceNumber, removed).ReadValue();
WriteNoise(
TraceType,
Root.TraceId,
"OnApplicationDeactivationCallback: Application={0}, SequenceNumber={1}",
applicationId,
applicationSequenceNumber);
if(this->OnDeactivateIfNotUsed(applicationId, applicationSequenceNumber))
{
this->appManager_.DeactivateApplication(applicationId);
}
}
|
rerobika/jerryscript
|
tests/unit-core/test-api-binary-operations-comparisons.c
|
<gh_stars>1-10
/* Copyright JS Foundation and other contributors, http://js.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.
*/
#include "jerryscript.h"
#include "test-common.h"
#define T(op, lhs, rhs, res) \
{ op, lhs, rhs, res }
typedef struct
{
jerry_binary_operation_t op;
jerry_value_t lhs;
jerry_value_t rhs;
bool expected;
} test_entry_t;
int
main (void)
{
TEST_INIT ();
jerry_init (JERRY_INIT_EMPTY);
jerry_value_t obj1 = jerry_eval ((const jerry_char_t *) "o={x:1};o", 9, JERRY_PARSE_NO_OPTS);
jerry_value_t obj2 = jerry_eval ((const jerry_char_t *) "o={x:1};o", 9, JERRY_PARSE_NO_OPTS);
jerry_value_t err1 = jerry_create_error (JERRY_ERROR_SYNTAX, (const jerry_char_t *) "error");
test_entry_t tests[] =
{
/* Testing strict equal comparison */
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_number (5.0), jerry_create_number (5.0), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_number (3.1), jerry_create_number (10), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_number (3.1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_number (3.1), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_STRICT_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_string ((const jerry_char_t *) "example string"),
true),
T (JERRY_BIN_OP_STRICT_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_undefined (),
false),
T (JERRY_BIN_OP_STRICT_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_null (),
false),
T (JERRY_BIN_OP_STRICT_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_number (5.0),
false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_undefined (), jerry_create_undefined (), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_undefined (), jerry_create_null (), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_null (), jerry_create_null (), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_boolean (true), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_boolean (true), jerry_create_boolean (false), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_boolean (false), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_boolean (false), jerry_create_boolean (false), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj1), jerry_acquire_value (obj1), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj1), jerry_acquire_value (obj2), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj2), jerry_acquire_value (obj1), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj1), jerry_create_null (), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj1), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj1), jerry_create_boolean (false), false),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (obj1), jerry_create_number (5.0), false),
T (JERRY_BIN_OP_STRICT_EQUAL,
jerry_acquire_value (obj1),
jerry_create_string ((const jerry_char_t *) "example string"),
false),
/* Testing equal comparison */
T (JERRY_BIN_OP_EQUAL, jerry_create_number (5.0), jerry_create_number (5.0), true),
T (JERRY_BIN_OP_EQUAL, jerry_create_number (3.1), jerry_create_number (10), false),
T (JERRY_BIN_OP_EQUAL, jerry_create_number (3.1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_EQUAL, jerry_create_number (3.1), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_string ((const jerry_char_t *) "example string"),
true),
T (JERRY_BIN_OP_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_undefined (),
false),
T (JERRY_BIN_OP_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_null (),
false),
T (JERRY_BIN_OP_EQUAL,
jerry_create_string ((const jerry_char_t *) "example string"),
jerry_create_number (5.0),
false),
T (JERRY_BIN_OP_EQUAL, jerry_create_undefined (), jerry_create_undefined (), true),
T (JERRY_BIN_OP_EQUAL, jerry_create_undefined (), jerry_create_null (), true),
T (JERRY_BIN_OP_EQUAL, jerry_create_null (), jerry_create_null (), true),
T (JERRY_BIN_OP_EQUAL, jerry_create_boolean (true), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_EQUAL, jerry_create_boolean (true), jerry_create_boolean (false), false),
T (JERRY_BIN_OP_EQUAL, jerry_create_boolean (false), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_EQUAL, jerry_create_boolean (false), jerry_create_boolean (false), true),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj1), jerry_acquire_value (obj1), true),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj1), jerry_acquire_value (obj2), false),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj2), jerry_acquire_value (obj1), false),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj1), jerry_create_null (), false),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj1), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj1), jerry_create_boolean (false), false),
T (JERRY_BIN_OP_EQUAL, jerry_acquire_value (obj1), jerry_create_number (5.0), false),
T (JERRY_BIN_OP_EQUAL,
jerry_acquire_value (obj1),
jerry_create_string ((const jerry_char_t *) "example string"),
false),
/* Testing less comparison */
T (JERRY_BIN_OP_LESS, jerry_create_number (5.0), jerry_create_number (5.0), false),
T (JERRY_BIN_OP_LESS, jerry_create_number (3.1), jerry_create_number (10), true),
T (JERRY_BIN_OP_LESS, jerry_create_number (3.1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_LESS, jerry_create_number (3.1), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_LESS,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_string ((const jerry_char_t *) "2"),
true),
T (JERRY_BIN_OP_LESS,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_undefined (),
false),
T (JERRY_BIN_OP_LESS,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_null (),
false),
T (JERRY_BIN_OP_LESS,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_number (5.0),
true),
T (JERRY_BIN_OP_LESS, jerry_create_undefined (), jerry_create_undefined (), false),
T (JERRY_BIN_OP_LESS, jerry_create_undefined (), jerry_create_null (), false),
T (JERRY_BIN_OP_LESS, jerry_create_null (), jerry_create_null (), false),
T (JERRY_BIN_OP_LESS, jerry_create_boolean (true), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_LESS, jerry_create_boolean (true), jerry_create_boolean (false), false),
T (JERRY_BIN_OP_LESS, jerry_create_boolean (false), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_LESS, jerry_create_boolean (false), jerry_create_boolean (false), false),
/* Testing less or equal comparison */
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_number (5.0), jerry_create_number (5.0), true),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_number (5.1), jerry_create_number (5.0), false),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_number (3.1), jerry_create_number (10), true),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_number (3.1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_number (3.1), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_LESS_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_string ((const jerry_char_t *) "2"),
true),
T (JERRY_BIN_OP_LESS_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_string ((const jerry_char_t *) "1"),
true),
T (JERRY_BIN_OP_LESS_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_undefined (),
false),
T (JERRY_BIN_OP_LESS_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_null (),
false),
T (JERRY_BIN_OP_LESS_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_number (5.0),
true),
T (JERRY_BIN_OP_LESS_EQUAL,
jerry_create_string ((const jerry_char_t *) "5.0"),
jerry_create_number (5.0),
true),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_undefined (), jerry_create_undefined (), false),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_undefined (), jerry_create_null (), false),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_null (), jerry_create_null (), true),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_boolean (true), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_boolean (true), jerry_create_boolean (false), false),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_boolean (false), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_LESS_EQUAL, jerry_create_boolean (false), jerry_create_boolean (false), true),
/* Testing greater comparison */
T (JERRY_BIN_OP_GREATER, jerry_create_number (5.0), jerry_create_number (5.0), false),
T (JERRY_BIN_OP_GREATER, jerry_create_number (10), jerry_create_number (3.1), true),
T (JERRY_BIN_OP_GREATER, jerry_create_number (3.1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_GREATER, jerry_create_number (3.1), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_GREATER,
jerry_create_string ((const jerry_char_t *) "2"),
jerry_create_string ((const jerry_char_t *) "1"),
true),
T (JERRY_BIN_OP_GREATER,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_string ((const jerry_char_t *) "2"),
false),
T (JERRY_BIN_OP_GREATER,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_undefined (),
false),
T (JERRY_BIN_OP_GREATER,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_null (),
true),
T (JERRY_BIN_OP_GREATER,
jerry_create_number (5.0),
jerry_create_string ((const jerry_char_t *) "1"),
true),
T (JERRY_BIN_OP_GREATER, jerry_create_undefined (), jerry_create_undefined (), false),
T (JERRY_BIN_OP_GREATER, jerry_create_undefined (), jerry_create_null (), false),
T (JERRY_BIN_OP_GREATER, jerry_create_null (), jerry_create_null (), false),
T (JERRY_BIN_OP_GREATER, jerry_create_boolean (true), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_GREATER, jerry_create_boolean (true), jerry_create_boolean (false), true),
T (JERRY_BIN_OP_GREATER, jerry_create_boolean (false), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_GREATER, jerry_create_boolean (false), jerry_create_boolean (false), false),
/* Testing greater or equal comparison */
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_number (5.0), jerry_create_number (5.0), true),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_number (5.0), jerry_create_number (5.1), false),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_number (10), jerry_create_number (3.1), true),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_number (3.1), jerry_create_undefined (), false),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_number (3.1), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_GREATER_EQUAL,
jerry_create_string ((const jerry_char_t *) "2"),
jerry_create_string ((const jerry_char_t *) "1"),
true),
T (JERRY_BIN_OP_GREATER_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_string ((const jerry_char_t *) "1"),
true),
T (JERRY_BIN_OP_GREATER_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_undefined (),
false),
T (JERRY_BIN_OP_GREATER_EQUAL,
jerry_create_string ((const jerry_char_t *) "1"),
jerry_create_null (),
true),
T (JERRY_BIN_OP_GREATER_EQUAL,
jerry_create_number (5.0),
jerry_create_string ((const jerry_char_t *) "1"),
true),
T (JERRY_BIN_OP_GREATER_EQUAL,
jerry_create_string ((const jerry_char_t *) "5.0"),
jerry_create_number (5.0),
true),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_undefined (), jerry_create_undefined (), false),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_undefined (), jerry_create_null (), false),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_null (), jerry_create_null (), true),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_boolean (true), jerry_create_boolean (true), true),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_boolean (true), jerry_create_boolean (false), true),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_boolean (false), jerry_create_boolean (true), false),
T (JERRY_BIN_OP_GREATER_EQUAL, jerry_create_boolean (false), jerry_create_boolean (false), true),
};
for (uint32_t idx = 0; idx < sizeof (tests) / sizeof (test_entry_t); idx++)
{
jerry_value_t result = jerry_binary_operation (tests[idx].op, tests[idx].lhs, tests[idx].rhs);
TEST_ASSERT (!jerry_value_is_error (result));
TEST_ASSERT (jerry_value_is_true (result) == tests[idx].expected);
jerry_release_value (tests[idx].lhs);
jerry_release_value (tests[idx].rhs);
jerry_release_value (result);
}
test_entry_t error_tests[] =
{
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (err1), jerry_acquire_value (err1), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_acquire_value (err1), jerry_create_undefined (), true),
T (JERRY_BIN_OP_STRICT_EQUAL, jerry_create_undefined (), jerry_acquire_value (err1), true),
};
for (uint32_t idx = 0; idx < sizeof (error_tests) / sizeof (test_entry_t); idx++)
{
jerry_value_t result = jerry_binary_operation (tests[idx].op, error_tests[idx].lhs, error_tests[idx].rhs);
TEST_ASSERT (jerry_value_is_error (result) == error_tests[idx].expected);
jerry_release_value (error_tests[idx].lhs);
jerry_release_value (error_tests[idx].rhs);
jerry_release_value (result);
}
jerry_release_value (obj1);
jerry_release_value (obj2);
jerry_release_value (err1);
jerry_cleanup ();
return 0;
} /* main */
|
smaccm/smaccm
|
fm-workbench/agree/com.rockwellcollins.atc.agree/src-gen/com/rockwellcollins/atc/agree/agree/impl/AADLEnumeratorImpl.java
|
/**
*/
package com.rockwellcollins.atc.agree.agree.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import com.rockwellcollins.atc.agree.agree.AADLEnumerator;
import com.rockwellcollins.atc.agree.agree.AgreePackage;
import com.rockwellcollins.atc.agree.agree.NestedDotID;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>AADL Enumerator</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link com.rockwellcollins.atc.agree.agree.impl.AADLEnumeratorImpl#getEnumType <em>Enum Type</em>}</li>
* <li>{@link com.rockwellcollins.atc.agree.agree.impl.AADLEnumeratorImpl#getValue <em>Value</em>}</li>
* </ul>
*
* @generated
*/
public class AADLEnumeratorImpl extends ExprImpl implements AADLEnumerator {
/**
* The cached value of the '{@link #getEnumType() <em>Enum Type</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getEnumType()
* @generated
* @ordered
*/
protected NestedDotID enumType;
/**
* The default value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected static final String VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected String value = VALUE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AADLEnumeratorImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return AgreePackage.Literals.AADL_ENUMERATOR;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NestedDotID getEnumType() {
return enumType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetEnumType(NestedDotID newEnumType, NotificationChain msgs) {
NestedDotID oldEnumType = enumType;
enumType = newEnumType;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET,
AgreePackage.AADL_ENUMERATOR__ENUM_TYPE, oldEnumType, newEnumType);
if (msgs == null) {
msgs = notification;
} else {
msgs.add(notification);
}
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setEnumType(NestedDotID newEnumType) {
if (newEnumType != enumType) {
NotificationChain msgs = null;
if (enumType != null) {
msgs = ((InternalEObject) enumType).eInverseRemove(this,
EOPPOSITE_FEATURE_BASE - AgreePackage.AADL_ENUMERATOR__ENUM_TYPE, null, msgs);
}
if (newEnumType != null) {
msgs = ((InternalEObject) newEnumType).eInverseAdd(this,
EOPPOSITE_FEATURE_BASE - AgreePackage.AADL_ENUMERATOR__ENUM_TYPE, null, msgs);
}
msgs = basicSetEnumType(newEnumType, msgs);
if (msgs != null) {
msgs.dispatch();
}
} else if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, AgreePackage.AADL_ENUMERATOR__ENUM_TYPE, newEnumType,
newEnumType));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setValue(String newValue) {
String oldValue = value;
value = newValue;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, AgreePackage.AADL_ENUMERATOR__VALUE, oldValue,
value));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case AgreePackage.AADL_ENUMERATOR__ENUM_TYPE:
return basicSetEnumType(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AgreePackage.AADL_ENUMERATOR__ENUM_TYPE:
return getEnumType();
case AgreePackage.AADL_ENUMERATOR__VALUE:
return getValue();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case AgreePackage.AADL_ENUMERATOR__ENUM_TYPE:
setEnumType((NestedDotID) newValue);
return;
case AgreePackage.AADL_ENUMERATOR__VALUE:
setValue((String) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case AgreePackage.AADL_ENUMERATOR__ENUM_TYPE:
setEnumType((NestedDotID) null);
return;
case AgreePackage.AADL_ENUMERATOR__VALUE:
setValue(VALUE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AgreePackage.AADL_ENUMERATOR__ENUM_TYPE:
return enumType != null;
case AgreePackage.AADL_ENUMERATOR__VALUE:
return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) {
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (value: ");
result.append(value);
result.append(')');
return result.toString();
}
} // AADLEnumeratorImpl
|
dcfSec/SecurityRAT
|
src/main/java/org/appsec/securityRAT/repository/search/StatusColumnValueSearchRepository.java
|
package org.appsec.securityRAT.repository.search;
import org.appsec.securityRAT.domain.StatusColumnValue;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data ElasticSearch repository for the StatusColumnValue entity.
*/
public interface StatusColumnValueSearchRepository extends ElasticsearchRepository<StatusColumnValue, Long> {
}
|
zhangkn/iOS14Header
|
System/Library/PrivateFrameworks/SPOwner.framework/SPBeacon.h
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:41:42 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/SPOwner.framework/SPOwner
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <SPOwner/SPOwner-Structs.h>
#import <libobjc.A.dylib/NSCopying.h>
#import <libobjc.A.dylib/NSSecureCoding.h>
@class NSUUID, SPHandle, NSString, SPBeaconRole, SPLostModeInfo, NSSet, NSDictionary, NSDate;
@interface SPBeacon : NSObject <NSCopying, NSSecureCoding> {
BOOL _accepted;
NSUUID* _identifier;
SPHandle* _owner;
NSString* _name;
NSString* _model;
SPBeaconRole* _role;
SPLostModeInfo* _lostModeInfo;
NSSet* _shares;
NSDictionary* _taskInformation;
NSString* _systemVersion;
long long _vendorId;
long long _productId;
NSString* _stableIdentifier;
NSDate* _pairingDate;
NSString* _correlationIdentifier;
}
@property (nonatomic,copy) NSUUID * identifier; //@synthesize identifier=_identifier - In the implementation block
@property (nonatomic,copy) NSString * stableIdentifier; //@synthesize stableIdentifier=_stableIdentifier - In the implementation block
@property (nonatomic,copy) SPHandle * owner; //@synthesize owner=_owner - In the implementation block
@property (assign,nonatomic) BOOL accepted; //@synthesize accepted=_accepted - In the implementation block
@property (nonatomic,copy) NSDate * pairingDate; //@synthesize pairingDate=_pairingDate - In the implementation block
@property (nonatomic,copy) NSString * name; //@synthesize name=_name - In the implementation block
@property (nonatomic,copy) NSString * model; //@synthesize model=_model - In the implementation block
@property (nonatomic,copy) SPBeaconRole * role; //@synthesize role=_role - In the implementation block
@property (nonatomic,copy) SPLostModeInfo * lostModeInfo; //@synthesize lostModeInfo=_lostModeInfo - In the implementation block
@property (nonatomic,copy) NSSet * shares; //@synthesize shares=_shares - In the implementation block
@property (nonatomic,copy) NSDictionary * taskInformation; //@synthesize taskInformation=_taskInformation - In the implementation block
@property (nonatomic,copy) NSString * correlationIdentifier; //@synthesize correlationIdentifier=_correlationIdentifier - In the implementation block
@property (nonatomic,copy) NSString * systemVersion; //@synthesize systemVersion=_systemVersion - In the implementation block
@property (assign,nonatomic) long long vendorId; //@synthesize vendorId=_vendorId - In the implementation block
@property (assign,nonatomic) long long productId; //@synthesize productId=_productId - In the implementation block
+(BOOL)supportsSecureCoding;
+(id)SPOwner;
-(NSUUID *)identifier;
-(SPHandle *)owner;
-(id)copyWithZone:(NSZone*)arg1 ;
-(NSString *)systemVersion;
-(void)setOwner:(SPHandle *)arg1 ;
-(SPLostModeInfo *)lostModeInfo;
-(NSSet *)shares;
-(id)debugDescription;
-(void)setIdentifier:(NSUUID *)arg1 ;
-(SPBeaconRole *)role;
-(NSString *)model;
-(void)setRole:(SPBeaconRole *)arg1 ;
-(void)setModel:(NSString *)arg1 ;
-(void)setSystemVersion:(NSString *)arg1 ;
-(BOOL)isEqual:(id)arg1 ;
-(void)setName:(NSString *)arg1 ;
-(id)initWithCoder:(id)arg1 ;
-(long long)productId;
-(void)encodeWithCoder:(id)arg1 ;
-(void)setVendorId:(long long)arg1 ;
-(BOOL)accepted;
-(unsigned long long)hash;
-(NSString *)name;
-(NSString *)correlationIdentifier;
-(void)setAccepted:(BOOL)arg1 ;
-(void)setCorrelationIdentifier:(NSString *)arg1 ;
-(NSString *)stableIdentifier;
-(void)setStableIdentifier:(NSString *)arg1 ;
-(NSDate *)pairingDate;
-(void)setPairingDate:(NSDate *)arg1 ;
-(void)setLostModeInfo:(SPLostModeInfo *)arg1 ;
-(void)setShares:(NSSet *)arg1 ;
-(NSDictionary *)taskInformation;
-(void)setTaskInformation:(NSDictionary *)arg1 ;
-(void)setProductId:(long long)arg1 ;
-(long long)vendorId;
@end
|
igorstojanovski/Central-Committee
|
server/src/main/java/co/igorski/centralcommittee/controllers/events/RunEventController.java
|
<reponame>igorstojanovski/Central-Committee<gh_stars>0
package co.igorski.centralcommittee.controllers.events;
import co.igorski.centralcommittee.model.Project;
import co.igorski.centralcommittee.model.Run;
import co.igorski.centralcommittee.model.events.Event;
import co.igorski.centralcommittee.model.events.RunFinished;
import co.igorski.centralcommittee.model.events.RunStarted;
import co.igorski.centralcommittee.model.responses.RunCreatedResponse;
import co.igorski.centralcommittee.services.ProjectService;
import co.igorski.centralcommittee.services.RunService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/event/run")
public class RunEventController {
private final ProjectService projectService;
private RunService runService;
@Autowired
private KafkaTemplate<String, Event> template;
@Autowired
public RunEventController(RunService runService, ProjectService projectService) {
this.runService = runService;
this.projectService = projectService;
}
@PostMapping
@RequestMapping("/started")
public ResponseEntity runStarted(@RequestBody RunStarted runStartedEvent) {
if(runStartedEvent.getTimestamp() == null) {
return new ResponseEntity<>("Timestamp must not be empty.", HttpStatus.BAD_REQUEST);
}
if(runStartedEvent.getTests().size() == 0) {
return new ResponseEntity<>("Tests must be present.", HttpStatus.BAD_REQUEST);
}
Project project = projectService.getProject(runStartedEvent.getProjectName());
if (project == null) {
return new ResponseEntity<>("Project with that name does not exist.", HttpStatus.NOT_FOUND);
}
Run run = runService.startRun(runStartedEvent, project);
RunCreatedResponse runCreatedResponse = new RunCreatedResponse();
runCreatedResponse.setId(run.getId());
return new ResponseEntity<>(runCreatedResponse, HttpStatus.CREATED);
}
@PostMapping
@RequestMapping("/finished")
public ResponseEntity<Run> runFinished(@RequestBody RunFinished runFinished) {
template.send("test-events", runFinished);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
}
|
Hakaze/crowdfund-example-app
|
src/routes/Terms/index.js
|
import TermsView from './components/TermsView'
export default {
path: '/terms',
component : TermsView
}
|
OutOfTheVoid/ProjectRed
|
include/Red/Data/Base64/Base64.h
|
#ifndef RED_DATA_BASE64_BASE64_H
#define RED_DATA_BASE64_BASE64_H
#include <Red/Data/Data.h>
namespace Red
{
namespace Data
{
namespace Base64
{
}
}
}
#endif
|
madeso/pegasus
|
libs/ride/src/ride/keybind.h
|
#pragma once
#include <vector>
#include <map>
#include <string>
#include "api/key.h"
struct CommandList;
struct KeyBind
{
std::map<Stroke, std::vector<std::string>> commands;
void add(const Stroke& stroke, std::vector<std::string> command_order);
bool run(const Stroke& stroke, CommandList* command_list);
};
|
sapcc/juno
|
libs/juno-ui-components/src/components/CheckboxGroup/CheckboxGroup.component.js
|
<reponame>sapcc/juno<gh_stars>1-10
import React, { useState, useEffect, useRef } from "react"
import PropTypes from "prop-types"
import { Label } from "../Label/index.js"
const checkboxgroupstyles = `
mb-5
`
export const CheckboxGroup = ({
name,
label,
selected,
required,
disabled,
children,
className,
...props
}) => {
const [selectedOptions, setSelectedOptions] = useState([])
useEffect( () => {
setSelectedOptions(selected)
}, [selected])
const handleCheckboxChange = (event) => {
const changedValue = event.target.value
const exists = selectedOptions.includes(changedValue)
if (exists) {
// remove element if it was the previously selected element…
setSelectedOptions(selectedOptions.filter((value) => { return value !== changedValue }))
} else {
// …otherwise add element
setSelectedOptions(selectedOptions => [...selectedOptions, changedValue])
}
}
const namedChildren = () => {
return React.Children.map(children, (child) => {
const isSelected = selectedOptions.includes(child.props.value)
return React.cloneElement(child, {
name: name,
className: className,
disabled: disabled,
checked: isSelected,
onChange: handleCheckboxChange
});
});
};
return (
<div role="group" className={`juno-checkbox-group ${checkboxgroupstyles} ${className}`} {...props} >
{ label ? <Label text={label} htmlFor={name} required={required} /> : "" }
{ namedChildren() }
</div>
)
}
CheckboxGroup.propTypes = {
/** Name attribute. Checkboxes within the group will have this name attribute */
name: PropTypes.string,
/** Label for the groupd as a whole */
label: PropTypes.string,
/** Array of values of individual selected options in the group */
selected: PropTypes.array,
/** Whether a selection in the group is required */
required: PropTypes.bool,
/** Disable the whole group */
disabled: PropTypes.bool,
/** Custom class to be passed to the individual checkboxes of the group */
className: PropTypes.string,
/** Child checkbox components */
children: PropTypes.node,
}
CheckboxGroup.defaultProps = {
name: null,
className: "",
label: null,
required: null,
selected: [],
disabled: null,
children: null,
}
|
SlideAtlas/SlideAtlas-Server
|
slideatlas/models/collection.py
|
<filename>slideatlas/models/collection.py<gh_stars>1-10
# coding=utf-8
from mongoengine import Q, ListField, ReferenceField, StringField
from .common import ModelDocument, Operation, ResourceType, AdminSitePermission
from .common.model_document import ModelQuerySet
from .image_store import ImageStore
import session # this style required to avoid circular imports
################################################################################
__all__ = ('Collection',)
################################################################################
class CollectionQuerySet(ModelQuerySet):
class MaxValueDict(dict):
def set_max(self, key, value):
if self.get(key, 0) < value:
self[key] = value
def _filter_permissions(self, return_accesses, permissions_set, required_operation=Operation.view, strict_operation=False):
if not isinstance(permissions_set, set):
raise ValueError('permissions_set must be a set of Permissions')
queryset = self.clone()
if AdminSitePermission() in permissions_set and \
((not strict_operation) or (required_operation == Operation.admin)):
result = queryset.all()
if return_accesses:
return [(doc, Operation.admin) for doc in result]
else:
return result
else:
collection_accesses = self.MaxValueDict()
query_collections = set()
query_sessions = set()
for permission in permissions_set:
if permission.resource_type == ResourceType.collection:
if permission.operation >= required_operation:
query_collections.add(permission.resource_id)
if return_accesses:
collection_accesses.set_max(permission.resource_id, permission.operation)
elif (permission.resource_type == ResourceType.session) and \
(required_operation == Operation.view):
query_sessions.add(permission.resource_id)
if query_sessions:
session_collections = session.Session.objects(id__in=list(query_sessions)).no_dereference().distinct('collection')
query_collections.update(session_collections)
if return_accesses:
for collection_id in session_collections:
collection_accesses.set_max(collection_id, Operation.view)
query = Q(id__in=list(query_collections))
result = queryset.filter(query)
if return_accesses:
return [(doc, collection_accesses[doc.id]) for doc in result]
else:
return result
def can_access(self, permissions_set, required_operation=Operation.view, strict_operation=False):
"""
:param permissions_set: A set of Permission objects to filter the collection query by.
:type permissions_set: set of [common.Permission]
:param required_operation: The minimum operation allowed on the collections.
:type required_operation: common.Operation
:param strict_operation: Make 'required_operation' strictly refer to an operation type, instead of a minimum.
:type strict_operation: bool
:rtype: CollectionQuerySet
"""
return self._filter_permissions(False, permissions_set, required_operation, strict_operation)
def with_accesses(self, permissions_set, required_operation=Operation.view, strict_operation=False):
"""
:param permissions_set: A set of Permission objects to filter the collection query by.
:type permissions_set: set of [common.Permission]
:param required_operation: The minimum operation allowed on the collections.
:type required_operation: common.Operation
:param strict_operation: Make 'required_operation' strictly refer to an operation type, instead of a minimum.
:type strict_operation: bool
:rtype: list of (Collection, Operation)
"""
return self._filter_permissions(True, permissions_set, required_operation, strict_operation)
################################################################################
class Collection(ModelDocument):
"""
An ImageStore holds image metadata and tiles.
"""
meta = {
'db_alias': 'admin_db',
'collection': 'collections',
'queryset_class': CollectionQuerySet,
}
image_store = ReferenceField(ImageStore, required=True,
verbose_name='Image Store', help_text='The default image store for content uploaded to this collection.')
label = StringField(required=True, #TODO: make unique
verbose_name='Label', help_text='The human-readable label.')
copyright = StringField(required=True, default='Copyright © 2014. All rights reserved.',
verbose_name='Copyright', help_text='The default copyright for content.')
creator_codes = ListField(StringField(), required=False,
verbose_name='Creator Codes', help_text='A list of identifier codes for images to be uploaded to this collection.')
|
github188/tunnel
|
tunnel-core/src/main/java/dll/struct/hw/PU_KF_CODING_STRATEGY_PARA.java
|
<reponame>github188/tunnel
package dll.struct;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* <i>native declaration : D:\HWPuSDK.h</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/"><NAME></a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class PU_KF_CODING_STRATEGY_PARA extends Structure {
public NativeLong ulChnID;
public boolean bEnable;
/** C type : PU_STREAM_TYPE_E */
public int enStreamType;
public NativeLong ulLevel;
public PU_KF_CODING_STRATEGY_PARA() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("ulChnID", "bEnable", "enStreamType", "ulLevel");
}
/** @param enStreamType C type : PU_STREAM_TYPE_E */
public PU_KF_CODING_STRATEGY_PARA(NativeLong ulChnID, boolean bEnable, int enStreamType, NativeLong ulLevel) {
super();
this.ulChnID = ulChnID;
this.bEnable = bEnable;
this.enStreamType = enStreamType;
this.ulLevel = ulLevel;
}
public PU_KF_CODING_STRATEGY_PARA(Pointer peer) {
super(peer);
}
public static class ByReference extends PU_KF_CODING_STRATEGY_PARA implements Structure.ByReference {
};
public static class ByValue extends PU_KF_CODING_STRATEGY_PARA implements Structure.ByValue {
};
}
|
ron2015schmitt/COOLL
|
include/expressionsRW.h
|
<filename>include/expressionsRW.h
#ifndef MATHQ__EXPRESSIONSRW_H
#define MATHQ__EXPRESSIONSRW_H
namespace mathq {
//---------------------------------------------------------------------------
// TERW_Subset Subset Expression
//---------------------------------------------------------------------------
template<class D>
class TERW_Subset : public TensorRW<TERW_Subset<D>, D, D, 1, 1> {
public:
constexpr static int Rvalue = 1;
constexpr static int Mvalue = 1;
typedef Materialize<D, D, Mvalue, Rvalue> XType;
typedef D EType;
typedef D DType;
private:
// can't be constant since we alow to be on left hand side
Vector<D>& x_;
const Vector<index_type>& ii_;
const bool delete_ii_;
VectorofPtrs* vptrs;
public:
typedef typename NumberType<D>::Type MyNumberType;
TERW_Subset(Vector<D>& x, const Vector<index_type>& ii)
: x_(x), ii_(ii), delete_ii_(false) {
vptrs = new VectorofPtrs();
vptrs->add(&x_);
vptrs->add(&ii_);
}
TERW_Subset(Vector<D>& x, const std::initializer_list<index_type>& list)
: x_(x), ii_(*(new Vector<index_type>(list))), delete_ii_(true) {
vptrs = new VectorofPtrs();
vptrs->add(&x_);
vptrs->add(&ii_);
}
~TERW_Subset() {
if (delete_ii_) delete& ii_;
delete vptrs;
}
const D dat(const index_type i) const {
index_type ind = ii_[i];
if (ind < 0) {
ind = x_.size() + ind;
}
return x_.dat(ind);
}
MyNumberType& dat(const index_type i) {
index_type ind = ii_[i];
if (ind < 0) {
ind = x_.size() + ind;
}
return x_.dat(ind);
}
const D operator[](const index_type i) const {
index_type ind = ii_[i];
if (ind < 0) {
ind = x_.size() + ind;
}
return x_[ind];
}
D& operator[](const index_type i) {
index_type ind = ii_[i];
if (ind < 0) {
ind = x_.size() + ind;
}
return x_[ind];
}
template <class Y, class D2>
TERW_Subset<D>& operator=(const TensorR<Y, D2, D2, Mvalue, Rvalue>& rhs) {
return this->equals(rhs);
}
TERW_Subset<D>& operator=(const D d) {
return this->equals(d);
}
//----------------------------------------------
VectorofPtrs getAddresses(void) const {
return *vptrs;
}
size_type size(void) const {
return ii_.size();
}
size_type ndims(void) const {
return x_.ndims();
}
Dimensions dims(void) const {
return x_.dims();
}
Dimensions tdims(void) const {
return this->dims();
}
std::vector<Dimensions>& deepdims(void) const {
return x_.deepdims();
}
std::vector<Dimensions>& deepdims(std::vector<Dimensions>& parentdims) const {
return x_.deepdims(parentdims);
}
bool isExpression(void) const {
return true;
}
size_type depth(void) const {
return Mvalue;
}
size_type elsize(void) const {
if constexpr (Mvalue<=1) {
return 1;
}
else {
return x_.elsize();
}
}
size_type eldeepsize(void) const {
if constexpr (Mvalue<=1) {
return 1;
}
else {
return x_.eldeepsize();
}
}
size_type deepsize(void) const {
if constexpr (Mvalue<=1) {
return this->size();
}
else {
return (this->size())*(this->eldeepsize());
}
}
std::string classname() const {
return "TERW_Subset";
}
#if MATRICKS_DEBUG>=1
std::string expression(void) const {
return "";
//return expression_TERW_Subset(a_.expression(),ii_.expression());
}
#endif
};
//--------------------------------------------------------------------------
// TERW_Submask Submask Expression
//--------------------------------------------------------------------------
template<class D>
class TERW_Submask : public TensorRW<TERW_Submask<D>, D, D, 1, 1> {
public:
constexpr static int Rvalue = 1;
constexpr static int Mvalue = 1;
typedef Materialize<D, D, Mvalue, Rvalue> XType;
typedef D EType;
typedef D DType;
private:
// can't be constant since we alow to be on left hand side
Vector<D>& x_;
const Vector<index_type>& ii_;
VectorofPtrs* vptrs;
public:
typedef typename NumberType<D>::Type MyNumberType;
TERW_Submask(Vector<D>& x, const Vector<bool>& mask)
: x_(x), ii_(*(new Vector<index_type>(findtrue(mask)))) {
vptrs = new VectorofPtrs();
vptrs->add(&x_);
vptrs->add(&ii_);
}
~TERW_Submask() {
delete& ii_;
delete vptrs;
}
const D dat(const index_type i) const {
index_type ind = ii_[i];
return x_.dat(ind);
}
MyNumberType& dat(const index_type i) {
index_type ind = ii_[i];
return x_.dat(ind);
}
const D operator[](const index_type i) const {
index_type ind = ii_[i];
return x_[ind];
}
D& operator[](const index_type i) {
index_type ind = ii_[i];
return x_[ind];
}
template <class Y, class D2>
TERW_Submask<D>& operator=(const TensorR<Y, D2, D2, Mvalue, Rvalue>& rhs) {
return this->equals(rhs);
}
TERW_Submask<D>& operator=(const D d) {
return this->equals(d);
}
//---------------------------------------------
VectorofPtrs getAddresses(void) const {
return *vptrs;
}
size_type size(void) const {
return ii_.size();
}
size_type ndims(void) const {
return x_.ndims();
}
Dimensions dims(void) const {
return x_.dims();
}
Dimensions tdims(void) const {
return this->dims();
}
std::vector<Dimensions>& deepdims(void) const {
return x_.deepdims();
}
std::vector<Dimensions>& deepdims(std::vector<Dimensions>& parentdims) const {
return x_.deepdims(parentdims);
}
bool isExpression(void) const {
return true;
}
size_type depth(void) const {
return Mvalue;
}
size_type elsize(void) const {
if constexpr (Mvalue<=1) {
return 1;
}
else {
return x_.elsize();
}
}
size_type eldeepsize(void) const {
if constexpr (Mvalue<=1) {
return 1;
}
else {
return x_.eldeepsize();
}
}
size_type deepsize(void) const {
if constexpr (Mvalue<=1) {
return this->size();
}
else {
return (this->size())*(this->eldeepsize());
}
}
std::string classname() const {
return "TERW_Submask";
}
#if MATRICKS_DEBUG>=1
std::string expression(void) const {
return "";
//return expression_TERW_Submask(a_.expression(),ii_.expression());
}
#endif
};
//---------------------------------------------------------------------------
// VERW_Join joining two Vectors (RHS only)
//---------------------------------------------------------------------------
template <class X, class Y, class E, class D, int M>
class TERW_Join : public TensorRW<TERW_Join<X, Y, E, D, M>, E, D, M, 1> {
public:
constexpr static int Rvalue = 1;
constexpr static int Mvalue = M;
typedef Materialize<E, D, M, Rvalue> XType;
typedef E EType;
typedef D DType;
private:
// can't be constant since we alow to be on left hand side
X& x_;
Y& y_;
VectorofPtrs* vptrs;
public:
TERW_Join(X& x, Y& y) : x_(x), y_(y) {
vptrs = new VectorofPtrs();
vptrs->add(x_.getAddresses());
vptrs->add(y_.getAddresses());
// DISP3(x);
}
~TERW_Join() {
delete vptrs;
}
const D dat(const index_type i) const {
if (i < x_.deepsize()) {
return x_.dat(i);
}
else {
return y_.dat(i-x_.deepsize());
}
}
D& dat(const index_type i) {
if (i < x_.deepsize()) {
return x_.dat(i);
}
else {
return y_.dat(i-x_.deepsize());
}
}
const E operator[](const index_type i) const {
if (i < x_.size()) {
return x_[i];
}
else {
return y_[i-x_.size()];
}
}
E& operator[](const index_type i) {
if (i < x_.size()) {
return x_[i];
}
else {
return y_[i-x_.size()];
}
}
template <class Z>
TERW_Join<X, Y, E, D, M>& operator=(const TensorR<Z, E, D, M, 1>& rhs) {
return this->equals(rhs);
}
TERW_Join<X, Y, E, D, M>& operator=(const D d) {
return this->equals(d);
}
TERW_Join<X, Y, E, D, M>& operator=(const E& e) {
return this->equals(e);
}
//----------------------------------------------
VectorofPtrs getAddresses(void) const {
return *vptrs;
}
size_type size(void) const {
return x_.size()+y_.size();
}
size_type ndims(void) const {
return Rvalue;
}
Dimensions dims(void) const {
Dimensions d(x_.size()+y_.size());
return d;
}
Dimensions tdims(void) const {
return this->dims();
}
std::vector<Dimensions>& deepdims(void) const {
std::vector<Dimensions>& ddims = *(new std::vector<Dimensions>);
return deepdims(ddims);
}
std::vector<Dimensions>& deepdims(std::vector<Dimensions>& parentdims) const {
const int N = parentdims.size();
std::vector<Dimensions>& ddims = x_.deepdims(parentdims);
ddims[N] = this->dims();
return ddims;
}
bool isExpression(void) const {
return true;
}
size_type depth(void) const {
return M;
}
Dimensions eldims(void) const {
return x_.eldims();
}
size_type elsize(void) const {
if constexpr (M<=1) {
return 1;
}
else {
return x_.elsize();
}
}
size_type eldeepsize(void) const {
if constexpr (M<=1) {
return 1;
}
else {
return x_.eldeepsize();
}
}
size_type deepsize(void) const {
if constexpr (M<=1) {
return this->size();
}
else {
return x_.deepsize() + y_.deepsize();
}
}
std::string classname() const {
return "TERW_Join";
}
#if MATHQ_DEBUG>=1
std::string expression(void) const {
std::string sx = x_.expression();
return sx;
}
#endif
};
// //---------------------------------------------------------------------------
// // TERW_RealFromComplex used for accessing real/imag part of complex vector
// //---------------------------------------------------------------------------
// template <class D, class OP, int M>
// class TERW_RealFromComplex : public TensorRW<D,TERW_RealFromComplex<D,OP,M> > {
// private:
// can't be constant since we alow to be on left hand side
// Vector<std::complex<D> >& a_;
// VectorofPtrs *vptrs;
// public:
// typedef typename NumberType<D>::Type MyNumberType;
// TERW_RealFromComplex(Vector<std::complex<D> >& a)
// : a_(a) {
// vptrs = new VectorofPtrs();
// vptrs->add(&a_);
// }
// ~TERW_RealFromComplex() {
// delete vptrs;
// }
// const D operator[](index_type i) const{
// return OP::give(a_[i]);
// }
// D& operator[](index_type i) {
// return OP::give(a_[i]);
// }
// const MyNumberType dat(const index_type i) const {
// return OP::give(a_.dat(i));
// }
// MyNumberType& dat(const index_type i) {
// return OP::give(a_.dat(i));
// }
// VectorofPtrs getAddresses(void) const {
// return *vptrs;
// }
// size_type size(void) const {
// return a_.size();
// }
// size_type ndims(void) const {
// return a_.ndims();
// }
// Dimensions dims(void) const {
// return a_.dims();
// }
// bool isExpression(void) const {
// return true;
// }
// size_type depth(void) const {
// return M;
// }
// size_type elsize(void) const {
// if constexpr(M<2) {
// return 1;
// } else {
// return a_.elsize();
// }
// }
// size_type eldeepsize(void) const {
// if constexpr(M<2) {
// return 1;
// } else {
// return a_.eldeepsize();
// }
// }
// size_type deepsize(void) const {
// if constexpr(M<2) {
// return this->size();
// } else {
// return (this->size())*(this->eldeepsize());
// }
// }
// std::string classname() const {
// return "TERW_RealFromComplex";
// }
// template <class D2, class B>
// TERW_RealFromComplex<D,OP,M>& operator=(const TensorR<D2,B>& rhs) {
// return this->equals(rhs);
// }
// TERW_RealFromComplex<D,OP,M>& operator=(const MyNumberType d) {
// return this->equals(d);
// }
// #if MATRICKS_DEBUG>=1
// std::string expression(void) const {
// return a_.expression();
// // return expression_VSliceObj(a_.expression(),start_,end_,step_);
// }
// #endif
// };
};
#endif
|
shunfei/indexr
|
indexr-common/src/main/java/io/indexr/data/DictStruct.java
|
package io.indexr.data;
import io.indexr.util.MemoryUtil;
import static io.indexr.util.MemoryUtil.getDouble;
import static io.indexr.util.MemoryUtil.getFloat;
import static io.indexr.util.MemoryUtil.getInt;
import static io.indexr.util.MemoryUtil.getLong;
import static io.indexr.util.MemoryUtil.setDouble;
import static io.indexr.util.MemoryUtil.setFloat;
import static io.indexr.util.MemoryUtil.setInt;
import static io.indexr.util.MemoryUtil.setLong;
/**
* A class help explain the structure of dict encoding.
* <pre>
* | entryCount | dict | dataSize | data(encoded ids) |
* 4 dictSize 4 dataSize
* </pre>
*/
public final class DictStruct {
private final byte dataType;
private final long addr;
private final int dictEntryCount;
private final int dictSize;
private final int dataSize;
private final StringsStruct stringDictEntries;
public DictStruct(byte dataType, long addr) {
this.dataType = dataType;
this.addr = addr;
this.dictEntryCount = MemoryUtil.getInt(addr);
if (DataType.isNumber(dataType)) {
this.stringDictEntries = null;
this.dictSize = dictEntryCount << DataType.numTypeShift(dataType);
} else {
this.stringDictEntries = new StringsStruct(dictEntryCount, addr + 4);
this.dictSize = stringDictEntries.totalLen();
}
this.dataSize = MemoryUtil.getInt(addr + 4 + dictSize);
}
// @formatter:off
public byte dataType(){return dataType;}
public long addr() {return addr;}
public int size(){return 4 + dictSize + 4 + dataSize;}
public int dictEntryCount() {return dictEntryCount;}
public int dictSize() {return dictSize;}
public long dictEntriesAddr() {return addr + 4;}
public StringsStruct stringDictEntries() {return stringDictEntries;}
public int dataSize() {return dataSize;}
public long dataAddr() {return addr + 4 + dictSize + 4;}
// @formatter:on
public void decodeInts(int valCount, long outputAddr) {
long dataAddr = dataAddr();
long dictEntriesAddr = dictEntriesAddr();
for (int i = 0; i < valCount; i++) {
int vid = getInt(dataAddr + (i << 2));
int v = getInt(dictEntriesAddr + (vid << 2));
setInt(outputAddr + (i << 2), v);
}
}
public void decodeLongs(int valCount, long outputAddr) {
long dataAddr = dataAddr();
long dictEntriesAddr = dictEntriesAddr();
for (int i = 0; i < valCount; i++) {
int vid = getInt(dataAddr + (i << 2));
long v = getLong(dictEntriesAddr + (vid << 3));
setLong(outputAddr + (i << 3), v);
}
}
public void decodeFloats(int valCount, long outputAddr) {
long dataAddr = dataAddr();
long dictEntriesAddr = dictEntriesAddr();
for (int i = 0; i < valCount; i++) {
int vid = getInt(dataAddr + (i << 2));
float v = getFloat(dictEntriesAddr + (vid << 2));
setFloat(outputAddr + (i << 2), v);
}
}
public void decodeDoubles(int valCount, long outputAddr) {
long dataAddr = dataAddr();
long dictEntriesAddr = dictEntriesAddr();
for (int i = 0; i < valCount; i++) {
int vid = getInt(dataAddr + (i << 2));
double v = getDouble(dictEntriesAddr + (vid << 3));
setDouble(outputAddr + (i << 3), v);
}
}
public void decodeStrings(int valCount, long outputAddr) {
long dataAddr = dataAddr();
long dictEntriesAddr = dictEntriesAddr();
StringsStruct stringDictEntries = stringDictEntries();
StringsStruct.Builder stringDataBuilder = new StringsStruct.Builder(valCount, outputAddr);
OffheapBytes container = new OffheapBytes();
for (int i = 0; i < valCount; i++) {
int vid = getInt(dataAddr + (i << 2));
stringDictEntries.getString(vid, container);
stringDataBuilder.addString(null, container.addr(), container.len());
}
stringDataBuilder.build();
}
}
|
zealoussnow/chromium
|
ui/accessibility/extensions/chromevoxclassic/host/interface/braille_interface.js
|
<filename>ui/accessibility/extensions/chromevoxclassic/host/interface/braille_interface.js
// 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.
/**
* @fileoverview Defines a Braille interface.
*
* All Braille engines in ChromeVox conform to this interface.
*
*/
goog.provide('cvox.BrailleInterface');
goog.require('cvox.BrailleKeyCommand');
goog.require('cvox.BrailleKeyEvent');
goog.require('cvox.NavBraille');
/**
* @interface
*/
cvox.BrailleInterface = function() { };
/**
* Sends the given params to the Braille display for output.
* @param {!cvox.NavBraille} params Parameters to send to the
* platform braille service.
*/
cvox.BrailleInterface.prototype.write =
function(params) { };
|
ruhan1/indy
|
core/src/main/java/org/commonjava/indy/core/content/RepairChecksumAdvisor.java
|
/**
* Copyright (C) 2011-2019 Red Hat, Inc. (https://github.com/Commonjava/indy)
*
* 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.commonjava.indy.core.content;
import org.commonjava.indy.content.IndyChecksumAdvisor;
import org.commonjava.indy.model.core.StoreType;
import org.commonjava.indy.model.galley.KeyedLocation;
import org.commonjava.maven.galley.event.EventMetadata;
import org.commonjava.maven.galley.io.checksum.ChecksummingDecoratorAdvisor;
import org.commonjava.maven.galley.model.Location;
import org.commonjava.maven.galley.model.Transfer;
import org.commonjava.maven.galley.model.TransferOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import static org.commonjava.indy.core.content.ContentMetadataGenerator.FORCE_CHECKSUM_AND_WRITE;
import static org.commonjava.maven.galley.io.checksum.ChecksummingDecoratorAdvisor.ChecksumAdvice.CALCULATE_AND_WRITE;
public class RepairChecksumAdvisor
implements IndyChecksumAdvisor
{
@Override
public Optional<ChecksummingDecoratorAdvisor.ChecksumAdvice> getChecksumReadAdvice( Transfer transfer,
TransferOperation operation,
EventMetadata eventMetadata )
{
Logger logger = LoggerFactory.getLogger( getClass() );
Location loc = transfer.getLocation();
Object forceObj = eventMetadata.get( FORCE_CHECKSUM_AND_WRITE );
boolean force = Boolean.TRUE.equals( forceObj ) || Boolean.parseBoolean( String.valueOf( forceObj ) );
if ( force && ( loc instanceof KeyedLocation
&& ( (KeyedLocation) loc ).getKey().getType() == StoreType.hosted ) )
{
logger.debug( "Enable checksumming for {} of: {} with advice: CALCULATE_AND_WRITE", operation, transfer );
return Optional.of( CALCULATE_AND_WRITE );
}
logger.debug( "Skip checksumming for {} of: {}", operation, transfer );
return Optional.empty();
}
@Override
public Optional<ChecksummingDecoratorAdvisor.ChecksumAdvice> getChecksumWriteAdvice( Transfer transfer,
TransferOperation operation,
EventMetadata eventMetadata )
{
return Optional.empty();
}
}
|
zettadb/zettalib
|
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/writeengine/wrapper/we_colopcompress.cpp
|
/* Copyright (C) 2014 InfiniDB, Inc.
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., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
// $Id: we_colopcompress.cpp 4726 2013-08-07 03:38:36Z bwilkinson $
/** @file */
#include <stdio.h>
#include <string.h>
#include <vector>
#include "we_log.h"
#include "we_chunkmanager.h"
#include "idbcompress.h"
#include "we_colopcompress.h"
namespace WriteEngine
{
class ChunkManager;
// --------------------------------------------------------------------------------------------
// ColumnOp with compression type 0
// --------------------------------------------------------------------------------------------
/**
* Constructor
*/
ColumnOpCompress0::ColumnOpCompress0()
{
m_compressionType = 0;
}
ColumnOpCompress0::ColumnOpCompress0(Log* logger)
{
m_compressionType = 0;
setDebugLevel( logger->getDebugLevel() );
setLogger ( logger );
}
/**
* Default Destructor
*/
ColumnOpCompress0::~ColumnOpCompress0()
{}
// @bug 5572 - HDFS usage: add *.tmp file backup flag
IDBDataFile* ColumnOpCompress0::openFile(
const Column& column, const uint16_t dbRoot, const uint32_t partition, const uint16_t segment,
std::string& segFile, bool useTmpSuffix, const char* mode, const int ioBuffSize) const
{
return FileOp::openFile(column.dataFile.fid, dbRoot, partition, segment, segFile,
mode, column.colWidth, useTmpSuffix);
}
bool ColumnOpCompress0::abbreviatedExtent(IDBDataFile* pFile, int colWidth) const
{
long long fsize;
if (getFileSize(pFile, fsize) == NO_ERROR)
{
return (fsize == INITIAL_EXTENT_ROWS_TO_DISK * colWidth);
}
// TODO: Log error
return false;
}
int ColumnOpCompress0::blocksInFile(IDBDataFile* pFile) const
{
long long fsize;
if (getFileSize(pFile, fsize) == NO_ERROR)
{
return (fsize / BYTE_PER_BLOCK);
}
// TODO: Log error
return 0;
}
int ColumnOpCompress0::readBlock(IDBDataFile* pFile, unsigned char* readBuf, const uint64_t fbo)
{
return readDBFile(pFile, readBuf, fbo, true);
}
int ColumnOpCompress0::saveBlock(IDBDataFile* pFile, const unsigned char* writeBuf, const uint64_t fbo)
{
return writeDBFileFbo(pFile, writeBuf, fbo, 1);
}
// --------------------------------------------------------------------------------------------
// ColumnOp with compression type 1
// --------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------
/**
* Constructor
*/
ColumnOpCompress1::ColumnOpCompress1(uint32_t compressionType, Log* logger)
{
m_compressionType = compressionType;
m_chunkManager = new ChunkManager();
if (logger)
{
setDebugLevel( logger->getDebugLevel() );
setLogger ( logger );
}
m_chunkManager->fileOp(this);
}
/**
* Default Destructor
*/
ColumnOpCompress1::~ColumnOpCompress1()
{
if (m_chunkManager)
{
delete m_chunkManager;
}
}
// @bug 5572 - HDFS usage: add *.tmp file backup flag
IDBDataFile* ColumnOpCompress1::openFile(
const Column& column, const uint16_t dbRoot, const uint32_t partition, const uint16_t segment,
std::string& segFile, bool useTmpSuffix, const char* mode, const int ioBuffSize) const
{
return m_chunkManager->getFilePtr(column, dbRoot, partition, segment, segFile,
mode, ioBuffSize, useTmpSuffix);
}
bool ColumnOpCompress1::abbreviatedExtent(IDBDataFile* pFile, int colWidth) const
{
return (blocksInFile(pFile) == INITIAL_EXTENT_ROWS_TO_DISK * colWidth / BYTE_PER_BLOCK);
}
int ColumnOpCompress1::blocksInFile(IDBDataFile* pFile) const
{
return m_chunkManager->getBlockCount(pFile);
}
int ColumnOpCompress1::readBlock(IDBDataFile* pFile, unsigned char* readBuf, const uint64_t fbo)
{
return m_chunkManager->readBlock(pFile, readBuf, fbo);
}
int ColumnOpCompress1::saveBlock(IDBDataFile* pFile, const unsigned char* writeBuf, const uint64_t fbo)
{
return m_chunkManager->saveBlock(pFile, writeBuf, fbo);
}
int ColumnOpCompress1::flushFile(int rc, std::map<FID, FID>& columnOids)
{
return m_chunkManager->flushChunks(rc, columnOids);
}
int ColumnOpCompress1::expandAbbrevColumnExtent(
IDBDataFile* pFile, uint16_t dbRoot, const uint8_t* emptyVal, int width,
execplan::CalpontSystemCatalog::ColDataType colDataType )
{
// update the uncompressed initial chunk to full chunk
int rc = m_chunkManager->expandAbbrevColumnExtent(pFile, emptyVal, width);
// ERR_COMP_FILE_NOT_FOUND is acceptable here. It just means that the
// file hasn't been loaded into the chunk manager yet. No big deal.
if (rc != NO_ERROR && rc != ERR_COMP_FILE_NOT_FOUND)
{
return rc;
}
// let the base to physically expand extent.
return FileOp::expandAbbrevColumnExtent(pFile, dbRoot, emptyVal, width,
colDataType);
}
int ColumnOpCompress1::updateColumnExtent(IDBDataFile* pFile, int nBlocks, int64_t lbid)
{
return m_chunkManager->updateColumnExtent(pFile, nBlocks, lbid);
}
void ColumnOpCompress1::closeColumnFile(Column& column) const
{
// Leave file closing to chunk manager.
column.dataFile.pFile = NULL;
}
} //end of namespace
|
ticuss/Mon-parcours
|
SDA1/iterateurs/ex2/liste.c
|
#include "liste.h"
#include <stdlib.h>
struct liste {
S element;
struct liste *suivant;
struct liste *precedent;
};
liste *liste_vide(void) {
return NULL;
}
void liste_free(liste *const l) {
liste *parcours = l;
while (parcours) {
liste *next = parcours->suivant;
free(parcours);
parcours = next;
}
}
liste *liste_insertion(liste *l, S x) {
liste *const nouveau_maillon = malloc(sizeof *nouveau_maillon);
nouveau_maillon->element = x;
nouveau_maillon->suivant = l;
nouveau_maillon->precedent = l ? l->precedent : NULL;
if (l) {
if (l->precedent)
l->precedent->suivant = nouveau_maillon;
l->precedent = l;
}
return nouveau_maillon;
}
liste *liste_insertion_tete(liste *l, S x) {
liste *const nouveau_maillon = malloc(sizeof *nouveau_maillon);
nouveau_maillon->element = x;
liste *const debut = liste_debut(l);
nouveau_maillon->precedent = NULL;
nouveau_maillon->suivant = debut;
if (debut)
debut->precedent = nouveau_maillon;
return nouveau_maillon;
}
liste *liste_insertion_queue(liste *l, S x) {
liste *const nouveau_maillon = malloc(sizeof *nouveau_maillon);
nouveau_maillon->element = x;
liste *const fin = liste_fin(l);
nouveau_maillon->precedent = fin;
nouveau_maillon->suivant = NULL;
if (fin)
fin->suivant = nouveau_maillon;
return nouveau_maillon;
}
liste *liste_suppression_tete(liste *l) {
if (!l)
return NULL;
liste *const debut = liste_debut(l);
liste *const retour = debut->suivant;
free(debut);
if (retour)
retour->precedent = NULL;
return retour;
}
liste *liste_suppression_queue(liste *l) {
if (!l)
return NULL;
liste *const fin = liste_fin(l);
liste *const retour = fin->precedent;
free(fin);
if (retour)
retour->suivant = NULL;
return retour;
}
liste *liste_fin(const liste *const l) {
if (!l)
return NULL;
const liste *parcours = l;
while (parcours->suivant)
parcours = parcours->suivant;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
return (liste *) parcours;
#pragma GCC diagnostic pop
}
liste *liste_debut(const liste *l) {
if (!l)
return NULL;
const liste *parcours = l;
while (parcours->precedent)
parcours = parcours->precedent;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
return (liste *) parcours;
#pragma GCC diagnostic pop
}
liste *liste_suivant(const liste *l) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
return (liste *) (l ? l->suivant : l);
#pragma GCC diagnostic pop
}
liste *liste_precedent(const liste *l) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
return (liste *) (l ? l->precedent : l);
#pragma GCC diagnostic pop
}
liste *liste_ieme(const liste *l, size_t n) {
liste *parcours = liste_debut(l);
for (size_t i = 0; parcours && i < n; ++i)
parcours = parcours->suivant;
return parcours;
}
S liste_element(const liste *l) {
return l->element;
}
bool liste_est_vide(const liste *l) {
return l ? false : true;
}
size_t liste_longueur(const liste *l) {
size_t longueur = 0;
for (const liste *parcours = l; parcours; parcours = parcours->suivant)
longueur++;
return longueur;
}
|
enigmax980/simba
|
src/main/java/com/chinalife/simba/dao/SmbFuseMapper.java
|
<gh_stars>0
package com.chinalife.simba.dao;
import com.chinalife.simba.model.SmbFuse;
import com.chinalife.simba.model.SmbFuseExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SmbFuseMapper {
long countByExample(SmbFuseExample example);
int deleteByExample(SmbFuseExample example);
int deleteByPrimaryKey(Integer fs_id);
int insert(SmbFuse record);
int insertSelective(SmbFuse record);
List<SmbFuse> selectByExample(SmbFuseExample example);
SmbFuse selectByPrimaryKey(Integer fs_id);
int updateByExampleSelective(@Param("record") SmbFuse record, @Param("example") SmbFuseExample example);
int updateByExample(@Param("record") SmbFuse record, @Param("example") SmbFuseExample example);
int updateByPrimaryKeySelective(SmbFuse record);
int updateByPrimaryKey(SmbFuse record);
}
|
ognjenjevremovic/pretty-easy-crud
|
lib/crud_methods/find.js
|
// Dependancies
var constructQuery = require('../construct').query,
validate = require('../validation'),
log = require('../logger'),
messages = require('../messages');
/*
* Function accepts 2 parameters
* (query<Object> && ?callbackPassed<function>)
*
* Returns CRUD instance
*
* Must be bind to the call (CRUD instance 'find' method)!
* find.bind(this)
*
*/
function findDocuments(query, callbackPassed) {
'use strict';
/* jshint validthis : true*/
var constructorInstance = this;
// init
var collection, configuration, queryDocument;
// Populate variables
collection = constructorInstance.collection;
configuration = constructorInstance.configuration;
// Define the query
queryDocument = constructQuery.call(this, query);
// Document invalid - return CRUD instance
if (!queryDocument) {
return constructorInstance;
}
// Document valid - Insert document
else {
_queryCollection(queryDocument, collection, configuration, callbackPassed, constructorInstance);
return constructorInstance;
}
}
// Query the collection
function _queryCollection(queryDocument, collection, configuration, callbackPassed, constructorInstance) {
'use strict';
// init
var messageToLog;
// Return a Promise
return new Promise(promise_cb);
// Promise callback
function promise_cb(resolve, reject) {
// Query the collection
return collection
.find(queryDocument)
.toArray()
.then(queryCollection_cb)
.catch(exception);
// Query document callback
function queryCollection_cb(documentsFound) {
// Log if specified
messageToLog = messages('document.info.documentsFound', documentsFound.length);
if (configuration.includeLogs.indexOf(messageToLog.type) > -1) {
log.info(messageToLog.message);
}
// Run callback if supplied
if (callbackPassed && validate.callback(callbackPassed)) {
callbackPassed(null, documentsFound);
}
}
// Exception
function exception(errorQueryingCollection) {
// Log the error (errors are always logged)
messageToLog = messages('collection.error.queryingCollection');
log.error(messageToLog.message);
// Callback supplied
if (callbackPassed && validate.callback(callbackPassed)) {
callbackPassed(messageToLog.message, null);
}
}
}
}
// Export the module
module.exports = findDocuments;
|
Nayls/shortlink
|
internal/services/link/infrastructure/store/cqrs/query/postgres/query.go
|
package postgres
import (
"context"
"database/sql"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/batazor/shortlink/internal/pkg/db"
v1 "github.com/batazor/shortlink/internal/services/link/domain/link/v1"
v12 "github.com/batazor/shortlink/internal/services/link/domain/link_cqrs/v1"
"github.com/batazor/shortlink/internal/services/link/infrastructure/store/crud/query"
)
var (
psql = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar) // nolint unused
)
// New ...
func New(ctx context.Context, db *db.Store) (*Store, error) {
s := &Store{}
// Set configuration
s.client = db.Store.GetConn().(*pgxpool.Pool)
return s, nil
}
// Get ...
func (s *Store) Get(ctx context.Context, id string) (*v12.LinkView, error) {
// query builder
links := psql.Select("url, hash, describe", "image_url", "meta_description", "meta_keywords").
From("shortlink.link_view").
Where(squirrel.Eq{"hash": id})
q, args, err := links.ToSql()
if err != nil {
return nil, err
}
rows, err := s.client.Query(ctx, q, args...)
if err != nil {
return nil, &v1.NotFoundError{Link: &v1.Link{Hash: id}, Err: fmt.Errorf("Not found id: %s", id)}
}
if rows.Err() != nil {
return nil, &v1.NotFoundError{Link: &v1.Link{Hash: id}, Err: fmt.Errorf("Not found id: %s", id)}
}
var response v12.LinkView
for rows.Next() {
err = rows.Scan(&response.Url, &response.Hash, &response.Describe, &response.ImageUrl, &response.MetaDescription, &response.MetaKeywords)
if err != nil {
return nil, &v1.NotFoundError{Link: &v1.Link{Hash: id}, Err: fmt.Errorf("Not found id: %s", id)}
}
}
if response.Hash == "" {
return nil, &v1.NotFoundError{Link: &v1.Link{Hash: id}, Err: fmt.Errorf("Not found id: %s", id)}
}
return &response, nil
}
// List ...
func (s *Store) List(ctx context.Context, filter *query.Filter) (*v12.LinksView, error) {
// query builder
links := psql.Select("hash, describe, ts_headline(meta_description, q, 'StartSel=<em>, StopSel=</em>') as meta_description, created_at, updated_at").
From(fmt.Sprintf(`shortlink.link_view, to_tsquery('%s') AS q`, *filter.Search.Contains)).
Where("make_tsvector_link_view(meta_keywords, meta_description) @@ q").
OrderBy("ts_rank(make_tsvector_link_view(meta_keywords, meta_description), q) DESC").
Limit(uint64(filter.Pagination.Limit)).
Offset(uint64(filter.Pagination.Page * filter.Pagination.Limit))
q, args, err := links.ToSql()
if err != nil {
return nil, err
}
rows, err := s.client.Query(ctx, q, args...)
if err != nil {
return nil, &v1.NotFoundError{Link: &v1.Link{}, Err: fmt.Errorf("Not found links")}
}
response := &v12.LinksView{
Links: []*v12.LinkView{},
}
for rows.Next() {
var result v12.LinkView
var (
created_ad sql.NullTime
updated_at sql.NullTime
)
err = rows.Scan(&result.Hash, &result.Describe, &result.MetaDescription, &created_ad, &updated_at)
if err != nil {
return nil, &v1.NotFoundError{Link: &v1.Link{}, Err: fmt.Errorf("Not found links")}
}
result.CreatedAt = ×tamp.Timestamp{Seconds: int64(created_ad.Time.Second()), Nanos: int32(created_ad.Time.Nanosecond())}
result.UpdatedAt = ×tamp.Timestamp{Seconds: int64(updated_at.Time.Second()), Nanos: int32(updated_at.Time.Nanosecond())}
response.Links = append(response.Links, &result)
}
return response, nil
}
|
RichyHBM/monzo-scala
|
src/main/scala/monzo_scala/models/webhooks/WebhookList.scala
|
<reponame>RichyHBM/monzo-scala
package monzo_scala.models.webhooks
import monzo_scala.models.JsonModel
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, Reads, Writes}
case class WebhookList(webhooks: Seq[Webhook]) extends JsonModel {
override def toJson(): String = Json.stringify(Json.toJson(this))
}
object WebhookList {
def fromJson(json: String): WebhookList = Json.parse(json).as[WebhookList]
implicit val reads: Reads[WebhookList] = (JsPath \ "webhooks").read[Seq[Webhook]].map(WebhookList(_))
implicit val writes: Writes[WebhookList] = (JsPath \ "webhooks").write[Seq[Webhook]].contramap[WebhookList](_.webhooks)
}
|
ben-sangster/js
|
modules/v8/dmzJsModuleRuntimeV8Basic.cpp
|
<gh_stars>1-10
#include "dmzJsModuleRuntimeV8Basic.h"
#include <dmzJsModuleV8.h>
#include <dmzJsModuleTypesV8.h>
#include <dmzJsV8UtilConvert.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
dmz::JsModuleRuntimeV8Basic::JsModuleRuntimeV8Basic (
const PluginInfo &Info,
Config &local) :
Plugin (Info),
JsModuleRuntimeV8 (Info),
JsExtV8 (Info),
UndoObserver (Info),
_log (Info),
_time (Info),
_defs (Info, &_log),
_undo (Info),
_convertBool (Info),
_convertNum (Info),
_convertStr (Info),
_convertHandle (Info),
_core (0),
_types (0) {
_init (local);
}
dmz::JsModuleRuntimeV8Basic::~JsModuleRuntimeV8Basic () {
_self.Dispose (); _self.Clear ();
}
// Plugin Interface
void
dmz::JsModuleRuntimeV8Basic::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::JsModuleRuntimeV8Basic::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
if (!_types) {
_types = JsModuleTypesV8::cast (PluginPtr);
}
}
else if (Mode == PluginDiscoverRemove) {
if (_types && (_types == JsModuleTypesV8::cast (PluginPtr))) {
_types = 0;
}
}
}
// JsExtV8 Interface
void
dmz::JsModuleRuntimeV8Basic::update_js_module_v8 (
const ModeEnum Mode,
JsModuleV8 &module) {
if (Mode == JsExtV8::Store) {
if (!_core) { _core = &module; }
}
else if (Mode == JsExtV8::Remove) {
if (_core == &module) { _core = 0; }
}
}
void
dmz::JsModuleRuntimeV8Basic::update_js_context_v8 (v8::Handle<v8::Context> context) {
_v8Context = context;
}
void
dmz::JsModuleRuntimeV8Basic::update_js_ext_v8_state (const StateEnum State) {
v8::HandleScope scope;
if (State == JsExtV8::Register) {
if (_configFuncTemplate.IsEmpty () == false) {
_configFunc = V8FunctionPersist::New (_configFuncTemplate->GetFunction ());
}
if (_dataFuncTemplate.IsEmpty () == false) {
_dataFunc = V8FunctionPersist::New (_dataFuncTemplate->GetFunction ());
}
if (_eventTypeFuncTemplate.IsEmpty () == false) {
_eventTypeFunc = V8FunctionPersist::New (_eventTypeFuncTemplate->GetFunction ());
}
if (_logFuncTemplate.IsEmpty () == false) {
_logFunc = V8FunctionPersist::New (_logFuncTemplate->GetFunction ());
}
if (_msgFuncTemplate.IsEmpty () == false) {
_msgFunc = V8FunctionPersist::New (_msgFuncTemplate->GetFunction ());
}
if (_objTypeFuncTemplate.IsEmpty () == false) {
_objTypeFunc = V8FunctionPersist::New (_objTypeFuncTemplate->GetFunction ());
}
if (_sphereTemplate.IsEmpty () == false) {
_sphereFunc = V8FunctionPersist::New (_sphereTemplate->GetFunction ());
}
if (_core) {
_core->register_interface (
"dmz/runtime/config",
_configApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/data",
_dataApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/definitions",
_defsApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/eventType",
_eventTypeApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/log",
_logApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/messaging",
_msgApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/objectType",
_objTypeApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/time",
_timeApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/undo",
_undoApi.get_new_instance ());
_core->register_interface (
"dmz/runtime/sphere",
_sphereApi.get_new_instance ());
}
}
else if (State == JsExtV8::Init) {
}
else if (State == JsExtV8::Shutdown) {
_configFunc.Dispose (); _configFunc.Clear ();
_dataFunc.Dispose (); _dataFunc.Clear ();
_eventTypeFunc.Dispose (); _eventTypeFunc.Clear ();
_logFunc.Dispose (); _logFunc.Clear ();
_msgFunc.Dispose (); _msgFunc.Clear ();
_objTypeFunc.Dispose (); _objTypeFunc.Clear ();
_sphereFunc.Dispose (); _sphereFunc.Clear ();
_configApi.clear ();
_dataApi.clear ();
_defsApi.clear ();
_eventTypeApi.clear ();
_logApi.clear ();
_msgApi.clear ();
_objTypeApi.clear ();
_timeApi.clear ();
_undoApi.clear ();
_sphereApi.clear ();
_reset_time ();
_reset_messaging ();
_reset_undo ();
_v8Context.Clear ();
}
}
void
dmz::JsModuleRuntimeV8Basic::release_js_instance_v8 (
const Handle InstanceHandle,
const String &InstanceName,
v8::Handle<v8::Object> &instance) {
_release_message_observer (InstanceHandle);
_release_timer (InstanceHandle);
_release_undo_observer (InstanceHandle);
}
// JsModuleRuntimeV8Basic Interface
void
dmz::JsModuleRuntimeV8Basic::handle_v8_exception (const Handle Source, v8::TryCatch &tc) {
if (_core) { _core->handle_v8_exception (Source, tc); }
}
dmz::Handle
dmz::JsModuleRuntimeV8Basic::_to_handle (V8Value value) {
Handle result (0);
if (value.IsEmpty () == false) {
if (value->IsInt32 ()) { result = value->Uint32Value (); }
else if (value->IsString ()) {
const String Str = *(v8::String::AsciiValue (value));
if (Str) { result = _defs.create_named_handle (Str); }
}
}
return result;
}
void
dmz::JsModuleRuntimeV8Basic::_init (Config &local) {
v8::HandleScope scope;
_self = V8ValuePersist::New (v8::External::Wrap (this));
_init_config ();
_init_data ();
_init_definitions ();
_init_event_type ();
_init_log ();
_init_messaging ();
_init_object_type ();
_init_time ();
_init_undo ();
_init_sphere ();
}
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzJsModuleRuntimeV8Basic (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::JsModuleRuntimeV8Basic (Info, local);
}
};
|
axiom6/aug
|
pub/vizu/main/Render.js
|
<gh_stars>0
var Render;
import {
WebGLRenderer,
PCFSoftShadowMap,
sRGBEncoding
} from 'three';
Render = class Render {
constructor(main) {
this.onResize = this.onResize.bind(this);
this.main = main;
this.klass = this.constructor.name;
this.opts = this.main.opts.render != null ? this.main.opts.render : {};
this.clearColor = this.opts.clearColor != null ? this.opts.clearColor : 0x000000; // 0x333F47, 1
this.renderer = new WebGLRenderer({
antialias: true
});
this.main.elem.appendChild(this.renderer.domElement);
this.renderer.setSize(this.main.screenWidth, this.main.screenHeight);
this.renderer.setClearColor(this.clearColor, 1);
this.renderer.setPixelRatio(window.devicePixelRatio);
if ((this.opts.shadowMap != null) && this.opts.shadowMap) {
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = PCFSoftShadowMap;
this.renderer.shadowMapSoft = true;
this.renderer.outputEncoding = sRGBEncoding;
}
this.main.stream.subscribe('Resize', this.klass, (obj) => {
return this.onResize(obj);
});
this.main.log(this.klass + '()', this);
}
onResize(obj) {
this.main.log(this.klass + '.onResize()', obj);
this.renderer.setSize(obj.screenWidth, obj.screenHeight);
}
};
export default Render;
//# sourceMappingURL=Render.js.map
|
nomadsinteractive/ark
|
plugin/box2d/forwarding.h
|
<gh_stars>1-10
#ifndef ARK_PLUGIN_BOX2D_FORWARDING_H_
#define ARK_PLUGIN_BOX2D_FORWARDING_H_
namespace ark {
namespace plugin {
namespace box2d {
class RigidBodyBox2D;
class BodyCreateInfo;
class Joint;
class Shape;
class ColliderBox2D;
}
}
}
#endif
|
mrdulin/python-codelab
|
src/stackoverflow/64708057/compute_examples.py
|
<reponame>mrdulin/python-codelab<gh_stars>0
class Compute:
def add(self, var1=0, var2=0):
return var1 + var2
|
201244010/store
|
src/pages/User/Login/MobileLogin.js
|
<reponame>201244010/store
import React, { Component } from 'react';
import { formatMessage } from 'umi/locale';
import { Form, Alert, Icon, Input, message } from 'antd';
import { ALERT_NOTICE_MAP, ERROR_OK, SHOW_VCODE, VCODE_ERROR } from '@/constants/errorCode';
import Captcha from '@/components/Captcha';
import ImgCaptchaModal from '@/components/Captcha/ImgCaptchaModal';
import { cellphone } from '@/constants/regexp';
import styles from '@/pages/User/Login/Login.less';
class MobileLogin extends Component {
constructor(props) {
super(props);
this.state = {
showImgCaptchaModal: false,
trigger: false,
};
}
getCode = async (params = {}) => {
const { imageStyle = {} } = params;
const {
form: { getFieldValue },
sendCode,
imgCaptcha,
needImgCaptcha,
} = this.props;
const response = await sendCode({
options: {
username: getFieldValue('phone'),
type: '2',
imgCode: getFieldValue('vcode2') || '',
key: needImgCaptcha ? imgCaptcha.key : '',
width: 76,
height: 30,
fontSize: 16,
...imageStyle,
},
});
if (response && response.code === ERROR_OK) {
message.success(formatMessage({ id: 'send.mobile.code.success' }));
this.setState({
trigger: true,
showImgCaptchaModal: false,
});
} else if (response && !response.data) {
if (Object.keys(ALERT_NOTICE_MAP).includes(`${response.code}`)) {
this.setState({
trigger: false,
});
}
} else if (response && [SHOW_VCODE, VCODE_ERROR].includes(response.code)) {
this.setState({ showImgCaptchaModal: true });
}
return response;
};
refreshCode = async (params = {}) => {
const { imageStyle = {} } = params;
const {
form: { getFieldValue },
sendCode,
} = this.props;
const response = await sendCode({
options: {
username: getFieldValue('phone'),
type: '2',
imgCode: '',
key: '',
width: 76,
height: 30,
fontSize: 16,
...imageStyle,
},
});
return response;
};
closeImgCaptchaModal = () => {
this.setState({ showImgCaptchaModal: false });
};
render() {
const { trigger, showImgCaptchaModal } = this.state;
const {
form,
form: { getFieldDecorator, getFieldValue },
imgCaptcha,
notice,
} = this.props;
return (
<>
{notice && (
<Form.Item>
<Alert
message={formatMessage({
id: ALERT_NOTICE_MAP[notice],
})}
type="error"
showIcon
/>
</Form.Item>
)}
<Form.Item className={notice ? '' : `${styles['formItem-with-margin']}`}>
{getFieldDecorator('phone', {
validateTrigger: 'onBlur',
rules: [
{
validator: (_, value, callback) => {
if (!value) {
callback(
formatMessage({
id: 'mobile.validate.isEmpty',
})
);
}
if (cellphone.test(value)) {
callback();
} else {
callback(
formatMessage({ id: 'username.invalid.character' })
);
}
},
},
],
})(
<Input
prefix={<Icon type="mobile" style={{ color: 'rgba(0,0,0,.25)' }} />}
maxLength={11}
size="large"
autoComplete="off"
placeholder={formatMessage({
id: 'mobile.placeholder',
})}
/>
)}
</Form.Item>
<ImgCaptchaModal
{...{
form,
visible: showImgCaptchaModal,
getCode: this.getCode,
refreshCode: this.refreshCode,
imgCaptcha,
onCancel: this.closeImgCaptchaModal,
}}
/>
<Form.Item>
{getFieldDecorator('code', {
validateTrigger: 'onBlur',
rules: [
{
required: true,
message: formatMessage({
id: 'code.validate.isEmpty',
}),
},
],
})(
<Captcha
{...{
trigger,
validateTarget: getFieldValue('phone') || '',
inputProps: {
maxLength: 4,
size: 'large',
placeholder: formatMessage({
id: 'mobile.code.placeholder',
}),
},
buttonText: {
initText: formatMessage({ id: 'btn.get.code' }),
countText: formatMessage({
id: 'countDown.unit.second',
}),
},
onClick: this.getCode,
}}
/>
)}
</Form.Item>
</>
);
}
}
export default MobileLogin;
|
jmcriffey/lax
|
test/rangeTest.js
|
<filename>test/rangeTest.js
import {assert} from 'chai';
import chain from '../src/chain';
import range from '../src/range';
describe('range', () => {
it('should handle a stop', () => {
let result = chain(range(4)).toArray();
assert.deepEqual(result, [0, 1, 2, 3]);
});
it('should handle a start and stop', () => {
let result = chain(range(2, 6)).toArray();
assert.deepEqual(result, [2, 3, 4, 5]);
});
it('should handle a start, stop, and step', () => {
let result = chain(range(2, 10, 2)).toArray();
assert.deepEqual(result, [2, 4, 6, 8]);
});
it('should work chained', () => {
let result = chain().range(4).toArray();
assert.deepEqual(result, [0, 1, 2, 3]);
});
it('should work unchained', () => {
let result = range(4);
assert.deepEqual(Array.from(result), [0, 1, 2, 3]);
});
});
|
etirelli/guvnor
|
guvnor-project/guvnor-project-backend/src/test/java/org/guvnor/common/services/project/backend/server/ProjectRepositoryResolverImplTest.java
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.guvnor.common.services.project.backend.server;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Set;
import javax.enterprise.inject.Instance;
import org.apache.maven.project.MavenProject;
import org.appformer.maven.integration.embedder.MavenProjectLoader;
import org.appformer.maven.integration.embedder.MavenSettings;
import org.guvnor.common.services.project.model.GAV;
import org.guvnor.common.services.project.model.MavenRepositoryMetadata;
import org.guvnor.common.services.project.model.MavenRepositorySource;
import org.guvnor.common.services.project.model.Project;
import org.guvnor.common.services.project.preferences.GAVPreferences;
import org.guvnor.common.services.shared.preferences.WorkbenchPreferenceScopeResolutionStrategies;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.Path;
import static org.guvnor.common.services.project.backend.server.MavenLocalRepositoryUtils.*;
import static org.guvnor.common.services.project.backend.server.RepositoryResolverTestUtils.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
// *** NOTE ***
// The transient Maven Repository used by these tests is only cleared after all the tests have ran.
// Therefore each test should use a unique GAV to avoid potential conflicts between tests.
public class ProjectRepositoryResolverImplTest {
@Mock
private IOService ioService;
@Mock
private Instance<GAVPreferences> gavPreferencesProvider;
@Mock
private GAVPreferences gavPreferences;
@Mock
private WorkbenchPreferenceScopeResolutionStrategies scopeResolutionStrategies;
private ProjectRepositoryResolverImpl service;
private static java.nio.file.Path m2Folder = null;
private static java.nio.file.Path settingsXmlPath = null;
@BeforeClass
public static void setupSystemProperties() {
//These are not needed for the tests
System.setProperty( "org.uberfire.nio.git.daemon.enabled",
"false" );
System.setProperty( "org.uberfire.nio.git.ssh.enabled",
"false" );
System.setProperty( "org.uberfire.sys.repo.monitor.disabled",
"true" );
}
@BeforeClass
public static void setupMavenRepository() {
try {
m2Folder = Files.createTempDirectory( "temp-m2" );
settingsXmlPath = generateSettingsXml( m2Folder );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
}
}
@Before
public void setup() {
service = new ProjectRepositoryResolverImpl( ioService, gavPreferencesProvider, scopeResolutionStrategies );
doReturn( gavPreferences ).when( gavPreferencesProvider ).get();
}
@AfterClass
public static void teardownMavenRepository() {
tearDownMavenRepository( m2Folder );
MavenSettings.reinitSettings();
}
@Test
public void testGetRemoteRepositoriesMetaData_WithoutExplicitProjectRepository() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path pomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.1</version>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( pomXmlPath );
when( pomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRemoteRepositoriesMetaData( project );
assertNotNull( metadata );
assertEquals( 6,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
assertContainsRepository( "jboss-developer-repository-group",
"https://repository.jboss.org/nexus/content/groups/developer/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"http://repository.jboss.org/nexus/content/groups/public/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-origin-repository-group",
"https://origin-repository.jboss.org/nexus/content/groups/ea/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"https://repository.jboss.org/nexus/content/repositories/snapshots/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "central",
"https://repo.maven.apache.org/maven2",
MavenRepositorySource.PROJECT,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRemoteRepositoriesMetaData_WithExplicitProjectRepository() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path pomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.2</version>\n" +
" <repositories>\n" +
" <repository>\n" +
" <id>explicit-repo</id>\n" +
" <name>Explicit Repository</name>\n" +
" <url>http://localhost/maven2/</url>\n" +
" </repository>\n" +
" </repositories>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( pomXmlPath );
when( pomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRemoteRepositoriesMetaData( project );
assertNotNull( metadata );
assertEquals( 7,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
assertContainsRepository( "jboss-developer-repository-group",
"https://repository.jboss.org/nexus/content/groups/developer/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"http://repository.jboss.org/nexus/content/groups/public/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-origin-repository-group",
"https://origin-repository.jboss.org/nexus/content/groups/ea/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"https://repository.jboss.org/nexus/content/repositories/snapshots/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "central",
"https://repo.maven.apache.org/maven2",
MavenRepositorySource.PROJECT,
metadata );
assertContainsRepository( "explicit-repo",
"http://localhost/maven2/",
MavenRepositorySource.PROJECT,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRemoteRepositoriesMetaData_WithDistributionManagementRepository() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path pomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.3</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>http://distribution-host/maven2/</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( pomXmlPath );
when( pomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRemoteRepositoriesMetaData( project );
assertNotNull( metadata );
assertEquals( 7,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
assertContainsRepository( "jboss-developer-repository-group",
"https://repository.jboss.org/nexus/content/groups/developer/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"http://repository.jboss.org/nexus/content/groups/public/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-origin-repository-group",
"https://origin-repository.jboss.org/nexus/content/groups/ea/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"https://repository.jboss.org/nexus/content/repositories/snapshots/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "central",
"https://repo.maven.apache.org/maven2",
MavenRepositorySource.PROJECT,
metadata );
assertContainsRepository( "distribution-repo",
"http://distribution-host/maven2/",
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRemoteRepositoriesMetaData_WithDistributionManagementSnapshotRepository_NonSnapshotVersion() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path pomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.4</version>\n" +
" <distributionManagement>\n" +
" <snapshotRepository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>http://distribution-host/maven2/</url>\n" +
" </snapshotRepository>\n" +
" </distributionManagement>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( pomXmlPath );
when( pomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRemoteRepositoriesMetaData( project );
assertNotNull( metadata );
assertEquals( 6,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
assertContainsRepository( "jboss-developer-repository-group",
"https://repository.jboss.org/nexus/content/groups/developer/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"http://repository.jboss.org/nexus/content/groups/public/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-origin-repository-group",
"https://origin-repository.jboss.org/nexus/content/groups/ea/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"https://repository.jboss.org/nexus/content/repositories/snapshots/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "central",
"https://repo.maven.apache.org/maven2",
MavenRepositorySource.PROJECT,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRemoteRepositoriesMetaData_WithDistributionManagementSnapshotRepository_SnapshotVersion() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path pomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.1-SNAPSHOT</version>\n" +
" <distributionManagement>\n" +
" <snapshotRepository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>http://distribution-host/maven2/</url>\n" +
" </snapshotRepository>\n" +
" </distributionManagement>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( pomXmlPath );
when( pomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRemoteRepositoriesMetaData( project );
assertNotNull( metadata );
assertEquals( 7,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
assertContainsRepository( "jboss-developer-repository-group",
"https://repository.jboss.org/nexus/content/groups/developer/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"http://repository.jboss.org/nexus/content/groups/public/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-origin-repository-group",
"https://origin-repository.jboss.org/nexus/content/groups/ea/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "jboss-public-repository-group",
"https://repository.jboss.org/nexus/content/repositories/snapshots/",
MavenRepositorySource.SETTINGS,
metadata );
assertContainsRepository( "central",
"https://repo.maven.apache.org/maven2",
MavenRepositorySource.PROJECT,
metadata );
assertContainsRepository( "distribution-repo",
"http://distribution-host/maven2/",
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_NewGAV_NotInstalledNotDeployed() {
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.5" );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav );
assertNotNull( metadata );
assertEquals( 0,
metadata.size() );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_NewGAV_IsInstalledNotDeployed() {
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.6</version>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.6" );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_NewGAV_IsInstalledIsDeployed() {
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.7</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.7" );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_NewGAV_NotInstalledIsDeployed() {
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.8</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.8" );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav );
assertNotNull( metadata );
assertEquals( 0,
metadata.size() );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_NewGAV_IsInstalledIsDeployed_Filtered() {
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.9</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.9" );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav,
new MavenRepositoryMetadata( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL ) );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ExplicitGAV_NotInstalledNotDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path pomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.10</version>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.10" );
when( project.getPomXMLPath() ).thenReturn( pomXmlPath );
when( pomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav,
project );
assertNotNull( metadata );
assertEquals( 0,
metadata.size() );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ExplicitGAV_IsInstalledNotDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.11</version>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.11" );
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav,
project );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ExplicitGAV_IsInstalledIsDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.12</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.12" );
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav,
project );
assertNotNull( metadata );
assertEquals( 2,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ExplicitGAV_NotInstalledIsDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.13</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.13" );
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav,
project );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
final Set<MavenRepositoryMetadata> metadata2 = service.getRepositoriesResolvingArtifact( gav,
project );
assertNotNull( metadata2 );
assertEquals( 1,
metadata2.size() );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata2 );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ExplicitGAV_IsInstalledIsDeployed_Filtered() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.14</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.14" );
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav,
project,
new MavenRepositoryMetadata( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT ) );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ImplicitGAV_NotInstalledNotDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path pomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.15</version>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( pomXmlPath );
when( pomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( pomXml );
assertNotNull( metadata );
assertEquals( 0,
metadata.size() );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ImplicitGAV_IsInstalledNotDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.16</version>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( pomXml );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ImplicitGAV_IsInstalledIsDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.17</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( pomXml );
assertNotNull( metadata );
assertEquals( 2,
metadata.size() );
assertContainsRepository( "local",
m2Folder.toString(),
MavenRepositorySource.LOCAL,
metadata );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ImplicitGAV_NotInstalledIsDeployed() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.18</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( pomXml );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
final Set<MavenRepositoryMetadata> metadata2 = service.getRepositoriesResolvingArtifact( pomXml );
assertNotNull( metadata2 );
assertEquals( 1,
metadata2.size() );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata2 );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_ImplicitGAV_IsInstalledIsDeployed_Filtered() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
java.nio.file.Path remoteRepositoryFolder = null;
try {
remoteRepositoryFolder = Files.createTempDirectory( "distribution-repo" );
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.19</version>\n" +
" <distributionManagement>\n" +
" <repository>\n" +
" <id>distribution-repo</id>\n" +
" <name>Distribution Repository</name>\n" +
" <url>file://" + remoteRepositoryFolder.toString() + "</url>\n" +
" </repository>\n" +
" </distributionManagement>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
deployArtifact( mavenProject,
pomXml );
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( pomXml,
new MavenRepositoryMetadata( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT ) );
assertNotNull( metadata );
assertEquals( 1,
metadata.size() );
assertContainsRepository( "distribution-repo",
"file://" + remoteRepositoryFolder.toString(),
MavenRepositorySource.DISTRIBUTION_MANAGEMENT,
metadata );
} catch ( IOException ioe ) {
fail( ioe.getMessage() );
} finally {
tearDownMavenRepository( remoteRepositoryFolder );
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_Disabled1() {
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.20</version>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.20" );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
doReturn( true ).when( gavPreferences ).isConflictingGAVCheckDisabled();
//Re-instantiate service to pick-up System Property
service = new ProjectRepositoryResolverImpl( ioService, gavPreferencesProvider, scopeResolutionStrategies );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
//Without being disabled this would return one resolved (LOCAL) Repository
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav );
assertNotNull( metadata );
assertEquals( 0,
metadata.size() );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_Disabled2() {
final Project project = mock( Project.class );
doReturn( "default://master@a/a%20b" ).when( project ).getIdentifier();
doCallRealMethod().when( project ).getEncodedIdentifier();
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.21</version>\n" +
"</project>";
final GAV gav = new GAV( "org.guvnor",
"test",
"0.0.21" );
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
doReturn( true ).when( gavPreferences ).isConflictingGAVCheckDisabled();
//Re-instantiate service to pick-up System Property
service = new ProjectRepositoryResolverImpl( ioService, gavPreferencesProvider, scopeResolutionStrategies );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
//Without being disabled this would return one resolved (LOCAL) Repository
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( gav,
project );
assertNotNull( metadata );
assertEquals( 0,
metadata.size() );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
@Test
public void testGetRepositoriesResolvingArtifact_Disabled3() {
final Project project = mock( Project.class );
final org.uberfire.backend.vfs.Path vfsPomXmlPath = mock( org.uberfire.backend.vfs.Path.class );
final String oldSettingsXmlPath = System.getProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY );
try {
final String pomXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <modelVersion>4.0.0</modelVersion>\n" +
" <groupId>org.guvnor</groupId>\n" +
" <artifactId>test</artifactId>\n" +
" <version>0.0.22</version>\n" +
"</project>";
when( project.getPomXMLPath() ).thenReturn( vfsPomXmlPath );
when( vfsPomXmlPath.toURI() ).thenReturn( "default://p0/pom.xml" );
when( ioService.readAllString( any( Path.class ) ) ).thenReturn( pomXml );
System.setProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
settingsXmlPath.toString() );
doReturn( true ).when( gavPreferences ).isConflictingGAVCheckDisabled();
//Re-instantiate service to pick-up System Property
service = new ProjectRepositoryResolverImpl( ioService, gavPreferencesProvider, scopeResolutionStrategies );
final InputStream pomStream = new ByteArrayInputStream( pomXml.getBytes( StandardCharsets.UTF_8 ) );
final MavenProject mavenProject = MavenProjectLoader.parseMavenPom( pomStream );
installArtifact( mavenProject,
pomXml );
//Without being disabled this would return one resolved (LOCAL) Repository
final Set<MavenRepositoryMetadata> metadata = service.getRepositoriesResolvingArtifact( pomXml );
assertNotNull( metadata );
assertEquals( 0,
metadata.size() );
} finally {
resetSystemProperty( MavenSettings.CUSTOM_SETTINGS_PROPERTY,
oldSettingsXmlPath );
}
}
private void assertContainsRepository( final String id,
final String url,
final MavenRepositorySource source,
final Collection<MavenRepositoryMetadata> metadata ) {
for ( MavenRepositoryMetadata md : metadata ) {
if ( md.getId().equals( id ) && md.getUrl().equals( url ) && md.getSource().equals( source ) ) {
return;
}
}
fail( "Repository Id '" + id + "' not found." );
}
private void resetSystemProperty( final String systemPropertyName,
final String oldSystemPropertyValue ) {
if ( oldSystemPropertyValue != null ) {
System.setProperty( systemPropertyName,
oldSystemPropertyValue );
} else {
System.clearProperty( systemPropertyName );
}
}
}
|
dylan-worth/OfflineRS
|
Server/src/net/nocturne/game/player/actions/skills/mining/SaltyCrabletineMining.java
|
<gh_stars>0
package net.nocturne.game.player.actions.skills.mining;
import net.nocturne.game.Animation;
import net.nocturne.game.item.ItemIdentifiers;
import net.nocturne.game.npc.NPC;
import net.nocturne.game.npc.others.SaltyCrabletine;
import net.nocturne.game.player.Player;
import net.nocturne.game.player.Skills;
import net.nocturne.game.player.actions.Action;
import net.nocturne.game.player.actions.skills.mining.MiningBase.PickAxeDefinitions;
public class SaltyCrabletineMining extends Action {
private SaltyCrabletine crab;
private PickAxeDefinitions axeDefinitions;
public SaltyCrabletineMining(NPC npc) {
this.crab = (SaltyCrabletine) npc;
}
@Override
public boolean start(Player player) {
axeDefinitions = MiningBase.getPickAxeDefinitions(player, false);
if (!crab.canMine(player))
return false;
else if (axeDefinitions == null) {
player.getPackets().sendGameMessage(
"You need a pickaxe in order to do this.");
return false;
}
player.getPackets().sendGameMessage(
"You swing your pickaxe at the crabletine.", true);
crab.startMining(player);
setActionDelay(player, 10);
return true;
}
@Override
public boolean process(Player player) {
player.setNextAnimation(new Animation(axeDefinitions.getAnimationId()));
return crab.canMine(player);
}
@Override
public int processWithDelay(Player player) {
if (!crab.canMine(player)) {
player.setNextAnimation(new Animation(-1));
player.stopAll();
return -1;
} else if (!player.getInventory().hasFreeSlots()) {
player.setNextAnimation(new Animation(-1));
player.getPackets().sendGameMessage(
"Not enough space in your inventory.");
return -1;
}
player.getSkills().addXp(Skills.MINING, 455.5);
player.getInventory().addItem(ItemIdentifiers.SEA_SALT, 1);
player.getPackets().sendGameMessage(
"You successfully mine some sea salt.");
return 10;
}
@Override
public void stop(Player player) {
setActionDelay(player, 3);
crab.stopMining();
}
}
|
squll1peter/elastix
|
Common/Transforms/itkBSplineInterpolationSecondOrderDerivativeWeightFunction.h
|
<filename>Common/Transforms/itkBSplineInterpolationSecondOrderDerivativeWeightFunction.h<gh_stars>1-10
/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* 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.txt
*
* 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 __itkBSplineInterpolationSecondOrderDerivativeWeightFunction_h
#define __itkBSplineInterpolationSecondOrderDerivativeWeightFunction_h
#include "itkBSplineInterpolationWeightFunctionBase.h"
#include "vnl/vnl_vector_fixed.h"
namespace itk
{
/** \class BSplineInterpolationSecondOrderDerivativeWeightFunction
* \brief Returns the weights over the support region used for B-spline
* interpolation/reconstruction.
*
* Computes/evaluate the B-spline interpolation weights over the
* support region of the B-spline.
*
* This class is templated over the coordinate representation type,
* the space dimension and the spline order.
*
* \sa Point
* \sa Index
* \sa ContinuousIndex
*
* \ingroup Functions ImageInterpolators
*/
template< class TCoordRep = float,
unsigned int VSpaceDimension = 2,
unsigned int VSplineOrder = 3 >
class BSplineInterpolationSecondOrderDerivativeWeightFunction :
public BSplineInterpolationWeightFunctionBase<
TCoordRep, VSpaceDimension, VSplineOrder >
{
public:
/** Standard class typedefs. */
typedef BSplineInterpolationSecondOrderDerivativeWeightFunction Self;
typedef BSplineInterpolationWeightFunctionBase<
TCoordRep, VSpaceDimension, VSplineOrder > Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** New macro for creation of through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( BSplineInterpolationSecondOrderDerivativeWeightFunction,
BSplineInterpolationWeightFunctionBase );
/** Space dimension. */
itkStaticConstMacro( SpaceDimension, unsigned int, VSpaceDimension );
/** Spline order. */
itkStaticConstMacro( SplineOrder, unsigned int, VSplineOrder );
/** Typedefs from Superclass. */
typedef typename Superclass::WeightsType WeightsType;
typedef typename Superclass::IndexType IndexType;
typedef typename Superclass::SizeType SizeType;
typedef typename Superclass::ContinuousIndexType ContinuousIndexType;
/** Set the second order derivative directions. */
virtual void SetDerivativeDirections( unsigned int dir0, unsigned int dir1 );
protected:
BSplineInterpolationSecondOrderDerivativeWeightFunction();
~BSplineInterpolationSecondOrderDerivativeWeightFunction() override {}
/** Interpolation kernel types. */
typedef typename Superclass::KernelType KernelType;
typedef typename Superclass::DerivativeKernelType DerivativeKernelType;
typedef typename Superclass
::SecondOrderDerivativeKernelType SecondOrderDerivativeKernelType;
typedef typename Superclass::TableType TableType;
typedef typename Superclass::OneDWeightsType OneDWeightsType;
/** Compute the 1D weights, which are:
* \f[ \beta( x[i] - startIndex[i] ), \beta( x[i] - startIndex[i] - 1 ),
* \beta( x[i] - startIndex[i] - 2 ), \beta( x[i] - startIndex[i] - 3 ), \f]
* with \f$\beta( x ) = \beta^2( x + 1/2 ) - \beta^2( x - 1/2 )\f$,
* in case of non-equal derivative directions,
* with \f$\beta( x ) = \beta^1( x + 1 ) - 2 * \beta^1( x ) + \beta^1( x - 1 ),\f$
* in case of equal derivative directions,
* with \f$\beta(x) = \beta^3(x)\f$ for the non-derivative directions.
*/
void Compute1DWeights(
const ContinuousIndexType & index,
const IndexType & startIndex,
OneDWeightsType & weights1D ) const override;
/** Print the member variables. */
void PrintSelf( std::ostream & os, Indent indent ) const override;
private:
BSplineInterpolationSecondOrderDerivativeWeightFunction( const Self & ); // purposely not implemented
void operator=( const Self & ); // purposely not implemented
vnl_vector_fixed< double, 2 > m_DerivativeDirections;
bool m_EqualDerivativeDirections;
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkBSplineInterpolationSecondOrderDerivativeWeightFunction.hxx"
#endif
#endif
|
andrebertonha/JavaOnline2
|
src/br/com/abc/javacore/threads/classes/ListaMembros.java
|
package br.com.abc.javacore.threads.classes;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class ListaMembros {
private final Queue<String> emails = new LinkedList<>();
public boolean aberta = true;
public int getEmailsPendentes() {
synchronized (emails) {
return this.emails.size();
}
}
public boolean isAberta() {
return aberta;
}
public String obterEmailMembro(){
String email = null;
try{
synchronized (this.emails){
while (this.emails.size() == 0){
if(!aberta) return null;
System.out.println("Lista vazia, colocando a thread: "+Thread.currentThread().getName()+ " em modo wait");
this.emails.wait();
}
email = this.emails.poll();
}
}catch (InterruptedException e){
e.printStackTrace();
}
return email;
}
public void adicionarEmailMembro(String email){
synchronized (this.emails) {
this.emails.add(email);
System.out.println("Email adicionado na lista");
System.out.println("Notificando as threads que estao em espera: "+Thread.currentThread().getName());
this.emails.notifyAll();
}
}
public void fecharLista(){
System.out.println("notificando todas as threads e fechando a lista");
aberta = false;
synchronized (this.emails) {
this.emails.notifyAll();
}
}
}
|
maheshp/performance
|
micro_performance/lib/go_constants.rb
|
module GoConstants
AUTH_HEADER = "Basic #{Base64.encode64('admin:badger')}".freeze
BASE_URL = 'http://localhost:8353/go'.freeze
end
|
L11R/td
|
internal/mt/tl_destroy_session_gen.go
|
<filename>internal/mt/tl_destroy_session_gen.go<gh_stars>0
// Code generated by gotdgen, DO NOT EDIT.
package mt
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"go.uber.org/multierr"
"github.com/gotd/td/bin"
"github.com/gotd/td/tdjson"
"github.com/gotd/td/tdp"
"github.com/gotd/td/tgerr"
)
// No-op definition for keeping imports.
var (
_ = bin.Buffer{}
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = multierr.AppendInto
_ = sort.Ints
_ = tdp.Format
_ = tgerr.Error{}
_ = tdjson.Encoder{}
)
// DestroySessionRequest represents TL type `destroy_session#e7512126`.
type DestroySessionRequest struct {
// SessionID field of DestroySessionRequest.
SessionID int64
}
// DestroySessionRequestTypeID is TL type id of DestroySessionRequest.
const DestroySessionRequestTypeID = 0xe7512126
// Ensuring interfaces in compile-time for DestroySessionRequest.
var (
_ bin.Encoder = &DestroySessionRequest{}
_ bin.Decoder = &DestroySessionRequest{}
_ bin.BareEncoder = &DestroySessionRequest{}
_ bin.BareDecoder = &DestroySessionRequest{}
)
func (d *DestroySessionRequest) Zero() bool {
if d == nil {
return true
}
if !(d.SessionID == 0) {
return false
}
return true
}
// String implements fmt.Stringer.
func (d *DestroySessionRequest) String() string {
if d == nil {
return "DestroySessionRequest(nil)"
}
type Alias DestroySessionRequest
return fmt.Sprintf("DestroySessionRequest%+v", Alias(*d))
}
// TypeID returns type id in TL schema.
//
// See https://core.telegram.org/mtproto/TL-tl#remarks.
func (*DestroySessionRequest) TypeID() uint32 {
return DestroySessionRequestTypeID
}
// TypeName returns name of type in TL schema.
func (*DestroySessionRequest) TypeName() string {
return "destroy_session"
}
// TypeInfo returns info about TL type.
func (d *DestroySessionRequest) TypeInfo() tdp.Type {
typ := tdp.Type{
Name: "destroy_session",
ID: DestroySessionRequestTypeID,
}
if d == nil {
typ.Null = true
return typ
}
typ.Fields = []tdp.Field{
{
Name: "SessionID",
SchemaName: "session_id",
},
}
return typ
}
// Encode implements bin.Encoder.
func (d *DestroySessionRequest) Encode(b *bin.Buffer) error {
if d == nil {
return fmt.Errorf("can't encode destroy_session#e7512126 as nil")
}
b.PutID(DestroySessionRequestTypeID)
return d.EncodeBare(b)
}
// EncodeBare implements bin.BareEncoder.
func (d *DestroySessionRequest) EncodeBare(b *bin.Buffer) error {
if d == nil {
return fmt.Errorf("can't encode destroy_session#e7512126 as nil")
}
b.PutLong(d.SessionID)
return nil
}
// Decode implements bin.Decoder.
func (d *DestroySessionRequest) Decode(b *bin.Buffer) error {
if d == nil {
return fmt.Errorf("can't decode destroy_session#e7512126 to nil")
}
if err := b.ConsumeID(DestroySessionRequestTypeID); err != nil {
return fmt.Errorf("unable to decode destroy_session#e7512126: %w", err)
}
return d.DecodeBare(b)
}
// DecodeBare implements bin.BareDecoder.
func (d *DestroySessionRequest) DecodeBare(b *bin.Buffer) error {
if d == nil {
return fmt.Errorf("can't decode destroy_session#e7512126 to nil")
}
{
value, err := b.Long()
if err != nil {
return fmt.Errorf("unable to decode destroy_session#e7512126: field session_id: %w", err)
}
d.SessionID = value
}
return nil
}
// GetSessionID returns value of SessionID field.
func (d *DestroySessionRequest) GetSessionID() (value int64) {
return d.SessionID
}
|
irahulgautam/ds3_java_browser
|
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/components/newsession/NewSessionPopup.java
|
package com.spectralogic.dsbrowser.gui.components.newsession;
import com.spectralogic.dsbrowser.gui.util.Popup;
public final class NewSessionPopup {
public static void show() {
final NewSessionView view = new NewSessionView();
Popup.show(view.getView(), "Sessions");
}
}
|
zhukovaskychina/X-JVM
|
classfile/ConstantPools.h
|
<filename>classfile/ConstantPools.h
//
// Created by zhukovasky on 2020/4/23.
//
#ifndef JVM_CONSTANTPOOLS_H
#define JVM_CONSTANTPOOLS_H
#include "../common/Internal.h"
namespace ClassFile{
class ConstantPools{
public:
ConstantPools();
virtual ~ConstantPools();
public:
u1 getTag() const;
void setTag(u1 tag);
private:
//定义常量池索引
u1 tag;
};
}
#endif //JVM_CONSTANTPOOLS_H
|
infocuittesting/Multioderingsystem
|
node_modules/@amcharts/amcharts4/core.js
|
<reponame>infocuittesting/Multioderingsystem
/**
* This module houses all core/framework functionality and is required for
* all charting components to work
*/
/**
* Elements: core
*/
export { System, system } from "./.internal/core/System";
export { BaseObject, BaseObjectEvents } from "./.internal/core/Base";
export { Component } from "./.internal/core/Component";
export { Container } from "./.internal/core/Container";
export { DataItem } from "./.internal/core/DataItem";
export { Sprite } from "./.internal/core/Sprite";
export { SpriteEventDispatcher } from "./.internal/core/SpriteEvents";
export { SpriteState } from "./.internal/core/SpriteState";
export { registry, Registry } from "./.internal/core/Registry";
export { options } from "./.internal/core/Options";
/**
* Elements: data
*/
export { CSVParser } from "./.internal/core/data/CSVParser";
export { DataLoader, dataLoader } from "./.internal/core/data/DataLoader";
export { DataParser } from "./.internal/core/data/DataParser";
export { DataSource } from "./.internal/core/data/DataSource";
export { JSONParser } from "./.internal/core/data/JSONParser";
export { SVGDefaults } from "./.internal/core/defs/SVGDefaults";
/**
* Elements: elements
*/
export { Button } from "./.internal/core/elements/Button";
export { Circle } from "./.internal/core/elements/Circle";
export { Ellipse } from "./.internal/core/elements/Ellipse";
export { Image } from "./.internal/core/elements/Image";
export { Label } from "./.internal/core/elements/Label";
export { Line } from "./.internal/core/elements/Line";
export { Popup } from "./.internal/core/elements/Popup";
export { Modal } from "./.internal/core/elements/Modal";
export { PointedRectangle } from "./.internal/core/elements/PointedRectangle";
export { PointedShape } from "./.internal/core/elements/PointedShape";
export { Polyarc } from "./.internal/core/elements/Polyarc";
export { Polygon } from "./.internal/core/elements/Polygon";
export { Polyline } from "./.internal/core/elements/Polyline";
export { Polyspline } from "./.internal/core/elements/Polyspline";
export { Preloader } from "./.internal/core/elements/Preloader";
export { Rectangle } from "./.internal/core/elements/Rectangle";
export { ResizeButton } from "./.internal/core/elements/ResizeButton";
export { RoundedRectangle } from "./.internal/core/elements/RoundedRectangle";
export { Scrollbar } from "./.internal/core/elements/Scrollbar";
export { Slider } from "./.internal/core/elements/Slider";
export { Slice } from "./.internal/core/elements/Slice";
export { TextLink } from "./.internal/core/elements/TextLink";
export { Tooltip } from "./.internal/core/elements/Tooltip";
export { Trapezoid } from "./.internal/core/elements/Trapezoid";
export { Triangle } from "./.internal/core/elements/Triangle";
export { WavedCircle } from "./.internal/core/elements/WavedCircle";
export { WavedLine } from "./.internal/core/elements/WavedLine";
export { WavedRectangle } from "./.internal/core/elements/WavedRectangle";
export { ZoomOutButton } from "./.internal/core/elements/ZoomOutButton";
export { PlayButton } from "./.internal/core/elements/PlayButton";
/**
* Elements: 3d
*/
export { Cone } from "./.internal/core/elements/3d/Cone";
export { Rectangle3D } from "./.internal/core/elements/3d/Rectangle3D";
export { Slice3D } from "./.internal/core/elements/3d/Slice3D";
/**
* Elements: export
*/
export { Export } from "./.internal/core/export/Export";
export { ExportMenu } from "./.internal/core/export/ExportMenu";
/**
* Elements: formatters
*/
export { DateFormatter } from "./.internal/core/formatters/DateFormatter";
export { DurationFormatter } from "./.internal/core/formatters/DurationFormatter";
export { NumberFormatter } from "./.internal/core/formatters/NumberFormatter";
export { TextFormatter, getTextFormatter } from "./.internal/core/formatters/TextFormatter";
/**
* Elements: interaction
*/
export { Inertia } from "./.internal/core/interaction/Inertia";
export { Interaction, getInteraction } from "./.internal/core/interaction/Interaction";
export { InteractionKeyboardObject } from "./.internal/core/interaction/InteractionKeyboardObject";
export { InteractionObject } from "./.internal/core/interaction/InteractionObject";
export { InteractionObjectEventDispatcher } from "./.internal/core/interaction/InteractionObjectEvents";
export { MouseCursorStyle } from "./.internal/core/interaction/Mouse";
/**
* Elements: rendering
*/
export { AMElement } from "./.internal/core/rendering/AMElement";
export { Group } from "./.internal/core/rendering/Group";
export { Paper } from "./.internal/core/rendering/Paper";
export { Tension, Basis } from "./.internal/core/rendering/Smoothing";
export { SVGContainer } from "./.internal/core/rendering/SVGContainer";
/**
* Elements: fills
*/
export { ColorModifier } from "./.internal/core/rendering/fills/ColorModifier";
export { LinearGradient } from "./.internal/core/rendering/fills/LinearGradient";
export { LinearGradientModifier } from "./.internal/core/rendering/fills/LinearGradientModifier";
export { RadialGradientModifier } from "./.internal/core/rendering/fills/RadialGradientModifier";
export { LinePattern } from "./.internal/core/rendering/fills/LinePattern";
export { Pattern } from "./.internal/core/rendering/fills/Pattern";
export { RadialGradient } from "./.internal/core/rendering/fills/RadialGradient";
export { RectPattern } from "./.internal/core/rendering/fills/RectPattern";
/**
* Elements: filters
*/
export { ColorizeFilter } from "./.internal/core/rendering/filters/ColorizeFilter";
export { DesaturateFilter } from "./.internal/core/rendering/filters/DesaturateFilter";
export { DropShadowFilter } from "./.internal/core/rendering/filters/DropShadowFilter";
export { BlurFilter } from "./.internal/core/rendering/filters/BlurFilter";
export { Filter } from "./.internal/core/rendering/filters/Filter";
export { FocusFilter } from "./.internal/core/rendering/filters/FocusFilter";
export { LightenFilter } from "./.internal/core/rendering/filters/LightenFilter";
/**
* Elements: utils
*/
export { GlobalAdapter, globalAdapter, Adapter } from "./.internal/core/utils/Adapter";
export { Animation, animate } from "./.internal/core/utils/Animation";
export { nextFrame, readFrame, writeFrame, whenIdle, triggerIdle } from "./.internal/core/utils/AsyncPending";
export { Cache, cache } from "./.internal/core/utils/Cache";
export { Color, color, isColor, castColor } from "./.internal/core/utils/Color";
export { ColorSet } from "./.internal/core/utils/ColorSet";
export { InterfaceColorSet } from "./.internal/core/utils/InterfaceColorSet";
export { DictionaryDisposer, Dictionary, DictionaryTemplate } from "./.internal/core/utils/Dictionary";
export { Disposer, MultiDisposer, MutableValueDisposer, CounterDisposer } from "./.internal/core/utils/Disposer";
export { StyleRule, StyleClass, getElement, addClass, removeClass, blur, focus, outerHTML, isElement, copyAttributes, fixPixelPerfect, ready } from "./.internal/core/utils/DOM";
export { EventDispatcher, TargetedEventDispatcher } from "./.internal/core/utils/EventDispatcher";
export { ListIterator, min, max, join } from "./.internal/core/utils/Iterator";
export { Keyboard, keyboard } from "./.internal/core/utils/Keyboard";
export { Language } from "./.internal/core/utils/Language";
export { IndexedIterable, ListGrouper, ListDisposer, List, ListTemplate } from "./.internal/core/utils/List";
export { Morpher } from "./.internal/core/utils/Morpher";
export { reverse, or } from "./.internal/core/utils/Order";
export { Percent, percent, isPercent } from "./.internal/core/utils/Percent";
export { Plugin } from "./.internal/core/utils/Plugin";
export { Responsive, ResponsiveBreakpoints, defaultRules } from "./.internal/core/utils/Responsive";
export { OrderedList, SortedList, OrderedListTemplate, SortedListTemplate } from "./.internal/core/utils/SortedList";
export { PX, STRING, NUMBER, DATE, DURATION, PLACEHOLDER, PLACEHOLDER2 } from "./.internal/core/utils/Strings";
export { isNaN, checkString, checkBoolean, checkNumber, checkObject, castString, castNumber, isString, isNumber, isObject, isArray } from "./.internal/core/utils/Type";
export { Validatable } from "./.internal/core/utils/Validatable";
/**
* Functions: rendering
*/
import * as path from "./.internal/core/rendering/Path";
export { path };
/**
* Functions: utils
*/
import * as colors from "./.internal/core/utils/Colors";
export { colors };
import * as ease from "./.internal/core/utils/Ease";
export { ease };
import * as math from "./.internal/core/utils/Math";
export { math };
import * as array from "./.internal/core/utils/Array";
export { array };
import * as number from "./.internal/core/utils/Number";
export { number };
import * as object from "./.internal/core/utils/Object";
export { object };
import * as string from "./.internal/core/utils/String";
export { string };
import * as time from "./.internal/core/utils/Time";
export { time };
import * as utils from "./.internal/core/utils/Utils";
export { utils };
import * as iter from "./.internal/core/utils/Iterator";
export { iter };
import * as type from "./.internal/core/utils/Type";
export { type };
export { create, createFromConfig } from "./.internal/core/utils/Instance";
export { useTheme, unuseTheme, unuseAllThemes } from "./.internal/core/utils/Instance";
//# sourceMappingURL=core.js.map
|
Dbevan/SunderingShadows
|
d/undead/rooms/street.c
|
#include "../undead.h"
inherit VAULT;
void create() {
::create();
set_terrain(CITY);
set_travel(PAVED_ROAD);
set_property("light", 2);
set_property("indoors", 0);
set_name("The City of Graez");
set_short("%^GREEN%^A street in the city of Graez");
set_long("%^GREEN%^A street in the city of Graez%^RESET%^\n"
"This %^ORANGE%^dusty street %^RESET%^travels in a full circuit of twists and "
"turns, around what remains of the city of Graez. Buildings that once formed "
"part of a %^BOLD%^%^WHITE%^magnificent island empire %^RESET%^lie in rubble "
"and ruin at the roadside. Armed or injured people, not all of them human, "
"come and go in a seeming constant flow upon these few besieged streets, "
"forming the last defense against the evils that constantly assail the city.");
set_smell("default","The fresh scent of the ocean drifts through the ruined city.");
set_listen("default","You hear the sounds of battle in the distance.");
set_exits(([
"out" :TOWN"street1",
]));
}
|
Tapyr/tapyr
|
_GTW/__test__/Entity_Reload.py
|
<reponame>Tapyr/tapyr
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# ****************************************************************************
# This module is part of the package GTW.__test__.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# ****************************************************************************
#
#++
# Name
# GTW.__test__.Entity_Reload
#
# Purpose
# Test entity reloading after a scope.commit and changes in a different
# process
#
# Revision Dates
# 15-Jun-2012 (MG) Creation
# 27-Jun-2012 (CT) Test `b1.name` before querying for `b3`
# ««revision-date»»···
#--
_test_code = """
>>> scope = Scaffold.scope (%(p1)s, %(n1)s) # doctest:+ELLIPSIS
Creating new scope MOMT__...
>>> SRM = scope.SRM
>>> opti = SRM.Boat_Class (name = "Optimist", max_crew = 1)
>>> laser = SRM.Boat_Class (name = "Laser", max_crew = 1)
>>> b1 = SRM.Boat (u'Optimist', u"1107", u"AUT", raw = True) ### 1
>>> b2 = SRM.Boat (u"Laser", "42", None, "OE", raw = True)
>>> laser.max_crew ### before commit
1
>>> prepr (b1.name) ### before commit
''
>>> scope.commit ()
>>> modify_scope (%(p1)s, %(n1)s)
>>> laser.max_crew ### after change
2
>>> prepr (b1.name) ### after change
'My Boat'
>>> b3 = scope.SRM.Boat.query (nation = u"AUT").one ()
>>> b3 is b1
True
"""
from _GTW.__test__.model import *
from multiprocessing import Process
_Ancestor_Essence = GTW.OMP.SRM.Boat
Scaffold.Backend_Parameters ["SQL"] = "'sqlite:///test.sqlite'"
Scaffold.Backend_Parameters ["sq"] = "'sqlite:///test.sqlite'"
def _modify_scope (* args) :
scope = Scaffold.scope (* args, create = False, verbose = False)
laser = scope.SRM.Boat_Class.query (name = u"laser").one ()
laser.max_crew = 2
boat = scope.SRM.Boat.query (nation = u"AUT").one ()
boat.name = "My Boat"
scope.commit ()
scope.destroy ()
# end def _modify_scope
def modify_scope (* args) :
if 1 :
p = Process (target = _modify_scope, args = args)
p.start ()
p.join ()
else :
_modify_scope (* args)
# end def modify_scope
__test__ = Scaffold.create_test_dict (_test_code, ignore = "HPS")
### __END__ GTW.__test__.Entity_Reload
|
RippeR37/GLUL
|
include/GLUL/Interfaces/Camera.h
|
#pragma once
#include <GLUL/Config.h>
#include <glm/glm.hpp>
namespace GLUL {
namespace Interface {
class GLUL_API Camera {
public:
Camera();
virtual ~Camera();
virtual void update(double deltaTime) = 0;
virtual void updateMouse(double x, double y) = 0;
virtual void updateKeyboard(int key, int scancode, int action, int mods) = 0;
virtual void updateMouseWheel(double x, double y) = 0;
virtual void updateMouseButton(int button, int action, int mods) = 0;
virtual const glm::vec2 getPos2D() const = 0;
virtual const glm::vec3& getPos3D() const = 0;
virtual const glm::mat4& getMatrix() const;
virtual const glm::mat4& getProjection() const;
virtual const glm::vec3& getUp() const;
virtual const glm::vec3& getRight() const;
virtual const glm::vec3& getDirection() const;
protected:
glm::vec3 _up;
glm::vec3 _right;
glm::vec3 _direction;
glm::vec3 _position;
glm::mat4 _matrix;
glm::mat4 _projectionMatrix;
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.