repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_3744.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_3744 {
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_437.java | 145 | package fr.javatronic.blog.massive.annotation1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_437 {
}
| apache-2.0 |
mirsaeedi/CqrsSample | Kaftar/CqrsSample.BusinessRuleEngine/Core/Contracts/IRuleTagCollection.cs | 405 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CqrsSample.BusinessRuleEngine.Core.Implementations;
namespace CqrsSample.BusinessRuleEngine.Core.Contracts
{
public interface IRuleTagCollection
{
RuleTagCollection Add(RuleTag ruleTag);
RuleTagCollection Remove(RuleTag ruleTag);
}
}
| apache-2.0 |
rust-lang/uuid | src/v5.rs | 4377 | use crate::prelude::*;
use sha1;
impl Uuid {
/// Creates a UUID using a name from a namespace, based on the SHA-1 hash.
///
/// A number of namespaces are available as constants in this crate:
///
/// * [`NAMESPACE_DNS`]
/// * [`NAMESPACE_OID`]
/// * [`NAMESPACE_URL`]
/// * [`NAMESPACE_X500`]
///
/// Note that usage of this method requires the `v5` feature of this crate
/// to be enabled.
///
/// [`NAMESPACE_DNS`]: struct.Uuid.html#associatedconst.NAMESPACE_DNS
/// [`NAMESPACE_OID`]: struct.Uuid.html#associatedconst.NAMESPACE_OID
/// [`NAMESPACE_URL`]: struct.Uuid.html#associatedconst.NAMESPACE_URL
/// [`NAMESPACE_X500`]: struct.Uuid.html#associatedconst.NAMESPACE_X500
pub fn new_v5(namespace: &Uuid, name: &[u8]) -> Uuid {
let mut hash = sha1::Sha1::new();
hash.update(namespace.as_bytes());
hash.update(name);
let buffer = hash.digest().bytes();
let mut bytes = crate::Bytes::default();
bytes.copy_from_slice(&buffer[..16]);
let mut builder = crate::Builder::from_bytes(bytes);
builder
.set_variant(Variant::RFC4122)
.set_version(Version::Sha1);
builder.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::std::string::ToString;
static FIXTURE: &'static [(&'static Uuid, &'static str, &'static str)] = &[
(
&Uuid::NAMESPACE_DNS,
"example.org",
"aad03681-8b63-5304-89e0-8ca8f49461b5",
),
(
&Uuid::NAMESPACE_DNS,
"rust-lang.org",
"c66bbb60-d62e-5f17-a399-3a0bd237c503",
),
(
&Uuid::NAMESPACE_DNS,
"42",
"7c411b5e-9d3f-50b5-9c28-62096e41c4ed",
),
(
&Uuid::NAMESPACE_DNS,
"lorem ipsum",
"97886a05-8a68-5743-ad55-56ab2d61cf7b",
),
(
&Uuid::NAMESPACE_URL,
"example.org",
"54a35416-963c-5dd6-a1e2-5ab7bb5bafc7",
),
(
&Uuid::NAMESPACE_URL,
"rust-lang.org",
"c48d927f-4122-5413-968c-598b1780e749",
),
(
&Uuid::NAMESPACE_URL,
"42",
"5c2b23de-4bad-58ee-a4b3-f22f3b9cfd7d",
),
(
&Uuid::NAMESPACE_URL,
"lorem ipsum",
"15c67689-4b85-5253-86b4-49fbb138569f",
),
(
&Uuid::NAMESPACE_OID,
"example.org",
"34784df9-b065-5094-92c7-00bb3da97a30",
),
(
&Uuid::NAMESPACE_OID,
"rust-lang.org",
"8ef61ecb-977a-5844-ab0f-c25ef9b8d5d6",
),
(
&Uuid::NAMESPACE_OID,
"42",
"ba293c61-ad33-57b9-9671-f3319f57d789",
),
(
&Uuid::NAMESPACE_OID,
"lorem ipsum",
"6485290d-f79e-5380-9e64-cb4312c7b4a6",
),
(
&Uuid::NAMESPACE_X500,
"example.org",
"e3635e86-f82b-5bbc-a54a-da97923e5c76",
),
(
&Uuid::NAMESPACE_X500,
"rust-lang.org",
"26c9c3e9-49b7-56da-8b9f-a0fb916a71a3",
),
(
&Uuid::NAMESPACE_X500,
"42",
"e4b88014-47c6-5fe0-a195-13710e5f6e27",
),
(
&Uuid::NAMESPACE_X500,
"lorem ipsum",
"b11f79a5-1e6d-57ce-a4b5-ba8531ea03d0",
),
];
#[test]
fn test_get_version() {
let uuid =
Uuid::new_v5(&Uuid::NAMESPACE_DNS, "rust-lang.org".as_bytes());
assert_eq!(uuid.get_version(), Some(Version::Sha1));
assert_eq!(uuid.get_version_num(), 5);
}
#[test]
fn test_hyphenated() {
for &(ref ns, ref name, ref expected) in FIXTURE {
let uuid = Uuid::new_v5(*ns, name.as_bytes());
assert_eq!(uuid.to_hyphenated().to_string(), *expected)
}
}
#[test]
fn test_new() {
for &(ref ns, ref name, ref u) in FIXTURE {
let uuid = Uuid::new_v5(*ns, name.as_bytes());
assert_eq!(uuid.get_variant(), Some(Variant::RFC4122));
assert_eq!(uuid.get_version(), Some(Version::Sha1));
assert_eq!(Ok(uuid), u.parse());
}
}
}
| apache-2.0 |
320504/jsf-blank01 | src/projetoPet/dto/Pet.java | 1088 | package projetoPet.dto;
public class Pet {
private int id;
private String nome;
private String telefone;
private String endereco;
private String nomePet;
private String tipoPet;
private int idadePet;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getNomePet() {
return nomePet;
}
public void setNomePet(String nomePet) {
this.nomePet = nomePet;
}
public String getTipoPet() {
return tipoPet;
}
public void setTipoPet(String tipoPet) {
this.tipoPet = tipoPet;
}
public int getIdadePet() {
return idadePet;
}
public void setIdadePet(int idadePet) {
this.idadePet = idadePet;
}
public String isAtivo() {
return null;
}
}
| apache-2.0 |
nicoschuele/pad_utils | test/units/filename_to_class_test.rb | 492 | require 'pad_utils'
require_relative '../template/test'
# Test name
test_name = "FilenameToClass"
class FilenameToClassTest < Test
def prepare
# Add test preparation here
end
def run_test
require_relative '../fixtures/foo_bar'
foobar = PadUtils.filename_to_class("fixtures/foo_bar.rb")
f = foobar.new
result = f.say_hello
if result != "Hello!"
@errors << "Error in the method result"
end
end
def cleanup
# Add cleanup code here
end
end
| apache-2.0 |
Banno/sbt-plantuml-plugin | src/main/java/net/sourceforge/plantuml/classdiagram/command/CommandCreateElementFull2.java | 8223 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.classdiagram.command;
import net.sourceforge.plantuml.FontParam;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.Url;
import net.sourceforge.plantuml.UrlBuilder;
import net.sourceforge.plantuml.UrlBuilder.ModeUrl;
import net.sourceforge.plantuml.classdiagram.ClassDiagram;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexOr;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.cucadiagram.Code;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.cucadiagram.IEntity;
import net.sourceforge.plantuml.cucadiagram.LeafType;
import net.sourceforge.plantuml.cucadiagram.Stereotype;
import net.sourceforge.plantuml.graphic.USymbol;
import net.sourceforge.plantuml.graphic.color.ColorParser;
import net.sourceforge.plantuml.graphic.color.ColorType;
public class CommandCreateElementFull2 extends SingleLineCommand2<ClassDiagram> {
private final Mode mode;
public static enum Mode {
NORMAL_KEYWORD, WITH_MIX_PREFIX
}
public CommandCreateElementFull2(Mode mode) {
super(getRegexConcat(mode));
this.mode = mode;
}
private static RegexConcat getRegexConcat(Mode mode) {
String regex = "(?:(actor|usecase|component)[%s]+)";
if (mode == Mode.WITH_MIX_PREFIX) {
regex = "mix_" + regex;
}
return new RegexConcat(new RegexLeaf("^"), //
new RegexLeaf("SYMBOL", regex), //
new RegexLeaf("[%s]*"), //
new RegexOr(//
new RegexLeaf("CODE1", CODE_WITH_QUOTE) //
), //
new RegexLeaf("STEREOTYPE", "(?:[%s]*(\\<\\<.+\\>\\>))?"), //
new RegexLeaf("[%s]*"), //
new RegexLeaf("URL", "(" + UrlBuilder.getRegexp() + ")?"), //
new RegexLeaf("[%s]*"), //
ColorParser.exp1(), //
new RegexLeaf("$"));
}
private static final String CODE_CORE = "[\\p{L}0-9_.]+|\\(\\)[%s]*[\\p{L}0-9_.]+|\\(\\)[%s]*[%g][^%g]+[%g]|:[^:]+:|\\([^()]+\\)|\\[[^\\[\\]]+\\]";
private static final String CODE = "(" + CODE_CORE + ")";
private static final String CODE_WITH_QUOTE = "(" + CODE_CORE + "|[%g][^%g]+[%g])";
private static final String DISPLAY_CORE = "[%g][^%g]+[%g]|:[^:]+:|\\([^()]+\\)|\\[[^\\[\\]]+\\]";
private static final String DISPLAY = "(" + DISPLAY_CORE + ")";
private static final String DISPLAY_WITHOUT_QUOTE = "(" + DISPLAY_CORE + "|[\\p{L}0-9_.]+)";
@Override
final protected boolean isForbidden(CharSequence line) {
if (line.toString().matches("^[\\p{L}0-9_.]+$")) {
return true;
}
return false;
}
@Override
protected CommandExecutionResult executeArg(ClassDiagram diagram, RegexResult arg) {
if (mode == Mode.NORMAL_KEYWORD && diagram.isAllowMixing() == false) {
return CommandExecutionResult
.error("Use 'allow_mixing' if you want to mix classes and other UML elements.");
}
String codeRaw = arg.getLazzy("CODE", 0);
final String displayRaw = arg.getLazzy("DISPLAY", 0);
final char codeChar = getCharEncoding(codeRaw);
final char codeDisplay = getCharEncoding(displayRaw);
final String symbol;
if (codeRaw.startsWith("()")) {
symbol = "interface";
codeRaw = StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(StringUtils.trin(codeRaw.substring(2)));
} else if (codeChar == '(' || codeDisplay == '(') {
symbol = "usecase";
} else if (codeChar == ':' || codeDisplay == ':') {
symbol = "actor";
} else if (codeChar == '[' || codeDisplay == '[') {
symbol = "component";
} else {
symbol = arg.get("SYMBOL", 0);
}
final LeafType type;
final USymbol usymbol;
if (symbol == null) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.ACTOR;
} else if (symbol.equalsIgnoreCase("artifact")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.ARTIFACT;
} else if (symbol.equalsIgnoreCase("folder")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.FOLDER;
} else if (symbol.equalsIgnoreCase("package")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.PACKAGE;
} else if (symbol.equalsIgnoreCase("rectangle")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.RECTANGLE;
} else if (symbol.equalsIgnoreCase("node")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.NODE;
} else if (symbol.equalsIgnoreCase("frame")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.FRAME;
} else if (symbol.equalsIgnoreCase("cloud")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.CLOUD;
} else if (symbol.equalsIgnoreCase("database")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.DATABASE;
} else if (symbol.equalsIgnoreCase("storage")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.STORAGE;
} else if (symbol.equalsIgnoreCase("agent")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.AGENT;
} else if (symbol.equalsIgnoreCase("actor")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.ACTOR;
} else if (symbol.equalsIgnoreCase("component")) {
type = LeafType.DESCRIPTION;
usymbol = diagram.getSkinParam().useUml2ForComponent() ? USymbol.COMPONENT2 : USymbol.COMPONENT1;
} else if (symbol.equalsIgnoreCase("boundary")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.BOUNDARY;
} else if (symbol.equalsIgnoreCase("control")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.CONTROL;
} else if (symbol.equalsIgnoreCase("entity")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.ENTITY_DOMAIN;
} else if (symbol.equalsIgnoreCase("interface")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.INTERFACE;
} else if (symbol.equalsIgnoreCase("()")) {
type = LeafType.DESCRIPTION;
usymbol = USymbol.INTERFACE;
} else if (symbol.equalsIgnoreCase("usecase")) {
type = LeafType.USECASE;
usymbol = null;
} else {
throw new IllegalStateException();
}
final Code code = Code.of(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(codeRaw));
String display = displayRaw;
if (display == null) {
display = code.getFullName();
}
display = StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(display);
final String stereotype = arg.getLazzy("STEREOTYPE", 0);
final IEntity entity = diagram.getOrCreateLeaf(code, type, usymbol);
entity.setDisplay(Display.getWithNewlines(display));
entity.setUSymbol(usymbol);
if (stereotype != null) {
entity.setStereotype(new Stereotype(stereotype, diagram.getSkinParam().getCircledCharacterRadius(), diagram
.getSkinParam().getFont(null, false, FontParam.CIRCLED_CHARACTER), diagram.getSkinParam()
.getIHtmlColorSet()));
}
final String urlString = arg.get("URL", 0);
if (urlString != null) {
final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT);
final Url url = urlBuilder.getUrl(urlString);
entity.addUrl(url);
}
entity.setSpecificColorTOBEREMOVED(ColorType.BACK, diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("COLOR", 0)));
return CommandExecutionResult.ok();
}
private char getCharEncoding(final String codeRaw) {
return codeRaw != null && codeRaw.length() > 2 ? codeRaw.charAt(0) : 0;
}
}
| apache-2.0 |
schlaile/phabricator | src/applications/tokens/controller/PhabricatorTokenLeaderController.php | 1659 | <?php
final class PhabricatorTokenLeaderController
extends PhabricatorTokenController {
public function shouldAllowPublic() {
return true;
}
public function processRequest() {
$request = $this->getRequest();
$user = $request->getUser();
$pager = new PHUIPagerView();
$pager->setURI($request->getRequestURI(), 'page');
$pager->setOffset($request->getInt('page'));
$query = id(new PhabricatorTokenReceiverQuery());
$objects = $query->setViewer($user)->executeWithOffsetPager($pager);
$counts = $query->getTokenCounts();
$handles = array();
$phids = array();
if ($counts) {
$phids = mpull($objects, 'getPHID');
$handles = id(new PhabricatorHandleQuery())
->setViewer($user)
->withPHIDs($phids)
->execute();
}
$list = new PHUIObjectItemListView();
foreach ($phids as $object) {
$count = idx($counts, $object, 0);
$item = id(new PHUIObjectItemView());
$handle = $handles[$object];
$item->setHeader($handle->getFullName());
$item->setHref($handle->getURI());
$item->addAttribute(pht('Tokens: %s', $count));
$list->addItem($item);
}
$title = pht('Token Leader Board');
$box = id(new PHUIObjectBoxView())
->setHeaderText($title)
->setObjectList($list);
$nav = $this->buildSideNav();
$nav->setCrumbs(
$this->buildApplicationCrumbs()
->addTextCrumb($title));
$nav->selectFilter('leaders/');
$nav->appendChild($box);
$nav->appendChild($pager);
return $this->buildApplicationPage(
$nav,
array(
'title' => $title,
));
}
}
| apache-2.0 |
supernebula/evol-core | src/Evol.TMovie.Domain/Repositories/IMovieRepository.cs | 193 | using Evol.TMovie.Domain.Models.AggregateRoots;
using Evol.Domain.Data;
namespace Evol.TMovie.Domain.Repositories
{
public interface IMovieRepository : IRepository<Movie>
{
}
}
| apache-2.0 |
gentics/mesh | rest-model/src/main/java/com/gentics/mesh/core/rest/node/field/impl/NumberFieldImpl.java | 712 | package com.gentics.mesh.core.rest.node.field.impl;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.gentics.mesh.core.rest.common.FieldTypes;
import com.gentics.mesh.core.rest.node.field.NumberField;
/**
* @see NumberField
*/
public class NumberFieldImpl implements NumberField {
@JsonPropertyDescription("Number field value")
private Number number;
@Override
public Number getNumber() {
return number;
}
@Override
public NumberField setNumber(Number number) {
this.number = number;
return this;
}
@Override
public String getType() {
return FieldTypes.NUMBER.toString();
}
@Override
public String toString() {
return String.valueOf(getNumber());
}
}
| apache-2.0 |
WIZARD-CXY/pl | leetcode/combinationsum.cpp | 787 | class Solution {
public:
vector<vector<int> > res;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<int> path;
dfs(candidates,path,0,target);
return res;
}
void dfs(vector<int> &candidates, vector<int> &path, int start, int target){
if(target==0){
res.push_back(path);
return;
}
for(int i=start; i<candidates.size(); i++){
if(target<candidates[i]){
return; //return early. prune
}
path.push_back(candidates[i]);
dfs(candidates,path,i,target-candidates[i]);
path.pop_back();
}
}
}; | apache-2.0 |
tobyweston/temperature-machine | src/main/scala/bad/robot/temperature/server/VersionEndpoint.scala | 632 | package bad.robot.temperature.server
import bad.robot.temperature._
import cats.effect.IO
import io.circe.Json
import org.http4s.HttpService
import org.http4s.dsl.io._
object VersionEndpoint {
private val version = Json.obj(
("name", Json.fromString(BuildInfo.name)),
("version", Json.fromString(BuildInfo.version)),
("latestSha", Json.fromString(BuildInfo.latestSha)),
("scalaVersion", Json.fromString(BuildInfo.scalaVersion)),
("sbtVersion", Json.fromString(BuildInfo.sbtVersion))
)
def apply() = HttpService[IO] {
case GET -> Root / "version" => Ok(version)(implicitly, jsonEncoder)
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/transform/ExecuteCommandRequestMarshaller.java | 3232 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ecs.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.ecs.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ExecuteCommandRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ExecuteCommandRequestMarshaller {
private static final MarshallingInfo<String> CLUSTER_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("cluster").build();
private static final MarshallingInfo<String> CONTAINER_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("container").build();
private static final MarshallingInfo<String> COMMAND_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("command").build();
private static final MarshallingInfo<Boolean> INTERACTIVE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("interactive").build();
private static final MarshallingInfo<String> TASK_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("task").build();
private static final ExecuteCommandRequestMarshaller instance = new ExecuteCommandRequestMarshaller();
public static ExecuteCommandRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ExecuteCommandRequest executeCommandRequest, ProtocolMarshaller protocolMarshaller) {
if (executeCommandRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(executeCommandRequest.getCluster(), CLUSTER_BINDING);
protocolMarshaller.marshall(executeCommandRequest.getContainer(), CONTAINER_BINDING);
protocolMarshaller.marshall(executeCommandRequest.getCommand(), COMMAND_BINDING);
protocolMarshaller.marshall(executeCommandRequest.getInteractive(), INTERACTIVE_BINDING);
protocolMarshaller.marshall(executeCommandRequest.getTask(), TASK_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
WU-ARL/RLI | Conditional.java | 1133 | /*
* Copyright (c) 2005-2013 Jyoti Parwatikar
* and Washington University in St. Louis
*
* 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.
*
*/
/*
* File: Conditional.java
* Author: Jyoti Parwatikar
* Email: [email protected]
* Organization: Washington University
*
* Derived from: none
*
* Date Created: 10/23/2003
*
* Description:
*
* Modification History:
*
*/
public interface Conditional extends Monitor
{
public boolean isTrue(Monitor mp); //does test
public void addConditionListener(ConditionListener l);
public void removeConditionListener(ConditionListener l);
public boolean isPassive();
}
| apache-2.0 |
aalexandrov/emma | emma-spark/src/main/scala/org/emmalanguage/api/SparkMutableBag.scala | 2715 | /*
* Copyright © 2014 TU Berlin ([email protected])
*
* 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.emmalanguage
package api
import api.Meta.Projections._
import api.spark._
import edu.berkeley.cs.amplab.spark.indexedrdd.IndexedRDD
import edu.berkeley.cs.amplab.spark.indexedrdd.KeySerializer
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import java.util.UUID
class SparkMutableBag[K: Meta, V: Meta]
(
init: DataBag[(K, V)]
)(
implicit spark: SparkSession
) extends MutableBag[K, V] with Serializable {
import SparkMutableBag.keySerializer
/* Distrubted state - a (mutable) reference to an (immutable) indexed collection. */
@transient var si = IndexedRDD(init.as[RDD]).cache()
def update[M: Meta](ms: DataBag[Group[K, M]])(f: UpdateFunction[M]): DataBag[(K, V)] = {
// update messages as RDD
val delta = (si rightOuterJoin ms.map(m => m.key -> m.values).as[RDD])
.flatMap { case (k, (ov, m)) => f(k, ov, m).map(v => k -> v) }
si = si.multiputRDD(delta)
// return the result wrapped in a DataSet
new SparkRDD(delta)
}
def bag(): DataBag[(K, V)] =
new SparkRDD(si.map(identity[(K, V)]))
def copy(): MutableBag[K, V] =
new SparkMutableBag(bag())
}
object SparkMutableBag {
def apply[K: Meta, V: Meta](
init: DataBag[(K, V)]
)(
implicit spark: SparkSession
): MutableBag[K, V] = new SparkMutableBag[K, V](init)
implicit private def keySerializer[K](implicit m: Meta[K]): KeySerializer[K] = {
import scala.reflect.runtime.universe._
val ttag = m.ttag
if (ttag.tpe == typeOf[Long]) IndexedRDD.longSer.asInstanceOf[KeySerializer[K]]
else if (ttag.tpe == typeOf[String]) IndexedRDD.stringSer.asInstanceOf[KeySerializer[K]]
else if (ttag.tpe == typeOf[Short]) IndexedRDD.shortSer.asInstanceOf[KeySerializer[K]]
else if (ttag.tpe == typeOf[Int]) IndexedRDD.intSet.asInstanceOf[KeySerializer[K]]
else if (ttag.tpe == typeOf[BigInt]) IndexedRDD.bigintSer.asInstanceOf[KeySerializer[K]]
else if (ttag.tpe == typeOf[UUID]) IndexedRDD.uuidSer.asInstanceOf[KeySerializer[K]]
else throw new RuntimeException(s"Unsupported Key type ${ttag.tpe}")
}
}
| apache-2.0 |
raulnq/Jal.Validator | Jal.Validator/Impl/AbstractModelValidatorInterceptor.cs | 614 | using System;
using Jal.Validator.Interface;
using Jal.Validator.Model;
namespace Jal.Validator.Impl
{
public abstract class AbstractModelValidatorInterceptor : IModelValidatorInterceptor
{
public static IModelValidatorInterceptor Instance = new NullModelValidatorInterceptor();
public void OnEnter<T>(T instance)
{
}
public void OnSuccess<T>(T instance, ValidationResult result)
{
}
public void OnError<T>(T instance, Exception exception)
{
}
public void OnExit<T>(T instance)
{
}
}
} | apache-2.0 |
XuHuaiyu/tidb | store/mockstore/unistore/pd.go | 2559 | // Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package unistore
import (
"errors"
"math"
"sync"
us "github.com/ngaut/unistore/tikv"
"github.com/pingcap/kvproto/pkg/pdpb"
pd "github.com/tikv/pd/client"
"golang.org/x/net/context"
)
var _ pd.Client = new(pdClient)
type pdClient struct {
*us.MockPD
serviceSafePoints map[string]uint64
gcSafePointMu sync.Mutex
}
func newPDClient(pd *us.MockPD) *pdClient {
return &pdClient{
MockPD: pd,
serviceSafePoints: make(map[string]uint64),
}
}
func (c *pdClient) GetTSAsync(ctx context.Context) pd.TSFuture {
return &mockTSFuture{c, ctx, false}
}
type mockTSFuture struct {
pdc *pdClient
ctx context.Context
used bool
}
func (m *mockTSFuture) Wait() (int64, int64, error) {
if m.used {
return 0, 0, errors.New("cannot wait tso twice")
}
m.used = true
return m.pdc.GetTS(m.ctx)
}
func (c *pdClient) GetLeaderAddr() string { return "mockpd" }
func (c *pdClient) UpdateServiceGCSafePoint(ctx context.Context, serviceID string, ttl int64, safePoint uint64) (uint64, error) {
c.gcSafePointMu.Lock()
defer c.gcSafePointMu.Unlock()
if ttl == 0 {
delete(c.serviceSafePoints, serviceID)
} else {
var minSafePoint uint64 = math.MaxUint64
for _, ssp := range c.serviceSafePoints {
if ssp < minSafePoint {
minSafePoint = ssp
}
}
if len(c.serviceSafePoints) == 0 || minSafePoint <= safePoint {
c.serviceSafePoints[serviceID] = safePoint
}
}
// The minSafePoint may have changed. Reload it.
var minSafePoint uint64 = math.MaxUint64
for _, ssp := range c.serviceSafePoints {
if ssp < minSafePoint {
minSafePoint = ssp
}
}
return minSafePoint, nil
}
func (c *pdClient) GetOperator(ctx context.Context, regionID uint64) (*pdpb.GetOperatorResponse, error) {
return &pdpb.GetOperatorResponse{Status: pdpb.OperatorStatus_SUCCESS}, nil
}
func (c *pdClient) ScatterRegionWithOption(ctx context.Context, regionID uint64, opts ...pd.ScatterRegionOption) error {
return nil
}
func (c *pdClient) GetMemberInfo(ctx context.Context) ([]*pdpb.Member, error) {
return nil, nil
}
| apache-2.0 |
caskdata/cdap | cdap-proto/src/main/java/co/cask/cdap/proto/QueryStatus.java | 3217 | /*
* Copyright © 2014-2016 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.proto;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* Represents the status of a submitted query operation.
*/
public class QueryStatus {
public static final QueryStatus NO_OP = new QueryStatus(OpStatus.FINISHED, false);
private final OpStatus status;
private final boolean hasResults;
private final String errorMessage;
private String sqlState;
/**
* A query status for an operation that is not in error.
* @param status the status
* @param hasResults whether the query has produced results
*/
public QueryStatus(OpStatus status, boolean hasResults) {
this(status, hasResults, null, null);
}
/**
* A query status that represents failure with an error message.
* @param errorMessage the error message
*/
public QueryStatus(String errorMessage, @Nullable String sqlState) {
this(OpStatus.ERROR, false, errorMessage, sqlState);
}
private QueryStatus(OpStatus status, boolean hasResults, @Nullable String errorMessage, @Nullable String sqlState) {
this.status = status;
this.hasResults = hasResults;
this.errorMessage = errorMessage;
this.sqlState = sqlState;
}
public OpStatus getStatus() {
return status;
}
public boolean hasResults() {
return hasResults;
}
@Nullable
public String getErrorMessage() {
return errorMessage;
}
public String getSqlState() {
return sqlState;
}
@Override
public String toString() {
return "QueryStatus{" +
"status=" + status +
", hasResults=" + hasResults +
", errorMessage='" + errorMessage + '\'' +
", sqlState='" + sqlState + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QueryStatus that = (QueryStatus) o;
return Objects.equals(this.status, that.status) &&
Objects.equals(this.hasResults, that.hasResults) &&
Objects.equals(this.errorMessage, that.errorMessage) &&
Objects.equals(this.sqlState, that.sqlState);
}
@Override
public int hashCode() {
return Objects.hash(NO_OP, status, hasResults, errorMessage, sqlState);
}
/**
* Represents the status of an operation.
*/
@SuppressWarnings("UnusedDeclaration")
public enum OpStatus {
INITIALIZED,
RUNNING,
FINISHED,
CANCELED,
CLOSED,
ERROR,
UNKNOWN,
PENDING;
public boolean isDone() {
return this.equals(FINISHED) || this.equals(CANCELED) || this.equals(CLOSED) || this.equals(ERROR);
}
}
}
| apache-2.0 |
consulo/consulo-javaee | incubating/apache-tomcat/src/org/jetbrains/idea/tomcat/server/TomcatConfiguration.java | 755 | package org.jetbrains.idea.tomcat.server;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import consulo.apache.tomcat.bundle.TomcatBundleType;
/**
* Created by IntelliJ IDEA.
* User: michael.golubev
*/
public class TomcatConfiguration extends TomcatConfigurationBase
{
@NonNls
private static final String ID = "#com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory";
public static TomcatConfiguration getInstance()
{
return ConfigurationTypeUtil.findConfigurationType(TomcatConfiguration.class);
}
public TomcatConfiguration()
{
super(TomcatBundleType.getInstance());
}
@Nonnull
@Override
public String getId()
{
return ID;
}
} | apache-2.0 |
nagyist/marketcetera | photon/photon/plugins/org.marketcetera.photon.commons.ui.workbench.tests/src/test/java/org/marketcetera/photon/commons/ui/workbench/ChooseColumnsMenuTest.java | 9222 | package org.marketcetera.photon.commons.ui.workbench;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.marketcetera.photon.commons.ui.workbench.ChooseColumnsMenu;
import org.marketcetera.photon.commons.ui.workbench.ChooseColumnsMenu.IColumnProvider;
import org.marketcetera.photon.test.SWTTestUtil;
import org.marketcetera.photon.test.WorkbenchRunner;
import org.marketcetera.photon.test.AbstractUIRunner.UI;
/* $License$ */
/**
* Test {@link ChooseColumnsMenu}.
*
* @author <a href="mailto:[email protected]">Will Horn</a>
* @version $Id: ChooseColumnsMenuTest.java 16154 2012-07-14 16:34:05Z colin $
* @since 1.0.0
*/
@RunWith(WorkbenchRunner.class)
public class ChooseColumnsMenuTest {
private static final String MOCK_VIEW = "org.marketcetera.photon.commons.ui.workbench.ChooseColumnsMenuTest$MockColumnView"; //$NON-NLS-1$
private static final String RESTORED_WIDTH = "restoredWidth"; //$NON-NLS-1$
private static ChooseColumnsMenuTestCase sCurrent = null;
@Before
@UI
public void setUp() {
sCurrent = null;
}
@After
@UI
public void tearDown() {
sCurrent = null;
}
@Test
@UI
public void withoutColumns() throws Exception {
sCurrent = new ChooseColumnsMenuTestCase() {
@Override
protected Table createControl(Composite parent) {
return new Table(parent, SWT.NONE);
}
@Override
void validate(ChooseColumnsMenu fixture) {
assertEquals(0, fixture.getContributionItems().length);
}
};
sCurrent.run();
}
@Test
@UI
public void oneColumn() throws Exception {
final String columnName = "C1";
final int columnWidth = 101;
sCurrent = new ChooseColumnsMenuTestCase() {
private TableColumn column1;
@Override
protected Table createControl(Composite parent) {
final Table table = new Table(parent, SWT.NONE);
column1 = new TableColumn(table, SWT.NONE);
column1.setText(columnName);
column1.setWidth(columnWidth);
return table;
}
@Override
void validate(ChooseColumnsMenu fixture) {
// initial state
IContributionItem[] menuItems = fixture.getContributionItems();
assertEquals(1, menuItems.length);
IAction action = ((ActionContributionItem) menuItems[0])
.getAction();
assertEquals(columnName, action.getText());
assertTrue(action.isChecked());
assertEquals(columnWidth, column1.getWidth());
validateVisible();
// simulate uncheck
action.setChecked(false);
action.run();
SWTTestUtil.delay(100, TimeUnit.MILLISECONDS);
validateHidden();
// new state
menuItems[0].dispose();
menuItems = fixture.getContributionItems();
assertEquals(1, menuItems.length);
action = ((ActionContributionItem) menuItems[0]).getAction();
assertEquals(columnName, action.getText());
assertFalse(action.isChecked());
// simulate check
action.setChecked(true);
action.run();
validateVisible();
}
private void validateVisible() {
assertEquals(columnWidth, column1.getWidth());
assertTrue(column1.getResizable());
}
private void validateHidden() {
assertEquals(columnWidth, column1.getData(RESTORED_WIDTH));
assertEquals(0, column1.getWidth());
assertFalse(column1.getResizable());
}
};
sCurrent.run();
}
@Test
@UI
public void withoutTreeColumns() throws Exception {
sCurrent = new ChooseColumnsMenuTestCase() {
@Override
protected Tree createControl(Composite parent) {
return new Tree(parent, SWT.NONE);
}
@Override
void validate(ChooseColumnsMenu fixture) {
assertEquals(0, fixture.getContributionItems().length);
}
};
sCurrent.run();
}
@Test
@UI
public void oneTreeColumn() throws Exception {
final String columnName = "C1";
final int columnWidth = 101;
sCurrent = new ChooseColumnsMenuTestCase() {
private TreeColumn column1;
@Override
protected Tree createControl(Composite parent) {
final Tree tree = new Tree(parent, SWT.NONE);
new TreeColumn(tree, SWT.NONE); // node column
column1 = new TreeColumn(tree, SWT.NONE);
column1.setText(columnName);
column1.setWidth(columnWidth);
return tree;
}
@Override
void validate(ChooseColumnsMenu fixture) {
// initial state
IContributionItem[] menuItems = fixture.getContributionItems();
assertEquals(1, menuItems.length);
IAction action = ((ActionContributionItem) menuItems[0])
.getAction();
assertEquals(columnName, action.getText());
assertTrue(action.isChecked());
assertEquals(columnWidth, column1.getWidth());
validateVisible();
// simulate uncheck
action.setChecked(false);
action.run();
SWTTestUtil.delay(100, TimeUnit.MILLISECONDS);
validateHidden();
// new state
menuItems[0].dispose();
menuItems = fixture.getContributionItems();
assertEquals(1, menuItems.length);
action = ((ActionContributionItem) menuItems[0]).getAction();
assertEquals(columnName, action.getText());
assertFalse(action.isChecked());
// simulate check
action.setChecked(true);
action.run();
validateVisible();
}
private void validateVisible() {
assertEquals(columnWidth, column1.getWidth());
assertTrue(column1.getResizable());
}
private void validateHidden() {
assertEquals(columnWidth, column1.getData(RESTORED_WIDTH));
assertEquals(0, column1.getWidth());
assertFalse(column1.getResizable());
}
};
sCurrent.run();
}
/**
* Helper class for test cases.
*/
private abstract class ChooseColumnsMenuTestCase {
abstract Control createControl(Composite parent);
void run() throws Exception {
final IWorkbenchPage activePage = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
IViewPart part = activePage.showView(MOCK_VIEW);
validate(new ChooseColumnsMenu());
activePage.hideView(part);
}
abstract void validate(ChooseColumnsMenu fixture);
}
/**
* Dumb view to host table/tree for ChooseColumnMenu.
*
* @author <a href="mailto:[email protected]">Will Horn</a>
* @version $Id: ChooseColumnsMenuTest.java 10643 2009-07-13 17:48:29Z will
* $
* @since 1.0.0
*/
public static class MockColumnView extends ViewPart implements
IColumnProvider {
private Control mControl;
@Override
public void createPartControl(Composite parent) {
mControl = sCurrent.createControl(parent);
}
@Override
public void setFocus() {
mControl.setFocus();
}
@Override
public Control getColumnWidget() {
return mControl;
}
}
}
| apache-2.0 |
benoyprakash/java-hostel | JHipster-hostel/src/main/java/com/hostel/service/LocationService.java | 1169 | package com.hostel.service;
import com.hostel.domain.Location;
import com.hostel.service.dto.LocationDTO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
/**
* Service Interface for managing Location.
*/
public interface LocationService {
/**
* Save a location.
*
* @param locationDTO the entity to save
* @return the persisted entity
*/
LocationDTO save(LocationDTO locationDTO);
/**
* Get all the locations.
*
* @param pageable the pagination information
* @return the list of entities
*/
Page<LocationDTO> findAll(Pageable pageable, String clientId);
/**
* Get the "id" location.
*
* @param id the id of the entity
* @return the entity
*/
LocationDTO findOne(String id);
/**
* Get the "id" location.
*
* @param id the id of the entity
* @return the entity
*/
LocationDTO findLocation(String clientId, String locationId);
/**
* Delete the "id" location.
*
* @param id the id of the entity
*/
void delete(String id);
}
| apache-2.0 |
xunilrj/sandbox | sources/games/html5/pong.js | 4939 | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<canvas id="backbuffer" width="800" height="500">
</canvas>
<script>
function random(){ return (Math.random()-0.5)*2.0; }
function isInsideAABB(pos, posAABB, sizeAABB){
if(pos[0] < posAABB[0]) return false;
if(pos[1] < posAABB[1]) return false;
if(pos[0] > (posAABB[0] + sizeAABB[0])) return false;
if(pos[1] > (posAABB[1] + sizeAABB[1])) return false;
return true;
}
function GameState (){
this.constants = {
ballSize: 10,
courtHeight: 500,
minVel: 100,
incVel: 1.05,
paddleSize: [20,50],
paddleX: [0, 500]
}
this.world = Object.create(this.constants);
this.world.right = 250;
this.world.rightScore = 0;
this.resetMatch();
this.you = Object.create(this.world);
this.you.left = 250;
this.you.leftScore = 0;
var x = this;
var handler = {
get: function(obj, prop){
return x.you[prop];
},
set: function(obj, prop, value){
throw "Read-Only"
}
};
this.commands = [];
this.Data = Object.create(this.you);
};
GameState.prototype.resetMatch = function(){
this.world.ball = {
startPosition: [250.0, 250.0],
pos: [250.0,250.0],
vel: [random()*500,
0]
};
}
GameState.prototype.addCommand = function(c){
this.commands.push(c);
}
GameState.prototype.stepLeft = function(f){
this.you.left = Math.min(
Math.max(0, this.you.left + f), 300
);
};
GameState.prototype.step = function(dt){
var startPosition = this.world.ball.startPosition;
var ballPos = this.world.ball.pos;
var ballVel = this.world.ball.vel;
ballPos[0] += this.world.ball.vel[0]*dt;
ballPos[1] += this.world.ball.vel[1]*dt;
if(ballPos[0] > this.constants.paddleX[1] + this.constants.paddleSize[0]){
ballPos[0] = startPosition[0];
this.you.leftScore++;
this.resetMatch();
} else if (ballPos[0] < 0) {
ballPos[0] = startPosition[0]
this.world.rightScore++;
this.resetMatch();
}
var minBottom = this.constants.courtHeight - this.constants.ballSize;
if(ballPos[1] > minBottom && ballVel[1] > 0){
ballPos[1] = minBottom;
ballVel[1] *= - this.constants.incVel;
} else if(ballPos[1] < 0 && ballVel[1] < 0){
ballPos[1] = 0;
ballVel[1] *= - this.constants.incVel;
}
if(isInsideAABB(ballPos, [this.constants.paddleX[0], this.you.left], this.constants.paddleSize)
&& ballVel[0] < 0)
{
//ballPos[0] = this.constants.paddleSize;
ballVel[0] *= - this.constants.incVel;
ballVel[1] += Math.random() * 10;
}
if(isInsideAABB(ballPos, [this.constants.paddleX[1], this.world.right], this.constants.paddleSize)
&& ballVel[0] > 0)
{
//ballPos[0] = this.constants.paddleSize;
ballVel[0] *= - this.constants.incVel;
ballVel[1] += Math.random() * 10;
}
}
var state = new GameState();
var last = null;
var canvas = document.getElementById('backbuffer');
var ctx = canvas.getContext('2d');
function step(timestamp) {
if (!last) last = timestamp;
var dt = (timestamp - last)/1000.0;
state.commands.forEach(function(x){
if(x.type == "left.up") state.stepLeft(-5);
else if(x.type == "left.down") state.stepLeft(+5);
});
if(state.commands.length > 0) console.log(state.commands);
state.commands = [];
var data = state.Data;
state.step(dt);
ctx.globalCompositeOperation = 'destination-over';
ctx.clearRect(0, 0, 800, 500); // clear canvas
ctx.fillRect(data.paddleX[0], data.left, data.paddleSize[0], data.paddleSize[1]);
ctx.fillRect(data.paddleX[1], data.right, data.paddleSize[0], data.paddleSize[1]);
ctx.fillRect(data.ball.pos[0], data.ball.pos[1], data.ballSize, data.ballSize);
//ctx.font = "bold 16px Arial";
ctx.fillText("Score", 250, 10);
ctx.fillText(data.leftScore, 200, 30);
ctx.fillText(data.rightScore, 300, 30);
last = timestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
document.addEventListener("keydown", function(e){
if(e.keyCode == 38) state.addCommand({type:"left.up"});
else if(e.keyCode == 40) state.addCommand({type:"left.down"});
return false;
}, false);
document.addEventListener("keyup", function(e){
}, false);
</script>
</body>
</html> | apache-2.0 |
NeverNight/SimplesPatterns.Java | src/com/arthurb/combining/factory/DuckFactory.java | 889 | package com.arthurb.combining.factory;
// DuckFactory расширяет абстрактную фабрику
public class DuckFactory extends AbstractDuckFactory {
// Каждый метод создает продукт: конкретную разновидностью утки. Программа не знает фактический класс создаваемого
// продукта - ей известно лишь то, что создается реализация Quackable
@Override
public Quackable createMallardDuck() {
return new MallardDuck();
}
@Override
public Quackable createRedheadDuck() {
return new RedheadDuck();
}
@Override
public Quackable createDuckCall() {
return new DuckCall();
}
@Override
public Quackable createRubberDuck() {
return new RubberDuck();
}
}
| apache-2.0 |
Krzo/gartbistro | gartbistro/foodview/login.php | 1934 | <?php
require('db.php');
$sql = "SELECT admin_id FROM gb_admin
WHERE admin_name = '$_POST[username]'
AND admin_passwort='$_POST[password]'";
$result = mysql_query($sql);
$num = mysql_num_rows($result);
if ($num > 0) {
$id = mysql_fetch_assoc($result);
setcookie("auth", "yes", time() +3600);
setcookie("admin_id", $id['admin_id']);
setcookie("admin_name", $id['admin_name']);
echo "hakan hat es geschafft";
header ("Location: http://www.gartbistro.at");
exit();
} else {
echo "hakan hat es nicht geschafft";
header ("Location: http://www.gartbistro.at");
exit();
}
/*
$_sql = "SELECT * FROM gb_admin WHERE
username='$_username' AND
passwort='$_passwort' AND
user_geloescht=0
LIMIT 1";
$_res = mysql_query($_sql, $link);
$_anzahl = @mysql_num_rows($_res);
if (!empty($_POST["submit"]))
{
$_username = mysql_real_escape_string($_POST["username"]);
$_passwort = mysql_real_escape_string($_POST["password"]);
$_sql = "SELECT * FROM gb_admin WHERE
username='$_username' AND
passwort='$_passwort' AND
user_geloescht=0
LIMIT 1";
$_res = mysql_query($_sql, $link);
$_anzahl = @mysql_num_rows($_res);
if ($_anzahl > 0)
{
echo "Sie haben sich erfolgreich angemeldet.<br>";
$_SESSION["login"] = 1;
$_SESSION["user"] = mysql_fetch_array($_res, MYSQL_ASSOC);
mysql_query($_sql);
}
else
{
echo "Benutzername oder Passwort falsch!.<br>";
header('Location: http://www.gartbistro.at/');
}
}
*/
?> | apache-2.0 |
tectronics/hyracks | hyracks/hyracks-tests/hyracks-storage-am-lsm-rtree-test/src/test/java/org/apache/hyracks/storage/am/lsm/rtree/LSMRTreeWithAntiMatterTuplesMergeTest.java | 2697 | /*
* Copyright 2009-2013 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hyracks.storage.am.lsm.rtree;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.HyracksException;
import org.apache.hyracks.storage.am.common.api.IPrimitiveValueProviderFactory;
import org.apache.hyracks.storage.am.config.AccessMethodTestsConfig;
import org.apache.hyracks.storage.am.lsm.rtree.util.LSMRTreeTestHarness;
import org.apache.hyracks.storage.am.lsm.rtree.util.LSMRTreeWithAntiMatterTuplesTestContext;
import org.apache.hyracks.storage.am.rtree.AbstractRTreeTestContext;
import org.apache.hyracks.storage.am.rtree.frames.RTreePolicyType;
@SuppressWarnings("rawtypes")
public class LSMRTreeWithAntiMatterTuplesMergeTest extends LSMRTreeMergeTestDriver {
private final LSMRTreeTestHarness harness = new LSMRTreeTestHarness();
public LSMRTreeWithAntiMatterTuplesMergeTest() {
super(AccessMethodTestsConfig.LSM_RTREE_TEST_RSTAR_POLICY);
}
@Before
public void setUp() throws HyracksException {
harness.setUp();
}
@After
public void tearDown() throws HyracksDataException {
harness.tearDown();
}
@Override
protected AbstractRTreeTestContext createTestContext(ISerializerDeserializer[] fieldSerdes,
IPrimitiveValueProviderFactory[] valueProviderFactories, int numKeys, RTreePolicyType rtreePolicyType)
throws Exception {
return LSMRTreeWithAntiMatterTuplesTestContext.create(harness.getVirtualBufferCaches(),
harness.getFileReference(), harness.getDiskBufferCache(), harness.getDiskFileMapProvider(),
fieldSerdes, valueProviderFactories, numKeys, rtreePolicyType, harness.getMergePolicy(),
harness.getOperationTracker(), harness.getIOScheduler(), harness.getIOOperationCallback());
}
@Override
protected Random getRandom() {
return harness.getRandom();
}
}
| apache-2.0 |
Intel-bigdata/OAP | oap-shuffle/remote-shuffle/src/main/java/org/apache/spark/shuffle/sort/RemoteUnsafeShuffleWriter.java | 19673 | package org.apache.spark.shuffle.sort;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.*;
import java.util.Iterator;
import javax.annotation.Nullable;
import org.apache.spark.shuffle.ShuffleWriteMetricsReporter;
import org.apache.spark.shuffle.remote.RemoteShuffleManager$;
import scala.Option;
import scala.Product2;
import scala.collection.JavaConverters;
import scala.reflect.ClassTag;
import scala.reflect.ClassTag$;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import org.apache.commons.io.output.CloseShieldOutputStream;
import org.apache.commons.io.output.CountingOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.spark.Partitioner;
import org.apache.spark.ShuffleDependency;
import org.apache.spark.SparkConf;
import org.apache.spark.TaskContext;
import org.apache.spark.annotation.Private;
import org.apache.spark.executor.ShuffleWriteMetrics;
import org.apache.spark.internal.config.package$;
import org.apache.spark.io.CompressionCodec;
import org.apache.spark.io.CompressionCodec$;
import org.apache.spark.memory.TaskMemoryManager;
import org.apache.spark.network.util.LimitedInputStream;
import org.apache.spark.scheduler.MapStatus;
import org.apache.spark.scheduler.MapStatus$;
import org.apache.spark.serializer.SerializationStream;
import org.apache.spark.serializer.SerializerInstance;
import org.apache.spark.shuffle.ShuffleWriter;
import org.apache.spark.shuffle.remote.RemoteShuffleBlockResolver;
import org.apache.spark.shuffle.remote.RemoteShuffleManager;
import org.apache.spark.shuffle.remote.RemoteShuffleUtils;
import org.apache.spark.storage.BlockManager;
import org.apache.spark.storage.TimeTrackingOutputStream;
import org.apache.spark.unsafe.Platform;
@Private
public class RemoteUnsafeShuffleWriter<K, V> extends ShuffleWriter<K, V> {
private static final Logger logger =
LoggerFactory.getLogger(RemoteUnsafeShuffleWriter.class);
static {
logger.warn("******** Optimized Remote Shuffle Writer is used ********");
}
private static final ClassTag<Object> OBJECT_CLASS_TAG = ClassTag$.MODULE$.Object();
@VisibleForTesting
static final int DEFAULT_INITIAL_SORT_BUFFER_SIZE = 4096;
static final int DEFAULT_INITIAL_SER_BUFFER_SIZE = 1024 * 1024;
private final BlockManager blockManager;
private final RemoteShuffleBlockResolver shuffleBlockResolver;
private final TaskMemoryManager memoryManager;
private final SerializerInstance serializer;
private final Partitioner partitioner;
private final int shuffleId;
private final long mapId;
private final TaskContext taskContext;
private final SparkConf sparkConf;
private final ShuffleWriteMetricsReporter writeMetrics;
private final boolean transferToEnabled;
private final int initialSortBufferSize;
private final int inputBufferSizeInBytes;
private final int outputBufferSizeInBytes;
@Nullable private MapStatus mapStatus;
@Nullable private RemoteUnsafeShuffleSorter sorter;
private long peakMemoryUsedBytes = 0;
/** Subclass of ByteArrayOutputStream that exposes `buf` directly. */
private static final class MyByteArrayOutputStream extends ByteArrayOutputStream {
MyByteArrayOutputStream(int size) { super(size); }
public byte[] getBuf() { return buf; }
}
private MyByteArrayOutputStream serBuffer;
private SerializationStream serOutputStream;
/**
* Are we in the process of stopping? Because map tasks can call stop() with success = true
* and then call stop() with success = false if they get an exception, we want to make sure
* we don't try deleting files, etc twice.
*/
private boolean stopping = false;
private class CloseAndFlushShieldOutputStream extends CloseShieldOutputStream {
CloseAndFlushShieldOutputStream(OutputStream outputStream) {
super(outputStream);
}
@Override
public void flush() {
// do nothing
}
}
public RemoteUnsafeShuffleWriter(
BlockManager blockManager,
RemoteShuffleBlockResolver shuffleBlockResolver,
TaskMemoryManager memoryManager,
SerializedShuffleHandle<K, V> handle,
long mapId,
TaskContext taskContext,
SparkConf sparkConf,
ShuffleWriteMetricsReporter metrics) throws IOException {
final int numPartitions = handle.dependency().partitioner().numPartitions();
if (numPartitions > SortShuffleManager.MAX_SHUFFLE_OUTPUT_PARTITIONS_FOR_SERIALIZED_MODE()) {
throw new IllegalArgumentException(
"RemoteUnsafeShuffleWriter can only be used for shuffles with at most " +
SortShuffleManager.MAX_SHUFFLE_OUTPUT_PARTITIONS_FOR_SERIALIZED_MODE() +
" reduce partitions");
}
this.blockManager = blockManager;
this.shuffleBlockResolver = shuffleBlockResolver;
this.memoryManager = memoryManager;
this.mapId = mapId;
final ShuffleDependency<K, V, V> dep = handle.dependency();
this.shuffleId = dep.shuffleId();
this.serializer = dep.serializer().newInstance();
this.partitioner = dep.partitioner();
this.taskContext = taskContext;
this.sparkConf = sparkConf;
this.writeMetrics = metrics;
this.transferToEnabled = sparkConf.getBoolean("spark.file.transferTo", true);
this.initialSortBufferSize = sparkConf.getInt("spark.shuffle.sort.initialBufferSize",
DEFAULT_INITIAL_SORT_BUFFER_SIZE);
this.inputBufferSizeInBytes =
(int) (long) sparkConf
.get(package$.MODULE$.SHUFFLE_FILE_BUFFER_SIZE()) * 1024;
this.outputBufferSizeInBytes =
(int) (long) sparkConf
.get(package$.MODULE$.SHUFFLE_UNSAFE_FILE_OUTPUT_BUFFER_SIZE()) * 1024;
open();
}
private void updatePeakMemoryUsed() {
// sorter can be null if this writer is closed
if (sorter != null) {
long mem = sorter.getPeakMemoryUsedBytes();
if (mem > peakMemoryUsedBytes) {
peakMemoryUsedBytes = mem;
}
}
}
/**
* Return the peak memory used so far, in bytes.
*/
public long getPeakMemoryUsedBytes() {
updatePeakMemoryUsed();
return peakMemoryUsedBytes;
}
/**
* This convenience method should only be called in test code.
*/
@VisibleForTesting
public void write(Iterator<Product2<K, V>> records) throws IOException {
write(JavaConverters.asScalaIteratorConverter(records).asScala());
}
@Override
public void write(scala.collection.Iterator<Product2<K, V>> records) throws IOException {
// Keep track of success so we know if we encountered an exception
// We do this rather than a standard try/catch/re-throw to handle
// generic throwables.
boolean success = false;
try {
while (records.hasNext()) {
insertRecordIntoSorter(records.next());
}
closeAndWriteOutput();
success = true;
} finally {
if (sorter != null) {
try {
sorter.cleanupResources();
} catch (Exception e) {
// Only throw this error if we won't be masking another
// error.
if (success) {
throw e;
} else {
logger.error("In addition to a failure during writing, we failed during " +
"cleanup.", e);
}
}
}
}
}
private void open() {
assert (sorter == null);
sorter = new RemoteUnsafeShuffleSorter(
memoryManager,
blockManager,
taskContext,
shuffleBlockResolver,
initialSortBufferSize,
partitioner.numPartitions(),
sparkConf,
writeMetrics);
serBuffer = new RemoteUnsafeShuffleWriter
.MyByteArrayOutputStream(DEFAULT_INITIAL_SER_BUFFER_SIZE);
serOutputStream = serializer.serializeStream(serBuffer);
}
@VisibleForTesting
void closeAndWriteOutput() throws IOException {
assert(sorter != null);
updatePeakMemoryUsed();
serBuffer = null;
serOutputStream = null;
final RemoteSpillInfo[] spills = sorter.closeAndGetSpills();
sorter = null;
final long[] partitionLengths;
final Path output = shuffleBlockResolver.getDataFile(shuffleId, mapId);
final Path tmp = RemoteShuffleUtils.tempPathWith(output);
FileSystem fs = RemoteShuffleManager.getFileSystem();
try {
try {
partitionLengths = mergeSpills(spills, tmp);
} finally {
for (RemoteSpillInfo spill : spills) {
if (fs.exists(spill.file) && ! fs.delete(spill.file, true)) {
logger.error("Error while deleting spill file {}", spill.file.toString());
}
}
}
shuffleBlockResolver.writeIndexFileAndCommit(shuffleId, mapId, partitionLengths, tmp);
} finally {
if (fs.exists(tmp) && !fs.delete(tmp, true)) {
logger.error("Error while deleting temp file {}", tmp.toString());
}
}
mapStatus = MapStatus$.MODULE$.apply(
RemoteShuffleManager$.MODULE$.getResolver().shuffleServerId(), partitionLengths, mapId);
}
@VisibleForTesting
void insertRecordIntoSorter(Product2<K, V> record) throws IOException {
assert(sorter != null);
final K key = record._1();
final int partitionId = partitioner.getPartition(key);
serBuffer.reset();
serOutputStream.writeKey(key, OBJECT_CLASS_TAG);
serOutputStream.writeValue(record._2(), OBJECT_CLASS_TAG);
serOutputStream.flush();
final int serializedRecordSize = serBuffer.size();
assert (serializedRecordSize > 0);
sorter.insertRecord(
serBuffer.getBuf(), Platform.BYTE_ARRAY_OFFSET, serializedRecordSize, partitionId);
}
@VisibleForTesting
void forceSorterToSpill() throws IOException {
assert (sorter != null);
sorter.spill();
}
/**
* Merge zero or more spill files together, choosing the fastest merging strategy based on the
* number of spills and the IO compression codec.
*
* @return the partition lengths in the merged file.
*/
private long[] mergeSpills(RemoteSpillInfo[] spills, Path outputFile) throws IOException {
final FileSystem fs = RemoteShuffleManager.getFileSystem();
final boolean compressionEnabled = sparkConf.getBoolean("spark.shuffle.compress", true);
final CompressionCodec compressionCodec = CompressionCodec$.MODULE$.createCodec(sparkConf);
final boolean fastMergeEnabled =
sparkConf.getBoolean("spark.shuffle.unsafe.fastMergeEnabled", true);
final boolean fastMergeIsSupported = !compressionEnabled ||
CompressionCodec$.MODULE$.supportsConcatenationOfSerializedStreams(compressionCodec);
try {
if (spills.length == 0) {
fs.create(outputFile).close(); // Create an empty file
return new long[partitioner.numPartitions()];
} else if (spills.length == 1) {
// Here, we don't need to perform any metrics updates because the bytes written to this
// output file would have already been counted as shuffle bytes written.
fs.rename(spills[0].file, outputFile);
return spills[0].partitionLengths;
} else {
final long[] partitionLengths;
// There are multiple spills to merge, so none of these spill files' lengths were counted
// towards our shuffle write count or shuffle write time. If we use the slow merge path,
// then the final output file's size won't necessarily be equal to the sum of the spill
// files' sizes. To guard against this case, we look at the output file's actual size when
// computing shuffle bytes written.
//
// We allow the individual merge methods to report their own IO times since different merge
// strategies use different IO techniques. We count IO during merge towards the shuffle
// shuffle write time, which appears to be consistent with the "not bypassing merge-sort"
// branch in ExternalSorter.
// We do not perform a transferTo-optimized merge due to underground storage may not support
// this (NIO FileChannel.transferTo)
if (fastMergeEnabled && fastMergeIsSupported) {
// Compression is disabled or we are using an IO compression codec that supports
// decompression of concatenated compressed streams, so we can perform a fast spill merge
// that doesn't need to interpret the spilled bytes.
logger.debug("Using fileStream-based fast merge");
partitionLengths = mergeSpillsWithFileStream(spills, outputFile, null);
} else {
logger.debug("Using slow merge");
partitionLengths = mergeSpillsWithFileStream(spills, outputFile, compressionCodec);
}
// When closing an UnsafeShuffleExternalSorter that has already spilled once but also has
// in-memory records, we write out the in-memory records to a file but do not count that
// final write as bytes spilled (instead, it's accounted as shuffle write). The merge needs
// to be counted as shuffle write, but this will lead to double-counting of the final
// RemoteSpillInfo's bytes.
writeMetrics.decBytesWritten(fs.getFileStatus(spills[spills.length - 1].file).getLen());
writeMetrics.incBytesWritten(fs.getFileStatus(outputFile).getLen());
return partitionLengths;
}
} catch (IOException e) {
if (fs.exists(outputFile) && !fs.delete(outputFile, true)) {
logger.error("Unable to delete output file {}", outputFile.toString());
}
throw e;
}
}
/**
* Merges spill files using Java FileStreams. This code path is typically slower than
* the NIO-based merge,
* {@link RemoteUnsafeShuffleWriter#mergeSpillsWithTransferTo(RemoteSpillInfo[],
* Path)}, and it's mostly used in cases where the IO compression codec does not support
* concatenation of compressed data, when encryption is enabled, or when users have
* explicitly disabled use of {@code transferTo} in order to work around kernel bugs.
* This code path might also be faster in cases where individual partition size in a spill
* is small and RemoteUnsafeShuffleWriter#mergeSpillsWithTransferTo method performs many small
* disk ios which is inefficient. In those case, Using large buffers for input and output
* files helps reducing the number of disk ios, making the file merging faster.
*
* @param spills the spills to merge.
* @param outputFile the file to write the merged data to.
* @param compressionCodec the IO compression codec, or null if shuffle compression is disabled.
* @return the partition lengths in the merged file.
*/
private long[] mergeSpillsWithFileStream(
RemoteSpillInfo[] spills,
Path outputFile,
@Nullable CompressionCodec compressionCodec) throws IOException {
assert (spills.length >= 2);
final FileSystem fs = RemoteShuffleManager.getFileSystem();
final int numPartitions = partitioner.numPartitions();
final long[] partitionLengths = new long[numPartitions];
final InputStream[] spillInputStreams = new InputStream[spills.length];
final OutputStream bos = new BufferedOutputStream(
fs.create(outputFile),
outputBufferSizeInBytes);
// Use a counting output stream to avoid having to close the underlying file and ask
// the file system for its size after each partition is written.
final CountingOutputStream mergedFileOutputStream = new CountingOutputStream(bos);
boolean threwException = true;
try {
for (int i = 0; i < spills.length; i++) {
// Note by Chenzhao: Originally NioBufferedFileInputStream is used
spillInputStreams[i] = new BufferedInputStream(
fs.open(spills[i].file),
inputBufferSizeInBytes);
}
for (int partition = 0; partition < numPartitions; partition++) {
final long initialFileLength = mergedFileOutputStream.getByteCount();
// Shield the underlying output stream from close() and flush() calls, so that
// we can close the higher level streams to make sure all data is really flushed
// and internal state is cleaned.
OutputStream partitionOutput =
new RemoteUnsafeShuffleWriter.CloseAndFlushShieldOutputStream(
new TimeTrackingOutputStream(writeMetrics, mergedFileOutputStream));
partitionOutput = blockManager.serializerManager().wrapForEncryption(partitionOutput);
if (compressionCodec != null) {
partitionOutput = compressionCodec.compressedOutputStream(partitionOutput);
}
for (int i = 0; i < spills.length; i++) {
final long partitionLengthInSpill = spills[i].partitionLengths[partition];
if (partitionLengthInSpill > 0) {
InputStream partitionInputStream = new LimitedInputStream(spillInputStreams[i],
partitionLengthInSpill, false);
try {
partitionInputStream = blockManager.serializerManager().wrapForEncryption(
partitionInputStream);
if (compressionCodec != null) {
partitionInputStream = compressionCodec.compressedInputStream(partitionInputStream);
}
ByteStreams.copy(partitionInputStream, partitionOutput);
} finally {
partitionInputStream.close();
}
}
}
partitionOutput.flush();
partitionOutput.close();
partitionLengths[partition] = (mergedFileOutputStream.getByteCount() - initialFileLength);
}
threwException = false;
} finally {
// To avoid masking exceptions that caused us to prematurely enter the finally block, only
// throw exceptions during cleanup if threwException == false.
for (InputStream stream : spillInputStreams) {
Closeables.close(stream, threwException);
}
Closeables.close(mergedFileOutputStream, threwException);
}
return partitionLengths;
}
@Override
public Option<MapStatus> stop(boolean success) {
try {
taskContext.taskMetrics().incPeakExecutionMemory(getPeakMemoryUsedBytes());
if (stopping) {
return Option.apply(null);
} else {
stopping = true;
if (success) {
if (mapStatus == null) {
throw new IllegalStateException("Cannot call stop(true) without having called write()");
}
return Option.apply(mapStatus);
} else {
return Option.apply(null);
}
}
} finally {
if (sorter != null) {
// If sorter is non-null, then this implies that we called stop() in response to an error,
// so we need to clean up memory and spill files created by the sorter
try {
sorter.cleanupResources();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| apache-2.0 |
daileyet/webscheduler | src/main/java/com/openthinks/webscheduler/help/confs/SecurityConfig.java | 3977 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* @Title: SecurityConfig.java
* @Package com.openthinks.webscheduler.help.confs
* @Description: TODO
* @author [email protected]
* @date Aug 23, 2016
* @version V1.0
*/
package com.openthinks.webscheduler.help.confs;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.openthinks.easyweb.WebUtils;
import com.openthinks.easyweb.context.WebContexts;
import com.openthinks.libs.utilities.CommonUtilities;
import com.openthinks.libs.utilities.logger.ProcessLogger;
import com.openthinks.webscheduler.exception.FailedConfigPath;
import com.openthinks.webscheduler.exception.UnSupportConfigPath;
import com.openthinks.webscheduler.help.StaticDict;
import com.openthinks.webscheduler.model.security.WebSecurity;
import com.openthinks.webscheduler.service.WebSecurityService;
/**
* @author [email protected]
*
*/
public final class SecurityConfig extends AbstractConfigObject {
private WebSecurity webSecurity;
SecurityConfig(String configPath, ConfigObject parent) {
super(configPath, parent);
}
SecurityConfig(String configPath) {
super(configPath);
}
/*
* (non-Javadoc)
*
* @see com.openthinks.webscheduler.help.confs.ConfigObject#config()
*/
@Override
public void config() {
ProcessLogger.debug(getClass() + " start config...");
try {
InputStream in = new FileInputStream(getConfigFile());
unmarshal(in);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public File getConfigFile() {
File configFile = null;
if (configPath.startsWith(StaticDict.CLASS_PATH_PREFIX)) {// classpath:/conf/security.xml
String classpath = configPath.substring(StaticDict.CLASS_PATH_PREFIX.length());
configFile = new File(WebUtils.getWebClassDir(), classpath);
ProcessLogger.debug(CommonUtilities.getCurrentInvokerMethod(), configFile.getAbsolutePath());
} else if (configPath.startsWith(StaticDict.FILE_PREFIX)) {// file:R:/MyGit/webscheduler/target/classes/conf/security.xml
String filePath = configPath.substring(StaticDict.FILE_PREFIX.length());
File file = new File(filePath), absoulteFile = file, relativeFile = null;
if (!absoulteFile.exists()) {
relativeFile = new File(WebUtils.getWebClassDir(), filePath);
file = relativeFile;
}
if (file == null || !file.exists()) {
throw new FailedConfigPath(configPath);
}
configFile = file;
} else {
throw new UnSupportConfigPath(configPath);
}
return configFile;
}
public WebSecurity getWebSecurity() {
return webSecurity;
}
private void unmarshal(InputStream in) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(WebSecurity.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
this.webSecurity = (WebSecurity) unmarshaller.unmarshal(in);
WebContexts.get().lookup(WebSecurityService.class).init(this);
}
}
| apache-2.0 |
googleads/google-ads-php | tests/Google/Ads/GoogleAds/V9/Services/InvoiceServiceClientTest.php | 5040 | <?php
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* GENERATED CODE WARNING
* This file was automatically generated - do not edit!
*/
namespace Google\Ads\GoogleAds\V9\Services;
use Google\Ads\GoogleAds\V9\Services\InvoiceServiceClient;
use Google\Ads\GoogleAds\V9\Enums\MonthOfYearEnum\MonthOfYear;
use Google\Ads\GoogleAds\V9\Services\ListInvoicesResponse;
use Google\ApiCore\ApiException;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\Testing\GeneratedTest;
use Google\ApiCore\Testing\MockTransport;
use Google\Rpc\Code;
use stdClass;
/**
* @group services
*
* @group gapic
*/
class InvoiceServiceClientTest extends GeneratedTest
{
/**
* @return TransportInterface
*/
private function createTransport($deserialize = null)
{
return new MockTransport($deserialize);
}
/**
* @return CredentialsWrapper
*/
private function createCredentials()
{
return $this->getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock();
}
/**
* @return InvoiceServiceClient
*/
private function createClient(array $options = [])
{
$options += [
'credentials' => $this->createCredentials(),
];
return new InvoiceServiceClient($options);
}
/**
* @test
*/
public function listInvoicesTest()
{
$transport = $this->createTransport();
$client = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
// Mock response
$expectedResponse = new ListInvoicesResponse();
$transport->addResponse($expectedResponse);
// Mock request
$customerId = 'customerId-1772061412';
$billingSetup = 'billingSetup-1181632583';
$issueYear = 'issueYear1443510243';
$issueMonth = MonthOfYear::UNSPECIFIED;
$response = $client->listInvoices($customerId, $billingSetup, $issueYear, $issueMonth);
$this->assertEquals($expectedResponse, $response);
$actualRequests = $transport->popReceivedCalls();
$this->assertSame(1, count($actualRequests));
$actualFuncCall = $actualRequests[0]->getFuncCall();
$actualRequestObject = $actualRequests[0]->getRequestObject();
$this->assertSame('/google.ads.googleads.v9.services.InvoiceService/ListInvoices', $actualFuncCall);
$actualValue = $actualRequestObject->getCustomerId();
$this->assertProtobufEquals($customerId, $actualValue);
$actualValue = $actualRequestObject->getBillingSetup();
$this->assertProtobufEquals($billingSetup, $actualValue);
$actualValue = $actualRequestObject->getIssueYear();
$this->assertProtobufEquals($issueYear, $actualValue);
$actualValue = $actualRequestObject->getIssueMonth();
$this->assertProtobufEquals($issueMonth, $actualValue);
$this->assertTrue($transport->isExhausted());
}
/**
* @test
*/
public function listInvoicesExceptionTest()
{
$transport = $this->createTransport();
$client = $this->createClient([
'transport' => $transport,
]);
$this->assertTrue($transport->isExhausted());
$status = new stdClass();
$status->code = Code::DATA_LOSS;
$status->details = 'internal error';
$expectedExceptionMessage = json_encode([
'message' => 'internal error',
'code' => Code::DATA_LOSS,
'status' => 'DATA_LOSS',
'details' => [],
], JSON_PRETTY_PRINT);
$transport->addResponse(null, $status);
// Mock request
$customerId = 'customerId-1772061412';
$billingSetup = 'billingSetup-1181632583';
$issueYear = 'issueYear1443510243';
$issueMonth = MonthOfYear::UNSPECIFIED;
try {
$client->listInvoices($customerId, $billingSetup, $issueYear, $issueMonth);
// If the $client method call did not throw, fail the test
$this->fail('Expected an ApiException, but no exception was thrown.');
} catch (ApiException $ex) {
$this->assertEquals($status->code, $ex->getCode());
$this->assertEquals($expectedExceptionMessage, $ex->getMessage());
}
// Call popReceivedCalls to ensure the stub is exhausted
$transport->popReceivedCalls();
$this->assertTrue($transport->isExhausted());
}
}
| apache-2.0 |
veggiespam/zap-extensions | addOns/pscanrules/src/test/java/org/zaproxy/zap/extension/pscanrules/CrossDomainScriptInclusionScannerUnitTest.java | 14297 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2016 The ZAP Development Team
*
* 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.zaproxy.zap.extension.pscanrules;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.parosproxy.paros.core.scanner.Plugin.AlertThreshold;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.model.Context;
/** Unit test for {@link CrossDomainScriptInclusionScanner}. */
public class CrossDomainScriptInclusionScannerUnitTest
extends PassiveScannerTest<CrossDomainScriptInclusionScanner> {
@Mock Model model;
@Mock Session session;
@Before
public void setup() {
when(session.getContextsForUrl(anyString())).thenReturn(Collections.emptyList());
when(model.getSession()).thenReturn(session);
rule.setModel(model);
}
@Override
protected CrossDomainScriptInclusionScanner createScanner() {
return new CrossDomainScriptInclusionScanner();
}
@Test
public void noScripts() throws HttpMalformedHeaderException {
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET http://www.example.com/test/ HTTP/1.1");
msg.setResponseBody("<html></html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(0));
}
@Test
public void noCrossDomainScripts() throws HttpMalformedHeaderException {
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.example.com/script2\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(0));
}
@Test
public void crossDomainScript() throws HttpMalformedHeaderException {
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.otherDomain.com/script2\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(1));
assertThat(alertsRaised.get(0).getParam(), equalTo("https://www.otherDomain.com/script2"));
assertThat(
alertsRaised.get(0).getEvidence(),
equalTo("<script src=\"https://www.otherDomain.com/script2\"/>"));
}
@Test
public void crossDomainScriptWithIntegrity() throws HttpMalformedHeaderException {
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.otherDomain.com/script2\" integrity=\"12345678\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(0));
}
@Test
public void crossDomainScriptWithNullIntegrity() throws HttpMalformedHeaderException {
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.otherDomain.com/script2\" integrity=\"\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(1));
assertThat(alertsRaised.get(0).getParam(), equalTo("https://www.otherDomain.com/script2"));
assertThat(
alertsRaised.get(0).getEvidence(),
equalTo("<script src=\"https://www.otherDomain.com/script2\" integrity=\"\"/>"));
}
@Test
public void crossDomainScriptNotInContext() throws HttpMalformedHeaderException {
// Given
Context context = new Context(session, -1);
context.addIncludeInContextRegex("https://www.example.com/.*");
when(session.getContextsForUrl(anyString())).thenReturn(asList(context));
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.otherDomain.com/script2\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(1));
assertThat(alertsRaised.get(0).getParam(), equalTo("https://www.otherDomain.com/script2"));
assertThat(
alertsRaised.get(0).getEvidence(),
equalTo("<script src=\"https://www.otherDomain.com/script2\"/>"));
}
@Test
public void shouldIgnoreNonHtmlResponses() throws HttpMalformedHeaderException {
// Given
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/thing.js HTTP/1.1");
msg.setResponseBody(
"/* ------------------------------------------------------------\n"
+ "Sample usage:\n"
+ "<script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.8.2.min.js\"></script>\n"
+ "<script type=\"text/javascript\" src=\"http://code.jquery.com/ui/1.9.0/jquery-ui.js\"></script>\n"
+ "...\n"
+ "----------------------------------------------------------- */\n"
+ "function myFunction(p1, p2) {\n"
+ " return p1 * p2;\n"
+ "}\n");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: application/javascript\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
// When
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
// Then
assertThat(alertsRaised.size(), equalTo(0));
}
@Test
public void crossDomainScriptInContextHigh() throws HttpMalformedHeaderException {
// Given
Context context = new Context(session, -1);
context.addIncludeInContextRegex("https://www.example.com/.*");
context.addIncludeInContextRegex("https://www.otherDomain.com/.*");
when(session.getContextsForUrl(anyString())).thenReturn(asList(context));
rule.setAlertThreshold(AlertThreshold.HIGH);
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.otherDomain.com/script2\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(0));
}
@Test
public void crossDomainScriptInContextMed() throws HttpMalformedHeaderException {
// Given
Context context = new Context(session, -1);
context.addIncludeInContextRegex("https://www.example.com/.*");
context.addIncludeInContextRegex("https://www.otherDomain.com/.*");
when(session.getContextsForUrl(anyString())).thenReturn(asList(context));
rule.setAlertThreshold(AlertThreshold.MEDIUM);
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.otherDomain.com/script2\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(0));
}
@Test
public void crossDomainScriptInContextLow() throws HttpMalformedHeaderException {
// Given
rule.setAlertThreshold(AlertThreshold.LOW);
HttpMessage msg = new HttpMessage();
msg.setRequestHeader("GET https://www.example.com/test/ HTTP/1.1");
msg.setResponseBody(
"<html>"
+ "<head>"
+ "<script src=\"https://www.example.com/script1\"/>"
+ "<script src=\"https://www.otherDomain.com/script2\"/>"
+ "<head>"
+ "</html>");
msg.setResponseHeader(
"HTTP/1.1 200 OK\r\n"
+ "Server: Apache-Coyote/1.1\r\n"
+ "Content-Type: text/html;charset=ISO-8859-1\r\n"
+ "Content-Length: "
+ msg.getResponseBody().length()
+ "\r\n");
rule.scanHttpResponseReceive(msg, -1, this.createSource(msg));
assertThat(alertsRaised.size(), equalTo(1));
assertThat(alertsRaised.get(0).getParam(), equalTo("https://www.otherDomain.com/script2"));
assertThat(
alertsRaised.get(0).getEvidence(),
equalTo("<script src=\"https://www.otherDomain.com/script2\"/>"));
}
}
| apache-2.0 |
CarloMicieli/java8-for-hipsters | src/test/java/io/github/carlomicieli/java8/streams/IntStreamTests.java | 4652 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.carlomicieli.java8.streams;
import org.junit.Test;
import java.util.List;
import java.util.function.IntSupplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
/**
* @author Carlo Micieli
*/
public class IntStreamTests {
@Test(expected = IllegalStateException.class)
public void terminalOperations_shouldCloseIntStreams_anyFurtherOperationShouldThrowException() {
IntStream intStream = IntStream.of(1);
intStream.count();
intStream.max(); // <-- stream has been closed by count()
}
@Test
public void builder_shouldBuildNewIntStreams() {
IntStream intStream = IntStream.builder().add(1).add(2).add(3).build();
List<Integer> values = valuesOf(intStream);
assertThat(values, hasSize(3));
assertThat(values, hasItems(1, 2, 3));
}
@Test(expected = IllegalStateException.class)
public void builder_shouldThrowIllegalStateException_modifyingAlreadyBuildIntStreams() {
IntStream.Builder builder = IntStream.builder().add(1).add(2);
builder.build();
builder.add(5);
}
@Test
public void range_shouldReturnsAnOrderedSequenceWithIncrementOf1() {
IntStream s = IntStream.range(1, 10);
List<Integer> values = valuesOf(s);
assertThat(values, hasSize(9));
assertThat(values, hasItems(1, 2, 3, 4, 5, 6, 7, 8, 9));
}
@Test
public void concat_shouldConcatTwoIntStreams() {
IntStream intStream1 = IntStream.builder().add(1).add(3).add(5).build();
IntStream intStream2 = IntStream.builder().add(2).add(4).add(6).build();
IntStream intStream = IntStream.concat(intStream1, intStream2);
List<Integer> values = valuesOf(intStream);
assertThat(values, hasSize(6));
assertThat(values, hasItems(1, 3, 5, 2, 4, 6));
}
@Test
public void rangeClosed_shouldReturnsAnOrderedAndClosedSequenceWithIncrementOf1() {
IntStream s = IntStream.rangeClosed(1, 10);
List<Integer> values = valuesOf(s);
assertThat(values, hasSize(10));
assertThat(values, hasItems(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
@Test
public void generate_shouldReturnInfiniteSequenceGeneratedByTheProvidedSupplier() {
IntSupplier onesSupplier = () -> 1;
IntStream infinite = IntStream.generate(onesSupplier);
int sum = infinite.limit(100L).sum();
assertThat(sum, is(equalTo(100)));
}
@Test
public void empty_shouldGenerateEmptyIntStreams() {
IntStream empty = IntStream.empty();
assertThat(empty.count(), is(equalTo(0L)));
}
@Test
public void iterate_shouldGenerateIntStreams_producedByIterativeFunctions() {
IntStream powersOf2 = IntStream.iterate(2, n -> n * 2).limit(10);
List<Integer> values = valuesOf(powersOf2);
assertThat(values, hasSize(10));
}
@Test
public void of_shouldGenerateIntStreams_withTheProvidedValues() {
IntStream streamOf2and5 = IntStream.of(2, 5);
assertThat(streamOf2and5.count(), is(equalTo(2L)));
}
@Test
public void allMatch_shouldCheckWhetherAllElements_matchTheProvidedPredicate() {
boolean match = IntStream
.iterate(2, n -> n * 2)
.limit(10)
.allMatch(n -> n % 2 == 0);
assertThat(match, is(true));
}
@Test
public void noneMatch_shouldCheckWhetherNoElement_matchTheProvidedPredicate() {
boolean noneMatch = IntStream
.iterate(2, n -> n * 2)
.limit(10)
.noneMatch(n -> n % 2 != 0);
assertThat(noneMatch, is(true));
}
private static List<Integer> valuesOf(IntStream is) {
return is.boxed().collect(Collectors.toList());
}
}
| apache-2.0 |
jskeet/google-api-dotnet-client | Src/Generated/Google.Apis.CloudIot.v1/Google.Apis.CloudIot.v1.cs | 168368 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.CloudIot.v1
{
/// <summary>The CloudIot Service.</summary>
public class CloudIotService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudIotService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudIotService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "cloudiot";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://cloudiot.googleapis.com/";
#else
"https://cloudiot.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://cloudiot.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Cloud IoT API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Register and manage devices in the Google Cloud IoT service</summary>
public static string Cloudiot = "https://www.googleapis.com/auth/cloudiot";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Cloud IoT API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Register and manage devices in the Google Cloud IoT service</summary>
public const string Cloudiot = "https://www.googleapis.com/auth/cloudiot";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for CloudIot requests.</summary>
public abstract class CloudIotBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new CloudIotBaseServiceRequest instance.</summary>
protected CloudIotBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudIot parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Registries = new RegistriesResource(service);
}
/// <summary>Gets the Registries resource.</summary>
public virtual RegistriesResource Registries { get; }
/// <summary>The "registries" collection of methods.</summary>
public class RegistriesResource
{
private const string Resource = "registries";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public RegistriesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Devices = new DevicesResource(service);
Groups = new GroupsResource(service);
}
/// <summary>Gets the Devices resource.</summary>
public virtual DevicesResource Devices { get; }
/// <summary>The "devices" collection of methods.</summary>
public class DevicesResource
{
private const string Resource = "devices";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DevicesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
ConfigVersions = new ConfigVersionsResource(service);
States = new StatesResource(service);
}
/// <summary>Gets the ConfigVersions resource.</summary>
public virtual ConfigVersionsResource ConfigVersions { get; }
/// <summary>The "configVersions" collection of methods.</summary>
public class ConfigVersionsResource
{
private const string Resource = "configVersions";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ConfigVersionsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Lists the last few versions of the device configuration in descending order (i.e.: newest
/// first).
/// </summary>
/// <param name="name">
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists the last few versions of the device configuration in descending order (i.e.: newest
/// first).
/// </summary>
public class ListRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.ListDeviceConfigVersionsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// The number of versions to list. Versions are listed in decreasing order of the version
/// number. The maximum number of versions retained is 10. If this value is zero, it will
/// return all the versions available.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("numVersions", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> NumVersions { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/configVersions";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/devices/[^/]+$",
});
RequestParameters.Add("numVersions", new Google.Apis.Discovery.Parameter
{
Name = "numVersions",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Gets the States resource.</summary>
public virtual StatesResource States { get; }
/// <summary>The "states" collection of methods.</summary>
public class StatesResource
{
private const string Resource = "states";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public StatesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Lists the last few versions of the device state in descending order (i.e.: newest first).
/// </summary>
/// <param name="name">
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists the last few versions of the device state in descending order (i.e.: newest first).
/// </summary>
public class ListRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.ListDeviceStatesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// The number of states to list. States are listed in descending order of update time. The
/// maximum number of states retained is 10. If this value is zero, it will return all the
/// states available.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("numStates", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> NumStates { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}/states";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/devices/[^/]+$",
});
RequestParameters.Add("numStates", new Google.Apis.Discovery.Parameter
{
Name = "numStates",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Creates a device in a device registry.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The name of the device registry where this device should be created. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual CreateRequest Create(Google.Apis.CloudIot.v1.Data.Device body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a device in a device registry.</summary>
public class CreateRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Device>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.Device body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The name of the device registry where this device should be created. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.Device Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/devices";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
/// <summary>Deletes a device.</summary>
/// <param name="name">
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a device.</summary>
public class DeleteRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/devices/[^/]+$",
});
}
}
/// <summary>Gets details about a device.</summary>
/// <param name="name">
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets details about a device.</summary>
public class GetRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Device>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// The fields of the `Device` resource to be returned in the response. If the field mask is
/// unset or empty, all fields are returned. Fields have to be provided in snake_case format,
/// for example: `last_heartbeat_time`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("fieldMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object FieldMask { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/devices/[^/]+$",
});
RequestParameters.Add("fieldMask", new Google.Apis.Discovery.Parameter
{
Name = "fieldMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>List devices in a device registry.</summary>
/// <param name="parent">
/// Required. The device registry path. Required. For example,
/// `projects/my-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>List devices in a device registry.</summary>
public class ListRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.ListDevicesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The device registry path. Required. For example,
/// `projects/my-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// A list of device string IDs. For example, `['device0', 'device12']`. If empty, this field is
/// ignored. Maximum IDs: 10,000
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("deviceIds", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> DeviceIds { get; set; }
/// <summary>
/// A list of device numeric IDs. If empty, this field is ignored. Maximum IDs: 10,000.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("deviceNumIds", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> DeviceNumIds { get; set; }
/// <summary>
/// The fields of the `Device` resource to be returned in the response. The fields `id` and
/// `num_id` are always returned, along with any other fields specified in snake_case format,
/// for example: `last_heartbeat_time`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("fieldMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object FieldMask { get; set; }
/// <summary>
/// If set, returns only the gateways with which the specified device is associated. The device
/// ID can be numeric (`num_id`) or the user-defined string (`id`). For example, if `456` is
/// specified, returns only the gateways to which the device with `num_id` 456 is bound.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("gatewayListOptions.associationsDeviceId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string GatewayListOptionsAssociationsDeviceId { get; set; }
/// <summary>
/// If set, only devices associated with the specified gateway are returned. The gateway ID can
/// be numeric (`num_id`) or the user-defined string (`id`). For example, if `123` is specified,
/// only devices bound to the gateway with `num_id` 123 are returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("gatewayListOptions.associationsGatewayId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string GatewayListOptionsAssociationsGatewayId { get; set; }
/// <summary>
/// If `GATEWAY` is specified, only gateways are returned. If `NON_GATEWAY` is specified, only
/// non-gateway devices are returned. If `GATEWAY_TYPE_UNSPECIFIED` is specified, all devices
/// are returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("gatewayListOptions.gatewayType", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<GatewayListOptionsGatewayTypeEnum> GatewayListOptionsGatewayType { get; set; }
/// <summary>
/// If `GATEWAY` is specified, only gateways are returned. If `NON_GATEWAY` is specified, only
/// non-gateway devices are returned. If `GATEWAY_TYPE_UNSPECIFIED` is specified, all devices
/// are returned.
/// </summary>
public enum GatewayListOptionsGatewayTypeEnum
{
/// <summary>If unspecified, the device is considered a non-gateway device.</summary>
[Google.Apis.Util.StringValueAttribute("GATEWAY_TYPE_UNSPECIFIED")]
GATEWAYTYPEUNSPECIFIED = 0,
/// <summary>The device is a gateway.</summary>
[Google.Apis.Util.StringValueAttribute("GATEWAY")]
GATEWAY = 1,
/// <summary>The device is not a gateway.</summary>
[Google.Apis.Util.StringValueAttribute("NON_GATEWAY")]
NONGATEWAY = 2,
}
/// <summary>
/// The maximum number of devices to return in the response. If this value is zero, the service
/// will select a default size. A call may return fewer objects than requested. A non-empty
/// `next_page_token` in the response indicates that more data is available.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// The value returned by the last `ListDevicesResponse`; indicates that this is a continuation
/// of a prior `ListDevices` call and the system should return the next page of data.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/devices";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
RequestParameters.Add("deviceIds", new Google.Apis.Discovery.Parameter
{
Name = "deviceIds",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("deviceNumIds", new Google.Apis.Discovery.Parameter
{
Name = "deviceNumIds",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fieldMask", new Google.Apis.Discovery.Parameter
{
Name = "fieldMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("gatewayListOptions.associationsDeviceId", new Google.Apis.Discovery.Parameter
{
Name = "gatewayListOptions.associationsDeviceId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("gatewayListOptions.associationsGatewayId", new Google.Apis.Discovery.Parameter
{
Name = "gatewayListOptions.associationsGatewayId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("gatewayListOptions.gatewayType", new Google.Apis.Discovery.Parameter
{
Name = "gatewayListOptions.gatewayType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Modifies the configuration for the device, which is eventually sent from the Cloud IoT Core
/// servers. Returns the modified configuration version and its metadata.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </param>
public virtual ModifyCloudToDeviceConfigRequest ModifyCloudToDeviceConfig(Google.Apis.CloudIot.v1.Data.ModifyCloudToDeviceConfigRequest body, string name)
{
return new ModifyCloudToDeviceConfigRequest(service, body, name);
}
/// <summary>
/// Modifies the configuration for the device, which is eventually sent from the Cloud IoT Core
/// servers. Returns the modified configuration version and its metadata.
/// </summary>
public class ModifyCloudToDeviceConfigRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.DeviceConfig>
{
/// <summary>Constructs a new ModifyCloudToDeviceConfig request.</summary>
public ModifyCloudToDeviceConfigRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.ModifyCloudToDeviceConfigRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.ModifyCloudToDeviceConfigRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "modifyCloudToDeviceConfig";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:modifyCloudToDeviceConfig";
/// <summary>Initializes ModifyCloudToDeviceConfig parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/devices/[^/]+$",
});
}
}
/// <summary>Updates a device.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource path name. For example,
/// `projects/p1/locations/us-central1/registries/registry0/devices/dev0` or
/// `projects/p1/locations/us-central1/registries/registry0/devices/{num_id}`. When `name` is
/// populated as a response from the service, it always ends in the device numeric ID.
/// </param>
public virtual PatchRequest Patch(Google.Apis.CloudIot.v1.Data.Device body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates a device.</summary>
public class PatchRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Device>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.Device body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource path name. For example,
/// `projects/p1/locations/us-central1/registries/registry0/devices/dev0` or
/// `projects/p1/locations/us-central1/registries/registry0/devices/{num_id}`. When `name` is
/// populated as a response from the service, it always ends in the device numeric ID.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Only updates the `device` fields indicated by this mask. The field mask must not
/// be empty, and it must not contain fields that are immutable or only set by the server.
/// Mutable top-level fields: `credentials`, `blocked`, and `metadata`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.Device Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/devices/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sends a command to the specified device. In order for a device to be able to receive commands,
/// it must: 1) be connected to Cloud IoT Core using the MQTT protocol, and 2) be subscribed to the
/// group of MQTT topics specified by /devices/{device-id}/commands/#. This subscription will
/// receive commands at the top-level topic /devices/{device-id}/commands as well as commands for
/// subfolders, like /devices/{device-id}/commands/subfolder. Note that subscribing to specific
/// subfolders is not supported. If the command could not be delivered to the device, this method
/// will return an error; in particular, if the device is not subscribed, this method will return
/// FAILED_PRECONDITION. Otherwise, this method will return OK. If the subscription is QoS 1, at
/// least once delivery will be guaranteed; for QoS 0, no acknowledgment will be expected from the
/// device.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </param>
public virtual SendCommandToDeviceRequest SendCommandToDevice(Google.Apis.CloudIot.v1.Data.SendCommandToDeviceRequest body, string name)
{
return new SendCommandToDeviceRequest(service, body, name);
}
/// <summary>
/// Sends a command to the specified device. In order for a device to be able to receive commands,
/// it must: 1) be connected to Cloud IoT Core using the MQTT protocol, and 2) be subscribed to the
/// group of MQTT topics specified by /devices/{device-id}/commands/#. This subscription will
/// receive commands at the top-level topic /devices/{device-id}/commands as well as commands for
/// subfolders, like /devices/{device-id}/commands/subfolder. Note that subscribing to specific
/// subfolders is not supported. If the command could not be delivered to the device, this method
/// will return an error; in particular, if the device is not subscribed, this method will return
/// FAILED_PRECONDITION. Otherwise, this method will return OK. If the subscription is QoS 1, at
/// least once delivery will be guaranteed; for QoS 0, no acknowledgment will be expected from the
/// device.
/// </summary>
public class SendCommandToDeviceRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.SendCommandToDeviceResponse>
{
/// <summary>Constructs a new SendCommandToDevice request.</summary>
public SendCommandToDeviceRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.SendCommandToDeviceRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The name of the device. For example,
/// `projects/p0/locations/us-central1/registries/registry0/devices/device0` or
/// `projects/p0/locations/us-central1/registries/registry0/devices/{num_id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.SendCommandToDeviceRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "sendCommandToDevice";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:sendCommandToDevice";
/// <summary>Initializes SendCommandToDevice parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/devices/[^/]+$",
});
}
}
}
/// <summary>Gets the Groups resource.</summary>
public virtual GroupsResource Groups { get; }
/// <summary>The "groups" collection of methods.</summary>
public class GroupsResource
{
private const string Resource = "groups";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public GroupsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Devices = new DevicesResource(service);
}
/// <summary>Gets the Devices resource.</summary>
public virtual DevicesResource Devices { get; }
/// <summary>The "devices" collection of methods.</summary>
public class DevicesResource
{
private const string Resource = "devices";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public DevicesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>List devices in a device registry.</summary>
/// <param name="parent">
/// Required. The device registry path. Required. For example,
/// `projects/my-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>List devices in a device registry.</summary>
public class ListRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.ListDevicesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The device registry path. Required. For example,
/// `projects/my-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// A list of device string IDs. For example, `['device0', 'device12']`. If empty, this
/// field is ignored. Maximum IDs: 10,000
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("deviceIds", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> DeviceIds { get; set; }
/// <summary>
/// A list of device numeric IDs. If empty, this field is ignored. Maximum IDs: 10,000.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("deviceNumIds", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> DeviceNumIds { get; set; }
/// <summary>
/// The fields of the `Device` resource to be returned in the response. The fields `id` and
/// `num_id` are always returned, along with any other fields specified in snake_case
/// format, for example: `last_heartbeat_time`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("fieldMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object FieldMask { get; set; }
/// <summary>
/// If set, returns only the gateways with which the specified device is associated. The
/// device ID can be numeric (`num_id`) or the user-defined string (`id`). For example, if
/// `456` is specified, returns only the gateways to which the device with `num_id` 456 is
/// bound.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("gatewayListOptions.associationsDeviceId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string GatewayListOptionsAssociationsDeviceId { get; set; }
/// <summary>
/// If set, only devices associated with the specified gateway are returned. The gateway ID
/// can be numeric (`num_id`) or the user-defined string (`id`). For example, if `123` is
/// specified, only devices bound to the gateway with `num_id` 123 are returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("gatewayListOptions.associationsGatewayId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string GatewayListOptionsAssociationsGatewayId { get; set; }
/// <summary>
/// If `GATEWAY` is specified, only gateways are returned. If `NON_GATEWAY` is specified,
/// only non-gateway devices are returned. If `GATEWAY_TYPE_UNSPECIFIED` is specified, all
/// devices are returned.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("gatewayListOptions.gatewayType", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<GatewayListOptionsGatewayTypeEnum> GatewayListOptionsGatewayType { get; set; }
/// <summary>
/// If `GATEWAY` is specified, only gateways are returned. If `NON_GATEWAY` is specified,
/// only non-gateway devices are returned. If `GATEWAY_TYPE_UNSPECIFIED` is specified, all
/// devices are returned.
/// </summary>
public enum GatewayListOptionsGatewayTypeEnum
{
/// <summary>If unspecified, the device is considered a non-gateway device.</summary>
[Google.Apis.Util.StringValueAttribute("GATEWAY_TYPE_UNSPECIFIED")]
GATEWAYTYPEUNSPECIFIED = 0,
/// <summary>The device is a gateway.</summary>
[Google.Apis.Util.StringValueAttribute("GATEWAY")]
GATEWAY = 1,
/// <summary>The device is not a gateway.</summary>
[Google.Apis.Util.StringValueAttribute("NON_GATEWAY")]
NONGATEWAY = 2,
}
/// <summary>
/// The maximum number of devices to return in the response. If this value is zero, the
/// service will select a default size. A call may return fewer objects than requested. A
/// non-empty `next_page_token` in the response indicates that more data is available.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// The value returned by the last `ListDevicesResponse`; indicates that this is a
/// continuation of a prior `ListDevices` call and the system should return the next page of
/// data.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/devices";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/groups/[^/]+$",
});
RequestParameters.Add("deviceIds", new Google.Apis.Discovery.Parameter
{
Name = "deviceIds",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("deviceNumIds", new Google.Apis.Discovery.Parameter
{
Name = "deviceNumIds",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fieldMask", new Google.Apis.Discovery.Parameter
{
Name = "fieldMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("gatewayListOptions.associationsDeviceId", new Google.Apis.Discovery.Parameter
{
Name = "gatewayListOptions.associationsDeviceId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("gatewayListOptions.associationsGatewayId", new Google.Apis.Discovery.Parameter
{
Name = "gatewayListOptions.associationsGatewayId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("gatewayListOptions.gatewayType", new Google.Apis.Discovery.Parameter
{
Name = "gatewayListOptions.gatewayType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists
/// and does not have a policy set.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(Google.Apis.CloudIot.v1.Data.GetIamPolicyRequest body, string resource)
{
return new GetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists
/// and does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.GetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.GetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/groups/[^/]+$",
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CloudIot.v1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy.
/// </summary>
public class SetIamPolicyRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/groups/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a NOT_FOUND error.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CloudIot.v1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a NOT_FOUND error.
/// </summary>
public class TestIamPermissionsRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+/groups/[^/]+$",
});
}
}
}
/// <summary>Associates the device with the gateway.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The name of the registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual BindDeviceToGatewayRequest BindDeviceToGateway(Google.Apis.CloudIot.v1.Data.BindDeviceToGatewayRequest body, string parent)
{
return new BindDeviceToGatewayRequest(service, body, parent);
}
/// <summary>Associates the device with the gateway.</summary>
public class BindDeviceToGatewayRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.BindDeviceToGatewayResponse>
{
/// <summary>Constructs a new BindDeviceToGateway request.</summary>
public BindDeviceToGatewayRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.BindDeviceToGatewayRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The name of the registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.BindDeviceToGatewayRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "bindDeviceToGateway";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}:bindDeviceToGateway";
/// <summary>Initializes BindDeviceToGateway parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
/// <summary>Creates a device registry that contains devices.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The project and cloud region where this device registry must be created. For example,
/// `projects/example-project/locations/us-central1`.
/// </param>
public virtual CreateRequest Create(Google.Apis.CloudIot.v1.Data.DeviceRegistry body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>Creates a device registry that contains devices.</summary>
public class CreateRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.DeviceRegistry>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.DeviceRegistry body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The project and cloud region where this device registry must be created. For example,
/// `projects/example-project/locations/us-central1`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.DeviceRegistry Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/registries";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
}
}
/// <summary>Deletes a device registry configuration.</summary>
/// <param name="name">
/// Required. The name of the device registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a device registry configuration.</summary>
public class DeleteRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the device registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
/// <summary>Gets a device registry configuration.</summary>
/// <param name="name">
/// Required. The name of the device registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets a device registry configuration.</summary>
public class GetRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.DeviceRegistry>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// Required. The name of the device registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual GetIamPolicyRequest GetIamPolicy(Google.Apis.CloudIot.v1.Data.GetIamPolicyRequest body, string resource)
{
return new GetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Gets the access control policy for a resource. Returns an empty policy if the resource exists and
/// does not have a policy set.
/// </summary>
public class GetIamPolicyRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.GetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.GetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "getIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:getIamPolicy";
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
/// <summary>Lists device registries.</summary>
/// <param name="parent">
/// Required. The project and cloud region path. For example,
/// `projects/example-project/locations/us-central1`.
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists device registries.</summary>
public class ListRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.ListDeviceRegistriesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// Required. The project and cloud region path. For example,
/// `projects/example-project/locations/us-central1`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// The maximum number of registries to return in the response. If this value is zero, the service
/// will select a default size. A call may return fewer objects than requested. A non-empty
/// `next_page_token` in the response indicates that more data is available.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// The value returned by the last `ListDeviceRegistriesResponse`; indicates that this is a
/// continuation of a prior `ListDeviceRegistries` call and the system should return the next page
/// of data.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}/registries";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates a device registry configuration.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The resource path name. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual PatchRequest Patch(Google.Apis.CloudIot.v1.Data.DeviceRegistry body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates a device registry configuration.</summary>
public class PatchRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.DeviceRegistry>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.DeviceRegistry body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The resource path name. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>
/// Required. Only updates the `device_registry` fields indicated by this mask. The field mask must
/// not be empty, and it must not contain fields that are immutable or only set by the server.
/// Mutable top-level fields: `event_notification_config`, `http_config`, `mqtt_config`, and
/// `state_notification_config`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.DeviceRegistry Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation for
/// the appropriate value for this field.
/// </param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.CloudIot.v1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>
/// Sets the access control policy on the specified resource. Replaces any existing policy.
/// </summary>
public class SetIamPolicyRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.SetIamPolicyRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.SetIamPolicyRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "setIamPolicy";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:setIamPolicy";
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a NOT_FOUND error.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.CloudIot.v1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>
/// Returns permissions that a caller has on the specified resource. If the resource does not exist,
/// this will return an empty set of permissions, not a NOT_FOUND error.
/// </summary>
public class TestIamPermissionsRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.TestIamPermissionsRequest body, string resource) : base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>
/// REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.TestIamPermissionsRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "testIamPermissions";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+resource}:testIamPermissions";
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
/// <summary>Deletes the association between the device and the gateway.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// Required. The name of the registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </param>
public virtual UnbindDeviceFromGatewayRequest UnbindDeviceFromGateway(Google.Apis.CloudIot.v1.Data.UnbindDeviceFromGatewayRequest body, string parent)
{
return new UnbindDeviceFromGatewayRequest(service, body, parent);
}
/// <summary>Deletes the association between the device and the gateway.</summary>
public class UnbindDeviceFromGatewayRequest : CloudIotBaseServiceRequest<Google.Apis.CloudIot.v1.Data.UnbindDeviceFromGatewayResponse>
{
/// <summary>Constructs a new UnbindDeviceFromGateway request.</summary>
public UnbindDeviceFromGatewayRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudIot.v1.Data.UnbindDeviceFromGatewayRequest body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// Required. The name of the registry. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudIot.v1.Data.UnbindDeviceFromGatewayRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "unbindDeviceFromGateway";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+parent}:unbindDeviceFromGateway";
/// <summary>Initializes UnbindDeviceFromGateway parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/registries/[^/]+$",
});
}
}
}
}
}
}
namespace Google.Apis.CloudIot.v1.Data
{
/// <summary>Request for `BindDeviceToGateway`.</summary>
public class BindDeviceToGatewayRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The device to associate with the specified gateway. The value of `device_id` can be either the
/// device numeric ID or the user-defined device identifier.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceId")]
public virtual string DeviceId { get; set; }
/// <summary>
/// Required. The value of `gateway_id` can be either the device numeric ID or the user-defined device
/// identifier.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatewayId")]
public virtual string GatewayId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for `BindDeviceToGateway`.</summary>
public class BindDeviceToGatewayResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Associates `members` with a `role`.</summary>
public class Binding : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding
/// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to
/// the current request. However, a different role binding might grant the same role to one or more of the
/// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual Expr Condition { get; set; }
/// <summary>
/// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following
/// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a
/// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated
/// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific
/// Google account. For example, `[email protected]` . * `serviceAccount:{emailid}`: An email address that
/// represents a service account. For example, `[email protected]`. * `group:{emailid}`:
/// An email address that represents a Google group. For example, `[email protected]`. *
/// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that
/// has been recently deleted. For example, `[email protected]?uid=123456789012345678901`. If the user is
/// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. *
/// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a
/// service account that has been recently deleted. For example,
/// `[email protected]?uid=123456789012345678901`. If the service account is undeleted,
/// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the
/// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing
/// a Google group that has been recently deleted. For example, `[email protected]?uid=123456789012345678901`.
/// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role
/// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that
/// domain. For example, `google.com` or `example.com`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("members")]
public virtual System.Collections.Generic.IList<string> Members { get; set; }
/// <summary>
/// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The device resource.</summary>
public class Device : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If a device is blocked, connections or requests from this device will fail. Can be used to temporarily
/// prevent the device from connecting if, for example, the sensor is generating bad data and needs maintenance.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("blocked")]
public virtual System.Nullable<bool> Blocked { get; set; }
/// <summary>
/// The most recent device configuration, which is eventually sent from Cloud IoT Core to the device. If not
/// present on creation, the configuration will be initialized with an empty payload and version value of `1`.
/// To update this field after creation, use the `DeviceManager.ModifyCloudToDeviceConfig` method.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("config")]
public virtual DeviceConfig Config { get; set; }
/// <summary>
/// The credentials used to authenticate this device. To allow credential rotation without interruption,
/// multiple device credentials can be bound to this device. No more than 3 credentials can be bound to a single
/// device at a time. When new credentials are added to a device, they are verified against the registry
/// credentials. For details, see the description of the `DeviceRegistry.credentials` field.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("credentials")]
public virtual System.Collections.Generic.IList<DeviceCredential> Credentials { get; set; }
/// <summary>Gateway-related configuration and state.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatewayConfig")]
public virtual GatewayConfig GatewayConfig { get; set; }
/// <summary>
/// The user-defined device identifier. The device ID must be unique within a device registry.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>
/// [Output only] The last time a cloud-to-device config version acknowledgment was received from the device.
/// This field is only for configurations sent through MQTT.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastConfigAckTime")]
public virtual object LastConfigAckTime { get; set; }
/// <summary>[Output only] The last time a cloud-to-device config version was sent to the device.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastConfigSendTime")]
public virtual object LastConfigSendTime { get; set; }
/// <summary>
/// [Output only] The error message of the most recent error, such as a failure to publish to Cloud Pub/Sub.
/// 'last_error_time' is the timestamp of this field. If no errors have occurred, this field has an empty
/// message and the status code 0 == OK. Otherwise, this field is expected to have a status code other than OK.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastErrorStatus")]
public virtual Status LastErrorStatus { get; set; }
/// <summary>
/// [Output only] The time the most recent error occurred, such as a failure to publish to Cloud Pub/Sub. This
/// field is the timestamp of 'last_error_status'.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastErrorTime")]
public virtual object LastErrorTime { get; set; }
/// <summary>
/// [Output only] The last time a telemetry event was received. Timestamps are periodically collected and
/// written to storage; they may be stale by a few minutes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastEventTime")]
public virtual object LastEventTime { get; set; }
/// <summary>
/// [Output only] The last time an MQTT `PINGREQ` was received. This field applies only to devices connecting
/// through MQTT. MQTT clients usually only send `PINGREQ` messages if the connection is idle, and no other
/// messages have been sent. Timestamps are periodically collected and written to storage; they may be stale by
/// a few minutes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastHeartbeatTime")]
public virtual object LastHeartbeatTime { get; set; }
/// <summary>
/// [Output only] The last time a state event was received. Timestamps are periodically collected and written to
/// storage; they may be stale by a few minutes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastStateTime")]
public virtual object LastStateTime { get; set; }
/// <summary>
/// **Beta Feature** The logging verbosity for device activity. If unspecified, DeviceRegistry.log_level will be
/// used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("logLevel")]
public virtual string LogLevel { get; set; }
/// <summary>
/// The metadata key-value pairs assigned to the device. This metadata is not interpreted or indexed by Cloud
/// IoT Core. It can be used to add contextual information for the device. Keys must conform to the regular
/// expression a-zA-Z+ and be less than 128 bytes in length. Values are free-form strings. Each value must be
/// less than or equal to 32 KB in size. The total size of all keys and values must be less than 256 KB, and the
/// maximum number of key-value pairs is 500.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, string> Metadata { get; set; }
/// <summary>
/// The resource path name. For example, `projects/p1/locations/us-central1/registries/registry0/devices/dev0`
/// or `projects/p1/locations/us-central1/registries/registry0/devices/{num_id}`. When `name` is populated as a
/// response from the service, it always ends in the device numeric ID.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// [Output only] A server-defined unique numeric ID for the device. This is a more compact way to identify
/// devices, and it is globally unique.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("numId")]
public virtual System.Nullable<ulong> NumId { get; set; }
/// <summary>
/// [Output only] The state most recently received from the device. If no state has been reported, this field is
/// not present.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual DeviceState State { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The device configuration. Eventually delivered to devices.</summary>
public class DeviceConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The device configuration data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("binaryData")]
public virtual string BinaryData { get; set; }
/// <summary>
/// [Output only] The time at which this configuration version was updated in Cloud IoT Core. This timestamp is
/// set by the server.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("cloudUpdateTime")]
public virtual object CloudUpdateTime { get; set; }
/// <summary>
/// [Output only] The time at which Cloud IoT Core received the acknowledgment from the device, indicating that
/// the device has received this configuration version. If this field is not present, the device has not yet
/// acknowledged that it received this version. Note that when the config was sent to the device, many config
/// versions may have been available in Cloud IoT Core while the device was disconnected, and on connection,
/// only the latest version is sent to the device. Some versions may never be sent to the device, and therefore
/// are never acknowledged. This timestamp is set by Cloud IoT Core.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceAckTime")]
public virtual object DeviceAckTime { get; set; }
/// <summary>
/// [Output only] The version of this update. The version number is assigned by the server, and is always
/// greater than 0 after device creation. The version must be 0 on the `CreateDevice` request if a `config` is
/// specified; the response of `CreateDevice` will always have a value of 1.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<long> Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A server-stored device credential used for authentication.</summary>
public class DeviceCredential : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// [Optional] The time at which this credential becomes invalid. This credential will be ignored for new client
/// authentication requests after this timestamp; however, it will not be automatically deleted.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("expirationTime")]
public virtual object ExpirationTime { get; set; }
/// <summary>
/// A public key used to verify the signature of JSON Web Tokens (JWTs). When adding a new device credential,
/// either via device creation or via modifications, this public key credential may be required to be signed by
/// one of the registry level certificates. More specifically, if the registry contains at least one
/// certificate, any new device credential must be signed by one of the registry certificates. As a result, when
/// the registry contains certificates, only X.509 certificates are accepted as device credentials. However, if
/// the registry does not contain a certificate, self-signed certificates and public keys will be accepted. New
/// device credentials must be different from every registry-level certificate.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("publicKey")]
public virtual PublicKeyCredential PublicKey { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A container for a group of devices.</summary>
public class DeviceRegistry : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The credentials used to verify the device credentials. No more than 10 credentials can be bound to a single
/// registry at a time. The verification process occurs at the time of device creation or update. If this field
/// is empty, no verification is performed. Otherwise, the credentials of a newly created device or added
/// credentials of an updated device should be signed with one of these registry credentials. Note, however,
/// that existing devices will never be affected by modifications to this list of credentials: after a device
/// has been successfully created in a registry, it should be able to connect even if its registry credentials
/// are revoked, deleted, or modified.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("credentials")]
public virtual System.Collections.Generic.IList<RegistryCredential> Credentials { get; set; }
/// <summary>
/// The configuration for notification of telemetry events received from the device. All telemetry events that
/// were successfully published by the device and acknowledged by Cloud IoT Core are guaranteed to be delivered
/// to Cloud Pub/Sub. If multiple configurations match a message, only the first matching configuration is used.
/// If you try to publish a device telemetry event using MQTT without specifying a Cloud Pub/Sub topic for the
/// device's registry, the connection closes automatically. If you try to do so using an HTTP connection, an
/// error is returned. Up to 10 configurations may be provided.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("eventNotificationConfigs")]
public virtual System.Collections.Generic.IList<EventNotificationConfig> EventNotificationConfigs { get; set; }
/// <summary>The DeviceService (HTTP) configuration for this device registry.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("httpConfig")]
public virtual HttpConfig HttpConfig { get; set; }
/// <summary>The identifier of this device registry. For example, `myRegistry`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>
/// **Beta Feature** The default logging verbosity for activity from devices in this registry. The verbosity
/// level can be overridden by Device.log_level.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("logLevel")]
public virtual string LogLevel { get; set; }
/// <summary>The MQTT configuration for this device registry.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("mqttConfig")]
public virtual MqttConfig MqttConfig { get; set; }
/// <summary>
/// The resource path name. For example,
/// `projects/example-project/locations/us-central1/registries/my-registry`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The configuration for notification of new states received from the device. State updates are guaranteed to
/// be stored in the state history, but notifications to Cloud Pub/Sub are not guaranteed. For example, if
/// permissions are misconfigured or the specified topic doesn't exist, no notification will be published but
/// the state will still be stored in Cloud IoT Core.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("stateNotificationConfig")]
public virtual StateNotificationConfig StateNotificationConfig { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The device state, as reported by the device.</summary>
public class DeviceState : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The device state data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("binaryData")]
public virtual string BinaryData { get; set; }
/// <summary>[Output only] The time at which this state version was updated in Cloud IoT Core.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateTime")]
public virtual object UpdateTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON
/// object `{}`.
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The configuration for forwarding telemetry events.</summary>
public class EventNotificationConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A Cloud Pub/Sub topic name. For example, `projects/myProject/topics/deviceEvents`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pubsubTopicName")]
public virtual string PubsubTopicName { get; set; }
/// <summary>
/// If the subfolder name matches this string exactly, this configuration will be used. The string must not
/// include the leading '/' character. If empty, all strings are matched. This field is used only for telemetry
/// events; subfolders are not supported for state changes.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subfolderMatches")]
public virtual string SubfolderMatches { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression
/// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example
/// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars"
/// expression: "document.summary.size() &lt; 100" Example (Equality): title: "Requestor is owner" description:
/// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email"
/// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly
/// visible" expression: "document.type != 'private' &amp;&amp; document.type != 'internal'" Example (Data
/// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp."
/// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that
/// may be referenced within an expression are determined by the service that evaluates it. See the service
/// documentation for additional information.
/// </summary>
public class Expr : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when
/// hovered over it in a UI.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Textual representation of an expression in Common Expression Language syntax.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expression")]
public virtual string Expression { get; set; }
/// <summary>
/// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a
/// position in the file.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>
/// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs
/// which allow to enter the expression.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Gateway-related configuration and state.</summary>
public class GatewayConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Indicates how to authorize and/or authenticate devices to access the gateway.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatewayAuthMethod")]
public virtual string GatewayAuthMethod { get; set; }
/// <summary>Indicates whether the device is a gateway.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatewayType")]
public virtual string GatewayType { get; set; }
/// <summary>[Output only] The ID of the gateway the device accessed most recently.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastAccessedGatewayId")]
public virtual string LastAccessedGatewayId { get; set; }
/// <summary>
/// [Output only] The most recent time at which the device accessed the gateway specified in
/// `last_accessed_gateway`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastAccessedGatewayTime")]
public virtual object LastAccessedGatewayTime { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `GetIamPolicy` method.</summary>
public class GetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>OPTIONAL: A `GetPolicyOptions` object for specifying options to `GetIamPolicy`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("options")]
public virtual GetPolicyOptions Options { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Encapsulates settings provided to GetIamPolicy.</summary>
public class GetPolicyOptions : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Optional. The policy format version to be returned. Valid values are 0, 1, and 3. Requests specifying an
/// invalid value will be rejected. Requests for policies with any conditional bindings must specify version 3.
/// Policies without any conditional bindings may specify any valid value or leave the field unset. To learn
/// which resources support conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestedPolicyVersion")]
public virtual System.Nullable<int> RequestedPolicyVersion { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The configuration of the HTTP bridge for a device registry.</summary>
public class HttpConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If enabled, allows devices to use DeviceService via the HTTP protocol. Otherwise, any requests to
/// DeviceService will fail for this registry.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("httpEnabledState")]
public virtual string HttpEnabledState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for `ListDeviceConfigVersions`.</summary>
public class ListDeviceConfigVersionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The device configuration for the last few versions. Versions are listed in decreasing order, starting from
/// the most recent one.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceConfigs")]
public virtual System.Collections.Generic.IList<DeviceConfig> DeviceConfigs { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for `ListDeviceRegistries`.</summary>
public class ListDeviceRegistriesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The registries that matched the query.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceRegistries")]
public virtual System.Collections.Generic.IList<DeviceRegistry> DeviceRegistries { get; set; }
/// <summary>
/// If not empty, indicates that there may be more registries that match the request; this value should be
/// passed in a new `ListDeviceRegistriesRequest`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for `ListDeviceStates`.</summary>
public class ListDeviceStatesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The last few device states. States are listed in descending order of server update time, starting from the
/// most recent one.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceStates")]
public virtual System.Collections.Generic.IList<DeviceState> DeviceStates { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for `ListDevices`.</summary>
public class ListDevicesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The devices that match the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("devices")]
public virtual System.Collections.Generic.IList<Device> Devices { get; set; }
/// <summary>
/// If not empty, indicates that there may be more devices that match the request; this value should be passed
/// in a new `ListDevicesRequest`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request for `ModifyCloudToDeviceConfig`.</summary>
public class ModifyCloudToDeviceConfigRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The configuration data for the device.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("binaryData")]
public virtual string BinaryData { get; set; }
/// <summary>
/// The version number to update. If this value is zero, it will not check the version number of the server and
/// will always update the current version; otherwise, this update will fail if the version number found on the
/// server does not match this version number. This is used to support multiple simultaneous updates without
/// losing data.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("versionToUpdate")]
public virtual System.Nullable<long> VersionToUpdate { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The configuration of MQTT for a device registry.</summary>
public class MqttConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If enabled, allows connections using the MQTT protocol. Otherwise, MQTT connections to this registry will
/// fail.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("mqttEnabledState")]
public virtual string MqttEnabledState { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A
/// `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can
/// be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of
/// permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google
/// Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to
/// a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of
/// the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the
/// [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** {
/// "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:[email protected]",
/// "group:[email protected]", "domain:google.com", "serviceAccount:[email protected]" ] },
/// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:[email protected]" ], "condition": {
/// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time
/// &lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:**
/// bindings: - members: - user:[email protected] - group:[email protected] - domain:google.com -
/// serviceAccount:[email protected] role: roles/resourcemanager.organizationAdmin -
/// members: - user:[email protected] role: roles/resourcemanager.organizationViewer condition: title: expirable
/// access description: Does not grant access after Sep 2020 expression: request.time &lt;
/// timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features,
/// see the [IAM documentation](https://cloud.google.com/iam/docs/).
/// </summary>
public class Policy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and
/// when the `bindings` are applied. Each of the `bindings` must contain at least one member.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindings")]
public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; }
/// <summary>
/// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy
/// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned
/// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to
/// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:**
/// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit
/// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>
/// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid
/// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This
/// requirement applies to the following operations: * Getting a policy that includes a conditional role binding
/// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing
/// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you
/// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this
/// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the
/// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on
/// that policy may specify any valid version or leave the field unset. To learn which resources support
/// conditions in their IAM policies, see the [IAM
/// documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<int> Version { get; set; }
}
/// <summary>A public key certificate format and data.</summary>
public class PublicKeyCertificate : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The certificate data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("certificate")]
public virtual string Certificate { get; set; }
/// <summary>The certificate format.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>[Output only] The certificate details. Used only for X.509 certificates.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("x509Details")]
public virtual X509CertificateDetails X509Details { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A public key format and data.</summary>
public class PublicKeyCredential : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The format of the key.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("format")]
public virtual string Format { get; set; }
/// <summary>The key data.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A server-stored registry credential used to validate device credentials.</summary>
public class RegistryCredential : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A public key certificate used to verify the device credentials.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("publicKeyCertificate")]
public virtual PublicKeyCertificate PublicKeyCertificate { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request for `SendCommandToDevice`.</summary>
public class SendCommandToDeviceRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. The command data to send to the device.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("binaryData")]
public virtual string BinaryData { get; set; }
/// <summary>
/// Optional subfolder for the command. If empty, the command will be delivered to the
/// /devices/{device-id}/commands topic, otherwise it will be delivered to the
/// /devices/{device-id}/commands/{subfolder} topic. Multi-level subfolders are allowed. This field must not
/// have more than 256 characters, and must not contain any MQTT wildcards ("+" or "#") or null characters.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("subfolder")]
public virtual string Subfolder { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for `SendCommandToDevice`.</summary>
public class SendCommandToDeviceResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `SetIamPolicy` method.</summary>
public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few
/// 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might
/// reject them.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("policy")]
public virtual Policy Policy { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The configuration for notification of new states received from the device.</summary>
public class StateNotificationConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A Cloud Pub/Sub topic name. For example, `projects/myProject/topics/deviceEvents`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pubsubTopicName")]
public virtual string PubsubTopicName { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different programming environments,
/// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; }
/// <summary>
/// A developer-facing error message, which should be in English. Any user-facing error message should be
/// localized and sent in the google.rpc.Status.details field, or localized by the client.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*')
/// are not allowed. For more information see [IAM
/// Overview](https://cloud.google.com/iam/docs/overview#permissions).
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request for `UnbindDeviceFromGateway`.</summary>
public class UnbindDeviceFromGatewayRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// Required. The device to disassociate from the specified gateway. The value of `device_id` can be either the
/// device numeric ID or the user-defined device identifier.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("deviceId")]
public virtual string DeviceId { get; set; }
/// <summary>
/// Required. The value of `gateway_id` can be either the device numeric ID or the user-defined device
/// identifier.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("gatewayId")]
public virtual string GatewayId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response for `UnbindDeviceFromGateway`.</summary>
public class UnbindDeviceFromGatewayResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Details of an X.509 certificate. For informational purposes only.</summary>
public class X509CertificateDetails : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The time the certificate becomes invalid.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expiryTime")]
public virtual object ExpiryTime { get; set; }
/// <summary>The entity that signed the certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("issuer")]
public virtual string Issuer { get; set; }
/// <summary>The type of public key in the certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("publicKeyType")]
public virtual string PublicKeyType { get; set; }
/// <summary>The algorithm used to sign the certificate.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("signatureAlgorithm")]
public virtual string SignatureAlgorithm { get; set; }
/// <summary>The time the certificate becomes valid.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual object StartTime { get; set; }
/// <summary>The entity the certificate and public key belong to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subject")]
public virtual string Subject { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| apache-2.0 |
bigchange/AI | src/main/scala/com/bigchange/ssql/MySQLDemo.scala | 604 | package com.bigchange.ssql
import com.bigchange.config.XMLConfig
/**
* Created by C.J.YOU on 2017/2/17.
* MySql 操作实例
*/
object MySQLDemo {
def main(args: Array[String]) {
// val Array(xmlPath) = args
val xmlPath = "src/test/resources/config.xml"
val pool = MysqlPool.apply(XMLConfig.apply(xmlPath), isTestOrNot = false)
val connection = pool.getConnect
val handler = MysqlHandler.apply(connection.get)
val res = handler.executeQuery("select count(*) from events").get
while(res.next()) {
println(res.getString(1))
}
pool.close()
}
}
| apache-2.0 |
savantly-net/sprout-platform | backend/starters/sprout-spring-boot-starter/src/test/resources/static/test.js | 34 | // ** Testing resource locator **/ | apache-2.0 |
ndlib/honeycomb | app/controllers/v1/metadata_controller.rb | 437 | module V1
# Version 1 API
class MetadataController < APIController
def update
@item = ItemQuery.new.public_find(params[:item_id])
return if rendered_forbidden?(@item.collection)
if SaveMetadata.call(@item, save_params)
render :update
else
render :errors, status: :unprocessable_entity
end
end
private
def save_params
params[:metadata].to_hash
end
end
end
| apache-2.0 |
ressec/thot | thot-akka/src/main/java/org/heliosphere/thot/akka/tutorial/print/PrintMyActorRefActor.java | 1387 | /*
* Copyright(c) 2017 - Heliosphere Corp.
* ---------------------------------------------------------------------------
* This file is part of the Heliosphere's project which is licensed under the
* Apache license version 2 and use is subject to license terms.
* You should have received a copy of the license with the project's artifact
* binaries and/or sources.
*
* License can be consulted at http://www.apache.org/licenses/LICENSE-2.0
* ---------------------------------------------------------------------------
*/
package org.heliosphere.thot.akka.tutorial.print;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
/**
* Very simple {@code Akka} actor creating on a message type a child actor.
* <hr>
* @author <a href="mailto:[email protected]">Christophe Resse - Heliosphere</a>
* @version 1.0.0
*/
public class PrintMyActorRefActor extends AbstractActor
{
@SuppressWarnings("nls")
@Override
public Receive createReceive()
{
return receiveBuilder().matchEquals("printIt", p -> HandlePrint())
//.matchAny()
.build();
}
/**
* Handles the {@code printIt} message.
*/
@SuppressWarnings("nls")
private final void HandlePrint()
{
// Create a child actor that does nothing.
ActorRef second = getContext().actorOf(Props.empty(), "second-actor");
System.out.println("Second: " + second);
}
}
| apache-2.0 |
NovaOrdis/playground | spring/spring-in-action/cap3-jdbctemplate/src/test/java/playground/spring/sia/chapterthree/tacocloud/TacoCloudApplicationTests.java | 373 | package playground.spring.sia.chapterthree.tacocloud;
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 TacoCloudApplicationTests {
@Test
public void contextLoads() {
}
}
| apache-2.0 |
tjheslin1/Westie | src/test/java/io/github/tjheslin1/westie/todostructure/TodosStructureAnalyserTest.java | 3647 | package io.github.tjheslin1.westie.todostructure;
import io.github.tjheslin1.westie.LineAssertions;
import io.github.tjheslin1.westie.Violation;
import io.github.tjheslin1.westie.testinfrastructure.TestWestieFileReader;
import org.assertj.core.api.WithAssertions;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static io.github.tjheslin1.westie.WestieRegexes.TODOS_MUST_HAVE_DATE_REGEX;
import static java.util.Collections.singletonList;
public class TodosStructureAnalyserTest implements WithAssertions {
@Test
public void findsTodosComments() throws Exception {
TodosStructureAnalyser todosStructureAnalyser = new TodosStructureAnalyser(TODOS_MUST_HAVE_DATE_REGEX, new TestWestieFileReader());
Path pathToCheck = Paths.get("src/test/resources/io/github/tjheslin1/examples/todos");
List<Violation> todoViolations = todosStructureAnalyser.checkAllTodosFollowExpectedStructure(pathToCheck);
assertThat(todoViolations.size()).isEqualTo(3);
LineAssertions lineAssertions = new LineAssertions(todoViolations);
lineAssertions.containsViolationMessage("Violation in file 'AnotherClassWithTodos.java'\n" +
"\n" +
" // TODO NO_DATE another todo\n" +
"\n" +
"Violation was caused by the TODO not matching structure with regex: .*//.*(T|t)(O|o)(D|d)(O|o).*[0-9]{1,4}[/-]{1}[A-z0-9]{2,3}[/-]{1}[0-9]{1,4}.*\n");
lineAssertions.containsViolationMessage("Violation in file 'ClassWithTodos.java'\n" +
"\n" +
" //TODO make this final\n" +
"\n" +
"Violation was caused by the TODO not matching structure with regex: .*//.*(T|t)(O|o)(D|d)(O|o).*[0-9]{1,4}[/-]{1}[A-z0-9]{2,3}[/-]{1}[0-9]{1,4}.*\n");
lineAssertions.containsViolationMessage("Violation in file 'ClassWithTodos.java'\n" +
"\n" +
" // TODO NO_DATE move this to another class\n" +
"\n" +
"Violation was caused by the TODO not matching structure with regex: .*//.*(T|t)(O|o)(D|d)(O|o).*[0-9]{1,4}[/-]{1}[A-z0-9]{2,3}[/-]{1}[0-9]{1,4}.*\n");
}
@Test
public void ignoresExemptFile() throws Exception {
TodosStructureAnalyser todosStructureAnalyser = new TodosStructureAnalyser(TODOS_MUST_HAVE_DATE_REGEX, new TestWestieFileReader());
Path pathToCheck = Paths.get("src/test/resources/io/github/tjheslin1/examples/todos");
List<Violation> todoViolations = todosStructureAnalyser.checkAllTodosFollowExpectedStructure(pathToCheck, singletonList("io/github/tjheslin1/examples/todos/another/AnotherClassWithTodos.java"));
assertThat(todoViolations.size()).isEqualTo(2);
LineAssertions lineAssertions = new LineAssertions(todoViolations);
lineAssertions.containsViolationMessage("Violation in file 'ClassWithTodos.java'\n" +
"\n" +
" //TODO make this final\n" +
"\n" +
"Violation was caused by the TODO not matching structure with regex: .*//.*(T|t)(O|o)(D|d)(O|o).*[0-9]{1,4}[/-]{1}[A-z0-9]{2,3}[/-]{1}[0-9]{1,4}.*\n");
lineAssertions.containsViolationMessage("Violation in file 'ClassWithTodos.java'\n" +
"\n" +
" // TODO NO_DATE move this to another class\n" +
"\n" +
"Violation was caused by the TODO not matching structure with regex: .*//.*(T|t)(O|o)(D|d)(O|o).*[0-9]{1,4}[/-]{1}[A-z0-9]{2,3}[/-]{1}[0-9]{1,4}.*\n");
}
} | apache-2.0 |
pyros2097/Scene3d | src/scene3d/demo/Scene3dDemo.java | 12812 | /*******************************************************************************
* Copyright 2013 pyros2097
*
* 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 scene3d.demo;
import scene3d.Actor3d;
import scene3d.Camera3d;
import scene3d.Group3d;
import scene3d.Stage3d;
import scene3d.actions.Actions3d;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.InputListener;
public class Scene3dDemo implements ApplicationListener {
Stage3d stage3d;
Stage stage2d;
Skin skin;
ModelBuilder modelBuilder;
CameraInputController camController;
Model model, model2, model3;
Actor3d knight, actor2, actor3, floor, skydome;
Group3d group3d;
Label fpsLabel;
Label visibleLabel;
Label positionLabel;
Label rotationLabel;
Label positionCameraLabel;
Label rotationCameraLabel;
public static void main(String[] argc) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.audioDeviceBufferCount = 20;
cfg.title = "Stage3d Test";
cfg.useGL20 = false;
cfg.width = 852;
cfg.height = 480;
new LwjglApplication(new Scene3dDemo(), cfg);
}
boolean rightKey, leftKey, upKey, downKey, spaceKey;
@Override
public void create () {
//2d stuff
stage2d = new Stage();
skin = new Skin(Gdx.files.internal("skin/uiskin.json"));
fpsLabel = new Label("ff", skin);
fpsLabel.setPosition(Gdx.graphics.getWidth() - 260, Gdx.graphics.getHeight()-40);
visibleLabel = new Label("ff", skin);
visibleLabel.setPosition(Gdx.graphics.getWidth() - 260, Gdx.graphics.getHeight()- 60);
positionLabel = new Label("Position", skin);
positionLabel.setPosition(Gdx.graphics.getWidth() - 260, Gdx.graphics.getHeight()- 80);
rotationLabel = new Label("Rotation", skin);
rotationLabel.setPosition(Gdx.graphics.getWidth() - 260, Gdx.graphics.getHeight()- 100);
positionCameraLabel = new Label("Position", skin);
positionCameraLabel.setPosition(20, Gdx.graphics.getHeight()- 40);
rotationCameraLabel = new Label("Rotation", skin);
rotationCameraLabel.setPosition(20, Gdx.graphics.getHeight()- 60);
stage2d.addActor(fpsLabel);
stage2d.addActor(visibleLabel);
stage2d.addActor(positionLabel);
stage2d.addActor(rotationLabel);
stage2d.addActor(positionCameraLabel);
stage2d.addActor(rotationCameraLabel);
stage2d.addListener(new InputListener(){
@Override
public boolean keyUp(InputEvent event, int keycode) {
if (keycode == Keys.LEFT) leftKey = false;
if (keycode == Keys.RIGHT) rightKey = false;
if (keycode == Keys.UP) upKey = false;
if (keycode == Keys.DOWN) downKey = false;
if (keycode == Keys.SPACE) spaceKey = false;
return super.keyUp(event, keycode);
}
@Override
public boolean keyDown(InputEvent event, int keycode) {
if (keycode == Keys.LEFT) leftKey = true;
if (keycode == Keys.RIGHT) rightKey = true;
if (keycode == Keys.UP) upKey = true;
if (keycode == Keys.DOWN) downKey = true;
if (keycode == Keys.SPACE) spaceKey = true;
return super.keyDown(event, keycode);
}
});
//3dstuff
stage3d = new Stage3d();
modelBuilder = new ModelBuilder();
model = modelBuilder.createBox(5f, 5f, 5f, new Material("Color", ColorAttribute.createDiffuse(Color.WHITE)),
Usage.Position | Usage.Normal);
model2 = modelBuilder.createBox(2f, 2f, 2f, new Material("Color", ColorAttribute.createDiffuse(Color.WHITE)),
Usage.Position | Usage.Normal);
actor2 = new Actor3d(model2, 10f, 0f, 0f);
model3 = modelBuilder.createBox(2f, 2f, 2f, new Material("Color", ColorAttribute.createDiffuse(Color.ORANGE)),
Usage.Position | Usage.Normal);
actor3 = new Actor3d(model3, -10f, 0f, 0f);
actor2.setColor(Color.RED);
actor2.setName("actor2");
actor3.setName("actor3");
camController = new CameraInputController(stage3d.getCamera());
InputMultiplexer im = new InputMultiplexer();
im.addProcessor(stage2d);// 2d should get click events first
//im.addProcessor(stage3d);
im.addProcessor(camController);
Gdx.input.setInputProcessor(im);
stage3d.touchable = Touchable.enabled; // only then will it detect hit actor3d
ModelBuilder builder = new ModelBuilder();
builder.begin();
MeshPartBuilder part = builder.part("floor", GL20.GL_TRIANGLES, Usage.Position | Usage.TextureCoordinates | Usage.Normal,
new Material());
for (float x = -200f; x < 200f; x += 10f) {
for (float z = -200f; z < 200f; z += 10f) {
part.rect(x, 0, z + 10f, x + 10f, 0, z + 10f, x + 10f, 0, z, x, 0, z, 0, 1, 0);
}
}
floor = new Actor3d(builder.end());
AssetManager am = new AssetManager();
am.load("data/g3d/knight.g3db", Model.class);
am.load("data/g3d/skydome.g3db", Model.class);
am.load("data/g3d/concrete.png", Texture.class);
am.finishLoading();
knight = new Actor3d(am.get("data/g3d/knight.g3db", Model.class), 0f, 18f, 0f);
knight.getAnimation().inAction = true;
knight.getAnimation().animate("Walk", -1, 1f, null, 0.2f);
skydome = new Actor3d(am.get("data/g3d/skydome.g3db", Model.class));
floor.materials.get(0).set(TextureAttribute.createDiffuse(am.get("data/g3d/concrete.png",
Texture.class)));
stage3d.addActor3d(skydome);
stage3d.addActor3d(floor);
knight.setPitch(-90f);
knight.setYaw(-130f);
testActor3d();
//stage3d.addAction3d(Actions3d.rotateBy(0f, 90f, 0f, 2f));
//testGroup3d();
//testStage3d();
}
float angle, angle2;
@Override
public void render () {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
stage3d.act();
stage3d.draw();
stage2d.act();
stage2d.draw();
camController.update();
fpsLabel.setText("Fps: " + Gdx.graphics.getFramesPerSecond());
visibleLabel.setText("Visible: " + stage3d.getRoot().visibleCount);
positionLabel.setText("Knight X:" + knight.getX()+" Y:"+knight.getY()+" Z:"+knight.getZ());
rotationLabel.setText("Knight Yaw:" + knight.getYaw()+" Pitch:"+knight.getPitch()+" "
+ "Roll:"+knight.getRoll());
positionCameraLabel.setText("Camera X:" + stage3d.getCamera().position.x
+" Y:"+stage3d.getCamera().position.y+" Z:"+stage3d.getCamera().position.z);
rotationCameraLabel.setText("Camera Yaw:" + stage3d.getCamera().direction.x
+" Pitch:"+stage3d.getCamera().direction.y+" "+ "Roll:"+stage3d.getCamera().direction.z);
angle = MathUtils.cosDeg(knight.getYaw() - 90); //90 degrees is correction factor
angle2 = -MathUtils.sinDeg(knight.getYaw() - 90);
if (upKey) {
knight.addAction3d(Actions3d.moveBy(angle, 0f, angle2));
stage3d.getCamera().translate(angle, 0f, angle2);
}
else if (downKey) {
knight.addAction3d(Actions3d.moveBy(-angle, 0f, -angle2));
stage3d.getCamera().translate(-angle, 0f, -angle2);
}
else if (rightKey) {
knight.rotateYaw(-2f);
if(stage3d.getCamera().direction.z > -0.76f)
Camera3d.rotateBy(-2f, 0f, 0f, 0f);
//stage3d.getCamera().translate(angle, 0f, angle2); //get the angle calculations rite to make
// the camera truly follow knight
}
else if (leftKey) {
knight.rotateYaw(2f);
if(stage3d.getCamera().direction.z < -0.63f)
Camera3d.rotateBy(2f, 0f, 0f, 0f);
}
/* private float stateTime;
float angleDegrees;
stateTime+= delta;
angleDegrees = stateTime * 10.0f;
camera.position.set(200f * MathUtils.sinDeg(angleDegrees),
20, -200.0f * MathUtils.cosDeg(angleDegrees));
camera.rotate(Vector3.Y, angleDegrees/10f*delta);*/
}
@Override
public void resize(int width, int height) {
stage2d.setViewport(width, height);
stage3d.setViewport(width, height);
}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void dispose () {
stage3d.dispose();
}
void testActor3d(){
stage3d.addActor3d(knight);
stage3d.getCamera().position.set(knight.getX()+ 13f, knight.getY() + 24f, knight.getZ() + 45f);
//stage3d.getCamera().lookAt(knight.getX(), knight.getY(), knight.getZ());
//Camera3d.rotateCameraBy(knight.getYaw(), 0f, 0f, 1f);
//Camera3d.followOffset(20f, 20f, -20f);
//Camera3d.followActor3d(knight, false);
//stage3d.moveBy(-50f, 0f, 0f, 2f);
//stage3d.addActor3d(actor2);
//actor1.addAction3d(Actions3d.rotateTo(60f, 5f));
//actor1.addAction3d(Actions3d.scaleBy(0.5f, 0.5f, 0.5f, 5f, Interpolation.linear));
// actor1.addAction3d(Actions3d.forever(Actions3d.sequence(Actions3d.moveBy(50f, 0f, 0f, 10f),
// Actions3d.moveBy(-50f, 0f, 0f, 10f))));
// actor1.addAction3d(Actions3d.sequence(
// Actions3d.moveBy(7f, 0f, 0f, 2f),
// Actions3d.scaleTo(0.5f, 0.5f, 0.5f, 5f),
// Actions3d.moveBy(-7f, 0f, 0f, 2f)));
//actor1.addAction3d(Actions3d.scaleTo(1.2f, 1.2f, 1.2f, 1f));
//actor2.addAction3d(Actions3d.scaleBy(0.3f, 0.3f, 0.3f, 5f));
//actor1.addAction3d(Actions3d.sequence(Actions3d.moveBy(7f, 0f, 0f, 2f), Actions3d.moveBy(-7f, 0f, 0f, 2f)));
//actor1.addAction3d(Actions3d.moveTo(7f, 0f, 0f, 3f));
// actor1.addAction3d(Actions3d.moveTo(-10f, 0f, 0f, 2f));
/*
* Since both actions are running at same time we get the difference in x
* ans : actor.getX() = -3.0000014
*/
/* if you see this the setRotation method called alone works but after this moveTo is called and the actor1
* rotation is reset to original .. this is the problem because of transformation matrix
* and the Sequence action problem is i think because i'm using the pools from gdx.utils.pools
*/
//actor1.setRotation(59);
//actor1.setPosition(5f, 0f, 0f);
// actor2.addAction3d(Actions3d.moveBy(-7f, 0f, 0f, 2f));
// r.setRotation(59);
//r.addAction3d(Actions.rotateTo(59, 1f));
//r.addAction3d(Actions.rotateBy(59, 1f));
}
void testGroup3d(){
group3d = new Group3d();
group3d.setPosition(0f, 0f, 0f);
group3d.setName("group1");
stage3d.addActor3d(group3d);
group3d.addActor3d(knight);
group3d.addActor3d(actor2);
group3d.addActor3d(actor3);
group3d.addAction3d(Actions3d.sequence(Actions3d.moveTo(0f, 5f, 0f, 2f),
Actions3d.moveTo(5f, 0f, 0f, 2f), Actions3d.scaleTo(0f, 5f, 0f, 2f)));
}
void testStage3d(){
stage3d.addActor3d(knight);
stage3d.addActor3d(actor2);
stage3d.addAction3d(Actions3d.moveTo(-7f, 0f, 0f, 3f));
}
} | apache-2.0 |
eborodina/test_pdt-25 | src/com/example/tests/GroupRemovalTests.java | 890 | package com.example.tests;
//import static org.testng.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.Random;
//import org.apache.commons.el.EqualityOperator;
import org.testng.annotations.Test;
import com.example.utils.SortedListOf;
public class GroupRemovalTests extends TestBase {
@Test
public void deleteSomeGroup(){
//save old state
SortedListOf<GroupData> oldList = app.getGroupHelper().getGroups();
Random rnd = new Random();
int index = rnd.nextInt(oldList.size()-1);
//action
app.getGroupHelper().deleteGroup(index);
//save new state
SortedListOf<GroupData> newList = app.getGroupHelper().getGroups();
//compare states
assertThat(newList, equalTo(oldList.without(index)));
}
}
| apache-2.0 |
tuanchauict/annopref | annopref-annotation/src/main/java/com/tuanchauict/annopref/annotation/IntValue.java | 256 | package com.tuanchauict.annopref.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Created by tuanchauict on 11/29/16.
*/
@Target(value = ElementType.FIELD)
public @interface IntValue {
int[] value();
}
| apache-2.0 |
BeamFoundry/spring-jnrpe | jnrpe-lib/src/main/java/it/jnrpe/ReturnValue.java | 8047 | /*******************************************************************************
* Copyright (c) 2007, 2014 Massimiliano Ziccardi
*
* 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 it.jnrpe;
import it.jnrpe.plugins.Metric;
import it.jnrpe.utils.thresholds.IThreshold;
import java.util.ArrayList;
import java.util.List;
/**
* This class is just a container for the plugin result.
*
* @author Massimiliano Ziccardi
* @version $Revision: 1.0 $
*/
public final class ReturnValue {
/**
* An enumeration defining all supported unit of measures.
*
* @author Massimiliano Ziccardi
*/
public enum UnitOfMeasure {
/**
* microseconds.
*/
microseconds,
/**
* milliseconds.
*/
milliseconds,
/**
* seconds.
*/
seconds,
/**
* percentage.
*/
percentage,
/**
* bytes.
*/
bytes,
/**
* kilobytes.
*/
kilobytes,
/**
* megabytes.
*/
megabytes,
/**
* gigabytes.
*/
gigabytes,
/**
* terabytes.
*/
terabytes,
/**
* counter.
*/
counter
};
/**
* The performance data to attach to the result string.
*/
private final List<PerformanceData> performanceDataList = new ArrayList<PerformanceData>();
/**
* The raw return code.
*/
private Status statusCode;
/**
* The message.
*/
private String messageString;
/**
* Initializes an empty return value.
*/
public ReturnValue() {
}
/**
* Initializes the return value object with the given message and with the
* {@link Status.OK} state.
*
* @param message
* The message
*/
public ReturnValue(final String message) {
statusCode = Status.OK;
messageString = message;
}
/**
* Initializes the return value object with the given state and the given
* message.
*
* @param returnCode
* The state
* @param message
* The message
* @deprecated Use {@link #ReturnValue(Status, String)} instead
*/
@Deprecated
public ReturnValue(final int returnCode, final String message) {
statusCode = Status.fromIntValue(returnCode);
messageString = message;
}
/**
* Initializes the return value object with the given state and the given
* message.
*
* @param status
* The status to be returned
* @param message
* The message to be returned
*/
public ReturnValue(final Status status, final String message) {
statusCode = status;
messageString = message;
}
/**
* Sets the return code and returns 'this' so that the calls can be
* cascaded.
*
* @param returnCode
* The return code
* @deprecated Use {@link #withStatus(Status)} instead.
* @return this */
@Deprecated
public ReturnValue withReturnCode(final int returnCode) {
statusCode = Status.fromIntValue(returnCode);
return this;
}
/**
* Sets the return code and returns 'this' so that the calls can be
* cascaded.
*
* @param status
* The status to be returned to Nagios
* @return this */
public ReturnValue withStatus(final Status status) {
if (status == null) {
throw new IllegalArgumentException("Status can't be null");
}
statusCode = status;
return this;
}
/**
* Sets the message and returns 'this' so that the calls can be cascaded.
*
* @param message
* The message to be returned
* @return this */
public ReturnValue withMessage(final String message) {
messageString = message;
return this;
}
/**
* Returns the status.
*
* @deprecated Use {@link #getStatus()} instead.
* @return The state */
@Deprecated
public int getReturnCode() {
return statusCode.intValue();
}
/**
* Returns the status.
*
* @return The status */
public Status getStatus() {
return statusCode;
}
/**
* Returns the message. If the performance data has been passed in, they are
* attached at the end of the message accordingly to the Nagios
* specifications
*
* @return The message and optionally the performance data */
public String getMessage() {
if (performanceDataList.isEmpty()) {
return messageString;
}
StringBuilder res = new StringBuilder(messageString).append('|');
for (PerformanceData pd : performanceDataList) {
res.append(pd.toPerformanceString()).append(' ');
}
return res.toString();
}
/**
* Adds performance data to the plugin result. Thos data will be added to
* the output formatted as specified in Nagios specifications
* (http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN201)
*
* @param metric
* The metric relative to this result
* @param uom
* The Unit Of Measure
* @param warningRange
* The warning threshold used to check this metric (can be null)
* @param criticalRange
* The critical threshold used to check this value (can be null)
* @return this */
public ReturnValue withPerformanceData(final Metric metric, final UnitOfMeasure uom, final String warningRange,
final String criticalRange) {
performanceDataList.add(new PerformanceData(metric, uom, warningRange, criticalRange));
return this;
}
/**
* Adds performance data to the plugin result. Thos data will be added to
* the output formatted as specified in Nagios specifications
* (http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN201)
*
* @param metric
* The metric relative to this result
* @param warningRange
* The warning threshold used to check this metric (can be null)
* @param criticalRange
* The critical threshold used to check this value (can be null)
* @param minimumValue
* The minimum value for this metric (can be null if not
* applicable)
* @param maximumValue
* The maximum value for this metric (can be null if not
* applicable)
* @return this */
public ReturnValue withPerformanceData(final Metric metric, IThreshold threshold) {
performanceDataList.add(new PerformanceData(metric, threshold.getPrefix(), threshold.getUnitString(), threshold.getRangesAsString(Status.WARNING), threshold.getRangesAsString(Status.CRITICAL)));
return this;
}
/**
* Method toString.
* @return String
*/
@Override
public String toString() {
final int maxLen = 10;
return "ReturnValue [performanceDataList="
+ (performanceDataList != null ? performanceDataList.subList(0, Math.min(performanceDataList.size(), maxLen)) : null)
+ ", statusCode=" + statusCode + ", messageString=" + messageString + "]";
}
}
| apache-2.0 |
citygml4j/citygml4j | src-gen/main/java/net/opengis/gml/LinearCSType.java | 1447 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2019.02.03 um 11:14:53 PM CET
//
package net.opengis.gml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* A one-dimensional coordinate system that consists of the points that lie on the single axis described. The associated ordinate is the distance from the specified origin to the point along the axis. Example: usage of the line feature representing a road to describe points on or along that road. A LinearCS shall have one usesAxis association.
*
* <p>Java-Klasse für LinearCSType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="LinearCSType">
* <complexContent>
* <extension base="{http://www.opengis.net/gml}AbstractCoordinateSystemType">
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LinearCSType")
public class LinearCSType
extends AbstractCoordinateSystemType
{
}
| apache-2.0 |
nickolasnikolic/leesh-mobile-app | Resources/app.js | 7883 |
Ti.include("/struct/struct.js");
var controller = Stately.machine({
'NEW': {
//startup
'start': function () {
S.app.mainWindow = S.ui.createApplicationWindow();
S.app.mainWindow.open();
//based upon settings
//based upon roles
//return this.OBSERVE
//else
//this.REPORT.remote() or local();
//else this.COUPLE
}
},
'COUPLE': {
//couple 2 or more devices to a peer group
'connect': function(){
//generate group id
//give preliminary link to devices in peer group
//if error
//return this.COUPLE.error()
//else
this.COUPLE.giveRoles;
},
'giveRoles': function(){
//allow each user to choose a role
//be it observer, observed, or peer (mutual observation)
//upon selection
//if error
//return this.COUPLE.error()
//else
this.COUPLE.confirm;
},
'confirm': function(){
//show list of users in peer group with chosen roles listed
//if unanimous confirmation, write roles to db
//else show list again on all devices for those contested group members
//with option to remove contested members from group, or cancel entirely
//repeat if needed
//if error
//return this.COUPLE.error()
//else
//return this.OBSERVE
},
'error': function(){
//list coupling errors to group
}
},
'OBSERVE': {
//collecting info
'active': function () {
//get last report from paired device
//get distance from last known
//get bearing towards target from last known
//display onscreen
//update data
//return this.REPORT appropriate to application settings;
},
'passive': function () {
//get last report from paired device
//get distance from last known
//get bearing towards target from last known
//display notification of update with distance and age of data
//update data
//return this.REPORT appropriate to application settings;
}
},
'REPORT': {
//refresh datastore
'local': function(){
//if it hasn't hapened too often or for too long
//ask professionals what that might be...
//check location
//var currentPosition = JSON.parse( geo.getCurrentPosition() );
Ti.Geolocation.getCurrentPosition( function( e ){
if( !!e.error ) this.REPORT.error( e.error );
//plot point in db
var record = locations.newRecord({
timeStamp: e.coords.timestamp,
latitude: e.coords.latitude,
longitude: e.coords.longitude,
altitude: e.coords.altitude,
alltitudeAccuracy: e.coords.altitudeAccuracy,
heading: e.coords.heading,
accuracy: e.coords.accuracy,
speed: e.coords.speed
});
record.save();
//compare distance to last point
var whereWeAre = {
latitude: e.coords.latitude,
longitude: e.coords.longitude
};
var whereWeWere = locations.findOneById( record.id - 1 );
if( whereWeWere != 'undefined' ){
var lastPosition = {
latitude: whereWeWere.latitude,
longitude: whereWeWere.longitude
};
var distanceTraveled = geolib.getDistance( whereWeAre, whereWeWere );
Ti.API.info( 'distance traveled is: ' + distanceTraveled );
}else{
//just for testing, normally we would test gainst the other phones in the group
var northPole = { latitude: 90, longitude: 0 }
var distanceFromNorthPole = geolib.getDistance( whereWeAre, northPole );
Ti.API.info( 'distance from north pole is: ' + distanceFromNorthPole );
}
} );
Ti.API.info( 'locations count is: ' + locations.count() );
//if any concern, issue warning()
//if( concern ) return this.WARN;
//if error then go to error()
//if( error ) return this.error();
//otherwise, go to ok()
//else return this.REPORT.ok();
return this.WAIT; //@todo remove temp redirect
},
'remote': function(){
//log unreported points in google geofence
//get last timestamp in remote
//go to appropriate point in db
//post the remaining local measurements from db to remote from point of last timestamp
//check location
Ti.Geolocation.getCurrentPosition( function( e ){
if( !!e.error ) this.REPORT.error( e.error );
//plot point in db
var record = locations.newRecord({
timeStamp: e.coords.timestamp,
latitude: e.coords.latitude,
longitude: e.coords.longitude,
altitude: e.coords.altitude,
alltitudeAccuracy: e.coords.altitudeAccuracy,
heading: e.coords.heading,
accuracy: e.coords.accuracy,
speed: e.coords.speed
});
record.save();
} );
Ti.API.info( 'locations count is: ' + locations.count() );
//if any concern, issue warning()
//if( concern ) return this.WARN;
//if error then go to error()
//if( error ) return this.error();
//otherwise, go to ok()
//else return this.REPORT.ok();
return this.WAIT; //@todo remove temp redirect
},
'ok': function () {
//update is just fine
//if it has happened recently, go to wait
if( true ) return this.WAIT; //@todo get to this if true...
//return this.REPORT appropriate to application settings;
else return this.REPORT;
},
'error': function ( error ) {
Ti.API.info( error );
//log and count error
//if too many errors?
//what kind of error is it?
//what role is the current device?
//any alternatives?
//what was the circumstance of the user?
//wait and retry, issue this.WARNING, or this.DANGER
//return this.OBSERVING appropriate to application settings;
}
},
'WARN': {
//issue regular warning to group
'warn': function(){
//issue warning to group
//is it:
//too slow?
//too fast?
//too far?
//off?
//for any of the above
//display stats of device that misses safety test
//display confirm opportunity to notify authorities
//or cancel
}
},
'DANGER': {
//notify authorities
'danger': function(){}
},
'WAIT': {
//wait
'wait': function(){
setTimeout( function(){}, 3000 );
this.REPORT.local();
}
},
'SHUTDOWN': {
'end': function(){
//is this a surprise?
//what role is this device?
//if a surprise and device is target
//hide view and revert to passive
//is device being shut down
//log and report
//else clean up
}
}
});
controller.bind( function( event, oldState, newState ){
Ti.API.info( 'machine state is: ' + this.getMachineState() );
Ti.API.info( 'machine events are: ' + String( this.getMachineEvents() ) );
Ti.API.info( 'machine notification passed vars are: ' + 'e:' + event +' - states:'+ oldState + ' => ' + newState );
//bind a Titanium event to the events of Stately
//Ti.API.fireEvent( this.getMachineState() );
} );
controller
.start()
.wait()
.local()
.wait()
.end();
// hypothitical implementation
// if( localAppropriate ){
// controller.local();
// }else{
// controller.remote();
// }
//
// if( ok ){
// controller.ok();
// }else{
// controller.error();
// }
| apache-2.0 |
HiveKa/HiveKa | src/main/java/org/apache/hadoop/hive/kafka/camus/KafkaKey.java | 6733 | package org.apache.hadoop.hive.kafka.camus;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.UTF8;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
/**
* The key for the mapreduce job to pull kafka. Contains offsets and the
* checksum.
*/
public class KafkaKey implements WritableComparable<KafkaKey>, IKafkaKey {
public static final Text SERVER = new Text("server");
public static final Text SERVICE = new Text("service");
public static KafkaKey DUMMY_KEY = new KafkaKey();
private String leaderId = "";
private int partition = 0;
private long beginOffset = 0;
private long offset = 0;
private long checksum = 0;
private String topic = "";
private long time = 0;
private String server = "";
private String service = "";
private MapWritable partitionMap = new MapWritable();
/**
* dummy empty constructor
*/
public KafkaKey() {
this("dummy", "0", 0, 0, 0, 0);
}
public KafkaKey(KafkaKey other) {
this.partition = other.partition;
this.beginOffset = other.beginOffset;
this.offset = other.offset;
this.checksum = other.checksum;
this.topic = other.topic;
this.time = other.time;
this.server = other.server;
this.service = other.service;
this.partitionMap = new MapWritable(other.partitionMap);
}
public KafkaKey(String topic, String leaderId, int partition) {
this.set(topic, leaderId, partition, 0, 0, 0);
}
public KafkaKey(String topic, String leaderId, int partition, long beginOffset, long offset) {
this.set(topic, leaderId, partition, beginOffset, offset, 0);
}
public KafkaKey(String topic, String leaderId, int partition, long beginOffset, long offset, long checksum) {
this.set(topic, leaderId, partition, beginOffset, offset, checksum);
}
public void set(String topic, String leaderId, int partition, long beginOffset, long offset, long checksum) {
this.leaderId = leaderId;
this.partition = partition;
this.beginOffset = beginOffset;
this.offset = offset;
this.checksum = checksum;
this.topic = topic;
this.time = System.currentTimeMillis(); // if event can't be decoded,
// this time will be used for
// debugging.
}
public void clear() {
leaderId = "";
partition = 0;
beginOffset = 0;
offset = 0;
checksum = 0;
topic = "";
time = 0;
server = "";
service = "";
partitionMap = new MapWritable();
}
public String getServer() {
return partitionMap.get(SERVER).toString();
}
public void setServer(String newServer) {
partitionMap.put(SERVER, new Text(newServer));
}
public String getService() {
return partitionMap.get(SERVICE).toString();
}
public void setService(String newService) {
partitionMap.put(SERVICE, new Text(newService));
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getTopic() {
return topic;
}
public String getLeaderId() {
return leaderId;
}
public int getPartition() {
return this.partition;
}
public long getBeginOffset() {
return this.beginOffset;
}
public void setOffset(long offset) {
this.offset = offset;
}
public long getOffset() {
return this.offset;
}
public long getChecksum() {
return this.checksum;
}
@Override
public long getMessageSize() {
Text key = new Text("message.size");
if (this.partitionMap.containsKey(key))
return ((LongWritable) this.partitionMap.get(key)).get();
else
return 1024; //default estimated size
}
public void setMessageSize(long messageSize) {
Text key = new Text("message.size");
put(key, new LongWritable(messageSize));
}
public void put(Writable key, Writable value) {
this.partitionMap.put(key, value);
}
public void addAllPartitionMap(MapWritable partitionMap) {
this.partitionMap.putAll(partitionMap);
}
public MapWritable getPartitionMap() {
return partitionMap;
}
@Override
public void readFields(DataInput in) throws IOException {
this.leaderId = UTF8.readString(in);
this.partition = in.readInt();
this.beginOffset = in.readLong();
this.offset = in.readLong();
this.checksum = in.readLong();
this.topic = in.readUTF();
this.time = in.readLong();
this.server = in.readUTF(); // left for legacy
this.service = in.readUTF(); // left for legacy
this.partitionMap = new MapWritable();
try {
this.partitionMap.readFields(in);
} catch (IOException e) {
this.setServer(this.server);
this.setService(this.service);
}
}
@Override
public void write(DataOutput out) throws IOException {
UTF8.writeString(out, this.leaderId);
out.writeInt(this.partition);
out.writeLong(this.beginOffset);
out.writeLong(this.offset);
out.writeLong(this.checksum);
out.writeUTF(this.topic);
out.writeLong(this.time);
out.writeUTF(this.server); // left for legacy
out.writeUTF(this.service); // left for legacy
this.partitionMap.write(out);
}
@Override
public int compareTo(KafkaKey o) {
if (partition != o.partition) {
return partition = o.partition;
} else {
if (offset > o.offset) {
return 1;
} else if (offset < o.offset) {
return -1;
} else {
if (checksum > o.checksum) {
return 1;
} else if (checksum < o.checksum) {
return -1;
} else {
return 0;
}
}
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("topic=");
builder.append(topic);
builder.append(" partition=");
builder.append(partition);
builder.append("leaderId=");
builder.append(leaderId);
builder.append(" server=");
builder.append(server);
builder.append(" service=");
builder.append(service);
builder.append(" beginOffset=");
builder.append(beginOffset);
builder.append(" offset=");
builder.append(offset);
builder.append(" msgSize=");
builder.append(getMessageSize());
builder.append(" server=");
builder.append(server);
builder.append(" checksum=");
builder.append(checksum);
builder.append(" time=");
builder.append(time);
for (Map.Entry<Writable, Writable> e : partitionMap.entrySet()) {
builder.append(" " + e.getKey() + "=");
builder.append(e.getValue().toString());
}
return builder.toString();
}
}
| apache-2.0 |
michaelBenin/js-sdk | tests/unit/streamserver/plugins/text-counter.js | 319 | (function($) {
var suite = Echo.Tests.Unit.PluginsTextCounter = function() {
this.constructPluginRenderersTest();
};
suite.prototype.tests = {};
suite.prototype.info = {
"className": "Echo.StreamServer.Controls.Submit.Plugins.TextCounter",
"suiteName": "TextCounter plugin",
"functions": []
};
})(Echo.jQuery);
| apache-2.0 |
KSSDevelopment/Prism | Source/Wpf/Prism.Mef.Wpf/Modularity/DownloadedPartCatalogCollection.cs | 2432 | // Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Primitives;
using Prism.Modularity;
namespace Prism.Mef.Modularity
{
/// <summary>
/// Holds a collection of composable part catalogs keyed by module info.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix"), Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public class DownloadedPartCatalogCollection
{
private Dictionary<ModuleInfo, ComposablePartCatalog> catalogs = new Dictionary<ModuleInfo, ComposablePartCatalog>();
/// <summary>
/// Adds the specified catalog using the module info as a key.
/// </summary>
/// <param name="moduleInfo">The module info.</param>
/// <param name="catalog">The catalog.</param>
public void Add(ModuleInfo moduleInfo, ComposablePartCatalog catalog)
{
catalogs.Add(moduleInfo, catalog);
}
/// <summary>
/// Gets the catalog for the specified module info.
/// </summary>
/// <param name="moduleInfo">The module info.</param>
/// <returns></returns>
public ComposablePartCatalog Get(ModuleInfo moduleInfo)
{
return this.catalogs[moduleInfo];
}
/// <summary>
/// Tries to ge the catalog for the specified module info.
/// </summary>
/// <param name="moduleInfo">The module info.</param>
/// <param name="catalog">The catalog.</param>
/// <returns>true if found; otherwise false;</returns>
public bool TryGet(ModuleInfo moduleInfo, out ComposablePartCatalog catalog)
{
return this.catalogs.TryGetValue(moduleInfo, out catalog);
}
/// <summary>
/// Removes the catalgo for the specified module info.
/// </summary>
/// <param name="moduleInfo">The module info.</param>
public void Remove(ModuleInfo moduleInfo)
{
this.catalogs.Remove(moduleInfo);
}
/// <summary>
/// Clears the collection of catalogs.
/// </summary>
public void Clear()
{
this.catalogs.Clear();
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ecr/src/main/java/com/amazonaws/services/ecr/model/transform/RemediationMarshaller.java | 1944 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ecr.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.ecr.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* RemediationMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RemediationMarshaller {
private static final MarshallingInfo<StructuredPojo> RECOMMENDATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("recommendation").build();
private static final RemediationMarshaller instance = new RemediationMarshaller();
public static RemediationMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Remediation remediation, ProtocolMarshaller protocolMarshaller) {
if (remediation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(remediation.getRecommendation(), RECOMMENDATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
appbels/Org | Org/Schema/Thing/Intangible/Quantity/Distance.class.php | 1062 | <?php
namespace Org\Schema\Thing\Intangible\Quantity;
/**
* Class Distance
* Properties that take Distances as values are of the form '<Number> <Length unit of measure>'. E.g., '7 ft'.
* @author AppBels <[email protected]>
* @name Distance
* @namespace Org\Schema\Thing\Intangible\Quantity
* @package Org\Schema
* @see https://schema.org/Distance
* Date 30/03/2017
*/
class Distance extends \Org\Schema\Thing\Intangible\Quantity
{
/**
* Distance constructor.
* @access public
* @see \Org\Schema\Thing\Intangible\Quantity::__construct()
*/
public function __construct ()
{
parent::__construct();
}
/**
* Distance toString.
* @access public
* @see \Org\Schema\Thing\Intangible\Quantity::__toString()
*
* @return string
*/
public function __toString ()
{
return parent::__toString();
}
/**
* Distance destructor.
* @access public
* @see \Org\Schema\Thing\Intangible\Quantity::__destruct()
*/
public function __destruct ()
{
parent::__destruct();
}
}
?> | apache-2.0 |
gerdriesselmann/netty | codec/src/main/java/io/netty/handler/codec/LengthFieldPrepender.java | 7797 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec;
import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
import static java.util.Objects.requireNonNull;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import java.nio.ByteOrder;
import java.util.List;
/**
* An encoder that prepends the length of the message. The length value is
* prepended as a binary form.
* <p>
* For example, <tt>{@link LengthFieldPrepender}(2)</tt> will encode the
* following 12-bytes string:
* <pre>
* +----------------+
* | "HELLO, WORLD" |
* +----------------+
* </pre>
* into the following:
* <pre>
* +--------+----------------+
* + 0x000C | "HELLO, WORLD" |
* +--------+----------------+
* </pre>
* If you turned on the {@code lengthIncludesLengthFieldLength} flag in the
* constructor, the encoded data would look like the following
* (12 (original data) + 2 (prepended data) = 14 (0xE)):
* <pre>
* +--------+----------------+
* + 0x000E | "HELLO, WORLD" |
* +--------+----------------+
* </pre>
*/
@Sharable
public class LengthFieldPrepender extends MessageToMessageEncoder<ByteBuf> {
private final ByteOrder byteOrder;
private final int lengthFieldLength;
private final boolean lengthIncludesLengthFieldLength;
private final int lengthAdjustment;
/**
* Creates a new instance.
*
* @param lengthFieldLength the length of the prepended length field.
* Only 1, 2, 3, 4, and 8 are allowed.
*
* @throws IllegalArgumentException
* if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8
*/
public LengthFieldPrepender(int lengthFieldLength) {
this(lengthFieldLength, false);
}
/**
* Creates a new instance.
*
* @param lengthFieldLength the length of the prepended length field.
* Only 1, 2, 3, 4, and 8 are allowed.
* @param lengthIncludesLengthFieldLength
* if {@code true}, the length of the prepended
* length field is added to the value of the
* prepended length field.
*
* @throws IllegalArgumentException
* if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8
*/
public LengthFieldPrepender(int lengthFieldLength, boolean lengthIncludesLengthFieldLength) {
this(lengthFieldLength, 0, lengthIncludesLengthFieldLength);
}
/**
* Creates a new instance.
*
* @param lengthFieldLength the length of the prepended length field.
* Only 1, 2, 3, 4, and 8 are allowed.
* @param lengthAdjustment the compensation value to add to the value
* of the length field
*
* @throws IllegalArgumentException
* if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8
*/
public LengthFieldPrepender(int lengthFieldLength, int lengthAdjustment) {
this(lengthFieldLength, lengthAdjustment, false);
}
/**
* Creates a new instance.
*
* @param lengthFieldLength the length of the prepended length field.
* Only 1, 2, 3, 4, and 8 are allowed.
* @param lengthAdjustment the compensation value to add to the value
* of the length field
* @param lengthIncludesLengthFieldLength
* if {@code true}, the length of the prepended
* length field is added to the value of the
* prepended length field.
*
* @throws IllegalArgumentException
* if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8
*/
public LengthFieldPrepender(int lengthFieldLength, int lengthAdjustment, boolean lengthIncludesLengthFieldLength) {
this(ByteOrder.BIG_ENDIAN, lengthFieldLength, lengthAdjustment, lengthIncludesLengthFieldLength);
}
/**
* Creates a new instance.
*
* @param byteOrder the {@link ByteOrder} of the length field
* @param lengthFieldLength the length of the prepended length field.
* Only 1, 2, 3, 4, and 8 are allowed.
* @param lengthAdjustment the compensation value to add to the value
* of the length field
* @param lengthIncludesLengthFieldLength
* if {@code true}, the length of the prepended
* length field is added to the value of the
* prepended length field.
*
* @throws IllegalArgumentException
* if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8
*/
public LengthFieldPrepender(
ByteOrder byteOrder, int lengthFieldLength,
int lengthAdjustment, boolean lengthIncludesLengthFieldLength) {
if (lengthFieldLength != 1 && lengthFieldLength != 2 &&
lengthFieldLength != 3 && lengthFieldLength != 4 &&
lengthFieldLength != 8) {
throw new IllegalArgumentException(
"lengthFieldLength must be either 1, 2, 3, 4, or 8: " +
lengthFieldLength);
}
requireNonNull(byteOrder, "byteOrder");
this.byteOrder = byteOrder;
this.lengthFieldLength = lengthFieldLength;
this.lengthIncludesLengthFieldLength = lengthIncludesLengthFieldLength;
this.lengthAdjustment = lengthAdjustment;
}
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
int length = msg.readableBytes() + lengthAdjustment;
if (lengthIncludesLengthFieldLength) {
length += lengthFieldLength;
}
checkPositiveOrZero(length, "length");
switch (lengthFieldLength) {
case 1:
if (length >= 256) {
throw new IllegalArgumentException(
"length does not fit into a byte: " + length);
}
out.add(ctx.alloc().buffer(1).order(byteOrder).writeByte((byte) length));
break;
case 2:
if (length >= 65536) {
throw new IllegalArgumentException(
"length does not fit into a short integer: " + length);
}
out.add(ctx.alloc().buffer(2).order(byteOrder).writeShort((short) length));
break;
case 3:
if (length >= 16777216) {
throw new IllegalArgumentException(
"length does not fit into a medium integer: " + length);
}
out.add(ctx.alloc().buffer(3).order(byteOrder).writeMedium(length));
break;
case 4:
out.add(ctx.alloc().buffer(4).order(byteOrder).writeInt(length));
break;
case 8:
out.add(ctx.alloc().buffer(8).order(byteOrder).writeLong(length));
break;
default:
throw new Error("should not reach here");
}
out.add(msg.retain());
}
}
| apache-2.0 |
TITcs/TITcs.SharePoint | src/TITcs.SharePoint/Utils/ListUtils.cs | 9501 | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using TITcs.SharePoint.Log;
using DraftVisibilityType = Microsoft.SharePoint.DraftVisibilityType;
namespace TITcs.SharePoint.Utils
{
public class ListUtils
{
/// <summary>
/// Enable Anonymous Access list
/// </summary>
/// <param name="web">Context</param>
/// <param name="listTitle">List title</param>
public static void EnableAccessAnonymous(SPWeb web, string listTitle)
{
EnableAccessAnonymous(web, listTitle);
}
public static void EnableAccessAnonymous(SPWeb web, string listTitle, SPBasePermissions basePermissions = SPBasePermissions.ViewPages |
SPBasePermissions.OpenItems | SPBasePermissions.ViewVersions |
SPBasePermissions.Open | SPBasePermissions.UseClientIntegration |
SPBasePermissions.ViewFormPages | SPBasePermissions.ViewListItems)
{
runCodeInListInstance(web, listTitle, (list) =>
{
list.BreakRoleInheritance(true, false);
list.AllowEveryoneViewItems = true;
list.AnonymousPermMask64 = basePermissions;
list.Update();
Logger.Information("ListUtils.EnableAccessAnonymous", "Anonymous access enabled in the \"{0}\"", listTitle);
});
}
/// <summary>
/// Disable Anonymous Access list
/// </summary>
/// <param name="web">Context</param>
/// <param name="listTitle">List title</param>
public static void DisableAccessAnonymous(SPWeb web, string listTitle)
{
runCodeInListInstance(web, listTitle, (list) =>
{
list.ResetRoleInheritance();
list.Update();
});
}
/// <summary>
///
/// </summary>
/// <param name="web"></param>
/// <param name="listTitle"></param>
/// <param name="fieldName"></param>
/// <param name="allow"></param>
/// <reference>https://msdn.microsoft.com/en-us/library/office/ee536168(v=office.14).aspx</reference>
public static void AllowDuplicateValues(SPWeb web, string listTitle, string fieldName, bool allow = true)
{
runCodeInListInstance(web, listTitle, (list) =>
{
if (list.ItemCount > 0 && !allow)
{
Logger.Unexpected("ListUtils.AllowDuplicateValues", "Could not allow duplicate values for the field \"{0}\" list \"{1}\" because it contains items. Remove all items from the list.", fieldName, listTitle);
return;
}
if (list.Fields.ContainsField(fieldName))
{
SPField field = list.Fields[fieldName];
field.Indexed = !allow;
//field.AllowDuplicateValues = false;
field.EnforceUniqueValues = !allow;
field.Update();
list.Update();
var message = "The \"{0}\" field no longer allows duplicate values";
if (!allow)
message = "The \"{0}\" field allows duplicate values";
Logger.Information("ListUtils.AllowDuplicateValues", message, fieldName);
}
});
}
public static void ChangeDisplayNameInField(SPWeb web, string listTitle, string fieldName, string displayName)
{
runCodeInListInstance(web, listTitle, (list) =>
{
if (list.Fields.ContainsField(fieldName))
{
SPField field = list.Fields[fieldName];
field.Title = displayName;
field.Update();
list.Update();
Logger.Information("ListUtils.ChangeDisplayNameInField", "The display name of the \"{0}\" list \"{1}\" was changed to \"{2}\"", listTitle, fieldName, displayName);
}
});
}
public static void ChangeTitle(SPWeb web, string listTitle, string title)
{
runCodeInListInstance(web, listTitle, (list) =>
{
list.Title = title;
list.Update();
Logger.Information("ListUtils.ChangeTitle", "The title of the list \"{0}\" has changed to \"{1}\"", listTitle, title);
});
}
public static void DraftVersionVisibility(SPWeb web, string listTitle, DraftVisibilityType draftVisibilityType = DraftVisibilityType.Reader)
{
runCodeInListInstance(web, listTitle, (list) =>
{
list.DraftVersionVisibility = draftVisibilityType;
list.Update();
if(draftVisibilityType == DraftVisibilityType.Reader)
Logger.Information("ListUtils.ChangeTitle", "The list \"{0}\" has setted to \"Any user who can read items\"", listTitle);
else if (draftVisibilityType == DraftVisibilityType.Author)
Logger.Information("ListUtils.ChangeTitle", "The list \"{0}\" has setted to \"Only users who can edit items\"", listTitle);
else if (draftVisibilityType == DraftVisibilityType.Approver)
Logger.Information("ListUtils.ChangeTitle", "The list \"{0}\" has setted to \"Only users who can approve items (and the author of the item)\"", listTitle);
});
}
private static void runCodeInListInstance(SPWeb web, string listTitle, Action<SPList> action)
{
var list = web.Lists.TryGetList(listTitle);
if (list != null)
{
var allowSafeUpdates = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
action(list);
web.AllowUnsafeUpdates = allowSafeUpdates;
}
else
Logger.Unexpected("ListUtils.runCodeInListInstance", "The list \"{0}\" does not exist", listTitle);
}
private static void runCodeInListInstance(ClientContext clientContext, string listTitle, Action<List> action)
{
Web web = clientContext.Web;
ListCollection lists = web.Lists;
IEnumerable<List> existingLists = clientContext.LoadQuery(lists.Where(list => list.Title == listTitle));
clientContext.ExecuteQuery();
var existingList = existingLists.FirstOrDefault();
if (existingList != null)
{
action(existingList);
}
else
Logger.Unexpected("ListUtils.runCodeInListInstance", "The list \"{0}\" does not exist", listTitle);
}
public static void AddField(SPWeb web, string listTitle, string internalNameOfField, string displayNameOfField, bool isViewField, bool showEditCreateForm, bool showDisplayForm)
{
runCodeInListInstance(web, listTitle, (list) =>
{
if (!list.Fields.ContainsField(displayNameOfField) &&
web.AvailableFields.ContainsField(internalNameOfField))
{
if (!list.Fields.ContainsFieldWithStaticName(internalNameOfField))
{
SPField field = null;
try
{
field = web.AvailableFields[displayNameOfField];
}
catch (Exception)
{
field = web.AvailableFields.GetFieldByInternalName(internalNameOfField);
}
field.ShowInDisplayForm = showDisplayForm;
field.ShowInViewForms = showDisplayForm;
field.ShowInEditForm = showEditCreateForm;
field.ShowInNewForm = showEditCreateForm;
list.Fields.Add(field);
if (isViewField)
{
SPView viewList = list.DefaultView;
viewList.ViewFields.Add(web.AvailableFields[displayNameOfField]);
viewList.ViewFields.MoveFieldTo(internalNameOfField, 2);
viewList.Update();
}
}
else
{
var field = list.Fields.GetFieldByInternalName(internalNameOfField);
if (field.Title.ToLower() != displayNameOfField.ToLower())
{
field.Title = displayNameOfField;
field.Update();
}
}
Logger.Information("ListUtils.AddField", "The field \"{0}\" was added to the list \"{1}\"", displayNameOfField, listTitle);
list.Update();
}
else
{
Logger.Unexpected("ListUtils.AddField", string.Format("There is already a field in the list \"{2}\" with the name \"{0}\" and internal name \"{1}\"", displayNameOfField, internalNameOfField, listTitle));
}
});
}
}
}
| apache-2.0 |
ncherkasov01/cherkasov-selenium-training | java-project/src/test/java/train/sel/java/project/AdminList.java | 3555 | package train.sel.java.project;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Created by Nikolay on 10.05.2017.
*/
public class AdminList {
private WebDriver driver;
private WebDriver wait;
@Before
public void start() {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void Test() {
//заходим как администратор
driver.get("http://localhost/litecart/admin/");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin");
driver.findElement(By.name("login")).click();
// собираем список меню, выводим на экран количество меню
List<WebElement> menuItems = driver.findElements(By.xpath("//ul[@id='box-apps-menu']/li"));
int menuItemSize = menuItems.size();
System.out.println("Items Count: "+menuItems.size());
// проходим в цикле по каждому элементу меню
for (int i=1;i<=menuItemSize;i++) {
// получаем i-тый элемент меню
WebElement item = driver.findElement(By.xpath("//ul[@id='box-apps-menu']/li["+i+"]"));
System.out.println("Item: "+item.getText());
item.click();
// проверяем наличие заголовка на странице после клика по меню
WebElement h1 = driver.findElement(By.xpath("//*[@id='content']/h1"));
System.out.println(" H1 = "+h1.getText());
// вновь получаем i-тый элемент меню, т.к. старый "протух" после клика
item = driver.findElement(By.xpath("//ul[@id='box-apps-menu']/li["+i+"]"));
// собираем список подменю, узнаем количество, если > 0
List<WebElement> subItems = item.findElements(By.xpath(".//ul/li"));
int menuSubItemSize = subItems.size();
if(subItems.size()>0) {
for (int j=1;j<=menuSubItemSize;j++) {
// получаем i-тый элемент подменюменю, выводим на экран
WebElement subitem = item.findElement(By.xpath(".//ul/li["+j+"]"));
System.out.println(" --- SubItem: "+subitem.getText());
subitem.click();
// проверяем наличие заголовка на странице после клика по подменю
h1 = driver.findElement(By.xpath("//*[@id='content']/h1"));
System.out.println(" ---- H1 = "+h1.getText());
// вновь получаем i-тый элемент меню, т.к. старый "протух" после клика
item = driver.findElement(By.xpath("//ul[@id='box-apps-menu']/li["+i+"]"));
}
}
}
}
@After
public void stop() {
driver.quit();
driver = null;
}
} | apache-2.0 |
heriram/incubator-asterixdb | asterixdb/asterix-transactions/src/main/java/org/apache/asterix/transaction/management/service/logging/LogManager.java | 27157 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.asterix.transaction.management.service.logging;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.asterix.common.exceptions.ACIDException;
import org.apache.asterix.common.replication.IReplicationManager;
import org.apache.asterix.common.transactions.ILogBuffer;
import org.apache.asterix.common.transactions.ILogManager;
import org.apache.asterix.common.transactions.ILogReader;
import org.apache.asterix.common.transactions.ILogRecord;
import org.apache.asterix.common.transactions.ITransactionContext;
import org.apache.asterix.common.transactions.ITransactionManager;
import org.apache.asterix.common.transactions.ITransactionSubsystem;
import org.apache.asterix.common.transactions.LogManagerProperties;
import org.apache.asterix.common.transactions.LogType;
import org.apache.asterix.common.transactions.MutableLong;
import org.apache.asterix.common.transactions.TxnLogFile;
import org.apache.hyracks.api.lifecycle.ILifeCycleComponent;
public class LogManager implements ILogManager, ILifeCycleComponent {
/*
* Constants
*/
private static final Logger LOGGER = Logger.getLogger(LogManager.class.getName());
private static final long SMALLEST_LOG_FILE_ID = 0;
private static final int INITIAL_LOG_SIZE = 0;
public static final boolean IS_DEBUG_MODE = false;// true
/*
* Finals
*/
private final ITransactionSubsystem txnSubsystem;
private final LogManagerProperties logManagerProperties;
private final int numLogPages;
private final String logDir;
private final String logFilePrefix;
private final MutableLong flushLSN;
private final String nodeId;
private final FlushLogsLogger flushLogsLogger;
private final HashMap<Long, Integer> txnLogFileId2ReaderCount = new HashMap<>();
protected final long logFileSize;
protected final int logPageSize;
protected final AtomicLong appendLSN;
/*
* Mutables
*/
private LinkedBlockingQueue<ILogBuffer> emptyQ;
private LinkedBlockingQueue<ILogBuffer> flushQ;
private LinkedBlockingQueue<ILogBuffer> stashQ;
private FileChannel appendChannel;
protected ILogBuffer appendPage;
private LogFlusher logFlusher;
private Future<? extends Object> futureLogFlusher;
protected LinkedBlockingQueue<ILogRecord> flushLogsQ;
public LogManager(ITransactionSubsystem txnSubsystem) {
this.txnSubsystem = txnSubsystem;
logManagerProperties =
new LogManagerProperties(this.txnSubsystem.getTransactionProperties(), this.txnSubsystem.getId());
logFileSize = logManagerProperties.getLogPartitionSize();
logPageSize = logManagerProperties.getLogPageSize();
numLogPages = logManagerProperties.getNumLogPages();
logDir = logManagerProperties.getLogDir();
logFilePrefix = logManagerProperties.getLogFilePrefix();
flushLSN = new MutableLong();
appendLSN = new AtomicLong();
nodeId = txnSubsystem.getId();
flushLogsQ = new LinkedBlockingQueue<>();
flushLogsLogger = new FlushLogsLogger();
initializeLogManager(SMALLEST_LOG_FILE_ID);
}
private void initializeLogManager(long nextLogFileId) {
emptyQ = new LinkedBlockingQueue<>(numLogPages);
flushQ = new LinkedBlockingQueue<>(numLogPages);
stashQ = new LinkedBlockingQueue<>(numLogPages);
for (int i = 0; i < numLogPages; i++) {
emptyQ.offer(new LogBuffer(txnSubsystem, logPageSize, flushLSN));
}
appendLSN.set(initializeLogAnchor(nextLogFileId));
flushLSN.set(appendLSN.get());
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("LogManager starts logging in LSN: " + appendLSN);
}
appendChannel = getFileChannel(appendLSN.get(), false);
getAndInitNewPage(INITIAL_LOG_SIZE);
logFlusher = new LogFlusher(this, emptyQ, flushQ, stashQ);
futureLogFlusher = txnSubsystem.getAsterixAppRuntimeContextProvider().getThreadExecutor().submit(logFlusher);
if (!flushLogsLogger.isAlive()) {
txnSubsystem.getAsterixAppRuntimeContextProvider().getThreadExecutor().execute(flushLogsLogger);
}
}
@Override
public void log(ILogRecord logRecord) throws ACIDException {
if (logRecord.getLogType() == LogType.FLUSH) {
flushLogsQ.offer(logRecord);
return;
}
appendToLogTail(logRecord);
}
protected void appendToLogTail(ILogRecord logRecord) throws ACIDException {
syncAppendToLogTail(logRecord);
if ((logRecord.getLogType() == LogType.JOB_COMMIT || logRecord.getLogType() == LogType.ABORT
|| logRecord.getLogType() == LogType.WAIT) && !logRecord.isFlushed()) {
synchronized (logRecord) {
while (!logRecord.isFlushed()) {
try {
logRecord.wait();
} catch (InterruptedException e) {
//ignore
}
}
}
}
}
protected synchronized void syncAppendToLogTail(ILogRecord logRecord) throws ACIDException {
if (logRecord.getLogType() != LogType.FLUSH) {
ITransactionContext txnCtx = logRecord.getTxnCtx();
if (txnCtx.getTxnState() == ITransactionManager.ABORTED && logRecord.getLogType() != LogType.ABORT) {
throw new ACIDException(
"Aborted job(" + txnCtx.getJobId() + ") tried to write non-abort type log record.");
}
}
/**
* To eliminate the case where the modulo of the next appendLSN = 0 (the next
* appendLSN = the first LSN of the next log file), we do not allow a log to be
* written at the last offset of the current file.
*/
final int logSize = logRecord.getLogSize();
// Make sure the log will not exceed the log file size
if (getLogFileOffset(appendLSN.get()) + logSize >= logFileSize) {
prepareNextLogFile();
prepareNextPage(logSize);
} else if (!appendPage.hasSpace(logSize)) {
prepareNextPage(logSize);
}
appendPage.append(logRecord, appendLSN.get());
if (logRecord.getLogType() == LogType.FLUSH) {
logRecord.setLSN(appendLSN.get());
}
if (logRecord.isMarker()) {
logRecord.logAppended(appendLSN.get());
}
appendLSN.addAndGet(logSize);
}
protected void prepareNextPage(int logSize) {
appendPage.setFull();
getAndInitNewPage(logSize);
}
protected void getAndInitNewPage(int logSize) {
if (logSize > logPageSize) {
// before creating a new page, we need to stash a normal sized page since our queues have fixed capacity
appendPage = null;
while (appendPage == null) {
try {
appendPage = emptyQ.take();
stashQ.add(appendPage);
} catch (InterruptedException e) {
//ignore
}
}
// for now, alloc a new buffer for each large page
// TODO: pool large pages??
appendPage = new LogBuffer(txnSubsystem, logSize, flushLSN);
appendPage.setFileChannel(appendChannel);
flushQ.offer(appendPage);
} else {
appendPage = null;
while (appendPage == null) {
try {
appendPage = emptyQ.take();
} catch (InterruptedException e) {
//ignore
}
}
appendPage.reset();
appendPage.setFileChannel(appendChannel);
flushQ.offer(appendPage);
}
}
protected void prepareNextLogFile() {
// Mark the page as the last page so that it will close the output file channel.
appendPage.setLastPage();
// Make sure to flush whatever left in the log tail.
appendPage.setFull();
//wait until all log records have been flushed in the current file
synchronized (flushLSN) {
try {
while (flushLSN.get() != appendLSN.get()) {
//notification will come from LogBuffer.internalFlush(.)
flushLSN.wait();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
//move appendLSN and flushLSN to the first LSN of the next log file
appendLSN.addAndGet(logFileSize - getLogFileOffset(appendLSN.get()));
flushLSN.set(appendLSN.get());
appendChannel = getFileChannel(appendLSN.get(), true);
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("Created new txn log file with id(" + getLogFileId(appendLSN.get()) + ") starting with LSN = "
+ appendLSN.get());
}
//[Notice]
//the current log file channel is closed if
//LogBuffer.flush() completely flush the last page of the file.
}
@Override
public ILogReader getLogReader(boolean isRecoveryMode) {
return new LogReader(this, logFileSize, logPageSize, flushLSN, isRecoveryMode);
}
public LogManagerProperties getLogManagerProperties() {
return logManagerProperties;
}
public ITransactionSubsystem getTransactionSubsystem() {
return txnSubsystem;
}
@Override
public long getAppendLSN() {
return appendLSN.get();
}
@Override
public void start() {
// no op
}
@Override
public void stop(boolean dumpState, OutputStream os) {
terminateLogFlusher();
if (dumpState) {
dumpState(os);
}
}
@Override
public void dumpState(OutputStream os) {
// #. dump Configurable Variables
dumpConfVars(os);
// #. dump LSNInfo
dumpLSNInfo(os);
}
private void dumpConfVars(OutputStream os) {
try {
StringBuilder sb = new StringBuilder();
sb.append("\n>>dump_begin\t>>----- [ConfVars] -----");
sb.append(logManagerProperties.toString());
sb.append("\n>>dump_end\t>>----- [ConfVars] -----\n");
os.write(sb.toString().getBytes());
} catch (Exception e) {
// ignore exception and continue dumping as much as possible.
if (IS_DEBUG_MODE) {
e.printStackTrace();
}
}
}
private void dumpLSNInfo(OutputStream os) {
try {
StringBuilder sb = new StringBuilder();
sb.append("\n>>dump_begin\t>>----- [LSNInfo] -----");
sb.append("\nappendLsn: " + appendLSN);
sb.append("\nflushLsn: " + flushLSN.get());
sb.append("\n>>dump_end\t>>----- [LSNInfo] -----\n");
os.write(sb.toString().getBytes());
} catch (Exception e) {
// ignore exception and continue dumping as much as possible.
if (IS_DEBUG_MODE) {
e.printStackTrace();
}
}
}
private long initializeLogAnchor(long nextLogFileId) {
long fileId = 0;
long offset = 0;
File fileLogDir = new File(logDir);
try {
if (fileLogDir.exists()) {
List<Long> logFileIds = getLogFileIds();
if (logFileIds == null) {
fileId = nextLogFileId;
createFileIfNotExists(getLogFilePath(fileId));
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("created a log file: " + getLogFilePath(fileId));
}
} else {
fileId = logFileIds.get(logFileIds.size() - 1);
File logFile = new File(getLogFilePath(fileId));
offset = logFile.length();
}
} else {
fileId = nextLogFileId;
createNewDirectory(logDir);
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("created the log directory: " + logManagerProperties.getLogDir());
}
createFileIfNotExists(getLogFilePath(fileId));
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("created a log file: " + getLogFilePath(fileId));
}
}
} catch (IOException ioe) {
throw new IllegalStateException("Failed to initialize the log anchor", ioe);
}
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("log file Id: " + fileId + ", offset: " + offset);
}
return logFileSize * fileId + offset;
}
@Override
public void renewLogFiles() {
terminateLogFlusher();
long lastMaxLogFileId = deleteAllLogFiles();
initializeLogManager(lastMaxLogFileId + 1);
}
@Override
public void deleteOldLogFiles(long checkpointLSN) {
Long checkpointLSNLogFileID = getLogFileId(checkpointLSN);
List<Long> logFileIds = getLogFileIds();
if (logFileIds != null) {
//sort log files from oldest to newest
Collections.sort(logFileIds);
/**
* At this point, any future LogReader should read from LSN >= checkpointLSN
*/
synchronized (txnLogFileId2ReaderCount) {
for (Long id : logFileIds) {
/**
* Stop deletion if:
* The log file which contains the checkpointLSN has been reached.
* The oldest log file being accessed by a LogReader has been reached.
*/
if (id >= checkpointLSNLogFileID
|| (txnLogFileId2ReaderCount.containsKey(id) && txnLogFileId2ReaderCount.get(id) > 0)) {
break;
}
//delete old log file
File file = new File(getLogFilePath(id));
file.delete();
txnLogFileId2ReaderCount.remove(id);
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("Deleted log file " + file.getAbsolutePath());
}
}
}
}
}
private void terminateLogFlusher() {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("Terminating LogFlusher thread ...");
}
logFlusher.terminate();
try {
futureLogFlusher.get();
} catch (ExecutionException | InterruptedException e) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("---------- warning(begin): LogFlusher thread is terminated abnormally --------");
e.printStackTrace();
LOGGER.info("---------- warning(end) : LogFlusher thread is terminated abnormally --------");
}
}
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("LogFlusher thread is terminated.");
}
}
private long deleteAllLogFiles() {
if (appendChannel != null) {
try {
appendChannel.close();
} catch (IOException e) {
throw new IllegalStateException("Failed to close a fileChannel of a log file");
}
}
txnLogFileId2ReaderCount.clear();
List<Long> logFileIds = getLogFileIds();
if (logFileIds != null) {
for (Long id : logFileIds) {
File file = new File(getLogFilePath(id));
if (!file.delete()) {
throw new IllegalStateException("Failed to delete a file: " + file.getAbsolutePath());
}
}
return logFileIds.get(logFileIds.size() - 1);
} else {
throw new IllegalStateException("Couldn't find any log files.");
}
}
public List<Long> getLogFileIds() {
File fileLogDir = new File(logDir);
String[] logFileNames = null;
List<Long> logFileIds = null;
if (fileLogDir.exists()) {
logFileNames = fileLogDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.startsWith(logFilePrefix)) {
return true;
}
return false;
}
});
if (logFileNames != null && logFileNames.length != 0) {
logFileIds = new ArrayList<>();
for (String fileName : logFileNames) {
logFileIds.add(Long.parseLong(fileName.substring(logFilePrefix.length() + 1)));
}
Collections.sort(logFileIds, new Comparator<Long>() {
@Override
public int compare(Long arg0, Long arg1) {
return arg0.compareTo(arg1);
}
});
}
}
return logFileIds;
}
public String getLogFilePath(long fileId) {
return logDir + File.separator + logFilePrefix + "_" + fileId;
}
public long getLogFileOffset(long lsn) {
return lsn % logFileSize;
}
public long getLogFileId(long lsn) {
return lsn / logFileSize;
}
private static boolean createFileIfNotExists(String path) throws IOException {
File file = new File(path);
File parentFile = file.getParentFile();
if (parentFile != null) {
parentFile.mkdirs();
}
return file.createNewFile();
}
private static boolean createNewDirectory(String path) {
return (new File(path)).mkdir();
}
private FileChannel getFileChannel(long lsn, boolean create) {
FileChannel newFileChannel = null;
try {
long fileId = getLogFileId(lsn);
String logFilePath = getLogFilePath(fileId);
File file = new File(logFilePath);
if (create) {
if (!file.createNewFile()) {
throw new IllegalStateException();
}
} else {
if (!file.exists()) {
throw new IllegalStateException();
}
}
RandomAccessFile raf = new RandomAccessFile(new File(logFilePath), "rw");
newFileChannel = raf.getChannel();
newFileChannel.position(getLogFileOffset(lsn));
} catch (IOException e) {
throw new IllegalStateException(e);
}
return newFileChannel;
}
@Override
public long getReadableSmallestLSN() {
List<Long> logFileIds = getLogFileIds();
if (logFileIds != null) {
return logFileIds.get(0) * logFileSize;
} else {
throw new IllegalStateException("Couldn't find any log files.");
}
}
@Override
public String getNodeId() {
return nodeId;
}
@Override
public int getLogPageSize() {
return logPageSize;
}
@Override
public void renewLogFilesAndStartFromLSN(long LSNtoStartFrom) throws IOException {
terminateLogFlusher();
deleteAllLogFiles();
long newLogFile = getLogFileId(LSNtoStartFrom);
initializeLogManager(newLogFile + 1);
}
@Override
public void setReplicationManager(IReplicationManager replicationManager) {
throw new IllegalStateException("This log manager does not support replication");
}
@Override
public int getNumLogPages() {
return numLogPages;
}
@Override
public TxnLogFile getLogFile(long LSN) throws IOException {
long fileId = getLogFileId(LSN);
String logFilePath = getLogFilePath(fileId);
File file = new File(logFilePath);
if (!file.exists()) {
throw new IOException("Log file with id(" + fileId + ") was not found. Requested LSN: " + LSN);
}
RandomAccessFile raf = new RandomAccessFile(new File(logFilePath), "r");
FileChannel newFileChannel = raf.getChannel();
TxnLogFile logFile = new TxnLogFile(this, newFileChannel, fileId, fileId * logFileSize);
touchLogFile(fileId);
return logFile;
}
@Override
public void closeLogFile(TxnLogFile logFileRef, FileChannel fileChannel) throws IOException {
if (!fileChannel.isOpen()) {
throw new IllegalStateException("File channel is not open");
}
fileChannel.close();
untouchLogFile(logFileRef.getLogFileId());
}
private void touchLogFile(long fileId) {
synchronized (txnLogFileId2ReaderCount) {
if (txnLogFileId2ReaderCount.containsKey(fileId)) {
txnLogFileId2ReaderCount.put(fileId, txnLogFileId2ReaderCount.get(fileId) + 1);
} else {
txnLogFileId2ReaderCount.put(fileId, 1);
}
}
}
private void untouchLogFile(long fileId) {
synchronized (txnLogFileId2ReaderCount) {
if (txnLogFileId2ReaderCount.containsKey(fileId)) {
int newReaderCount = txnLogFileId2ReaderCount.get(fileId) - 1;
if (newReaderCount < 0) {
throw new IllegalStateException(
"Invalid log file reader count (ID=" + fileId + ", count: " + newReaderCount + ")");
}
txnLogFileId2ReaderCount.put(fileId, newReaderCount);
} else {
throw new IllegalStateException("Trying to close log file id(" + fileId + ") which was not opened.");
}
}
}
/**
* This class is used to log FLUSH logs.
* FLUSH logs are flushed on a different thread to avoid a possible deadlock in LogBuffer batchUnlock which calls PrimaryIndexOpeartionTracker.completeOperation
* The deadlock happens when PrimaryIndexOpeartionTracker.completeOperation results in generating a FLUSH log and there are no empty log buffers available to log it.
*/
private class FlushLogsLogger extends Thread {
private ILogRecord logRecord;
@Override
public void run() {
while (true) {
try {
logRecord = flushLogsQ.take();
appendToLogTail(logRecord);
} catch (ACIDException e) {
e.printStackTrace();
} catch (InterruptedException e) {
//ignore
}
}
}
}
}
class LogFlusher implements Callable<Boolean> {
private static final Logger LOGGER = Logger.getLogger(LogFlusher.class.getName());
private static final ILogBuffer POISON_PILL = new LogBuffer(null, ILogRecord.JOB_TERMINATE_LOG_SIZE, null);
private final LogManager logMgr;//for debugging
private final LinkedBlockingQueue<ILogBuffer> emptyQ;
private final LinkedBlockingQueue<ILogBuffer> flushQ;
private final LinkedBlockingQueue<ILogBuffer> stashQ;
private ILogBuffer flushPage;
private final AtomicBoolean isStarted;
private final AtomicBoolean terminateFlag;
public LogFlusher(LogManager logMgr, LinkedBlockingQueue<ILogBuffer> emptyQ, LinkedBlockingQueue<ILogBuffer> flushQ,
LinkedBlockingQueue<ILogBuffer> stashQ) {
this.logMgr = logMgr;
this.emptyQ = emptyQ;
this.flushQ = flushQ;
this.stashQ = stashQ;
flushPage = null;
isStarted = new AtomicBoolean(false);
terminateFlag = new AtomicBoolean(false);
}
public void terminate() {
//make sure the LogFlusher thread started before terminating it.
synchronized (isStarted) {
while (!isStarted.get()) {
try {
isStarted.wait();
} catch (InterruptedException e) {
//ignore
}
}
}
terminateFlag.set(true);
if (flushPage != null) {
synchronized (flushPage) {
flushPage.stop();
flushPage.notify();
}
}
//[Notice]
//The return value doesn't need to be checked
//since terminateFlag will trigger termination if the flushQ is full.
flushQ.offer(POISON_PILL);
}
@Override
public Boolean call() {
synchronized (isStarted) {
isStarted.set(true);
isStarted.notify();
}
try {
while (true) {
flushPage = null;
try {
flushPage = flushQ.take();
if (flushPage == POISON_PILL || terminateFlag.get()) {
return true;
}
} catch (InterruptedException e) {
if (flushPage == null) {
continue;
}
}
flushPage.flush();
emptyQ.offer(flushPage.getLogPageSize() == logMgr.getLogPageSize() ? flushPage : stashQ.remove());
}
} catch (Exception e) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("-------------------------------------------------------------------------");
LOGGER.info("LogFlusher is terminating abnormally. System is in unusalbe state.");
LOGGER.info("-------------------------------------------------------------------------");
}
e.printStackTrace();
throw e;
}
}
}
| apache-2.0 |
leafclick/intellij-community | jps/jps-builders/src/org/jetbrains/jps/incremental/java/ModulePathSplitter.java | 9004 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.incremental.java;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.library.OrderedClassLibraryBuilder;
import com.thoughtworks.qdox.model.JavaModule;
import com.thoughtworks.qdox.model.JavaModuleDescriptor;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.javac.JpsJavacFileManager;
import org.jetbrains.jps.javac.ModulePath;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
/**
* @author Eugene Zhuravlev
* Date: 26-Sep-19
*/
public class ModulePathSplitter {
private final Map<File, ModuleInfo> myCache = Collections.synchronizedMap(new THashMap<>(FileUtil.FILE_HASHING_STRATEGY));
private static final Attributes.Name AUTOMATIC_MODULE_NAME = new Attributes.Name("Automatic-Module-Name");
private static final Method myModuleFinderCreateMethod;
private static final Method myFindAll;
private static final Method myGetDescriptor;
private static final Method myDescriptorName;
private static final Method myRequiresName;
private static final Method myDescriptorRequires;
static {
Method of = null;
Method findAll = null;
Method getDescriptor = null;
Method descriptorName = null;
Method requiresName = null;
Method descriptorRequires = null;
try {
final Class<?> finderClass = Class.forName("java.lang.module.ModuleFinder");
final Class<?> descriptorClass = Class.forName("java.lang.module.ModuleDescriptor");
final Class<?> referenceClass = Class.forName("java.lang.module.ModuleReference");
final Class<?> requireClass = Class.forName("java.lang.module.ModuleDescriptor$Requires");
of = finderClass.getDeclaredMethod("of", Path[].class);
findAll = finderClass.getDeclaredMethod("findAll");
getDescriptor = referenceClass.getDeclaredMethod("descriptor");
descriptorName = descriptorClass.getDeclaredMethod("name");
descriptorRequires = descriptorClass.getDeclaredMethod("requires");
requiresName = requireClass.getDeclaredMethod("name");
}
catch (Throwable ignored) {
}
myModuleFinderCreateMethod = of;
myFindAll = findAll;
myGetDescriptor = getDescriptor;
myDescriptorName = descriptorName;
myRequiresName = requiresName;
myDescriptorRequires = descriptorRequires;
}
// derives module name from filename
public static final Function<File, String> DEFAULT_MODULE_NAME_SEARCH = file -> {
final String fName = file.getName();
final int dotIndex = fName.lastIndexOf('.'); // drop extension
return dotIndex >= 0? fName.substring(0, dotIndex) : fName;
};
@NotNull
private final Function<File, String> myModuleNameSearch;
public ModulePathSplitter() {
this(DEFAULT_MODULE_NAME_SEARCH);
}
public ModulePathSplitter(@NotNull Function<File, String> moduleNameSearch) {
myModuleNameSearch = moduleNameSearch;
}
public Pair<ModulePath, Collection<File>> splitPath(File chunkModuleInfo, Set<File> chunkOutputs, Collection<File> path) {
if (myModuleFinderCreateMethod == null) {
// the module API is not available
return Pair.create(ModulePath.create(path), Collections.emptyList());
}
final ModulePath.Builder mpBuilder = ModulePath.newBuilder();
final List<File> classpath = new ArrayList<>();
final Set<String> allRequired = collectRequired(chunkModuleInfo, JpsJavacFileManager.filter(path, file -> !chunkOutputs.contains(file)));
for (File file : path) {
if (chunkOutputs.contains(file)) {
mpBuilder.add(null, file);
}
else {
final ModuleInfo info = getModuleInfo(file);
if (allRequired.contains(info.name)) {
// storing only names for automatic modules in "exploded" form.
// for all other kinds of roots module-name is correctly determined by javac itself
mpBuilder.add(info.isAutomaticExploded? info.name : null, file);
}
else {
classpath.add(file);
}
}
}
return Pair.create(mpBuilder.create(), Collections.unmodifiableList(classpath));
}
private static final Pattern NON_ALPHANUM = Pattern.compile("[^A-Za-z0-9]");
private static final Pattern REPEATING_DOTS = Pattern.compile("(\\.)(\\1)+");
/**
* Following the logic of jdk.internal.module.ModulePath.cleanModuleName() that normalizes the module name derived from a jar artifact name
*/
private static String normalizeModuleName(String fName) {
if (fName != null) {
fName = NON_ALPHANUM.matcher(fName).replaceAll(".");
// collapse repeating dots
fName = REPEATING_DOTS.matcher(fName).replaceAll(".");
// drop leading and trailing dots
final int len = fName.length();
if (len > 0) {
final int start = fName.startsWith(".") ? 1 : 0;
final int end = fName.endsWith(".") ? len - 1 : len;
if (start > 0 || end < len) {
fName = fName.substring(start, end);
}
}
}
return fName;
}
private Set<String> collectRequired(File chunkModuleInfo, Iterable<? extends File> path) {
final Set<String> result = new HashSet<>();
// first, add all requires from chunk module-info
final JavaModuleDescriptor chunkDescr = new JavaProjectBuilder(new OrderedClassLibraryBuilder()).addSourceFolder(chunkModuleInfo.getParentFile()).getDescriptor();
for (JavaModuleDescriptor.JavaRequires require : chunkDescr.getRequires()) {
final JavaModule rm = require.getModule();
if (rm != null) {
result.add(rm.getName());
}
}
for (File file : path) {
result.addAll(getModuleInfo(file).requires);
}
return result;
}
@NotNull
private ModuleInfo getModuleInfo(File f) {
ModuleInfo info = myCache.get(f);
if (info != null) {
return info;
}
info = ModuleInfo.EMPTY;
try {
Object mf = myModuleFinderCreateMethod.invoke(null, (Object)new Path[]{f.toPath()}); // ModuleFinder.of(f.toPath());
final Set<?> moduleRefs = (Set<?>)myFindAll.invoke(mf); // mf.findAll()
if (!moduleRefs.isEmpty()) {
for (Object moduleRef : moduleRefs) {
final Object descriptor = myGetDescriptor.invoke(moduleRef); // moduleRef.descriptor()
final String moduleName = (String)myDescriptorName.invoke(descriptor); // descriptor.name();
final Set<?> requires = (Set<?>)myDescriptorRequires.invoke(descriptor); //descriptor.requires();
if (requires.isEmpty()) {
info = new ModuleInfo(moduleName, false);
}
else {
final Set<String> req = new HashSet<>();
for (Object require : requires) {
req.add((String)myRequiresName.invoke(require)/*require.name()*/);
}
info = new ModuleInfo(moduleName, req);
}
break;
}
}
else {
final String explodedModuleName = deriveAutomaticModuleName(f);
if (explodedModuleName != null) {
info = new ModuleInfo(explodedModuleName, true);
}
}
}
catch (Throwable ignored) {
}
myCache.put(f, info);
return info;
}
private String deriveAutomaticModuleName(File dir) {
if (dir.isDirectory()) {
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(new File(dir, "META-INF/MANIFEST.MF")))) {
final String name = new Manifest(is).getMainAttributes().getValue(AUTOMATIC_MODULE_NAME);
return name != null ? name : normalizeModuleName(myModuleNameSearch.apply(dir));
}
catch (FileNotFoundException e) {
return normalizeModuleName(myModuleNameSearch.apply(dir)); // inferring the module name from the dir
}
catch (Throwable ignored) {
}
}
return null;
}
private static final class ModuleInfo {
static final ModuleInfo EMPTY = new ModuleInfo(null, false);
@Nullable
final String name;
@NotNull
final Collection<String> requires;
private final boolean isAutomaticExploded;
ModuleInfo(@Nullable String name, boolean isAutomaticExploded) {
this.name = name;
this.requires = Collections.emptyList();
this.isAutomaticExploded = isAutomaticExploded;
}
ModuleInfo(@Nullable String name, @NotNull Collection<String> requires) {
this.name = name;
this.requires = Collections.unmodifiableCollection(requires);
this.isAutomaticExploded = false;
}
}
}
| apache-2.0 |
flaminem/flamy | src/it/scala/com/flaminem/LauncherLocalSuite.scala | 1498 | /*
*
* 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.flaminem
import com.flaminem.flamy.Launcher
import com.flaminem.flamy.exec.utils.ReturnStatus
import com.flaminem.flamy.utils.CliUtils
import org.scalatest._
class LauncherLocalSuite extends FreeSpec {
def launch(line: String): ReturnStatus = {
val args: Array[String] = CliUtils.split(line).filter{_.nonEmpty}.toArray
Launcher.launch(args)
}
"show tables" in {
assert(launch("show tables").isSuccess)
}
"show select" in {
assert(launch("show select db_dest.dest1").isSuccess)
}
"show graph" ignore {
assert(launch("show graph").isSuccess)
}
"check quick" in {
assert(launch("check quick").isSuccess)
}
"check long" in {
assert(launch("check long").isSuccess)
}
"run --dry" in {
assert(launch("run --dry db_dest db_source").isSuccess)
}
"run --dry --from --to" in {
assert(launch("run --on test --from db_dest --to db_dest").isSuccess)
}
}
| apache-2.0 |
johnshen/phpcms | caches/configs/sub_config.php | 1577 | <?php
return array(
'一天排行'=>'day-0',
'本周排行'=>'week-0',
'本月排行'=>'month-0',
'精选视频排行'=>'accurate-0',
'上升最快视频排行'=>'top-0',
'当日编辑推荐'=>'today-0',
'最新-资讯'=>'N-101000',
'最新-体育'=>'N-102000',
'最新-娱乐'=>'N-103000',
'最新-电影'=>'N-104000',
'最新-原创'=>'N-105000',
'最新-美女'=>'N-107000',
'最新-广告'=>'N-106000',
'最新-搞笑'=>'N-108000',
'最新-游戏'=>'N-109000',
'最新-动漫'=>'N-110000',
'最新-教育'=>'N-111000',
'最新-生活'=>'N-113000',
'最新-汽车'=>'N-114000',
'最新-房产'=>'N-115000',
'最新-音乐'=>'N-116000',
'最新-电视'=>'N-117000',
'最新-综艺'=>'N-118000',
'最新-女生'=>'N-125000',
'最新-记录'=>'N-126000',
'最新-科技'=>'N-127000',
'最新-其他'=>'N-190000',
'推荐-资讯'=>'T-101000',
'推荐-体育'=>'T-102000',
'推荐-娱乐'=>'T-103000',
'推荐-电影'=>'T-104000',
'推荐-原创'=>'T-105000',
'推荐-美女'=>'T-107000',
'推荐-广告'=>'T-106000',
'推荐-搞笑'=>'T-108000',
'推荐-游戏'=>'T-109000',
'推荐-动漫'=>'T-110000',
'推荐-教育'=>'T-111000',
'推荐-生活'=>'T-113000',
'推荐-汽车'=>'T-114000',
'推荐-房产'=>'T-115000',
'推荐-音乐'=>'T-116000',
'推荐-电视'=>'T-117000',
'推荐-综艺'=>'T-118000',
'推荐-女生'=>'T-125000',
'推荐-记录'=>'T-126000',
'推荐-科技'=>'T-127000',
'推荐-其他'=>'T-190000',
'member_add_dir'=>'http://juhe.gcvideo.cn/api/',
);
?> | apache-2.0 |
adoyle-h/ad-conventional-changelog | index.js | 5052 | 'use strict';
var wrap = require('word-wrap');
var Path = require('path');
var fs = require('fs');
var get = require('get-value');
var os = require('os');
var path = Path.resolve(process.cwd(), 'package.json');
var packageJSON;
try {
fs.accessSync(path, fs.F_OK | fs.R_OK); // eslint-disable-line no-bitwise
packageJSON = require(path);
if (!packageJSON.config) {
packageJSON = require(Path.resolve(os.homedir(), 'package.json'));
}
} catch(err) {
// do nothing
}
// This can be any kind of SystemJS compatible module.
// We use Commonjs here, but ES6 or AMD would do just
// fine.
module.exports = {
// When a user runs `git cz`, prompter will
// be executed. We pass you cz, which currently
// is just an instance of inquirer.js. Using
// this you can ask questions and get answers.
//
// The commit callback should be executed when
// you're ready to send back a commit template
// to git.
//
// By default, we'll de-indent your commit
prompter: function(cz, commit) {
var maxLineWidth = 100;
var advice = '【提示】第一行建议在 ' + maxLineWidth + ' 字以内。其他行若超过 ' + maxLineWidth + ' 字会自动换行。\n';
console.log(advice); // eslint-disable-line no-console
var promptType = get(packageJSON, 'config.commitizen.promptType');
if (promptType !== 'list') {
promptType = 'rawlist';
}
// Let's ask some questions of the user
// so that we can populate our commit
// template.
//
// See inquirer.js docs for specifics.
// You can also opt to use another input
// collection library if you prefer.
cz.prompt([{
type: promptType,
name: 'type',
message: '选择类型',
default: '1',
choices: [{
key: '1',
name: 'feat: 新的功能',
value: 'feat',
}, {
key: '2',
name: 'fix: 修复 BUG',
value: 'fix',
}, {
key: '3',
name: 'docs: 更改文档',
value: 'docs',
}, {
key: '4',
name: 'style: 代码风格调整(如调整缩进、格式、补上分号等等)',
value: 'style',
}, {
key: '5',
name: 'refactor: 重构代码(不修复错误,不添加新功能,不影响功能)',
value: 'refactor',
}, {
key: '6',
name: 'perf: 提升性能的修改',
value: 'perf',
}, {
key: '7',
name: 'test: 测试相关的修改',
value: 'test',
}, {
key: '8',
name: 'chore: 构建工具的修改',
value: 'chore',
}],
}, {
type: 'input',
name: 'scope',
message: '改动范围 (scope)【回车跳过】:\n',
}, {
type: 'input',
name: 'subject',
message: '修改内容概述:\n',
}, {
type: 'input',
name: 'body',
message: '详细描述这次的修改内容【回车跳过】:\n',
}, {
type: 'input',
name: 'breaking',
message: 'Breaking Changes【回车跳过】:\n',
}, {
type: 'input',
name: 'footer',
message: '相关任务或者 Issue(以 # 开头会自动 Close Issue)【回车跳过】:\n',
}]).then(function(answers) {
var wrapOptions = {
trim: true,
newline: '\n',
indent: '',
width: maxLineWidth,
};
// parentheses are only needed when a scope is present
var scope = answers.scope.trim();
scope = scope ? '(' + answers.scope.trim() + ')' : '';
// Hard limit this line
var head = answers.type + scope + ': ' + answers.subject.trim();
// Wrap these lines at 100 characters
var body = wrap(answers.body, wrapOptions);
var breaking = wrap(answers.breaking, wrapOptions);
var footer = wrap(answers.footer, wrapOptions);
var msg = head;
if (body) {
msg += '\n\n' + body;
}
if (breaking) {
msg += '\n\nBREAKING CHANGE: ' + breaking;
}
if (footer) {
if (footer.startsWith('#')) {
msg += '\n\nCloses ' + footer;
} else {
msg += '\n\nReference: ' + footer;
}
}
commit(msg);
}).catch(function(err) {
console.error(err.stack || err); // eslint-disable-line no-console
});
},
};
| apache-2.0 |
EBIBioStudies/FrontEndUI | webapp/src/main/java/uk/ac/ebi/biostudies/utils/search/EFOExpansionLookupIndex.java | 14134 | /*
* Copyright 2009-2016 European Molecular Biology Laboratory
*
* 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 uk.ac.ebi.biostudies.utils.search;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress.utils.efo.EFONode;
import uk.ac.ebi.arrayexpress.utils.efo.IEFO;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class EFOExpansionLookupIndex implements IEFOExpansionLookup {
private final Logger logger = LoggerFactory.getLogger(getClass());
private FSDirectory indexDirectory;
private IEFO efo;
private Set<String> stopWords;
private Map<String, Set<String>> customSynonyms;
// maximum number of index documents to be processed; in reality shouldn't be more than 2
private static final int MAX_INDEX_HITS = 16;
public EFOExpansionLookupIndex(String indexLocation, Set<String> stopWords) throws IOException {
this.stopWords = stopWords;
this.indexDirectory = FSDirectory.open(new File(indexLocation).toPath());
}
private IEFO getEfo() {
return this.efo;
}
public void setEfo(IEFO efo) {
this.efo = efo;
}
public void setCustomSynonyms(Map<String, Set<String>> synonyms) {
this.customSynonyms = synonyms;
}
private Directory getIndexDirectory() {
return this.indexDirectory;
}
public void buildIndex() throws IOException, InterruptedException {
try (IndexWriter w = createIndex(this.indexDirectory, new LowercaseAnalyzer())) {
this.logger.debug("Building expansion lookup index");
addNodeAndChildren(this.efo.getMap().get(IEFO.ROOT_ID), w);
addCustomSynonyms(w);
w.commit();
this.logger.debug("Building completed");
}
}
private void addCustomSynonyms(IndexWriter w) throws IOException, InterruptedException {
// here we add all custom synonyms so those that weren't added during EFO processing
// get a chance to be included, too. don't worry about duplication, dupes will be removed during retrieval
if (null != this.customSynonyms) {
Set<String> addedTerms = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
for (String term : this.customSynonyms.keySet()) {
if (!addedTerms.contains(term)) {
Document d = new Document();
Set<String> syns = this.customSynonyms.get(term);
for (String syn : syns) {
addIndexField(d, "term", syn, true, true);
}
w.addDocument(d);
addedTerms.addAll(syns);
}
}
}
}
private void addNodeAndChildren(EFONode node, IndexWriter w) throws IOException, InterruptedException {
Thread.sleep(0);
if (null != node) {
addNodeToIndex(node, w);
for (EFONode child : node.getChildren()) {
addNodeAndChildren(child, w);
}
}
}
private void addNodeToIndex(EFONode node, IndexWriter w) throws IOException, InterruptedException {
String term = node.getTerm();
if (null != term && !isStopTerm(term)) {
Set<String> synonyms = node.getAlternativeTerms();
// if the node represents organizational class, just include its synonyms, but not children
Set<String> childTerms =
node.isOrganizationalClass()
? new HashSet<String>()
: getEfo().getTerms(node.getId(), IEFO.INCLUDE_CHILDREN);
// here we add custom synonyms to EFO synonyms/child terms and their synonyms
if (null != this.customSynonyms) {
for (String syn : new HashSet<>(synonyms)) {
if (null != syn && this.customSynonyms.containsKey(syn)) {
synonyms.addAll(this.customSynonyms.get(syn));
}
}
if (this.customSynonyms.containsKey(term)) {
synonyms.addAll(this.customSynonyms.get(term));
}
for (String child : new HashSet<>(childTerms)) {
if (null != child && this.customSynonyms.containsKey(child)) {
childTerms.addAll(this.customSynonyms.get(child));
}
}
}
if (synonyms.contains(term)) {
synonyms.remove(term);
}
// just to remove ridiculously long terms/synonyms from the list
if (synonyms.size() > 0 || childTerms.size() > 0) {
Document d = new Document();
int terms = 0, efoChildren = 0;
for (String syn : synonyms) {
if (childTerms.contains(syn)) {
// this.logger.debug("Synonym [{}] for term [{}] is present as a child term itelf, skipping", syn, term);
} else if (isStopExpansionTerm(syn)) {
// this.logger.debug("Synonym [{}] for term [{}] is a stop-word, skipping", syn, term);
} else {
addIndexField(d, "term", syn, true, true);
addIndexField(d, "all", syn, true, true);
terms++;
}
}
for (String efoTerm : childTerms) {
if (isStopExpansionTerm(efoTerm)) {
// this.logger.debug("Child EFO term [{}] for term [{}] is a stop-word, skipping", efoTerm, term);
} else {
addIndexField(d, "efo", efoTerm, false, true);
addIndexField(d, "all", efoTerm, true, true);
efoChildren++;
}
}
if (!isStopExpansionTerm(term)) {
addIndexField(d, "term", term, true, true);
addIndexField(d, "all", term, true, true);
terms++;
}
if (terms > 1 || (1 == terms && efoChildren > 0)) {
w.addDocument(d);
} else {
// this.logger.debug("EFO term [{}] was not added due to insufficient mappings", term);
}
Thread.sleep(0);
}
} else {
// this.logger.debug("EFO Term [{}] is a stop-word, skipping", term);
}
}
public EFOExpansionTerms getExpansionTerms(Query origQuery) throws IOException {
EFOExpansionTerms expansion = new EFOExpansionTerms();
if (DirectoryReader.indexExists(getIndexDirectory())) {
try (IndexReader reader = DirectoryReader.open(getIndexDirectory())) {
IndexSearcher searcher = new IndexSearcher(reader);
Query q = overrideQueryField(origQuery, "term");
TopDocs hits = searcher.search(q, MAX_INDEX_HITS);
this.logger.debug("Expansion lookup for query [{}] returned [{}] hits", q.toString(), hits.totalHits);
for (ScoreDoc d : hits.scoreDocs) {
Document doc = searcher.doc(d.doc);
String[] terms = doc.getValues("term");
String[] efo = doc.getValues("efo");
this.logger.debug("Synonyms [{}], EFO Terms [{}]", StringUtils.join(terms, ", "), StringUtils.join(efo, ", "));
if (0 != terms.length) {
expansion.synonyms.addAll(Arrays.asList(terms));
}
if (0 != efo.length) {
expansion.efo.addAll(Arrays.asList(efo));
}
}
}
}
return expansion;
}
public Set<String> getReverseExpansion(String text) throws IOException {
Set<String> reverseExpansion = new HashSet<>();
if (null != text && DirectoryReader.indexExists(getIndexDirectory())) {
try (IndexReader reader = DirectoryReader.open(getIndexDirectory())) {
IndexSearcher searcher = new IndexSearcher(reader);
// step 1: split terms
String[] terms = text.split("\\s+");
for (int termIndex = 0; termIndex < terms.length; ++termIndex) {
BooleanQuery.Builder qb = new BooleanQuery.Builder();
Term t = new Term("all", terms[termIndex]);
qb.add(new TermQuery(t), BooleanClause.Occur.SHOULD);
for (int phraseLength = 4; phraseLength <= 2; --phraseLength) {
if (termIndex + phraseLength > terms.length) {
continue;
}
PhraseQuery.Builder pqb = new PhraseQuery.Builder();
for (int phraseTermIndex = 0; phraseTermIndex < phraseLength; ++phraseTermIndex) {
t = new Term("all", terms[termIndex + phraseTermIndex]);
pqb.add(t);
}
qb.add(pqb.build(), BooleanClause.Occur.SHOULD);
}
Query q = qb.build();
TopDocs hits = searcher.search(q, MAX_INDEX_HITS);
this.logger.debug("Expansion lookup for query [{}] returned [{}] hits", q.toString(), hits.totalHits);
for (ScoreDoc d : hits.scoreDocs) {
Document doc = searcher.doc(d.doc);
String[] reverseTerms = doc.getValues("term");
//this.logger.debug("Synonyms [{}], EFO Terms [{}]", StringUtils.join(terms, ", "), StringUtils.join(efo, ", "));
if (0 != reverseTerms.length) {
reverseExpansion.addAll(Arrays.asList(reverseTerms));
}
}
}
}
}
return reverseExpansion;
}
private IndexWriter createIndex(Directory indexDirectory, Analyzer analyzer) throws IOException {
IndexWriterConfig config = new IndexWriterConfig(analyzer);
config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
return new IndexWriter(indexDirectory, config);
}
private void addIndexField(Document document, String name, String value, boolean shouldAnalyze, boolean shouldStore) {
value = value.replaceAll("[^\\d\\w-]", " ").toLowerCase();
FieldType fieldType = new FieldType();
fieldType.setIndexOptions(IndexOptions.DOCS);
fieldType.setTokenized(shouldAnalyze);
fieldType.setStored(shouldStore);
document.add(new Field(name, value, fieldType));
}
private Query overrideQueryField(Query origQuery, String fieldName) {
Query query = new TermQuery(new Term(""));
try {
if (origQuery instanceof PrefixQuery) {
Term term = ((PrefixQuery) origQuery).getPrefix();
query = new PrefixQuery(new Term(fieldName, term.text()));
} else if (origQuery instanceof WildcardQuery) {
Term term = ((WildcardQuery) origQuery).getTerm();
query = new WildcardQuery(new Term(fieldName, term.text()));
} else if (origQuery instanceof TermRangeQuery) {
TermRangeQuery trq = (TermRangeQuery) origQuery;
query = new TermRangeQuery(fieldName, trq.getLowerTerm(), trq.getUpperTerm(), trq.includesLower(), trq.includesUpper());
} else if (origQuery instanceof FuzzyQuery) {
Term term = ((FuzzyQuery) origQuery).getTerm();
query = new FuzzyQuery(new Term(fieldName, term.text()));
} else if (origQuery instanceof TermQuery) {
Term term = ((TermQuery) origQuery).getTerm();
query = new TermQuery(new Term(fieldName, term.text()));
} else if (origQuery instanceof PhraseQuery) {
Term[] terms = ((PhraseQuery) origQuery).getTerms();
StringBuilder text = new StringBuilder();
for (Term t : terms) {
text.append(t.text()).append(' ');
}
query = new TermQuery(new Term(fieldName, text.toString().trim()));
} else {
this.logger.error("Unsupported query type [{}]", origQuery.getClass().getCanonicalName());
}
} catch (Exception x) {
this.logger.error("Caught an exception:", x);
}
return query;
}
private boolean isStopTerm(String str) {
return null == str || stopWords.contains(str.toLowerCase());
}
private boolean isStopExpansionTerm(String str) {
return isStopTerm(str) || str.length() < 3 || str.matches(".*(\\s\\(.+\\)|\\s\\[.+\\]|,\\s|\\s-\\s|/|NOS).*");
}
@SuppressWarnings("unused")
private boolean isLongTerm(String str) {
// returns true if number of words is over 5;
return null != str && str.replaceAll("\\s+", " ").replaceAll("[^ ]+", "").length() >= 4;
}
}
| apache-2.0 |
ThiagoGarciaAlves/intellij-community | plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/UseOfObsoleteAssertInspection.java | 10113 | /*
* Copyright 2003-2016 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.junit;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class UseOfObsoleteAssertInspection extends BaseInspection {
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("usage.of.obsolete.assert.display.name");
}
@Override
@NotNull
protected String buildErrorString(Object... infos) {
String name = (String)infos[0];
return InspectionGadgetsBundle.message("use.of.obsolete.assert.problem.descriptor", name);
}
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
return new ReplaceObsoleteAssertsFix();
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new UseOfObsoleteAssertVisitor();
}
private static class UseOfObsoleteAssertVisitor extends BaseInspectionVisitor {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
final Project project = expression.getProject();
final Module module = ModuleUtilCore.findModuleForPsiElement(expression);
if (module == null) {
return;
}
final PsiClass newAssertClass = JavaPsiFacade.getInstance(project)
.findClass(JUnitCommonClassNames.ORG_JUNIT_ASSERT, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module));
if (newAssertClass == null) {
return;
}
final PsiMethod psiMethod = expression.resolveMethod();
if (psiMethod == null || !psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
return;
}
final PsiClass containingClass = psiMethod.getContainingClass();
if (containingClass == null) {
return;
}
final String name = containingClass.getQualifiedName();
if (JUnitCommonClassNames.JUNIT_FRAMEWORK_ASSERT.equals(name) || JUnitCommonClassNames.JUNIT_FRAMEWORK_TEST_CASE.equals(name)) {
registerMethodCallError(expression, name);
}
}
}
private static class ReplaceObsoleteAssertsFix extends InspectionGadgetsFix {
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
final PsiElement psiElement = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethodCallExpression.class);
if (psiElement == null) {
return;
}
final PsiClass newAssertClass =
JavaPsiFacade.getInstance(project).findClass(JUnitCommonClassNames.ORG_JUNIT_ASSERT, GlobalSearchScope.allScope(project));
final PsiClass oldAssertClass =
JavaPsiFacade.getInstance(project).findClass(JUnitCommonClassNames.JUNIT_FRAMEWORK_ASSERT, GlobalSearchScope.allScope(project));
if (newAssertClass == null) {
return;
}
final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)psiElement;
final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
final PsiElement usedImport = qualifierExpression instanceof PsiReferenceExpression ?
((PsiReferenceExpression)qualifierExpression).advancedResolve(true).getCurrentFileResolveScope() :
methodExpression.advancedResolve(true).getCurrentFileResolveScope();
final PsiMethod psiMethod = methodCallExpression.resolveMethod();
final boolean isImportUnused = isImportBecomeUnused(methodCallExpression, usedImport, psiMethod);
PsiImportStaticStatement staticStatement = null;
if (qualifierExpression == null) {
staticStatement = staticallyImported(oldAssertClass, methodExpression);
}
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
if (staticStatement == null) {
methodExpression.setQualifierExpression(JavaPsiFacade.getElementFactory(project).createReferenceExpression(newAssertClass));
if (isImportUnused && usedImport instanceof PsiImportStatementBase) {
usedImport.delete();
}
styleManager.shortenClassReferences(methodExpression);
}
else {
if (isImportUnused) {
final PsiJavaCodeReferenceElement importReference = staticStatement.getImportReference();
if (importReference != null) {
if (staticStatement.isOnDemand()) {
importReference.bindToElement(newAssertClass);
}
else {
final PsiElement importQExpression = importReference.getQualifier();
if (importQExpression instanceof PsiJavaCodeReferenceElement) {
((PsiJavaCodeReferenceElement)importQExpression).bindToElement(newAssertClass);
}
}
}
}
else {
methodExpression
.setQualifierExpression(JavaPsiFacade.getElementFactory(project).createReferenceExpression(newAssertClass));
styleManager.shortenClassReferences(methodExpression);
}
}
PsiMethod newTarget = methodCallExpression.resolveMethod();
if (newTarget != null && newTarget.isDeprecated()) {
PsiParameter[] parameters = newTarget.getParameterList().getParameters();
if (parameters.length > 0) {
PsiType paramType = parameters[parameters.length - 1].getType();
if (PsiType.DOUBLE.equals(paramType) || PsiType.FLOAT.equals(paramType)) {
methodCallExpression.getArgumentList().add(JavaPsiFacade.getElementFactory(project).createExpressionFromText("0.0", methodCallExpression));
}
}
}
/*
//refs can be optimized now but should we really?
if (isImportUnused) {
for (PsiReference reference : ReferencesSearch.search(newAssertClass, new LocalSearchScope(methodCallExpression.getContainingFile()))) {
final PsiElement element = reference.getElement();
styleManager.shortenClassReferences(element);
}
}*/
}
private static boolean isImportBecomeUnused(final PsiMethodCallExpression methodCallExpression,
final PsiElement usedImport,
final PsiMethod psiMethod) {
final boolean[] proceed = new boolean[]{true};
methodCallExpression.getContainingFile().accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
if (proceed[0]) {
super.visitElement(element);
}
}
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
if (expression == methodCallExpression) {
return;
}
final PsiMethod resolved = expression.resolveMethod();
if (resolved == psiMethod) {
proceed[0] = false;
}
else {
final PsiElement resolveScope =
expression.getMethodExpression().advancedResolve(false).getCurrentFileResolveScope();
if (resolveScope == usedImport) {
proceed[0] = false;
}
}
}
});
return proceed[0];
}
@Nullable
private static PsiImportStaticStatement staticallyImported(PsiClass oldAssertClass, PsiReferenceExpression methodExpression) {
final String referenceName = methodExpression.getReferenceName();
final PsiFile containingFile = methodExpression.getContainingFile();
if (!(containingFile instanceof PsiJavaFile)) {
return null;
}
final PsiImportList importList = ((PsiJavaFile)containingFile).getImportList();
if (importList == null) {
return null;
}
final PsiImportStaticStatement[] statements = importList.getImportStaticStatements();
for (PsiImportStaticStatement statement : statements) {
if (oldAssertClass != statement.resolveTargetClass()) {
continue;
}
final String importRefName = statement.getReferenceName();
final PsiJavaCodeReferenceElement importReference = statement.getImportReference();
if (importReference == null) {
continue;
}
if (Comparing.strEqual(importRefName, referenceName)) {
final PsiElement qualifier = importReference.getQualifier();
if (qualifier instanceof PsiJavaCodeReferenceElement) {
return statement;
}
}
else if (importRefName == null) {
return statement;
}
}
return null;
}
@NotNull
@Override
public String getFamilyName() {
return InspectionGadgetsBundle.message("use.of.obsolete.assert.quickfix");
}
}
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-pinpointemail/src/main/java/com/amazonaws/services/pinpointemail/model/transform/EmailContentMarshaller.java | 2547 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.pinpointemail.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.pinpointemail.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* EmailContentMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EmailContentMarshaller {
private static final MarshallingInfo<StructuredPojo> SIMPLE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Simple").build();
private static final MarshallingInfo<StructuredPojo> RAW_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Raw").build();
private static final MarshallingInfo<StructuredPojo> TEMPLATE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Template").build();
private static final EmailContentMarshaller instance = new EmailContentMarshaller();
public static EmailContentMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(EmailContent emailContent, ProtocolMarshaller protocolMarshaller) {
if (emailContent == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(emailContent.getSimple(), SIMPLE_BINDING);
protocolMarshaller.marshall(emailContent.getRaw(), RAW_BINDING);
protocolMarshaller.marshall(emailContent.getTemplate(), TEMPLATE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
learning-layers/SocialSemanticServer | servs/dataimport/dataimport.impl/src/main/java/at/tugraz/sss/servs/dataimport/impl/SSDataImportActAndLog.java | 5498 | /**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2016, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* 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 at.tugraz.sss.servs.dataimport.impl;
import at.tugraz.sss.serv.datatype.*;
import at.tugraz.sss.serv.util.SSLogU;
import at.tugraz.sss.serv.reg.SSServErrReg;
import at.tugraz.sss.serv.datatype.enums.SSToolContextE;
import at.tugraz.sss.serv.datatype.par.*;
import at.tugraz.sss.serv.reg.*;
import java.util.*;
import sss.serv.eval.api.SSEvalServerI;
import sss.serv.eval.datatypes.SSEvalLogE;
import sss.serv.eval.datatypes.par.SSEvalLogPar;
public class SSDataImportActAndLog {
public void addTag(
final SSServPar servPar,
final SSToolContextE toolContext,
final SSUri entity,
final String tag,
final List<SSUri> entities,
final Long creationTime,
final boolean shouldCommit) throws SSErr{
try{
final SSEvalServerI evalServ = (SSEvalServerI) SSServReg.getServ(SSEvalServerI.class);
evalServ.evalLog(
new SSEvalLogPar(
servPar,
servPar.user,
toolContext,
SSEvalLogE.addTag,
entity, //entity
tag, //content
entities, //entities
null, //users
creationTime, //creationTime
shouldCommit));
}catch(SSErr error){
switch(error.code){
case servInvalid: SSLogU.warn(error); break;
default:{ SSServErrReg.regErrThrow(error); break;}
}
}catch(Exception error){
SSServErrReg.regErrThrow(error);
}
}
public void addNotebook(
final SSServPar servPar,
final SSUri user,
final SSToolContextE toolContext,
final SSUri notebook,
final Long creationTime,
final boolean shouldCommit) throws SSErr{
try{
final SSEvalServerI evalServ = (SSEvalServerI) SSServReg.getServ(SSEvalServerI.class);
evalServ.evalLog(
new SSEvalLogPar(
servPar,
user,
toolContext,
SSEvalLogE.addNotebook,
notebook, //entity
null, //content
null, //entities
null, //users
creationTime, //creationTime
shouldCommit));
}catch(SSErr error){
switch(error.code){
case servInvalid: SSLogU.warn(error); break;
default:{ SSServErrReg.regErrThrow(error); break;}
}
}catch(Exception error){
SSServErrReg.regErrThrow(error);
}
}
public void addNote(
final SSServPar servPar,
final SSUri user,
final SSToolContextE toolContext,
final SSUri note,
final List<SSUri> entities,
final Long creationTime,
final boolean shouldCommit) throws SSErr{
try{
final SSEvalServerI evalServ = (SSEvalServerI) SSServReg.getServ(SSEvalServerI.class);
evalServ.evalLog(
new SSEvalLogPar(
servPar,
user,
toolContext,
SSEvalLogE.addNote,
note, //entity
null, //content
entities, //entities
null, //users
creationTime, //creationTime
shouldCommit));
}catch(SSErr error){
switch(error.code){
case servInvalid: SSLogU.warn(error); break;
default:{ SSServErrReg.regErrThrow(error); break;}
}
}catch(Exception error){
SSServErrReg.regErrThrow(error);
}
}
public void addResource(
final SSServPar servPar,
final SSUri user,
final SSToolContextE toolContext,
final SSUri resource,
final List<SSUri> entities,
final Long creationTime,
final boolean shouldCommit) throws SSErr{
try{
final SSEvalServerI evalServ = (SSEvalServerI) SSServReg.getServ(SSEvalServerI.class);
evalServ.evalLog(
new SSEvalLogPar(
servPar,
user,
toolContext,
SSEvalLogE.addResource,
resource, //entity
null, //content
entities, //entities
null, //users
creationTime, //creationTime
shouldCommit));
}catch(SSErr error){
switch(error.code){
case servInvalid: SSLogU.warn(error); break;
default:{ SSServErrReg.regErrThrow(error); break;}
}
}catch(Exception error){
SSServErrReg.regErrThrow(error);
}
}
} | apache-2.0 |
Minoli/carbon-apimgt | features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/FormComponents/TextArea.js | 1382 | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
const TextArea = (props) => (
<div className="form-group">
<label className="form-label">{props.title}</label>
<textarea
className="form-input"
style={props.resize ? null : {resize: 'none'}}
name={props.name}
rows={props.rows}
value={props.content}
onChange={props.controlFunc}
placeholder={props.placeholder} />
</div>
);
TextArea.propTypes = {
title: PropTypes.string.isRequired,
rows: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
resize: PropTypes.bool,
placeholder: PropTypes.string,
controlFunc: PropTypes.func.isRequired
};
export default TextArea;
| apache-2.0 |
miswenwen/My_bird_work | Bird_work/我的项目/Settings/src/com/android/settings/ApnPreference.java | 5085 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.preference.Preference;
import android.provider.Telephony;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
public class ApnPreference extends Preference implements
CompoundButton.OnCheckedChangeListener, OnClickListener {
final static String TAG = "ApnPreference";
public ApnPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ApnPreference(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.apnPreferenceStyle);
}
public ApnPreference(Context context) {
this(context, null);
}
private static String mSelectedKey = null;
private static CompoundButton mCurrentChecked = null;
private boolean mProtectFromCheckedChange = false;
private boolean mSelectable = true;
@Override
public View getView(View convertView, ViewGroup parent) {
View view = super.getView(convertView, parent);
View widget = view.findViewById(R.id.apn_radiobutton);
if ((widget != null) && widget instanceof RadioButton) {
RadioButton rb = (RadioButton) widget;
if (mSelectable) {
rb.setOnCheckedChangeListener(this);
boolean isChecked = getKey().equals(mSelectedKey);
if (isChecked) {
mCurrentChecked = rb;
mSelectedKey = getKey();
}
mProtectFromCheckedChange = true;
rb.setChecked(isChecked);
mProtectFromCheckedChange = false;
rb.setVisibility(View.VISIBLE);
} else {
rb.setVisibility(View.GONE);
}
}
View textLayout = view.findViewById(R.id.text_layout);
if ((textLayout != null) && textLayout instanceof RelativeLayout) {
textLayout.setOnClickListener(this);
}
return view;
}
public boolean isChecked() {
return getKey().equals(mSelectedKey);
}
public void setChecked() {
mSelectedKey = getKey();
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i(TAG, "ID: " + getKey() + " :" + isChecked);
if (mProtectFromCheckedChange) {
return;
}
if (isChecked) {
if (mCurrentChecked != null) {
mCurrentChecked.setChecked(false);
}
mCurrentChecked = buttonView;
mSelectedKey = getKey();
callChangeListener(mSelectedKey);
} else {
mCurrentChecked = null;
mSelectedKey = null;
}
}
public void onClick(android.view.View v) {
if ((v != null) && (R.id.text_layout == v.getId())) {
Context context = getContext();
if (context != null) {
int pos = Integer.parseInt(getKey());
Uri url = ContentUris.withAppendedId(Telephony.Carriers.CONTENT_URI, pos);
/// M: for [Read Only APN]
// context.startActivity(new Intent(Intent.ACTION_EDIT, url));
Intent intent = new Intent(Intent.ACTION_EDIT, url);
intent.putExtra("readOnly", !mEditable);
intent.putExtra("sub_id", mSubId);
context.startActivity(intent);
/// @}
}
}
}
public void setSelectable(boolean selectable) {
mSelectable = selectable;
}
public boolean getSelectable() {
return mSelectable;
}
///----------------------------------------MTK------------------------------------------------
private int mSubId;
private boolean mEditable;
public int getSubId() {
return mSubId;
}
public void setSubId(int subId) {
mSubId = subId;
}
/**
* M: for [Read Only APN]
* set whether the APN is editable, as some preset Apn can be be edited
* @param isEditable
*/
public void setApnEditable(boolean isEditable) {
mEditable = isEditable;
}
}
| apache-2.0 |
nafae/developer | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201402/cm/GeoLocationService.java | 692 | /**
* GeoLocationService.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201402.cm;
public interface GeoLocationService extends javax.xml.rpc.Service {
public java.lang.String getGeoLocationServiceInterfacePortAddress();
public com.google.api.ads.adwords.axis.v201402.cm.GeoLocationServiceInterface getGeoLocationServiceInterfacePort() throws javax.xml.rpc.ServiceException;
public com.google.api.ads.adwords.axis.v201402.cm.GeoLocationServiceInterface getGeoLocationServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException;
}
| apache-2.0 |
subincm/chain_replication | config/config1_3_add_server_failure.py | 2421 | ###############################################################################
# 1) This is a test case to verify that the deposit case works fine.
# 2) It also checks whether duplicate requests are processed correctly.
###############################################################################
####################################
# Client Settings
# The client configuration is a dictionary where each key is a list of
# all the clients of a particular bank. Each entry in the list is a key:value
# pair of all the configurations of that client
####################################
client_conf = { 'CITI':
[
{'index':0, 'account_no': 9999,'client_time_out': 8, 'num_retransmits':3, 'resend_to_new_head':1, 'msg_loss_freq':0},
],}
#The clients will issue the following requests in that order to the servers
client_seq = [('getBalance', ('UID1', 8888)),
('deposit', ('UID1', 8888, 100)),
('deposit', ('UID2', 8888, 100)),
('deposit', ('UID3', 8888, 100)),
('deposit', ('UID4', 8888, 100)),
('deposit', ('UID5', 8888, 100)),
('withdraw', ('UID6', 8888, 100)),
('withdraw', ('UID7', 8888, 100)),
('withdraw', ('UID8', 8888, 100)),
('withdraw', ('UID9', 8888, 100)),
('withdraw', ('UID10', 8888, 100)),
('getBalance', ('UID1', 8888))
]
#random(seed, numReq, probGetBalance, probDeposit, probWithdraw, probTransfer)
#client_prob_conf = [
#{'index':0, 'seed':450, 'numReq':10, 'prob':[('getBalance',0.10), ('deposit',0.5), ('withdraw',0.4), ('transfer',0)]}
#]
####################################
# Server Settings
# The server configuration is a dictionary where each key is a list of
# all the servers of a particular bank. Each entry in the list is a key:value
# pair of all the configurations of that server
####################################
server_conf = { 'CITI':
[
{'index':0, 'startup_delay': 0, 'rcv_lifetime':1000, 'snd_lifetime':1000, 'ip_addr': '127.0.0.1', 'port': 1001, 'heartbeat_interval':1},
{'index':1, 'startup_delay': 8, 'rcv_lifetime':2, 'snd_lifetime':2, 'ip_addr': '127.0.0.1', 'port': 1002, 'heartbeat_interval':1},
{'index':2, 'startup_delay': 0, 'rcv_lifetime':1000, 'snd_lifetime':1000, 'ip_addr': '127.0.0.1', 'port': 1003, 'heartbeat_interval':1}
],}
master_conf = { 'master_interval':5}
| apache-2.0 |
Terreii/andromeda-viewer | src/bundles/localChat.ts | 4411 | /*
* Stores all LocalChat-Messages
*/
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { UUID as LLUUID } from '../llsd'
import { login, logout, userWasKicked, LoginAction } from './session'
import { RootState } from '../store/configureStore'
import {
LocalChatMessage,
LocalChatAudible,
LocalChatSourceType,
LocalChatType,
NotificationInChat
} from '../types/chat'
const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
const chatSlice = createSlice({
name: 'localChat',
initialState: ((): LocalChatMessage[] => [])(),
reducers: {
received (state, action: PayloadAction<LocalChatMessage>) {
if (
action.payload.chatType === LocalChatType.StartTyping ||
action.payload.chatType === LocalChatType.StopTyping
) {
return
}
state.push({
...action.payload,
didSave: false
})
},
notificationInChatAdded: {
reducer (state, action: PayloadAction<NotificationInChat>) {
state.push({
_id: 'notification_' + state.length,
fromName: action.payload.fromName,
fromId: action.payload.fromId || 'object',
sourceType: LocalChatSourceType.Object,
chatType: LocalChatType.OwnerSay,
audible: LocalChatAudible.Fully,
position: [0, 0, 0],
message: action.payload.text,
time: action.payload.time,
didSave: false
})
},
/**
* Handles messages that are notifications, but should be displayed in local chat.
* @param {string} text - Text of the Notification that should be displayed.
* @param {string} [fromName=""] - Displayed name of the sender.
* @param {string|object} [fromId] - Optional UUID of the sender.
*/
prepare (text: string, fromName = '', fromId: string | any) {
return {
payload: {
text: text.toString(),
fromName: fromName.toString(),
fromId: typeof fromId === 'string'
? fromId
: (fromId != null && fromId instanceof LLUUID ? fromId.toString() : null),
time: Date.now()
}
}
}
},
savingStarted (state, action: PayloadAction<string[]>) {
if (action.payload.length === 0) return
for (const msg of state) {
if (action.payload.includes(msg._id)) {
msg.didSave = true
}
}
},
savingFinished (
state,
action: PayloadAction<{ saved: LocalChatMessage[], didError: string[] }>
) {
if (action.payload.didError.length === 0 && action.payload.saved.length === 0) return
const ids = action.payload.saved.map(msg => msg._id)
for (const msg of state) {
const index = ids.indexOf(msg._id)
if (index >= 0) {
// write all data to msg object
Object.assign(msg, action.payload.saved[index])
} else if (action.payload.didError.includes(msg._id)) {
msg.didSave = false
}
}
}
},
extraReducers: {
[login.type] (state, action: PayloadAction<LoginAction>) {
state.push(...action.payload.localChatHistory.map((msg: any) => {
const typeString: any = capitalize(msg.chatType)
const sourceTypeString: any = capitalize(msg.sourceType)
const audible: any = capitalize(msg.audible)
return {
...msg,
chatType: LocalChatType[typeString],
sourceType: LocalChatSourceType[sourceTypeString],
audible: LocalChatAudible[audible],
didSave: true
}
}))
state.push({
_id: 'messageOfTheDay',
fromName: 'Message of the Day',
fromId: 'messageOfTheDay',
sourceType: LocalChatSourceType.System,
chatType: LocalChatType.OwnerSay,
audible: LocalChatAudible.Fully,
position: [0, 0, 0],
message: action.payload.sessionInfo.message,
time: action.payload.sessionInfo.seconds_since_epoch * 1000,
didSave: true
})
},
[logout.type] () {
return []
},
[userWasKicked.type] () {
return []
}
}
})
export default chatSlice.reducer
export const {
received,
notificationInChatAdded,
savingStarted,
savingFinished
} = chatSlice.actions
export const selectLocalChat = (state: RootState): LocalChatMessage[] => state.localChat
| apache-2.0 |
ctr-lang/ctr | __tests__/cases-api/public-methods/get-last-result/raw-reset.js | 803 | const path = require('path');
const _h = require(path.join(process.cwd(), '__tests__/cases-api/helpers.js'));
const CTR = require('ctr').js;
const ctr = new CTR();
ctr.create('.test-dont-reset', {
width: '100px'
});
const one = ctr.create('.test-1', {
width: '200px'
}).getLastResult(true, true);
const two = ctr.create('.test-2', {
width: '400px'
}).getLastResult({
raw: true,
reset: true
});
module.exports = {
exp: function() {
//should not be empty string since reset only resets the last set
//as in it should have .test-dont-reset stlyes
const exp = ctr.getRes();
_h.cleanCSS(exp).should.equal(_h.readFile(__filename));
//since its returns a raw set both should have a size of 1
one.size.should.be.exactly(1);
two.size.should.be.exactly(1);
}
};
| apache-2.0 |
google/graphicsfuzz | generator/src/main/java/com/graphicsfuzz/generator/fuzzer/templates/IExprTemplate.java | 3155 | /*
* Copyright 2018 The GraphicsFuzz Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphicsfuzz.generator.fuzzer.templates;
import com.graphicsfuzz.common.ast.expr.Expr;
import com.graphicsfuzz.common.ast.type.Type;
import com.graphicsfuzz.common.util.IRandom;
import java.util.List;
public interface IExprTemplate {
/**
* Instantiates the template with the given arguments to produce an expression.
* @param generator Used when randomization is required to determine the result.
* @param args The expressions used to instantiate the template.
* @return An expression over the arguments, determinied by the kind of template this is.
*/
Expr generateExpr(IRandom generator, Expr... args);
/**
* Helper to allow templates to be instantiated using lists rather than arrays/variable numbers
* of arguments.
*/
default Expr generateExpr(IRandom generator, List<Expr> args) {
Expr[] temp = new Expr[args.size()];
return generateExpr(generator, args.toArray(temp));
}
/**
* Yields an unqualified type guaranteed to match the unqualified version of the result type of
* an expression generated by the template.
* @return The (unqualified) result type of the template.
*/
Type getResultType();
/**
* Returns a list of k lists, indicating that the template requires k expressions in order to be
* evaluated, and that the type of the ith expression used to evaluate the template must be one
* of the types in the ith list. Each list returned must thus contain at least one type.
*
* <p>Most templates will return a list of singleton lists. However, the comma operator template
* can work for any pair of argument types</p>
* @return The acceptable argument types with which the template can be instantiated.
*/
List<List<Type>> getArgumentTypes();
/**
* Indicates whether a particular argument of the template needs to be an l-value.
* @param index A template argument index.
* @return true if and only if the argument provided for this index is required to be an l-value.
*/
boolean requiresLValueForArgument(int index);
/**
* Indicates whether the template produces an l-value.
* @return true if and only if the expression generated by the template is guaranteed to be an
* l-value.
*/
boolean isLValue();
/**
* Indicates whether the template produces a compile-time constant expression.
* @return true if and only if the expression generated by the template is guaranteed to be
* compile-time constant.
*/
boolean isConst();
int getNumArguments();
}
| apache-2.0 |
yoyocms/YoYoCms.AbpProjectTemplate | src/YoYoCms.AbpProjectTemplate.Web/Assets/src/services/common/notificationService.js | 179 | /**
* Created by huanghx on 2017/7/10.
*/
import serviceHelper from '../serviceHelper'
let roleService = serviceHelper.requireService('notification')
export default roleService | apache-2.0 |
richygreat/service | src/main/java/com/occar/dao/RouteDAO.java | 3762 | package com.occar.dao;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import com.occar.entity.Location;
import com.occar.entity.Route;
@Named
@SessionScoped
public class RouteDAO implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(RouteDAO.class.getName());
@PersistenceContext(unitName = "servicedb")
private EntityManager entityManager;
public RouteDAO() {
log.info("RouteDAO Constructor called");
}
@Transactional
public Location getLocationById(int locationId) {
log.info("Entering getLocationById");
Location location = entityManager.find(Location.class, locationId);
log.info("Exiting getLocationById");
return location;
}
@Transactional
public Route getRouteById(int routeId) {
log.info("Entering getRouteByDescription");
Route route = entityManager.find(Route.class, routeId);
log.info("Exiting getRouteByDescription");
return route;
}
@Transactional
public List<Route> getRoutes() {
List<Route> routes = null;
log.info("Entering getRoutes");
routes = entityManager.createQuery("select r from Route r", Route.class).getResultList();
log.info("Exiting getRoutes");
return routes;
}
@Transactional
public void deleteRoute(int routeId) {
log.info("Entering deleteRoute");
Route route = entityManager.find(Route.class, routeId);
entityManager.remove(route);
log.info("Entering deleteRoute");
}
@Transactional
public void saveRoute(Route route) {
log.info("Entering saveRoute");
int i = 1;
for (Iterator<Location> iterator = route.getStops().iterator(); iterator.hasNext();) {
Location stop = iterator.next();
if (stop.getName() != null && stop.getName().trim().length() != 0) {
stop.setRouteOrder(i++);
if (stop.getLocationId() == 0) {
entityManager.persist(stop);
} else {
entityManager.merge(stop);
}
} else {
iterator.remove();
}
}
log.info("Persisting :: " + route);
if (route.getRouteId() == 0) {
entityManager.persist(route);
} else {
entityManager.merge(route);
}
log.info("Exiting saveRoute");
}
@Transactional
public void saveRouteList(List<Route> ls) {
log.info("Entering saveRouteList");
for (Route route : ls) {
saveRoute(route);
}
log.info("Exiting saveRouteList");
}
@Transactional
public List<Route> getRoutesForATrip(String stop, String destination) {
List<Route> routes = null;
log.info("Entering getRoutesForATrip");
routes = entityManager.createQuery("select r from Route r inner join r.stops st1 inner join r.stops st2 where st1.name=?1 and st2.name=?2", Route.class)
.setParameter(1, destination)
.setParameter(2, stop)
.getResultList();
log.info(routes.toString());
log.info("Exiting getRoutesForATrip");
return routes;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Location getStopByName(String name) {
log.info("Entering getStopByName");
Location loc = null;
try {
loc = entityManager.createQuery("select l from Location l where l.name = ?1", Location.class)
.setParameter(1, name).getSingleResult();
} catch (Exception e) {
log.info(e.getMessage());
}
log.info("Exiting getStopByName");
return loc;
}
}
| apache-2.0 |
Q42/Deployment-Shepherd | deployment-shepherd-cli/Program.cs | 7408 | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Octokit;
using PowerArgs;
namespace deployment_shepherd_cli
{
/// <summary>
/// This application will go and find out which deployment slot to use.
/// It will try to poll github for closed pull requests (if the branchname is a pull request) so we do not close a living pull request
///
/// if the branchname is a pull request the application will also comment on the pull request with the deployment url to which it will be deployed
/// </summary>
class Program
{
static void Main(string[] args)
{
try
{
var parsedArgs = Args.Parse<ProgramArguments>(args);
var task = findDeploymentSlot(parsedArgs);
task.Wait();
Console.WriteLine(task.Result);
Environment.Exit(0);
}
catch (ArgException ex)
{
Console.WriteLine(ex.Message);
ArgUsage.GetStyledUsage<ProgramArguments>().Write();
Environment.Exit(-2);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Environment.Exit(-1);
}
}
private static async Task<Tuple<string, ApiStatusResponse, bool>> getStatusObjectWithGithubData(ProgramArguments args, string slotId, GitHubClient githubClient)
{
var url = String.Format("http://{0}/api/status", String.Format(args.BaseUrl, slotId));
var wc = new WebClient();
var apiStatusString = await wc.DownloadStringTaskAsync(url);
consoleWriteLineIfDebug(args, "Got response of " + url + " : " + apiStatusString);
var apiStatus = JsonConvert.DeserializeObject<ApiStatusResponse>(apiStatusString);
/* determine if what lives in this slot is a pull request */
apiStatus.PullrequestId = parsePullRequestIdFromBranchName(apiStatus.BranchName);
apiStatus.DeploySlotId = slotId;
return Tuple.Create(slotId, apiStatus, await isClosedPullRequest(githubClient, args, apiStatus.PullrequestId));
}
private static IObservable<Tuple<string, ApiStatusResponse, bool>> retrieveSlotStatusWithFallBack(ProgramArguments args, string slotId, GitHubClient githubClient)
{
return Observable
.Defer(() => getStatusObjectWithGithubData(args, slotId, githubClient).ToObservable())
.Retry(3) // retry 3 times to poll the slot or use the fallback
.Catch<Tuple<string, ApiStatusResponse, bool>, Exception>(
ex => Observable.Return(Tuple.Create(slotId, (ApiStatusResponse)null, true)));
}
private static async Task<string> findDeploymentSlot(ProgramArguments args)
{
var githubClient = new GitHubClient(new ProductHeaderValue("Q42.PullRequestCommenter"))
{
Credentials = new Credentials(args.PersonalGithubAccessToken)
};
var pullRequestId = parsePullRequestIdFromBranchName(args.BranchName);
var slotItems = await Observable.Range(1, 4)
.Select(idx => "pullrequestslot" + idx)
.SelectMany(slotId => retrieveSlotStatusWithFallBack(args, slotId, githubClient))
.ToList();
var currentSlot = slotItems.Where(sl => sl.Item2 != null && sl.Item2.BranchName == args.BranchName).Select(sl => sl.Item1).FirstOrDefault();
if (!String.IsNullOrEmpty(currentSlot))
{
// we are already deployed here, no further comments are required (if we are a pull request)
consoleWriteLineIfDebug(args, "We found a slot in which we are already deployed = " + currentSlot);
return currentSlot;
}
var anEmptySlot = slotItems.Where(sl => sl.Item2 == null).Select(sl => sl.Item1).FirstOrDefault();
if (!String.IsNullOrEmpty(anEmptySlot))
{
consoleWriteLineIfDebug(args, "We found an empty slot in which we can deploy = " + anEmptySlot);
if (pullRequestId != null)
await addPullRquestCommentAboutDeploymentSlot(githubClient, args, pullRequestId.Value, anEmptySlot);
return anEmptySlot;
}
// find a slot with a closed pull request in it
var aClosedPullRequestSlot = slotItems.Where(sl => sl.Item2 != null && sl.Item2.PullrequestId != null && sl.Item3 == true).Select(sl => sl.Item1).FirstOrDefault();
if (!String.IsNullOrEmpty(aClosedPullRequestSlot))
{
consoleWriteLineIfDebug(args, String.Format("Found a slot ({0}) containing a closed pullrequest which we are going to use", aClosedPullRequestSlot));
if (pullRequestId != null)
await addPullRquestCommentAboutDeploymentSlot(githubClient, args, pullRequestId.Value, aClosedPullRequestSlot);
return aClosedPullRequestSlot;
}
// last resort - use the oldest deploy
var theOldestSlot = slotItems.Where(sl => sl.Item2 != null).OrderBy(sl => sl.Item2.BuildDate).FirstOrDefault();
if (theOldestSlot != null)
{
consoleWriteLineIfDebug(args, "We found the oldest slot in which we can deploy = " + theOldestSlot.Item1);
if (theOldestSlot.Item2.PullrequestId != null)
{
consoleWriteLineIfDebug(args, "Found the oldest slot but it still contains a open pull request. Going to comment it.");
await addCommentToPullRequest(githubClient, args, theOldestSlot.Item2.PullrequestId.Value,
":warning::no_entry: This deployment has been overwritten by another pull request thus is no longer available :no_entry::warning:");
}
if (pullRequestId != null)
await addPullRquestCommentAboutDeploymentSlot(githubClient, args, pullRequestId.Value, theOldestSlot.Item1);
return theOldestSlot.Item1;
}
throw new Exception("This should not happen, we should always select some slot");
}
private static async Task addPullRquestCommentAboutDeploymentSlot(GitHubClient githubClient, ProgramArguments args, int pullRequestId, string deploymentSlot)
{
await addCommentToPullRequest(githubClient, args, pullRequestId,
String.Format(CultureInfo.InvariantCulture, "Going to deploy this pull request to http://{0} so you can easily test it.",
String.Format(CultureInfo.InvariantCulture, args.BaseUrl, deploymentSlot)));
}
private static void consoleWriteLineIfDebug(ProgramArguments args, string message)
{
if (args.DebugModeEnabled)
Console.WriteLine("[DEBUG] " + message);
}
private static async Task<bool> isClosedPullRequest(GitHubClient githubClient, ProgramArguments args, int? pullRequestId)
{
if (pullRequestId == null)
return true;
var pr = await githubClient.PullRequest.Get(args.Owner, args.Repository, pullRequestId.Value);
return pr.State == ItemState.Closed;
}
private static async Task addCommentToPullRequest(GitHubClient githubClient, ProgramArguments args, int pullRequestId, string message)
{
if (args.DebugModeEnabled)
Console.WriteLine("[DEBUG] Was going to append comment to pullrequest {0} => '{1}'", pullRequestId, message);
else
await githubClient.Issue.Comment.Create(args.Owner, args.Repository, pullRequestId, message);
}
/// <summary>
/// try to locate the pullrequest id in the given branchName
/// </summary>
/// <param name="branchName"></param>
/// <returns></returns>
private static int? parsePullRequestIdFromBranchName(string branchName)
{
if (branchName.Contains("pull"))
{
int pullRequestId;
if (Int32.TryParse(Regex.Replace(branchName, "[^0-9]", ""), out pullRequestId))
{
//we have a pull request id,
return pullRequestId;
}
}
return null;
}
}
}
| apache-2.0 |
Scalr/libcloud | libcloud/common/azure_arm.py | 10277 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
import simplejson as json
except ImportError:
import json
import time
from libcloud.utils.py3 import urlparse
from libcloud.common.base import (ConnectionUserAndKey,
JsonResponse,
RawResponse)
from libcloud.http import LibcloudConnection
from libcloud.utils.py3 import basestring, urlencode
class AzureBaseDriver(object):
name = "Microsoft Azure Resource Management API"
class AzureJsonResponse(JsonResponse):
def parse_error(self):
b = self.parse_body()
if isinstance(b, basestring):
return b
elif isinstance(b, dict) and "error" in b:
return "[%s] %s" % (b["error"].get("code"),
b["error"].get("message"))
else:
return str(b)
class AzureAuthJsonResponse(JsonResponse):
def parse_error(self):
b = self.parse_body()
if isinstance(b, basestring):
return b
elif isinstance(b, dict) and "error_description" in b:
return b["error_description"]
else:
return str(b)
# Based on https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/cloud.py
publicEnvironments = {
"default": {
'name': 'default',
'portalUrl': 'http://go.microsoft.com/fwlink/?LinkId=254433',
'publishingProfileUrl':
'http://go.microsoft.com/fwlink/?LinkId=254432',
'managementEndpointUrl': 'https://management.core.windows.net',
'resourceManagerEndpointUrl':
'https://management.azure.com/',
'sqlManagementEndpointUrl':
'https://management.core.windows.net:8443/',
'sqlServerHostnameSuffix': '.database.windows.net',
'galleryEndpointUrl': 'https://gallery.azure.com/',
'activeDirectoryEndpointUrl': 'https://login.microsoftonline.com',
'activeDirectoryResourceId': 'https://management.core.windows.net/',
'activeDirectoryGraphResourceId': 'https://graph.windows.net/',
'activeDirectoryGraphApiVersion': '2013-04-05',
'storageEndpointSuffix': '.core.windows.net',
'keyVaultDnsSuffix': '.vault.azure.net',
'azureDataLakeStoreFileSystemEndpointSuffix': 'azuredatalakestore.net',
'azureDataLakeAnalyticsCatalogAndJobEndpointSuffix':
'azuredatalakeanalytics.net'
},
"AzureChinaCloud": {
'name': 'AzureChinaCloud',
'portalUrl': 'http://go.microsoft.com/fwlink/?LinkId=301902',
'publishingProfileUrl':
'http://go.microsoft.com/fwlink/?LinkID=301774',
'managementEndpointUrl': 'https://management.core.chinacloudapi.cn',
'resourceManagerEndpointUrl': 'https://management.chinacloudapi.cn',
'sqlManagementEndpointUrl':
'https://management.core.chinacloudapi.cn:8443/',
'sqlServerHostnameSuffix': '.database.chinacloudapi.cn',
'galleryEndpointUrl': 'https://gallery.chinacloudapi.cn/',
'activeDirectoryEndpointUrl': 'https://login.chinacloudapi.cn',
'activeDirectoryResourceId':
'https://management.core.chinacloudapi.cn/',
'activeDirectoryGraphResourceId': 'https://graph.chinacloudapi.cn/',
'activeDirectoryGraphApiVersion': '2013-04-05',
'storageEndpointSuffix': '.core.chinacloudapi.cn',
'keyVaultDnsSuffix': '.vault.azure.cn',
'azureDataLakeStoreFileSystemEndpointSuffix': 'N/A',
'azureDataLakeAnalyticsCatalogAndJobEndpointSuffix': 'N/A'
},
"AzureUSGovernment": {
'name': 'AzureUSGovernment',
'portalUrl': 'https://portal.azure.us',
'publishingProfileUrl':
'https://manage.windowsazure.us/publishsettings/index',
'managementEndpointUrl': 'https://management.core.usgovcloudapi.net',
'resourceManagerEndpointUrl': 'https://management.usgovcloudapi.net',
'sqlManagementEndpointUrl':
'https://management.core.usgovcloudapi.net:8443/',
'sqlServerHostnameSuffix': '.database.usgovcloudapi.net',
'galleryEndpointUrl': 'https://gallery.usgovcloudapi.net/',
'activeDirectoryEndpointUrl': 'https://login.microsoftonline.us',
'activeDirectoryResourceId':
'https://management.core.usgovcloudapi.net/',
'activeDirectoryGraphResourceId': 'https://graph.windows.net/',
'activeDirectoryGraphApiVersion': '2013-04-05',
'storageEndpointSuffix': '.core.usgovcloudapi.net',
'keyVaultDnsSuffix': '.vault.usgovcloudapi.net',
'azureDataLakeStoreFileSystemEndpointSuffix': 'N/A',
'azureDataLakeAnalyticsCatalogAndJobEndpointSuffix': 'N/A'
},
"AzureGermanCloud": {
'name': 'AzureGermanCloud',
'portalUrl': 'http://portal.microsoftazure.de/',
'publishingProfileUrl':
'https://manage.microsoftazure.de/publishsettings/index',
'managementEndpointUrl': 'https://management.core.cloudapi.de',
'resourceManagerEndpointUrl': 'https://management.microsoftazure.de',
'sqlManagementEndpointUrl':
'https://management.core.cloudapi.de:8443/',
'sqlServerHostnameSuffix': '.database.cloudapi.de',
'galleryEndpointUrl': 'https://gallery.cloudapi.de/',
'activeDirectoryEndpointUrl': 'https://login.microsoftonline.de',
'activeDirectoryResourceId': 'https://management.core.cloudapi.de/',
'activeDirectoryGraphResourceId': 'https://graph.cloudapi.de/',
'activeDirectoryGraphApiVersion': '2013-04-05',
'storageEndpointSuffix': '.core.cloudapi.de',
'keyVaultDnsSuffix': '.vault.microsoftazure.de',
'azureDataLakeStoreFileSystemEndpointSuffix': 'N/A',
'azureDataLakeAnalyticsCatalogAndJobEndpointSuffix': 'N/A'
}
}
class AzureResourceManagementConnection(ConnectionUserAndKey):
"""
Represents a single connection to Azure
"""
conn_class = LibcloudConnection
driver = AzureBaseDriver
name = 'Azure AD Auth'
responseCls = AzureJsonResponse
rawResponseCls = RawResponse
def __init__(self, key, secret, secure=True, tenant_id=None,
subscription_id=None, cloud_environment=None, **kwargs):
super(AzureResourceManagementConnection, self) \
.__init__(key, secret, **kwargs)
if not cloud_environment:
cloud_environment = "default"
if isinstance(cloud_environment, basestring):
cloud_environment = publicEnvironments[cloud_environment]
if not isinstance(cloud_environment, dict):
raise Exception("cloud_environment must be one of '%s' or a dict "
"containing keys 'resourceManagerEndpointUrl', "
"'activeDirectoryEndpointUrl', "
"'activeDirectoryResourceId', "
"'storageEndpointSuffix'" % (
"', '".join(publicEnvironments.keys())))
self.host = urlparse.urlparse(
cloud_environment['resourceManagerEndpointUrl']).hostname
self.login_host = urlparse.urlparse(
cloud_environment['activeDirectoryEndpointUrl']).hostname
self.login_resource = cloud_environment['activeDirectoryResourceId']
self.storage_suffix = cloud_environment['storageEndpointSuffix']
self.tenant_id = tenant_id
self.subscription_id = subscription_id
def add_default_headers(self, headers):
headers['Content-Type'] = "application/json"
headers['Authorization'] = "Bearer %s" % self.access_token
return headers
def encode_data(self, data):
"""Encode data to JSON"""
return json.dumps(data)
def get_token_from_credentials(self):
"""
Log in and get bearer token used to authorize API requests.
"""
conn = self.conn_class(self.login_host, 443, proxy_url=self.proxy_url, timeout=self.timeout)
conn.connect()
params = urlencode({
"grant_type": "client_credentials",
"client_id": self.user_id,
"client_secret": self.key,
"resource": self.login_resource
})
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn.request("POST", "/%s/oauth2/token" % self.tenant_id,
params, headers)
js = AzureAuthJsonResponse(conn.getresponse(), conn)
self.access_token = js.object["access_token"]
self.expires_on = js.object["expires_on"]
def connect(self, **kwargs):
self.get_token_from_credentials()
return super(AzureResourceManagementConnection, self).connect(**kwargs)
def request(self, action, params=None, data=None, headers=None,
method='GET', raw=False, stream=False):
# Log in again if the token has expired or is going to expire soon
# (next 5 minutes).
if (time.time() + 300) >= int(self.expires_on):
self.get_token_from_credentials()
return super(AzureResourceManagementConnection, self) \
.request(action, params=params,
data=data, headers=headers,
method=method, raw=raw, stream=stream)
def pre_connect_hook(self, params, headers):
# Azure redirects some requests to different hosts,
# but requests does not removes this old Host header
headers.pop('Host', None)
return params, headers
| apache-2.0 |
database-rider/database-rider | rider-spring/src/test/java/com/github/database/rider/spring/dataset/MetaDataSet.java | 726 | package com.github.database.rider.spring.dataset;
import com.github.database.rider.core.api.configuration.DBUnit;
import com.github.database.rider.core.api.dataset.DataSet;
import com.github.database.rider.spring.api.DBRider;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@DBUnit(caseSensitiveTableNames = true)
@DBRider
@DataSet
public @interface MetaDataSet {
@AliasFor(annotation = DataSet.class, attribute = "value")
String[] value() default "test.yml";
}
| apache-2.0 |
Im-dex/xray-162 | code/engine/xrGame/ui/UIInventoryUtilities.cpp | 17619 |
#include "pch_script.h"
#include "UIInventoryUtilities.h"
#include "../WeaponAmmo.h"
#include "../UIStaticItem.h"
#include "UIStatic.h"
#include "../eatable_item.h"
#include "../Level.h"
#include "../date_time.h"
#include "../string_table.h"
#include "../Inventory.h"
#include "../InventoryOwner.h"
#include "../InfoPortion.h"
#include "game_base_space.h"
#include "../actor.h"
#include "../ai_space.h"
#include "../../xrServerEntities/script_engine.h"
#include "xrRender/UIShader.h"
#define BUY_MENU_TEXTURE "ui\\ui_mp_buy_menu"
#define CHAR_ICONS "ui\\ui_icons_npc"
#define MAP_ICONS "ui\\ui_icons_map"
#define MP_CHAR_ICONS "ui\\ui_models_multiplayer"
const LPCSTR relationsLtxSection = "game_relations";
const LPCSTR ratingField = "rating_names";
const LPCSTR reputationgField = "reputation_names";
const LPCSTR goodwillField = "goodwill_names";
const LPCSTR st_months[12] = // StringTable for GetDateAsString()
{ "month_january", "month_february", "month_march", "month_april",
"month_may", "month_june", "month_july", "month_august",
"month_september", "month_october", "month_november", "month_december" };
ui_shader* g_BuyMenuShader = NULL;
ui_shader* g_EquipmentIconsShader = NULL;
ui_shader* g_MPCharIconsShader = NULL;
ui_shader* g_OutfitUpgradeIconsShader = NULL;
ui_shader* g_WeaponUpgradeIconsShader = NULL;
ui_shader* g_tmpWMShader = NULL;
static CUIStatic* GetUIStatic();
typedef std::pair<CHARACTER_RANK_VALUE, shared_str> CharInfoStringID;
using CharInfoStrings = xr_map<CHARACTER_RANK_VALUE, shared_str>;
CharInfoStrings* charInfoReputationStrings = NULL;
CharInfoStrings* charInfoRankStrings = NULL;
CharInfoStrings* charInfoGoodwillStrings = NULL;
void InventoryUtilities::CreateShaders() {
g_tmpWMShader = xr_new<ui_shader>();
(*g_tmpWMShader)->create("effects\\wallmark", "wm\\wm_grenade");
// g_tmpWMShader.create("effects\\wallmark", "wm\\wm_grenade");
}
void InventoryUtilities::DestroyShaders() {
xr_delete(g_BuyMenuShader);
g_BuyMenuShader = 0;
xr_delete(g_EquipmentIconsShader);
g_EquipmentIconsShader = 0;
xr_delete(g_MPCharIconsShader);
g_MPCharIconsShader = 0;
xr_delete(g_OutfitUpgradeIconsShader);
g_OutfitUpgradeIconsShader = 0;
xr_delete(g_WeaponUpgradeIconsShader);
g_WeaponUpgradeIconsShader = 0;
xr_delete(g_tmpWMShader);
g_tmpWMShader = 0;
}
bool InventoryUtilities::GreaterRoomInRuck(PIItem item1, PIItem item2) {
Ivector2 r1, r2;
r1 = item1->GetInvGridRect().rb;
r2 = item2->GetInvGridRect().rb;
if (r1.x > r2.x)
return true;
if (r1.x == r2.x) {
if (r1.y > r2.y)
return true;
if (r1.y == r2.y) {
if (item1->object().cNameSect() == item2->object().cNameSect())
return (item1->object().ID() > item2->object().ID());
else
return (item1->object().cNameSect() > item2->object().cNameSect());
}
return false;
}
return false;
}
bool InventoryUtilities::FreeRoom_inBelt(TIItemContainer& item_list, PIItem _item, int width,
int height) {
bool* ruck_room = (bool*)alloca(width * height);
int i, j, k, m;
int place_row = 0, place_col = 0;
bool found_place;
bool can_place;
for (i = 0; i < height; ++i)
for (j = 0; j < width; ++j)
ruck_room[i * width + j] = false;
item_list.push_back(_item);
std::sort(item_list.begin(), item_list.end(), GreaterRoomInRuck);
found_place = true;
for (xr_vector<PIItem>::iterator it = item_list.begin(); (item_list.end() != it) && found_place;
++it) {
PIItem pItem = *it;
Ivector2 iWH = pItem->GetInvGridRect().rb;
//ïðîâåðèòü ìîæíî ëè ðàçìåñòèòü ýëåìåíò,
//ïðîâåðÿåì ïîñëåäîâàòåëüíî êàæäóþ êëåòî÷êó
found_place = false;
for (i = 0; (i < height - iWH.y + 1) && !found_place; ++i) {
for (j = 0; (j < width - iWH.x + 1) && !found_place; ++j) {
can_place = true;
for (k = 0; (k < iWH.y) && can_place; ++k) {
for (m = 0; (m < iWH.x) && can_place; ++m) {
if (ruck_room[(i + k) * width + (j + m)])
can_place = false;
}
}
if (can_place) {
found_place = true;
place_row = i;
place_col = j;
}
}
}
//ðàçìåñòèòü ýëåìåíò íà íàéäåííîì ìåñòå
if (found_place) {
for (k = 0; k < iWH.y; ++k) {
for (m = 0; m < iWH.x; ++m) {
ruck_room[(place_row + k) * width + place_col + m] = true;
}
}
}
}
// remove
item_list.erase(std::remove(item_list.begin(), item_list.end(), _item), item_list.end());
//äëÿ êàêîãî-òî ýëåìåíòà ìåñòà íå íàøëîñü
if (!found_place)
return false;
return true;
}
const ui_shader& InventoryUtilities::GetBuyMenuShader() {
if (!g_BuyMenuShader) {
g_BuyMenuShader = xr_new<ui_shader>();
(*g_BuyMenuShader)->create("hud\\default", BUY_MENU_TEXTURE);
}
return *g_BuyMenuShader;
}
const ui_shader& InventoryUtilities::GetEquipmentIconsShader() {
if (!g_EquipmentIconsShader) {
g_EquipmentIconsShader = xr_new<ui_shader>();
(*g_EquipmentIconsShader)->create("hud\\default", "ui\\ui_icon_equipment");
}
return *g_EquipmentIconsShader;
}
const ui_shader& InventoryUtilities::GetMPCharIconsShader() {
if (!g_MPCharIconsShader) {
g_MPCharIconsShader = xr_new<ui_shader>();
(*g_MPCharIconsShader)->create("hud\\default", MP_CHAR_ICONS);
}
return *g_MPCharIconsShader;
}
const ui_shader& InventoryUtilities::GetOutfitUpgradeIconsShader() {
if (!g_OutfitUpgradeIconsShader) {
g_OutfitUpgradeIconsShader = xr_new<ui_shader>();
(*g_OutfitUpgradeIconsShader)->create("hud\\default", "ui\\ui_actor_armor");
}
return *g_OutfitUpgradeIconsShader;
}
const ui_shader& InventoryUtilities::GetWeaponUpgradeIconsShader() {
if (!g_WeaponUpgradeIconsShader) {
g_WeaponUpgradeIconsShader = xr_new<ui_shader>();
(*g_WeaponUpgradeIconsShader)->create("hud\\default", "ui\\ui_actor_weapons");
}
return *g_WeaponUpgradeIconsShader;
}
//////////////////////////////////////////////////////////////////////////
const shared_str InventoryUtilities::GetGameDateAsString(EDatePrecision datePrec,
char dateSeparator) {
return GetDateAsString(Level().GetGameTime(), datePrec, dateSeparator);
}
//////////////////////////////////////////////////////////////////////////
const shared_str InventoryUtilities::GetGameTimeAsString(ETimePrecision timePrec,
char timeSeparator) {
return GetTimeAsString(Level().GetGameTime(), timePrec, timeSeparator);
}
const shared_str InventoryUtilities::GetTimeAndDateAsString(ALife::_TIME_ID time) {
string256 buf;
LPCSTR time_str = GetTimeAsString(time, etpTimeToMinutes).c_str();
LPCSTR date_str = GetDateAsString(time, edpDateToDay).c_str();
strconcat(sizeof(buf), buf, time_str, ", ", date_str);
return buf;
}
const shared_str InventoryUtilities::Get_GameTimeAndDate_AsString() {
return GetTimeAndDateAsString(Level().GetGameTime());
}
//////////////////////////////////////////////////////////////////////////
const shared_str InventoryUtilities::GetTimeAsString(ALife::_TIME_ID time, ETimePrecision timePrec,
char timeSeparator, bool full_mode) {
string32 bufTime;
std::memset(bufTime, 0, sizeof(bufTime));
u32 year = 0, month = 0, day = 0, hours = 0, mins = 0, secs = 0, milisecs = 0;
split_time(time, year, month, day, hours, mins, secs, milisecs);
// Time
switch (timePrec) {
case etpTimeToHours:
xr_sprintf(bufTime, "%02i", hours);
break;
case etpTimeToMinutes:
if (full_mode || hours > 0) {
xr_sprintf(bufTime, "%02i%c%02i", hours, timeSeparator, mins);
break;
}
xr_sprintf(bufTime, "0%c%02i", timeSeparator, mins);
break;
case etpTimeToSeconds:
if (full_mode || hours > 0) {
xr_sprintf(bufTime, "%02i%c%02i%c%02i", hours, timeSeparator, mins, timeSeparator,
secs);
break;
}
if (mins > 0) {
xr_sprintf(bufTime, "%02i%c%02i", mins, timeSeparator, secs);
break;
}
xr_sprintf(bufTime, "0%c%02i", timeSeparator, secs);
break;
case etpTimeToMilisecs:
xr_sprintf(bufTime, "%02i%c%02i%c%02i%c%02i", hours, timeSeparator, mins, timeSeparator,
secs, timeSeparator, milisecs);
break;
case etpTimeToSecondsAndDay: {
int total_day = (int)(time / (1000 * 60 * 60 * 24));
xr_sprintf(bufTime, sizeof(bufTime), "%dd %02i%c%02i%c%02i", total_day, hours,
timeSeparator, mins, timeSeparator, secs);
break;
}
default:
R_ASSERT(!"Unknown type of date precision");
}
return bufTime;
}
const shared_str InventoryUtilities::GetDateAsString(ALife::_TIME_ID date, EDatePrecision datePrec,
char dateSeparator) {
string64 bufDate;
std::memset(bufDate, 0, sizeof(bufDate));
u32 year = 0, month = 0, day = 0, hours = 0, mins = 0, secs = 0, milisecs = 0;
split_time(date, year, month, day, hours, mins, secs, milisecs);
VERIFY(1 <= month && month <= 12);
LPCSTR month_str = CStringTable().translate(st_months[month - 1]).c_str();
// Date
switch (datePrec) {
case edpDateToYear:
xr_sprintf(bufDate, "%04i", year);
break;
case edpDateToMonth:
xr_sprintf(bufDate, "%s%c% 04i", month_str, dateSeparator, year);
break;
case edpDateToDay:
xr_sprintf(bufDate, "%s %d%c %04i", month_str, day, dateSeparator, year);
break;
default:
R_ASSERT(!"Unknown type of date precision");
}
return bufDate;
}
LPCSTR InventoryUtilities::GetTimePeriodAsString(LPSTR _buff, u32 buff_sz, ALife::_TIME_ID _from,
ALife::_TIME_ID _to) {
u32 year1, month1, day1, hours1, mins1, secs1, milisecs1;
u32 year2, month2, day2, hours2, mins2, secs2, milisecs2;
split_time(_from, year1, month1, day1, hours1, mins1, secs1, milisecs1);
split_time(_to, year2, month2, day2, hours2, mins2, secs2, milisecs2);
int cnt = 0;
_buff[0] = 0;
if (month1 != month2)
cnt = xr_sprintf(_buff + cnt, buff_sz - cnt, "%d %s ", month2 - month1,
*CStringTable().translate("ui_st_months"));
if (!cnt && day1 != day2)
cnt = xr_sprintf(_buff + cnt, buff_sz - cnt, "%d %s", day2 - day1,
*CStringTable().translate("ui_st_days"));
if (!cnt && hours1 != hours2)
cnt = xr_sprintf(_buff + cnt, buff_sz - cnt, "%d %s", hours2 - hours1,
*CStringTable().translate("ui_st_hours"));
if (!cnt && mins1 != mins2)
cnt = xr_sprintf(_buff + cnt, buff_sz - cnt, "%d %s", mins2 - mins1,
*CStringTable().translate("ui_st_mins"));
if (!cnt && secs1 != secs2)
cnt = xr_sprintf(_buff + cnt, buff_sz - cnt, "%d %s", secs2 - secs1,
*CStringTable().translate("ui_st_secs"));
return _buff;
}
//////////////////////////////////////////////////////////////////////////
void InventoryUtilities::UpdateWeightStr(CUITextWnd& wnd, CUITextWnd& wnd_max,
CInventoryOwner* pInvOwner) {
R_ASSERT(pInvOwner);
string128 buf;
float total = pInvOwner->inventory().CalcTotalWeight();
float max = pInvOwner->MaxCarryWeight();
LPCSTR kg_str = CStringTable().translate("st_kg").c_str();
xr_sprintf(buf, "%.1f %s", total, kg_str);
wnd.SetText(buf);
xr_sprintf(buf, "(max %.1f %s)", max, kg_str);
wnd_max.SetText(buf);
}
//////////////////////////////////////////////////////////////////////////
void LoadStrings(CharInfoStrings* container, LPCSTR section, LPCSTR field) {
R_ASSERT(container);
LPCSTR cfgRecord = pSettings->r_string(section, field);
u32 count = _GetItemCount(cfgRecord);
R_ASSERT3(count % 2, "there're must be an odd number of elements", field);
string64 singleThreshold;
std::memset(singleThreshold, 0, sizeof(singleThreshold));
int upBoundThreshold = 0;
CharInfoStringID id;
for (u32 k = 0; k < count; k += 2) {
_GetItem(cfgRecord, k, singleThreshold);
id.second = singleThreshold;
_GetItem(cfgRecord, k + 1, singleThreshold);
if (k + 1 != count)
sscanf(singleThreshold, "%i", &upBoundThreshold);
else
upBoundThreshold += 1;
id.first = upBoundThreshold;
container->insert(id);
}
}
//////////////////////////////////////////////////////////////////////////
void InitCharacterInfoStrings() {
if (charInfoReputationStrings && charInfoRankStrings)
return;
if (!charInfoReputationStrings) {
// Create string->Id DB
charInfoReputationStrings = xr_new<CharInfoStrings>();
// Reputation
LoadStrings(charInfoReputationStrings, relationsLtxSection, reputationgField);
}
if (!charInfoRankStrings) {
// Create string->Id DB
charInfoRankStrings = xr_new<CharInfoStrings>();
// Ranks
LoadStrings(charInfoRankStrings, relationsLtxSection, ratingField);
}
if (!charInfoGoodwillStrings) {
// Create string->Id DB
charInfoGoodwillStrings = xr_new<CharInfoStrings>();
// Goodwills
LoadStrings(charInfoGoodwillStrings, relationsLtxSection, goodwillField);
}
}
//////////////////////////////////////////////////////////////////////////
void InventoryUtilities::ClearCharacterInfoStrings() {
xr_delete(charInfoReputationStrings);
xr_delete(charInfoRankStrings);
xr_delete(charInfoGoodwillStrings);
}
//////////////////////////////////////////////////////////////////////////
LPCSTR InventoryUtilities::GetRankAsText(CHARACTER_RANK_VALUE rankID) {
InitCharacterInfoStrings();
CharInfoStrings::const_iterator cit = charInfoRankStrings->upper_bound(rankID);
if (charInfoRankStrings->end() == cit)
return charInfoRankStrings->rbegin()->second.c_str();
return cit->second.c_str();
}
//////////////////////////////////////////////////////////////////////////
LPCSTR InventoryUtilities::GetReputationAsText(CHARACTER_REPUTATION_VALUE rankID) {
InitCharacterInfoStrings();
CharInfoStrings::const_iterator cit = charInfoReputationStrings->upper_bound(rankID);
if (charInfoReputationStrings->end() == cit)
return charInfoReputationStrings->rbegin()->second.c_str();
return cit->second.c_str();
}
//////////////////////////////////////////////////////////////////////////
LPCSTR InventoryUtilities::GetGoodwillAsText(CHARACTER_GOODWILL goodwill) {
InitCharacterInfoStrings();
CharInfoStrings::const_iterator cit = charInfoGoodwillStrings->upper_bound(goodwill);
if (charInfoGoodwillStrings->end() == cit)
return charInfoGoodwillStrings->rbegin()->second.c_str();
return cit->second.c_str();
}
//////////////////////////////////////////////////////////////////////////
// ñïåöèàëüíàÿ ôóíêöèÿ äëÿ ïåðåäà÷è info_portions ïðè íàæàòèè êíîïîê UI
// (äëÿ tutorial)
void InventoryUtilities::SendInfoToActor(LPCSTR info_id) {
if (GameID() != eGameIDSingle)
return;
CActor* actor = smart_cast<CActor*>(Level().CurrentEntity());
if (actor) {
actor->TransferInfo(info_id, true);
}
}
void InventoryUtilities::SendInfoToLuaScripts(shared_str info) {
if (GameID() != eGameIDSingle)
return;
if (info == shared_str("ui_talk_show")) {
int mode = 10; // now Menu is Talk Dialog (show)
luabind::functor<void> funct;
R_ASSERT(ai().script_engine().functor("pda.actor_menu_mode", funct));
funct(mode);
}
if (info == shared_str("ui_talk_hide")) {
int mode = 11; // Talk Dialog hide
luabind::functor<void> funct;
R_ASSERT(ai().script_engine().functor("pda.actor_menu_mode", funct));
funct(mode);
}
}
u32 InventoryUtilities::GetGoodwillColor(CHARACTER_GOODWILL gw) {
u32 res = 0xffc0c0c0;
if (gw == NEUTRAL_GOODWILL) {
res = 0xffc0c0c0;
} else if (gw > 1000) {
res = 0xff00ff00;
} else if (gw < -1000) {
res = 0xffff0000;
}
return res;
}
u32 InventoryUtilities::GetReputationColor(CHARACTER_REPUTATION_VALUE rv) {
u32 res = 0xffc0c0c0;
if (rv == NEUTAL_REPUTATION) {
res = 0xffc0c0c0;
} else if (rv > 50) {
res = 0xff00ff00;
} else if (rv < -50) {
res = 0xffff0000;
}
return res;
}
u32 InventoryUtilities::GetRelationColor(ALife::ERelationType relation) {
switch (relation) {
case ALife::eRelationTypeFriend:
return 0xff00ff00;
break;
case ALife::eRelationTypeNeutral:
return 0xffc0c0c0;
break;
case ALife::eRelationTypeEnemy:
return 0xffff0000;
break;
default:
NODEFAULT;
}
#ifdef DEBUG
return 0xffffffff;
#endif
}
| apache-2.0 |
sky91/EnumGeneratorGradlePlugin | source/enum-generator-gradle-plugin/core/src/main/java/x/flyspace/gradle/plugin/enumgenerator/core/impl/items/filter/TypeMatchRegexHandleFilter.java | 656 | package x.flyspace.gradle.plugin.enumgenerator.core.impl.items.filter;
import x.flyspace.gradle.plugin.enumgenerator.core.impl.items.HandleFilter;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Created by sky91 on 2/5/15.
*/
public class TypeMatchRegexHandleFilter implements HandleFilter<Map<String, Object>> {
private Pattern pattern;
public TypeMatchRegexHandleFilter(String regex) {
pattern = Pattern.compile(regex);
}
@Override
public boolean shouldHandle(Map<String, Object> item) {
if(item == null || item.get("type") == null) {
return false;
}
return pattern.matcher(item.get("type").toString()).matches();
}
}
| apache-2.0 |
dsilva609/Project-Ariel | UnitTests/BusinessLogic/Enums/RankEnumTests.cs | 3006 | using BusinessLogic.Enums;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace UnitTests.BusinessLogic.Enums
{
[TestClass]
public class RankEnumTests
{
private const string ENUM_FAILURE_MESSAGE = "Enum value is not correct. Enum and update scripts may be out of date.";
[TestMethod]
public void ThatDefaultValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Default);
//--Assert
Assert.AreEqual(0, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatTwoValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Two);
//--Assert
Assert.AreEqual(2, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatThreeValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Three);
//--Assert
Assert.AreEqual(3, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatFourValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Four);
//--Assert
Assert.AreEqual(4, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatFiveValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Five);
//--Assert
Assert.AreEqual(5, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatSixValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Six);
//--Assert
Assert.AreEqual(6, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatSevenValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Seven);
//--Assert
Assert.AreEqual(7, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatEightValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Eight);
//--Assert
Assert.AreEqual(8, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatNineValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Nine);
//--Assert
Assert.AreEqual(9, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatTenValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Ten);
//--Assert
Assert.AreEqual(10, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatJackValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Jack);
//--Assert
Assert.AreEqual(11, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatQueenValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Queen);
//--Assert
Assert.AreEqual(12, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatKingValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.King);
//--Assert
Assert.AreEqual(13, result, ENUM_FAILURE_MESSAGE);
}
[TestMethod]
public void ThatAceValueHasCorrectValue()
{
//--Act
var result = Convert.ToInt32(Rank.Ace);
//--Assert
Assert.AreEqual(14, result, ENUM_FAILURE_MESSAGE);
}
}
} | apache-2.0 |
wyukawa/presto | presto-main/src/test/java/io/prestosql/operator/TestScanFilterAndProjectOperator.java | 20458 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.operator;
import com.google.common.collect.ImmutableList;
import io.airlift.units.DataSize;
import io.prestosql.SequencePageBuilder;
import io.prestosql.block.BlockAssertions;
import io.prestosql.connector.CatalogName;
import io.prestosql.execution.Lifespan;
import io.prestosql.metadata.Metadata;
import io.prestosql.metadata.Signature;
import io.prestosql.metadata.Split;
import io.prestosql.metadata.SqlScalarFunction;
import io.prestosql.operator.index.PageRecordSet;
import io.prestosql.operator.project.CursorProcessor;
import io.prestosql.operator.project.PageProcessor;
import io.prestosql.operator.project.TestPageProcessor.LazyPagePageProjection;
import io.prestosql.operator.project.TestPageProcessor.SelectAllFilter;
import io.prestosql.operator.scalar.AbstractTestFunctions;
import io.prestosql.spi.Page;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.LazyBlock;
import io.prestosql.spi.connector.ConnectorPageSource;
import io.prestosql.spi.connector.FixedPageSource;
import io.prestosql.spi.connector.RecordPageSource;
import io.prestosql.sql.gen.ExpressionCompiler;
import io.prestosql.sql.gen.PageFunctionCompiler;
import io.prestosql.sql.planner.plan.PlanNodeId;
import io.prestosql.sql.relational.RowExpression;
import io.prestosql.testing.MaterializedResult;
import io.prestosql.testing.TestingSplit;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.airlift.units.DataSize.Unit.BYTE;
import static io.airlift.units.DataSize.Unit.KILOBYTE;
import static io.prestosql.RowPagesBuilder.rowPagesBuilder;
import static io.prestosql.SessionTestUtils.TEST_SESSION;
import static io.prestosql.block.BlockAssertions.toValues;
import static io.prestosql.metadata.MetadataManager.createTestMetadataManager;
import static io.prestosql.metadata.Signature.internalScalarFunction;
import static io.prestosql.operator.OperatorAssertion.toMaterializedResult;
import static io.prestosql.operator.PageAssertions.assertPageEquals;
import static io.prestosql.operator.project.PageProcessor.MAX_BATCH_SIZE;
import static io.prestosql.spi.function.OperatorType.EQUAL;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static io.prestosql.sql.relational.Expressions.call;
import static io.prestosql.sql.relational.Expressions.constant;
import static io.prestosql.sql.relational.Expressions.field;
import static io.prestosql.testing.TestingHandles.TEST_TABLE_HANDLE;
import static io.prestosql.testing.TestingTaskContext.createTaskContext;
import static io.prestosql.testing.assertions.Assert.assertEquals;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
public class TestScanFilterAndProjectOperator
extends AbstractTestFunctions
{
private final Metadata metadata = createTestMetadataManager();
private final ExpressionCompiler expressionCompiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0));
private ExecutorService executor;
private ScheduledExecutorService scheduledExecutor;
public TestScanFilterAndProjectOperator()
{
executor = newCachedThreadPool(daemonThreadsNamed("test-executor-%s"));
scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s"));
}
@Test
public void testPageSource()
{
final Page input = SequencePageBuilder.createSequencePage(ImmutableList.of(VARCHAR), 10_000, 0);
DriverContext driverContext = newDriverContext();
List<RowExpression> projections = ImmutableList.of(field(0, VARCHAR));
Supplier<CursorProcessor> cursorProcessor = expressionCompiler.compileCursorProcessor(Optional.empty(), projections, "key");
Supplier<PageProcessor> pageProcessor = expressionCompiler.compilePageProcessor(Optional.empty(), projections);
ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory factory = new ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory(
0,
new PlanNodeId("test"),
new PlanNodeId("0"),
(session, split, table, columns) -> new FixedPageSource(ImmutableList.of(input)),
cursorProcessor,
pageProcessor,
TEST_TABLE_HANDLE,
ImmutableList.of(),
ImmutableList.of(VARCHAR),
new DataSize(0, BYTE),
0);
SourceOperator operator = factory.createOperator(driverContext);
operator.addSplit(new Split(new CatalogName("test"), TestingSplit.createLocalSplit(), Lifespan.taskWide()));
operator.noMoreSplits();
MaterializedResult expected = toMaterializedResult(driverContext.getSession(), ImmutableList.of(VARCHAR), ImmutableList.of(input));
MaterializedResult actual = toMaterializedResult(driverContext.getSession(), ImmutableList.of(VARCHAR), toPages(operator));
assertEquals(actual.getRowCount(), expected.getRowCount());
assertEquals(actual, expected);
}
@Test
public void testPageSourceMergeOutput()
{
List<Page> input = rowPagesBuilder(BIGINT)
.addSequencePage(100, 0)
.addSequencePage(100, 0)
.addSequencePage(100, 0)
.addSequencePage(100, 0)
.build();
RowExpression filter = call(
Signature.internalOperator(EQUAL, BOOLEAN.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature(), BIGINT.getTypeSignature())),
BOOLEAN,
field(0, BIGINT),
constant(10L, BIGINT));
List<RowExpression> projections = ImmutableList.of(field(0, BIGINT));
Supplier<CursorProcessor> cursorProcessor = expressionCompiler.compileCursorProcessor(Optional.of(filter), projections, "key");
Supplier<PageProcessor> pageProcessor = expressionCompiler.compilePageProcessor(Optional.of(filter), projections);
ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory factory = new ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory(
0,
new PlanNodeId("test"),
new PlanNodeId("0"),
(session, split, table, columns) -> new FixedPageSource(input),
cursorProcessor,
pageProcessor,
TEST_TABLE_HANDLE,
ImmutableList.of(),
ImmutableList.of(BIGINT),
new DataSize(64, KILOBYTE),
2);
SourceOperator operator = factory.createOperator(newDriverContext());
operator.addSplit(new Split(new CatalogName("test"), TestingSplit.createLocalSplit(), Lifespan.taskWide()));
operator.noMoreSplits();
List<Page> actual = toPages(operator);
assertEquals(actual.size(), 1);
List<Page> expected = rowPagesBuilder(BIGINT)
.row(10L)
.row(10L)
.row(10L)
.row(10L)
.build();
assertPageEquals(ImmutableList.of(BIGINT), actual.get(0), expected.get(0));
}
@Test
public void testPageSourceLazyLoad()
{
Block inputBlock = BlockAssertions.createLongSequenceBlock(0, 100);
// If column 1 is loaded, test will fail
Page input = new Page(100, inputBlock, new LazyBlock(100, lazyBlock -> {
throw new AssertionError("Lazy block should not be loaded");
}));
DriverContext driverContext = newDriverContext();
List<RowExpression> projections = ImmutableList.of(field(0, VARCHAR));
Supplier<CursorProcessor> cursorProcessor = expressionCompiler.compileCursorProcessor(Optional.empty(), projections, "key");
PageProcessor pageProcessor = new PageProcessor(Optional.of(new SelectAllFilter()), ImmutableList.of(new LazyPagePageProjection()));
ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory factory = new ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory(
0,
new PlanNodeId("test"),
new PlanNodeId("0"),
(session, split, table, columns) -> new SinglePagePageSource(input),
cursorProcessor,
() -> pageProcessor,
TEST_TABLE_HANDLE,
ImmutableList.of(),
ImmutableList.of(BIGINT),
new DataSize(0, BYTE),
0);
SourceOperator operator = factory.createOperator(driverContext);
operator.addSplit(new Split(new CatalogName("test"), TestingSplit.createLocalSplit(), Lifespan.taskWide()));
operator.noMoreSplits();
MaterializedResult expected = toMaterializedResult(driverContext.getSession(), ImmutableList.of(BIGINT), ImmutableList.of(new Page(inputBlock)));
MaterializedResult actual = toMaterializedResult(driverContext.getSession(), ImmutableList.of(BIGINT), toPages(operator));
assertEquals(actual.getRowCount(), expected.getRowCount());
assertEquals(actual, expected);
}
@Test
public void testRecordCursorSource()
{
final Page input = SequencePageBuilder.createSequencePage(ImmutableList.of(VARCHAR), 10_000, 0);
DriverContext driverContext = newDriverContext();
List<RowExpression> projections = ImmutableList.of(field(0, VARCHAR));
Supplier<CursorProcessor> cursorProcessor = expressionCompiler.compileCursorProcessor(Optional.empty(), projections, "key");
Supplier<PageProcessor> pageProcessor = expressionCompiler.compilePageProcessor(Optional.empty(), projections);
ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory factory = new ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory(
0,
new PlanNodeId("test"),
new PlanNodeId("0"),
(session, split, table, columns) -> new RecordPageSource(new PageRecordSet(ImmutableList.of(VARCHAR), input)),
cursorProcessor,
pageProcessor,
TEST_TABLE_HANDLE,
ImmutableList.of(),
ImmutableList.of(VARCHAR),
new DataSize(0, BYTE),
0);
SourceOperator operator = factory.createOperator(driverContext);
operator.addSplit(new Split(new CatalogName("test"), TestingSplit.createLocalSplit(), Lifespan.taskWide()));
operator.noMoreSplits();
MaterializedResult expected = toMaterializedResult(driverContext.getSession(), ImmutableList.of(VARCHAR), ImmutableList.of(input));
MaterializedResult actual = toMaterializedResult(driverContext.getSession(), ImmutableList.of(VARCHAR), toPages(operator));
assertEquals(actual.getRowCount(), expected.getRowCount());
assertEquals(actual, expected);
}
@Test
public void testPageYield()
{
int totalRows = 1000;
Page input = SequencePageBuilder.createSequencePage(ImmutableList.of(BIGINT), totalRows, 1);
DriverContext driverContext = newDriverContext();
// 20 columns; each column is associated with a function that will force yield per projection
int totalColumns = 20;
ImmutableList.Builder<SqlScalarFunction> functions = ImmutableList.builder();
for (int i = 0; i < totalColumns; i++) {
functions.add(new GenericLongFunction("page_col" + i, value -> {
driverContext.getYieldSignal().forceYieldForTesting();
return value;
}));
}
Metadata metadata = functionAssertions.getMetadata();
metadata.addFunctions(functions.build());
// match each column with a projection
ExpressionCompiler expressionCompiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0));
ImmutableList.Builder<RowExpression> projections = ImmutableList.builder();
for (int i = 0; i < totalColumns; i++) {
projections.add(call(internalScalarFunction("generic_long_page_col" + i, BIGINT.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature())), BIGINT, field(0, BIGINT)));
}
Supplier<CursorProcessor> cursorProcessor = expressionCompiler.compileCursorProcessor(Optional.empty(), projections.build(), "key");
Supplier<PageProcessor> pageProcessor = expressionCompiler.compilePageProcessor(Optional.empty(), projections.build(), MAX_BATCH_SIZE);
ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory factory = new ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory(
0,
new PlanNodeId("test"),
new PlanNodeId("0"),
(session, split, table, columns) -> new FixedPageSource(ImmutableList.of(input)),
cursorProcessor,
pageProcessor,
TEST_TABLE_HANDLE,
ImmutableList.of(),
ImmutableList.of(BIGINT),
new DataSize(0, BYTE),
0);
SourceOperator operator = factory.createOperator(driverContext);
operator.addSplit(new Split(new CatalogName("test"), TestingSplit.createLocalSplit(), Lifespan.taskWide()));
operator.noMoreSplits();
// In the below loop we yield for every cell: 20 X 1000 times
// Currently we don't check for the yield signal in the generated projection loop, we only check for the yield signal
// in the PageProcessor.PositionsPageProcessorIterator::computeNext() method. Therefore, after 20 calls we will have
// exactly 20 blocks (one for each column) and the PageProcessor will be able to create a Page out of it.
for (int i = 1; i <= totalRows * totalColumns; i++) {
driverContext.getYieldSignal().setWithDelay(SECONDS.toNanos(1000), driverContext.getYieldExecutor());
Page page = operator.getOutput();
if (i == totalColumns) {
assertNotNull(page);
assertEquals(page.getPositionCount(), totalRows);
assertEquals(page.getChannelCount(), totalColumns);
for (int j = 0; j < totalColumns; j++) {
assertEquals(toValues(BIGINT, page.getBlock(j)), toValues(BIGINT, input.getBlock(0)));
}
}
else {
assertNull(page);
}
driverContext.getYieldSignal().reset();
}
}
@Test
public void testRecordCursorYield()
{
// create a generic long function that yields for projection on every row
// verify we will yield #row times totally
// create a table with 15 rows
int length = 15;
Page input = SequencePageBuilder.createSequencePage(ImmutableList.of(BIGINT), length, 0);
DriverContext driverContext = newDriverContext();
// set up generic long function with a callback to force yield
Metadata metadata = functionAssertions.getMetadata();
metadata.addFunctions(ImmutableList.of(new GenericLongFunction("record_cursor", value -> {
driverContext.getYieldSignal().forceYieldForTesting();
return value;
})));
ExpressionCompiler expressionCompiler = new ExpressionCompiler(metadata, new PageFunctionCompiler(metadata, 0));
List<RowExpression> projections = ImmutableList.of(call(
internalScalarFunction("generic_long_record_cursor", BIGINT.getTypeSignature(), ImmutableList.of(BIGINT.getTypeSignature())),
BIGINT,
field(0, BIGINT)));
Supplier<CursorProcessor> cursorProcessor = expressionCompiler.compileCursorProcessor(Optional.empty(), projections, "key");
Supplier<PageProcessor> pageProcessor = expressionCompiler.compilePageProcessor(Optional.empty(), projections);
ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory factory = new ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory(
0,
new PlanNodeId("test"),
new PlanNodeId("0"),
(session, split, table, columns) -> new RecordPageSource(new PageRecordSet(ImmutableList.of(BIGINT), input)),
cursorProcessor,
pageProcessor,
TEST_TABLE_HANDLE,
ImmutableList.of(),
ImmutableList.of(BIGINT),
new DataSize(0, BYTE),
0);
SourceOperator operator = factory.createOperator(driverContext);
operator.addSplit(new Split(new CatalogName("test"), TestingSplit.createLocalSplit(), Lifespan.taskWide()));
operator.noMoreSplits();
// start driver; get null value due to yield for the first 15 times
for (int i = 0; i < length; i++) {
driverContext.getYieldSignal().setWithDelay(SECONDS.toNanos(1000), driverContext.getYieldExecutor());
assertNull(operator.getOutput());
driverContext.getYieldSignal().reset();
}
// the 16th yield is not going to prevent the operator from producing a page
driverContext.getYieldSignal().setWithDelay(SECONDS.toNanos(1000), driverContext.getYieldExecutor());
Page output = operator.getOutput();
driverContext.getYieldSignal().reset();
assertNotNull(output);
assertEquals(toValues(BIGINT, output.getBlock(0)), toValues(BIGINT, input.getBlock(0)));
}
private static List<Page> toPages(Operator operator)
{
ImmutableList.Builder<Page> outputPages = ImmutableList.builder();
// read output until input is needed or operator is finished
int nullPages = 0;
while (!operator.isFinished()) {
Page outputPage = operator.getOutput();
if (outputPage == null) {
// break infinite loop due to null pages
assertTrue(nullPages < 1_000_000, "Too many null pages; infinite loop?");
nullPages++;
}
else {
outputPages.add(outputPage);
nullPages = 0;
}
}
return outputPages.build();
}
private DriverContext newDriverContext()
{
return createTaskContext(executor, scheduledExecutor, TEST_SESSION)
.addPipelineContext(0, true, true, false)
.addDriverContext();
}
public static class SinglePagePageSource
implements ConnectorPageSource
{
private Page page;
public SinglePagePageSource(Page page)
{
this.page = page;
}
@Override
public void close()
{
page = null;
}
@Override
public long getCompletedBytes()
{
return 0;
}
@Override
public long getReadTimeNanos()
{
return 0;
}
@Override
public long getSystemMemoryUsage()
{
return 0;
}
@Override
public boolean isFinished()
{
return page == null;
}
@Override
public Page getNextPage()
{
Page page = this.page;
this.page = null;
return page;
}
}
}
| apache-2.0 |
GoogleCloudPlatform/k8s-cluster-bundle | examples/templatebuilder/bazel_init_test.go | 768 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package templatebuilder_test
import (
"github.com/GoogleCloudPlatform/k8s-cluster-bundle/pkg/testutil"
)
func init() {
testutil.ChangeToBazelDir("examples/templatebuilder")
}
| apache-2.0 |
sasaingit/ice-framework-testapp | ext/modules/dashboard/index.php | 1864 | <?php
/*
This file is part of iCE Hrm.
iCE Hrm is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
iCE Hrm 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 iCE Hrm. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------
Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd]
Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah)
*/
$moduleName = 'dashboard';
define('MODULE_PATH',dirname(__FILE__));
include APP_BASE_PATH.'header.php';
include APP_BASE_PATH.'modulejslibs.inc.php';
?><div class="span9">
<div class="row">
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-green">
<div class="inner">
<h3 >Last login</h3>
<p id="lastLoginTime">
</p>
</div>
<div class="icon">
<i class="ion ion-calendar"></i>
</div>
<a href="#" class="small-box-footer" id="profileLink">
Goto Profile <i class="fa fa-arrow-circle-right"></i>
</a>
</div>
</div><!-- ./col -->
</div>
</div>
<script>
var modJsList = new Array();
modJsList['tabDashboard'] = new DashboardAdapter('Dashboard','Dashboard');
var modJs = modJsList['tabDashboard'];
$("#profileLink").attr("href",modJs.getCustomUrl('?g=modules&n=profile'));
modJs.getLastLogin();
</script>
<?php include APP_BASE_PATH.'footer.php';?> | apache-2.0 |
adamkewley/jobson | jobson/src/main/java/com/github/jobson/scripting/functions/ToJSONFunction.java | 1283 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.jobson.scripting.functions;
import com.github.jobson.scripting.FreeFunction;
import static com.github.jobson.Helpers.toJSON;
import static java.lang.String.format;
public final class ToJSONFunction implements FreeFunction {
@Override
public Object call(Object... args) {
if (args.length != 1)
throw new RuntimeException(format("toJSON called with %s args (expects 1)", args.length));
return toJSON(args[0]);
}
}
| apache-2.0 |
jjlopezm/AkkaEncrypt | Client/src/main/scala/com/juanjo/akka/encrypt/Client.scala | 1202 | package com.juanjo.akka.encrypt
import akka.actor.ActorSystem
import akka.contrib.pattern.ClusterClient
import com.juanjo.akka.encrypt.common.domain.SecureMessage
import com.juanjo.akka.encrypt.config.ClientConfig
import com.typesafe.config.ConfigValue
import org.apache.log4j.Logger
import scala.collection.JavaConversions._
import scala.language.postfixOps
object Client extends ClientConfig {
override lazy val logger = Logger.getLogger(getClass)
def apply() = new Client()
}
class Client(properties: java.util.Map[String, ConfigValue]) {
def this() = this(Map.empty[String, ConfigValue])
def initClient(): Unit = {
lazy val logger = Client.logger
val finalConfig = properties.foldLeft(Client.config) { case (previousConfig, keyValue) =>
previousConfig.withValue(keyValue._1, keyValue._2)
}
val system = ActorSystem("SecureCluster", finalConfig)
if (logger.isDebugEnabled) {
system.logConfiguration()
}
val serverNode = s"${Client.config.getStringList(ClientConfig.ServerNode)(0)}/user/server"
val serverActor = system.actorSelection(serverNode)
//message to server
serverActor ! SecureMessage("Is this message secure?")
}
} | apache-2.0 |
sequenceiq/cloudbreak | core/src/main/java/com/sequenceiq/cloudbreak/controller/mapper/DuplicatedKeyValueExceptionMapper.java | 923 | package com.sequenceiq.cloudbreak.controller.mapper;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import com.sequenceiq.cloudbreak.controller.json.ExceptionResult;
import com.sequenceiq.cloudbreak.service.DuplicateKeyValueException;
@Provider
public class DuplicatedKeyValueExceptionMapper extends BaseExceptionMapper<DuplicateKeyValueException> {
@Override
protected Object getEntity(DuplicateKeyValueException exception) {
return new ExceptionResult(errorMessage(exception));
}
@Override
Response.Status getResponseStatus() {
return Response.Status.CONFLICT;
}
public static String errorMessage(DuplicateKeyValueException exception) {
return String.format("The %s name '%s' is already taken, please choose a different one",
exception.getResourceType().toString().toLowerCase(),
exception.getValue());
}
}
| apache-2.0 |
yanzhijun/jclouds-aliyun | providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/functions/PublicUriForObjectInfo.java | 2632 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.hpcloud.objectstorage.blobstore.functions;
import static org.jclouds.http.Uris.uriBuilder;
import java.net.URI;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.openstack.swift.domain.ObjectInfo;
import com.google.common.base.Function;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
@Singleton
public class PublicUriForObjectInfo implements Function<ObjectInfo, URI> {
private final LoadingCache<String, URI> cdnContainer;
@Inject
public PublicUriForObjectInfo(LoadingCache<String, URI> cdnContainer) {
this.cdnContainer = cdnContainer;
}
private static final URI NEGATIVE_ENTRY = URI.create("http://127.0.0.1");
public URI apply(ObjectInfo from) {
if (from == null)
return null;
String containerName = from.getContainer();
if (containerName == null)
return null;
try {
URI uri = cdnContainer.getUnchecked(containerName);
if (uri == NEGATIVE_ENTRY) { // intentionally use reference equality
// TODO: GetCDNMetadata.load returns null on failure cases. We use
// a negative entry to avoid repeatedly issuing failed CDN queries.
// The LoadingCache removes this value after its normal expiry.
return null;
}
return uriBuilder(uri).clearQuery().appendPath(from.getName()).build();
} catch (CacheLoader.InvalidCacheLoadException e) {
// nulls not permitted from cache loader
cdnContainer.put(containerName, NEGATIVE_ENTRY);
return null;
} catch (NullPointerException e) {
// nulls not permitted from cache loader
// TODO this shouldn't occur when the above exception is reliably presented
return null;
}
}
}
| apache-2.0 |
brettryan/jdk8-lambda-samples | src/main/java/com/drunkendev/lambdas/xml/LocalDateTimeAdapter.java | 1237 | /*
* LocalDateTimeAdapter.java Feb 2 2014, 02:48
*
* Copyright 2014 Drunken Dev.
*
* 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.drunkendev.lambdas.xml;
import java.time.LocalDateTime;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
*
* @author Brett Ryan
*/
public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
@Override
public String marshal(LocalDateTime value) throws Exception {
if (value != null) {
return value.toString();
}
return null;
}
@Override
public LocalDateTime unmarshal(String s) throws Exception {
return s == null || s.length() == 0 ? null : LocalDateTime.parse(s);
}
}
| apache-2.0 |
trappar/minecraft-cookbook | recipes/directories.rb | 404 | directory node['minecraft']['install_dir'] do
recursive true
user node['minecraft']['user']
group node['minecraft']['group']
end
directory "#{node['minecraft']['install_dir']}/minecraft-init" do
user node['minecraft']['user']
group node['minecraft']['group']
end
directory "#{node['minecraft']['install_dir']}/worlds" do
user node['minecraft']['user']
group node['minecraft']['group']
end | apache-2.0 |
tadayosi/camel | core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SecretsManagerEndpointBuilderFactory.java | 19637 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
/**
* Manage AWS Secrets Manager services using AWS SDK version 2.x.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface SecretsManagerEndpointBuilderFactory {
/**
* Builder for endpoint for the AWS Secrets Manager component.
*/
public interface SecretsManagerEndpointBuilder
extends
EndpointProducerBuilder {
/**
* Set if the secret is binary or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param binaryPayload the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder binaryPayload(
boolean binaryPayload) {
doSetProperty("binaryPayload", binaryPayload);
return this;
}
/**
* Set if the secret is binary or not.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param binaryPayload the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder binaryPayload(String binaryPayload) {
doSetProperty("binaryPayload", binaryPayload);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The operation to perform.
*
* The option is a:
* <code>org.apache.camel.component.aws.secretsmanager.SecretsManagerOperations</code> type.
*
* Required: true
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder operation(
SecretsManagerOperations operation) {
doSetProperty("operation", operation);
return this;
}
/**
* The operation to perform.
*
* The option will be converted to a
* <code>org.apache.camel.component.aws.secretsmanager.SecretsManagerOperations</code> type.
*
* Required: true
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder operation(String operation) {
doSetProperty("operation", operation);
return this;
}
/**
* Set the need for overidding the endpoint. This option needs to be
* used in combination with uriEndpointOverride option.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param overrideEndpoint the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder overrideEndpoint(
boolean overrideEndpoint) {
doSetProperty("overrideEndpoint", overrideEndpoint);
return this;
}
/**
* Set the need for overidding the endpoint. This option needs to be
* used in combination with uriEndpointOverride option.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param overrideEndpoint the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder overrideEndpoint(
String overrideEndpoint) {
doSetProperty("overrideEndpoint", overrideEndpoint);
return this;
}
/**
* If we want to use a POJO request as body or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param pojoRequest the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder pojoRequest(boolean pojoRequest) {
doSetProperty("pojoRequest", pojoRequest);
return this;
}
/**
* If we want to use a POJO request as body or not.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param pojoRequest the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder pojoRequest(String pojoRequest) {
doSetProperty("pojoRequest", pojoRequest);
return this;
}
/**
* To define a proxy host when instantiating the Secrets Manager client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param proxyHost the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder proxyHost(String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* To define a proxy port when instantiating the Secrets Manager client.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: producer
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder proxyPort(Integer proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy port when instantiating the Secrets Manager client.
*
* The option will be converted to a
* <code>java.lang.Integer</code> type.
*
* Group: producer
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder proxyPort(String proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy protocol when instantiating the Secrets Manager
* client.
*
* The option is a:
* <code>software.amazon.awssdk.core.Protocol</code> type.
*
* Default: HTTPS
* Group: producer
*
* @param proxyProtocol the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder proxyProtocol(
Protocol proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* To define a proxy protocol when instantiating the Secrets Manager
* client.
*
* The option will be converted to a
* <code>software.amazon.awssdk.core.Protocol</code> type.
*
* Default: HTTPS
* Group: producer
*
* @param proxyProtocol the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder proxyProtocol(String proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* The region in which Secrets Manager client needs to work. When using
* this parameter, the configuration will expect the lowercase name of
* the region (for example ap-east-1) You'll need to use the name
* Region.EU_WEST_1.id().
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param region the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder region(String region) {
doSetProperty("region", region);
return this;
}
/**
* To use a existing configured AWS Secrets Manager as client.
*
* The option is a:
* <code>software.amazon.awssdk.services.secretsmanager.SecretsManagerClient</code> type.
*
* Group: producer
*
* @param secretsManagerClient the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder secretsManagerClient(
Object secretsManagerClient) {
doSetProperty("secretsManagerClient", secretsManagerClient);
return this;
}
/**
* To use a existing configured AWS Secrets Manager as client.
*
* The option will be converted to a
* <code>software.amazon.awssdk.services.secretsmanager.SecretsManagerClient</code> type.
*
* Group: producer
*
* @param secretsManagerClient the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder secretsManagerClient(
String secretsManagerClient) {
doSetProperty("secretsManagerClient", secretsManagerClient);
return this;
}
/**
* If we want to trust all certificates in case of overriding the
* endpoint.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param trustAllCertificates the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder trustAllCertificates(
boolean trustAllCertificates) {
doSetProperty("trustAllCertificates", trustAllCertificates);
return this;
}
/**
* If we want to trust all certificates in case of overriding the
* endpoint.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param trustAllCertificates the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder trustAllCertificates(
String trustAllCertificates) {
doSetProperty("trustAllCertificates", trustAllCertificates);
return this;
}
/**
* Set the overriding uri endpoint. This option needs to be used in
* combination with overrideEndpoint option.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param uriEndpointOverride the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder uriEndpointOverride(
String uriEndpointOverride) {
doSetProperty("uriEndpointOverride", uriEndpointOverride);
return this;
}
/**
* Set whether the Translate client should expect to load credentials
* through a default credentials provider or to expect static
* credentials to be passed in.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param useDefaultCredentialsProvider the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder useDefaultCredentialsProvider(
boolean useDefaultCredentialsProvider) {
doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider);
return this;
}
/**
* Set whether the Translate client should expect to load credentials
* through a default credentials provider or to expect static
* credentials to be passed in.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param useDefaultCredentialsProvider the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder useDefaultCredentialsProvider(
String useDefaultCredentialsProvider) {
doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider);
return this;
}
/**
* Amazon AWS Access Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessKey the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder accessKey(String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* Amazon AWS Secret Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param secretKey the value to set
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder secretKey(String secretKey) {
doSetProperty("secretKey", secretKey);
return this;
}
}
/**
* Proxy enum for
* <code>org.apache.camel.component.aws.secretsmanager.SecretsManagerOperations</code> enum.
*/
enum SecretsManagerOperations {
listSecrets,
createSecret,
getSecret,
describeSecret,
deleteSecret,
rotateSecret,
updateSecret,
restoreSecret,
replicateSecretToRegions;
}
/**
* Proxy enum for <code>software.amazon.awssdk.core.Protocol</code> enum.
*/
enum Protocol {
HTTP,
HTTPS;
}
public interface SecretsManagerBuilders {
/**
* AWS Secrets Manager (camel-aws-secrets-manager)
* Manage AWS Secrets Manager services using AWS SDK version 2.x.
*
* Category: cloud,management
* Since: 3.9
* Maven coordinates: org.apache.camel:camel-aws-secrets-manager
*
* Syntax: <code>aws-secrets-manager://label</code>
*
* Path parameter: label (required)
* Logical name
*
* @param path //label
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder awsSecretsManager(String path) {
return SecretsManagerEndpointBuilderFactory.endpointBuilder("aws-secrets-manager", path);
}
/**
* AWS Secrets Manager (camel-aws-secrets-manager)
* Manage AWS Secrets Manager services using AWS SDK version 2.x.
*
* Category: cloud,management
* Since: 3.9
* Maven coordinates: org.apache.camel:camel-aws-secrets-manager
*
* Syntax: <code>aws-secrets-manager://label</code>
*
* Path parameter: label (required)
* Logical name
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path //label
* @return the dsl builder
*/
default SecretsManagerEndpointBuilder awsSecretsManager(
String componentName,
String path) {
return SecretsManagerEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static SecretsManagerEndpointBuilder endpointBuilder(
String componentName,
String path) {
class SecretsManagerEndpointBuilderImpl extends AbstractEndpointBuilder implements SecretsManagerEndpointBuilder {
public SecretsManagerEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new SecretsManagerEndpointBuilderImpl(path);
}
} | apache-2.0 |
eval1749/elang | elang/lir/instruction_visitor.cc | 559 | // Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elang/lir/instruction_visitor.h"
namespace elang {
namespace lir {
//////////////////////////////////////////////////////////////////////
//
// InstructionVisitor
//
InstructionVisitor::InstructionVisitor() {
}
InstructionVisitor::~InstructionVisitor() {
}
void InstructionVisitor::DoDefaultVisit(Instruction* instr) {
DCHECK(instr);
}
} // namespace lir
} // namespace elang
| apache-2.0 |
stdlib-js/stdlib | lib/node_modules/@stdlib/stats/incr/msummary/docs/types/index.d.ts | 3077 | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TypeScript Version: 2.0
/// <reference types="@stdlib/types"/>
interface Summary {
/**
* Window size.
*/
window: number;
/**
* Maximum value.
*/
max: number;
/**
* Minimum value.
*/
min: number;
/**
* Range.
*/
range: number;
/**
* Mid-range.
*/
midrange: number;
/**
* Sum.
*/
sum: number;
/**
* Arithmetic mean.
*/
mean: number;
/**
* Unbiased sample variance.
*/
variance: number;
/**
* Corrected sample standard deviation.
*/
stdev: number;
/**
* Corrected sample skewness.
*/
skewness: number;
/**
* Corrected sample excess kurtosis.
*/
kurtosis: number;
}
/**
* If provided a value, the accumulator function returns an updated summary; otherwise, the accumulator function returns the current summary.
*
* ## Notes
*
* - The returned summary is an object containing the following fields:
*
* - window: window size.
* - max: maximum value.
* - min: minimum value.
* - range: range.
* - midrange: mid-range.
* - sum: sum.
* - mean: arithmetic mean.
* - variance: unbiased sample variance.
* - stdev: corrected sample standard deviation.
* - skewness: corrected sample skewness.
* - kurtosis: corrected sample excess kurtosis.
*
*
* @param x - value
* @returns updated summary
*/
type accumulator = ( x?: number ) => Summary | null;
/**
* Returns an accumulator function which incrementally computes a moving statistical summary.
*
* ## Notes
*
* - The `W` parameter defines the number of values over which to compute the moving statistical summary.
* - If provided a value, the accumulator function returns an updated moving statistical summary. If not provided a value, the accumulator function returns the current moving statistical summary.
* - As `W` values are needed to fill the window buffer, the first `W-1` returned summaries are calculated from smaller sample sizes. Until the window is full, each returned summary is calculated from all provided values.
*
* @param W - window size
* @throws must provide a positive integer
* @returns accumulator function
*
* @example
* var accumulator = incrmsummary( 3 );
*
* var summary = accumulator();
* // returns {}
*
* summary = accumulator( 2.0 );
* // returns {...}
*
* summary = accumulator( -5.0 );
* // returns {...}
*
* summary = accumulator();
* // returns {...}
*/
declare function incrmsummary( W: number ): accumulator;
// EXPORTS //
export = incrmsummary;
| apache-2.0 |
SilentScope/mq-visualizer | src/mq-visualizer-model/src/main/java/com/mqvisualizer/model/destination/JmsQueue.java | 895 | package com.mqvisualizer.model.destination;
import javax.jms.JMSException;
import javax.jms.Queue;
/**
* Created by Mykolas on 2014-09-19.
*/
public class JmsQueue extends JmsDestination implements Queue {
private String queueName;
private Queue originalQueue;
public JmsQueue() {
}
public JmsQueue(Queue queue) {
try {
this.queueName = queue.getQueueName();
this.originalQueue = queue;
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
public JmsQueue(String queueName) {
this.queueName = queueName;
}
@Override
public String getQueueName() throws JMSException {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public Queue getOriginalQueue() {
return originalQueue;
}
}
| apache-2.0 |
nextsmsversion/macchina.io | platform/RemotingNG/src/EventDispatcher.cpp | 2680 | //
// EventDispatcher.cpp
//
// $Id: //poco/1.7/RemotingNG/src/EventDispatcher.cpp#3 $
//
// Library: RemotingNG
// Package: ORB
// Module: EventDispatcher
//
// Copyright (c) 2006-2014, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "Poco/RemotingNG/EventDispatcher.h"
#include "Poco/RemotingNG/TransportFactoryManager.h"
#include "Poco/Exception.h"
namespace Poco {
namespace RemotingNG {
EventDispatcher::EventDispatcher(const std::string& protocol):
_protocol(protocol)
{
}
EventDispatcher::~EventDispatcher()
{
}
void EventDispatcher::subscribe(const std::string& subscriberURI, const std::string& endpointURI, Poco::Clock expireTime)
{
Poco::FastMutex::ScopedLock lock(_mutex);
SubscriberMap::iterator it = _subscribers.find(subscriberURI);
if (it == _subscribers.end())
{
SubscriberInfo::Ptr pInfo = new SubscriberInfo;
pInfo->endpoint = endpointURI;
pInfo->expireTime = expireTime;
_subscribers[subscriberURI] = pInfo;
}
else
{
it->second->expireTime = expireTime;
}
}
void EventDispatcher::unsubscribe(const std::string& subscriberURI)
{
Poco::FastMutex::ScopedLock lock(_mutex);
SubscriberMap::iterator it = _subscribers.find(subscriberURI);
if (it != _subscribers.end())
{
_subscribers.erase(it);
}
else throw Poco::NotFoundException("event subscriber", subscriberURI);
}
void EventDispatcher::setEventFilterImpl(const std::string& subscriberURI, const std::string& event, const Poco::Any& filter)
{
Poco::FastMutex::ScopedLock lock(_mutex);
SubscriberMap::iterator it = _subscribers.find(subscriberURI);
if (it != _subscribers.end())
{
it->second->filters[event] = filter;
}
else throw Poco::NotFoundException("event subscriber", subscriberURI);
}
void EventDispatcher::removeEventFilter(const std::string& subscriberURI, const std::string& event)
{
Poco::FastMutex::ScopedLock lock(_mutex);
SubscriberMap::iterator it = _subscribers.find(subscriberURI);
if (it != _subscribers.end())
{
it->second->filters.erase(event);
}
}
Transport& EventDispatcher::transportForSubscriber(const std::string& subscriberURI)
{
// Note: the mutex will have already been locked by the caller
static TransportFactoryManager& tfm = TransportFactoryManager::instance();
SubscriberMap::iterator it = _subscribers.find(subscriberURI);
if (it != _subscribers.end())
{
if (!it->second->pTransport)
{
it->second->pTransport = tfm.createTransport(_protocol, it->second->endpoint);
}
return *it->second->pTransport;
}
else throw Poco::NotFoundException("event subscriber", subscriberURI);
}
} } // namespace Poco::RemotingNG
| apache-2.0 |
tempbottle/jsimpledb | src/java/org/jsimpledb/kv/raft/msg/RequestVote.java | 2625 |
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package org.jsimpledb.kv.raft.msg;
import com.google.common.base.Preconditions;
import java.nio.ByteBuffer;
import org.jsimpledb.util.LongEncoder;
/**
* Send from candidates to other nodes to request a vote during an election.
*/
public class RequestVote extends Message {
private final long lastLogTerm;
private final long lastLogIndex;
// Constructors
/**
* Constructor.
*
* @param clusterId cluster ID
* @param senderId identity of sender
* @param recipientId identity of recipient
* @param term sender's current term
* @param lastLogTerm term of the sender's last log entry
* @param lastLogIndex index of the sender's last log entry
*/
public RequestVote(int clusterId, String senderId, String recipientId, long term, long lastLogTerm, long lastLogIndex) {
super(Message.REQUEST_VOTE_TYPE, clusterId, senderId, recipientId, term);
this.lastLogTerm = lastLogTerm;
this.lastLogIndex = lastLogIndex;
this.checkArguments();
}
RequestVote(ByteBuffer buf) {
super(Message.REQUEST_VOTE_TYPE, buf);
this.lastLogTerm = LongEncoder.read(buf);
this.lastLogIndex = LongEncoder.read(buf);
this.checkArguments();
}
@Override
void checkArguments() {
super.checkArguments();
Preconditions.checkArgument(this.lastLogTerm > 0);
Preconditions.checkArgument(this.lastLogIndex > 0);
}
// Properties
public long getLastLogTerm() {
return this.lastLogTerm;
}
public long getLastLogIndex() {
return this.lastLogIndex;
}
// Message
@Override
public void visit(MessageSwitch handler) {
handler.caseRequestVote(this);
}
@Override
public void writeTo(ByteBuffer dest) {
super.writeTo(dest);
LongEncoder.write(dest, this.lastLogTerm);
LongEncoder.write(dest, this.lastLogIndex);
}
@Override
protected int calculateSize() {
return super.calculateSize()
+ LongEncoder.encodeLength(this.lastLogTerm)
+ LongEncoder.encodeLength(this.lastLogIndex);
}
// Object
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[\"" + this.getSenderId() + "\"->\"" + this.getRecipientId() + "\""
+ ",clusterId=" + String.format("%08x", this.getClusterId())
+ ",term=" + this.getTerm()
+ ",lastLogTerm=" + this.lastLogTerm
+ ",lastLogIndex=" + this.lastLogIndex
+ "]";
}
}
| apache-2.0 |
gerrit-review/gerrit | java/com/google/gerrit/pgm/util/RuntimeShutdown.java | 3015 | // Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.pgm.util;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RuntimeShutdown {
private static final ShutdownCallback cb = new ShutdownCallback();
/** Add a task to be performed when graceful shutdown is requested. */
public static void add(Runnable task) {
if (!cb.add(task)) {
// If the shutdown has already begun we cannot enqueue a new
// task. Instead trigger the task in the caller, without any
// of our locks held.
//
task.run();
}
}
/** Wait for the JVM shutdown to occur. */
public static void waitFor() {
cb.waitForShutdown();
}
public static void manualShutdown() {
cb.manualShutdown();
}
private RuntimeShutdown() {}
private static class ShutdownCallback extends Thread {
private static final Logger log = LoggerFactory.getLogger(ShutdownCallback.class);
private final List<Runnable> tasks = new ArrayList<>();
private boolean shutdownStarted;
private boolean shutdownComplete;
ShutdownCallback() {
setName("ShutdownCallback");
}
boolean add(Runnable newTask) {
synchronized (this) {
if (!shutdownStarted && !shutdownComplete) {
if (tasks.isEmpty()) {
Runtime.getRuntime().addShutdownHook(this);
}
tasks.add(newTask);
return true;
}
// We don't permit adding a task once shutdown has started.
//
return false;
}
}
@Override
public void run() {
log.debug("Graceful shutdown requested");
List<Runnable> taskList;
synchronized (this) {
shutdownStarted = true;
taskList = tasks;
}
for (Runnable task : taskList) {
try {
task.run();
} catch (Exception err) {
log.error("Cleanup task failed", err);
}
}
log.debug("Shutdown complete");
synchronized (this) {
shutdownComplete = true;
notifyAll();
}
}
void manualShutdown() {
Runtime.getRuntime().removeShutdownHook(this);
run();
}
void waitForShutdown() {
synchronized (this) {
while (!shutdownComplete) {
try {
wait();
} catch (InterruptedException e) {
return;
}
}
}
}
}
}
| apache-2.0 |
toby1984/raycast | src/main/java/de/codesourcery/raycast/TileId.java | 1144 | /**
* Copyright 2014 Tobias Gierke <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.codesourcery.raycast;
public final class TileId {
public final int x;
public final int y;
public TileId(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return 31 * (31 + x) + y;
}
@Override
public boolean equals(Object obj)
{
if ( obj instanceof TileId ) {
TileId other = (TileId ) obj;
return other.x == this.x && other.y == this.y;
}
return false;
}
@Override
public String toString() {
return "TileId[x=" + x + ", y=" + y + "]";
}
} | apache-2.0 |
tomatobang/tomato-server | app/model/asset.js | 663 | 'use strict';
module.exports = app => {
/**
* 资产
*/
const mongoose = app.mongoose;
const ObjectId = mongoose.Schema.ObjectId;
const asset = new mongoose.Schema({
// 用户编号
userid: { type: ObjectId, ref: 'user' },
// 名称
name: { type: String, default: '' },
// 数目
amount: { type: Number, default: 0 },
// 备注
note: { type: String, default: '' },
// 时间
create_at: { type: Date, default: Date.now },
// 是否已删除
deleted: { type: Boolean, default: false },
});
return mongoose.model('asset', asset);
};
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/transform/GetRoleResultStaxUnmarshaller.java | 2375 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.identitymanagement.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.identitymanagement.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* GetRoleResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetRoleResultStaxUnmarshaller implements Unmarshaller<GetRoleResult, StaxUnmarshallerContext> {
public GetRoleResult unmarshall(StaxUnmarshallerContext context) throws Exception {
GetRoleResult getRoleResult = new GetRoleResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return getRoleResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("Role", targetDepth)) {
getRoleResult.setRole(RoleStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return getRoleResult;
}
}
}
}
private static GetRoleResultStaxUnmarshaller instance;
public static GetRoleResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new GetRoleResultStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
lantanagroup/trifolia | Trifolia.Web/TrifoliaJsonValueProviderFactory.cs | 3132 | using System;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Globalization;
namespace Trifolia.Web
{
public sealed class TrifoliaJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = 2147483647;
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object jsonData = GetDeserializedObject(controllerContext);
if (jsonData == null)
{
return null;
}
Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
AddToBackingStore(backingStore, String.Empty, jsonData);
return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
}
}
} | apache-2.0 |
Inari-Soft/inari-firefly | src/main/java/com/inari/firefly/physics/movement/EulerIntegration.java | 2125 | package com.inari.firefly.physics.movement;
import com.inari.firefly.graphics.ETransform;
public final class EulerIntegration implements Integrator {
private float gravity = 9.8f;
private float shift = (float) Math.pow( 10, 0 );
private int scale = -1;
public final float getGravity() {
return gravity;
}
public final void setGravity( float gravity ) {
this.gravity = gravity;
}
public final int getScale() {
return scale;
}
public final void setScale( int scale ) {
this.scale = scale;
shift = ( scale < 0 )?
(float) Math.pow( 10, 0 ) :
(float) Math.pow( 10, scale );
}
@Override
public final void integrate( final EMovement movement, final ETransform transform, final float deltaTimeInSeconds ) {
gravityIntegration( movement );
movement.setVelocityX( movement.getVelocityX() + movement.getAccelerationX() * deltaTimeInSeconds );
movement.setVelocityY( movement.getVelocityY() + movement.getAccelerationY() * deltaTimeInSeconds );
}
@Override
public final void step( final EMovement movement, final ETransform transform, final float deltaTimeInSeconds ) {
transform.move(
Math.round( movement.getVelocityX() * deltaTimeInSeconds * shift ) / shift,
Math.round( movement.getVelocityY() * deltaTimeInSeconds * shift ) / shift
);
}
private void gravityIntegration( final EMovement movement ) {
if ( movement.onGround ) {
movement.setVelocityY( 0f );
movement.setAccelerationY( 0f );
} else {
final float maxGravityVelocity = movement.getMaxGravityVelocity();
final float massFactor = movement.getMassFactor();
if ( movement.getVelocityY() >= maxGravityVelocity ) {
movement.setAccelerationY( 0f );
movement.setVelocityY( maxGravityVelocity );
return;
}
movement.setAccelerationY( gravity * ( movement.mass * massFactor ) );
}
}
}
| apache-2.0 |
RcKeller/STF-Refresh | app/views/STF/Voting/Panels/Endorsements/Endorsements.js | 1760 | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Collapse } from 'antd'
const Panel = Collapse.Panel
import { makeManifestByID } from '../../../../../selectors'
import { Loading } from '../../../../../components'
/*
ENDORSEMENTS PANEL:
Renders a summary of student endorsements
*/
@connect(
// Might seem counterintuitive, but we're connecting to a manifest and pulling its proposal data.
(state, props) => {
const manifest = makeManifestByID(props.id)(state)
const { proposal: { comments } } = manifest
return {
manifest,
comments,
screen: state.screen
}
}
)
class Endorsements extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
manifest: PropTypes.object,
comments: PropTypes.array,
user: PropTypes.object
}
render (
{ screen, manifest, comments } = this.props
) {
return (
<section>
<Loading render={manifest} title='Voting Panel'>
<div>
{comments && comments.length > 0
? <Collapse bordered={false}
defaultActiveKey={Object.keys(comments)}
>
{comments.map((c, i) => (
<Panel key={i}
header={<b>{c.user.name || 'Endorsement'}</b>}
extra={c.user.netID || ''}
>
<p>{c.body}</p>
</Panel>
))}
</Collapse>
: <p><i>No endorsements available.</i></p>
}
</div>
</Loading>
</section>
)
}
}
export default Endorsements
| apache-2.0 |
Mainflux/mainflux-lite | twins/doc.go | 513 | // Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
// Package twins contains the domain concept definitions needed to support
// Mainflux twins service functionality. Twin is a semantic representation
// of a real world entity, be it device, application or something else.
// It holds the sequence of attribute based definitions of a real world
// thing and refers to the time series of definition based states that
// hold the historical data about the represented real world thing.
package twins
| apache-2.0 |
Top-Q/jsystem | jsystem-core-projects/jsystemApp/src/main/java/jsystem/treeui/params/AgentsSelectionDialog.java | 7346 | /*
* Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved.
*/
package jsystem.treeui.params;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import jsystem.runner.agent.clients.JSystemAgentClient;
import jsystem.runner.agent.server.RunnerEngine.ConnectionState;
import jsystem.treeui.actionItems.IgnisAction;
import jsystem.treeui.client.JSystemAgentClientsPool;
import jsystem.treeui.images.ImageCenter;
import jsystem.utils.StringUtils;
/**
* Agents chooser for the parameters panel.
*
* @author goland
*/
public class AgentsSelectionDialog extends JDialog {
private static final ImageIcon OKAY = ImageCenter.getInstance().getImage(ImageCenter.ICON_REMOTEAGENT_OK);
private static final ImageIcon ERROR = ImageCenter.getInstance().getImage(ImageCenter.ICON_REMOTEAGENT_PROBLEM);
private static final long serialVersionUID = 1L;
private AgentSelectTableModel agentsListTableModel;
private JTable table;
private Set<String> selectedUrlsSet;
private boolean isOkay = false;
public static void showAgentsDialog(String[] selectedUrls) throws Exception {
AgentsSelectionDialog dialog = new AgentsSelectionDialog();
dialog.initDialog(selectedUrls);
}
public void initDialog(String[] selectedUrls) throws Exception {
setTitle("Select Agents");
((Frame) this.getOwner()).setIconImage(ImageCenter.getInstance().getAwtImage(ImageCenter.ICON_JSYSTEM));
setModalityType(ModalityType.APPLICATION_MODAL);
selectedUrlsSet = StringUtils.stringArrayToSet(selectedUrls);
JPanel mainPanel = new JPanel(new BorderLayout());
buildAgentsListTableModel();
table = new JTable(agentsListTableModel);
table.setRowSelectionAllowed(false);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(30);
table.getColumnModel().getColumn(2).setPreferredWidth(300);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane tablescroll = new JScrollPane(table);
mainPanel.add(tablescroll, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(new JButton(new SaveAction(this)));
buttonsPanel.add(new JButton(new CloseAction(this)));
JButton selectUnSelect = new JButton(new SelectUnSelectAction(table));
selectUnSelect.setPreferredSize(new Dimension(120, selectUnSelect.getPreferredSize().height));
buttonsPanel.add(selectUnSelect);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
setContentPane(mainPanel);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setLocation(screenWidth / 4, screenHeight / 5);
setPreferredSize(new Dimension(350, 300));
pack();
setVisible(true);
}
private void buildAgentsListTableModel() throws Exception {
Vector<Object> model = new Vector<Object>();
JSystemAgentClient[] clients = (JSystemAgentClient[]) JSystemAgentClientsPool.getClients(null);
for (JSystemAgentClient client : clients) {
Vector<Object> clientRow = getJSystemAgentDataVector(client);
model.add(clientRow);
}
Vector<String> columns = new Vector<String>();
columns.add("");
columns.add("Status");
columns.add("URL");
agentsListTableModel = new AgentSelectTableModel(model, columns);
}
private Vector<Object> getJSystemAgentDataVector(JSystemAgentClient client) throws Exception {
Vector<Object> data = new Vector<Object>();
if (selectedUrlsSet.contains(client.getId())) {
data.add(Boolean.TRUE);
} else {
data.add(Boolean.FALSE);
}
if (!client.getConnectionState().equals(ConnectionState.connected)) {
data.add(ERROR);
} else {
data.add(OKAY);
}
data.add(client.getId());
return data;
}
public boolean isOkay() {
return isOkay;
}
public String[] getSelectedUrls() {
Set<String> selected = new HashSet<String>();
int numberOfRows = agentsListTableModel.getRowCount();
for (int i = 0; i < numberOfRows; i++) {
if (agentsListTableModel.getValueAt(i, 0).equals(Boolean.TRUE)) {
selected.add((String) agentsListTableModel.getValueAt(i, 2));
}
}
return selected.toArray(new String[0]);
}
class AgentSelectTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
AgentSelectTableModel(Vector<Object> model, Vector<String> columns) {
super(model, columns);
}
@Override
public boolean isCellEditable(int row, int column) {
return column == 0;
};
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return Boolean.class;
}
if (columnIndex == 1) {
return ImageIcon.class;
}
return super.getColumnClass(columnIndex);
}
}
/**
* Actions and events
*/
/**
* Refresh button is pressed. Fetching agent information;
*/
class SelectUnSelectAction extends IgnisAction {
private static final long serialVersionUID = 1L;
private static final String SELECT_ALL = "Select All";
private static final String UNSELECT_ALL = "Unselect All";
SelectUnSelectAction(JTable table) {
super();
putValue(Action.NAME, SELECT_ALL);
putValue(Action.SHORT_DESCRIPTION, "select all agents");
putValue(Action.ACTION_COMMAND_KEY, "selectunselect");
}
@Override
public void actionPerformed(ActionEvent e) {
String buttonText = (String) getValue(Action.NAME);
Boolean select = false;
if (SELECT_ALL.equals(buttonText)) {
select = true;
}
int numberOfRows = agentsListTableModel.getRowCount();
for (int i = 0; i < numberOfRows; i++) {
agentsListTableModel.setValueAt(select, i, 0);
}
putValue(Action.NAME, select ? UNSELECT_ALL : SELECT_ALL);
}
}
/**
* Dialog is closed
*/
class SaveAction extends IgnisAction {
private static final long serialVersionUID = 1L;
private JDialog dialog;
SaveAction(JDialog dialog) {
putValue(Action.SHORT_DESCRIPTION, "Save user selection");
putValue(Action.NAME, "Save");
putValue(Action.ACTION_COMMAND_KEY, "save");
this.dialog = dialog;
}
@Override
public void actionPerformed(ActionEvent e) {
isOkay = true;
dialog.setVisible(false);
dialog.dispose();
}
}
/**
* Dialog is closed
*/
class CloseAction extends IgnisAction {
private static final long serialVersionUID = 1L;
private JDialog dialog;
CloseAction(JDialog dialog) {
putValue(Action.SHORT_DESCRIPTION, "Synchronize agent project with local project");
putValue(Action.NAME, "Close");
putValue(Action.ACTION_COMMAND_KEY, "close");
this.dialog = dialog;
}
@Override
public void actionPerformed(ActionEvent e) {
isOkay = false;
dialog.setVisible(false);
dialog.dispose();
}
}
public static void main(String[] args) throws Exception {
JSystemAgentClientsPool.initPoolFromRepositoryFile();
// AgentsSelectionDialog dialog = new AgentsSelectionDialog();
AgentsSelectionDialog.showAgentsDialog(new String[0]);
}
}
| apache-2.0 |
shakamunyi/beam | sdks/java/core/src/main/java/org/apache/beam/sdk/runners/inprocess/ViewEvaluatorFactory.java | 5752 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.runners.inprocess;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.VoidCoder;
import org.apache.beam.sdk.runners.inprocess.InProcessPipelineRunner.PCollectionViewWriter;
import org.apache.beam.sdk.transforms.AppliedPTransform;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.Values;
import org.apache.beam.sdk.transforms.View.CreatePCollectionView;
import org.apache.beam.sdk.transforms.WithKeys;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.PInput;
import org.apache.beam.sdk.values.POutput;
import java.util.ArrayList;
import java.util.List;
/**
* The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the
* {@link CreatePCollectionView} primitive {@link PTransform}.
*
* <p>The {@link ViewEvaluatorFactory} produces {@link TransformEvaluator TransformEvaluators} for
* the {@link WriteView} {@link PTransform}, which is part of the
* {@link InProcessCreatePCollectionView} composite transform. This transform is an override for the
* {@link CreatePCollectionView} transform that applies windowing and triggers before the view is
* written.
*/
class ViewEvaluatorFactory implements TransformEvaluatorFactory {
@Override
public <T> TransformEvaluator<T> forApplication(
AppliedPTransform<?, ?, ?> application,
InProcessPipelineRunner.CommittedBundle<?> inputBundle,
InProcessEvaluationContext evaluationContext) {
@SuppressWarnings({"cast", "unchecked", "rawtypes"})
TransformEvaluator<T> evaluator = createEvaluator(
(AppliedPTransform) application, evaluationContext);
return evaluator;
}
private <InT, OuT> TransformEvaluator<Iterable<InT>> createEvaluator(
final AppliedPTransform<PCollection<Iterable<InT>>, PCollectionView<OuT>, WriteView<InT, OuT>>
application,
InProcessEvaluationContext context) {
PCollection<Iterable<InT>> input = application.getInput();
final PCollectionViewWriter<InT, OuT> writer =
context.createPCollectionViewWriter(input, application.getOutput());
return new TransformEvaluator<Iterable<InT>>() {
private final List<WindowedValue<InT>> elements = new ArrayList<>();
@Override
public void processElement(WindowedValue<Iterable<InT>> element) {
for (InT input : element.getValue()) {
elements.add(element.withValue(input));
}
}
@Override
public InProcessTransformResult finishBundle() {
writer.add(elements);
return StepTransformResult.withoutHold(application).build();
}
};
}
public static class InProcessViewOverrideFactory implements PTransformOverrideFactory {
@Override
public <InputT extends PInput, OutputT extends POutput>
PTransform<InputT, OutputT> override(PTransform<InputT, OutputT> transform) {
if (transform instanceof CreatePCollectionView) {
}
@SuppressWarnings({"rawtypes", "unchecked"})
PTransform<InputT, OutputT> createView =
(PTransform<InputT, OutputT>)
new InProcessCreatePCollectionView<>((CreatePCollectionView) transform);
return createView;
}
}
/**
* An in-process override for {@link CreatePCollectionView}.
*/
private static class InProcessCreatePCollectionView<ElemT, ViewT>
extends ForwardingPTransform<PCollection<ElemT>, PCollectionView<ViewT>> {
private final CreatePCollectionView<ElemT, ViewT> og;
private InProcessCreatePCollectionView(CreatePCollectionView<ElemT, ViewT> og) {
this.og = og;
}
@Override
public PCollectionView<ViewT> apply(PCollection<ElemT> input) {
return input.apply(WithKeys.<Void, ElemT>of((Void) null))
.setCoder(KvCoder.of(VoidCoder.of(), input.getCoder()))
.apply(GroupByKey.<Void, ElemT>create())
.apply(Values.<Iterable<ElemT>>create())
.apply(new WriteView<ElemT, ViewT>(og));
}
@Override
protected PTransform<PCollection<ElemT>, PCollectionView<ViewT>> delegate() {
return og;
}
}
/**
* An in-process implementation of the {@link CreatePCollectionView} primitive.
*
* This implementation requires the input {@link PCollection} to be an iterable, which is provided
* to {@link PCollectionView#fromIterableInternal(Iterable)}.
*/
public static final class WriteView<ElemT, ViewT>
extends PTransform<PCollection<Iterable<ElemT>>, PCollectionView<ViewT>> {
private final CreatePCollectionView<ElemT, ViewT> og;
WriteView(CreatePCollectionView<ElemT, ViewT> og) {
this.og = og;
}
@Override
public PCollectionView<ViewT> apply(PCollection<Iterable<ElemT>> input) {
return og.getView();
}
}
}
| apache-2.0 |
Subsets and Splits