code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
var CONFIG = {
// remote URL education target
'REMOTE_URL': 'http://berndmalle.com/anonymization/adults',
// remote target
'REMOTE_TARGET': 'education', //'marital', //'income'
// The path to the input dataset
'INPUT_FILE' : './test/io/test_input/house_data.csv',
// CSV TRIM RegExp, if necessary
'TRIM': '',
'TRIM_MOD': '',
// CSV Separator char
'SEPARATOR' : '\\s+',
'SEP_MOD': 'g',
// columns to preserve for later processing of anonymized dataset
'TARGET_COLUMN' : 'MEDV',
// Shall we write out a range or an average value?
'AVERAGE_OUTPUT_RANGES' : true,
// How many data points to fetch
'NR_DRAWS' : 506,
// Do we wnat to sample the dataset randomly?
'RANDOM_DRAWS': false,
// Min # of edges per node for graph generation
'EDGE_MIN' : 3,
// Max # of edges per node for graph generation
'EDGE_MAX' : 10,
// The k anonymization factor
'K_FACTOR' : 19,
// Weight of the Generalization Information Loss
'ALPHA' : 1,
// Weight of the Structural Information Loss
'BETA' : 0,
// Weight vector for generalization hierarchies
'GEN_WEIGHT_VECTORS' : {
'equal': {
'range': {
'CRIM': 1.0/13.0,
'ZN': 1.0/13.0,
'INDUS': 1.0/13.0,
'CHAS': 1.0/13.0,
'NOX': 1.0/13.0,
'RM': 1.0/13.0,
'AGE': 1.0/13.0,
'DIS': 1.0/13.0,
'RAD': 1.0/13.0,
'TAX': 1.0/13.0,
'PTRATIO': 1.0/13.0,
'B': 1.0/13.0,
'LSTAT': 1.0/13.0
}
}
},
// default weight vector
'VECTOR' : 'equal'
}
export { CONFIG };
|
cassinius/AnonymizationJS
|
src/config/SaNGreeAConfig_house.ts
|
TypeScript
|
apache-2.0
| 1,589 |
require 'crack'
require 'json'
require 'core/make_json'
module Blix
# this is a parser to parse and format json rpc messages.
#
class JsonRpcParser < AbstractParser
def format_request(request)
{"jsonrpc"=>"2.0", "method"=>request.method, "params"=>request.parameters, "id"=>request.id }.to_blix_json
end
# decode the message into request message format. Convert all objects to objects
# that are recognised on the server.
#
def parse_request(json)
begin
ck = Crack::JSON.parse json
rescue Crack::ParseError
raise ParseError
end
obj = RequestMessage.new
obj.data = json
obj.method = ck["method"]
parameters = ck["params"]
obj.id = ck["id"]
raise ParseError,"method missing" unless obj.method
raise ParseError,"id missing" unless obj.id
myparameters = {}
# convert any compound parameter values to local
# classes if possible.
parameters && parameters.each do |key,value|
if value.kind_of? Hash
myparameters[key.to_sym] = convert_to_class value
elsif value.kind_of? Array
myparameters[key.to_sym] = convert_to_class value
else
myparameters[key.to_sym] = convert_to_class value
end
end
obj.parameters = myparameters
obj
end
# format a response message into data
#
def format_response(message)
if message.error?
error={"code"=>message.code, "message"=>message.description}
{"jsonrpc"=>"2.0", "error"=>error, "id"=>message.id }.to_json
else
{"jsonrpc"=>"2.0", "result"=>message.value, "id"=>message.id }.to_blix_json
end
end
# parse response data into a response message
#
def parse_response(json)
begin
ck = Crack::JSON.parse json
rescue Crack::ParseError
raise ParseError
end
obj = ResponseMessage.new
obj.data = json
obj.id = ck["id"]
error = ck["error"]
if error
obj.set_error
obj.code = error["code"]
obj.description = error["message"]
else
obj.value = convert_to_class ck["result"]
end
obj
end
# format a notification into a json-rpc string
def format_notification(message)
hash = {:item=>message.value}
{"jsonrpc"=>"2.0", "method"=>message.signal, "params"=>hash }.to_blix_json
end
# parse notification data
def parse_notification(json)
begin
ck = Crack::JSON.parse json
rescue Crack::ParseError
raise ParseError
end
params = ck["params"]
obj = NotificationMessage.new
obj.data = json
obj.signal = ck["method"]
value = params && params["item"]
obj.value = convert_to_class value
obj
end
def convert_to_class( hash)
if hash.kind_of? Hash
klass = singular hash.keys.first # the name of the class
values = hash.values.first
if klass == 'value'
klass_info = [String]
elsif klass=='datetime'
klass_info = [Time]
elsif klass=='date'
klass_info = [Date]
elsif klass=='base64Binary'
klass_info = [String]
elsif klass=='decimal'
klass_info = [BigDecimal]
elsif klass[-3,3] == "_id" # aggregation class
klass = klass[0..-4]
raise ParseError,"#{klass} is not Valid!" unless klass_info = valid_klass[klass.downcase.to_sym]
puts "aggregation #{klass}: id:#{values}(#{values.class})" if $DEBUG
id = values
return defined?( DataMapper) ? klass_info[0].get(id) : klass_info[0].find(id)
else
raise ParseError,"#{klass} is not Valid!" unless klass_info = valid_klass[klass.downcase.to_sym]
end
if values.kind_of? Array
values.map do |av|
if false #av.kind_of? Hash
convert_to_class(av)
else
convert_to_class({klass=>av})
# values.map{ |av| convert_to_class({klass=>av})}
end
#
end
elsif values.kind_of? Hash
if ((defined? ActiveRecord) && ( klass_info[0].superclass == ActiveRecord::Base )) ||
((defined? DataMapper) && ( klass_info[0].included_modules.index( DataMapper::Resource) ))
myclass = klass_info[0].new
puts "[convert] class=#{myclass.class.name}, values=#{values.inspect}" if $DEBUG
else
myclass = klass_info[0].allocate
end
values.each do |k,v|
method = "#{k.downcase}=".to_sym
# we will trust the server and accept that values are valid
c_val = convert_to_class(v)
if myclass.respond_to? method
# first try to assign the value via a method
myclass.send method, c_val
else
# otherwise set an instance with this value
attr = "@#{k.downcase}".to_sym
myclass.instance_variable_set attr, c_val
end
end
# rationalize this value if neccessary
#myclass = myclass.blix_rationalize if myclass.respond_to? :blix_rationalize
myclass
elsif values.kind_of? NilClass
nil
else
if klass=='datetime'
values # crack converts the time!
elsif klass=='date'
#Date.parse(values)
values # crack converts the date!
elsif klass=="base64Binary"
Base64.decode64(values)
elsif klass=="decimal"
BigDecimal.new(values)
else
from_binary_data values
end
#raise ParseError, "inner values has class=#{values.class.name}\n#{values.inspect}" # inner value must be either a Hash or an array of Hashes
end
elsif hash.kind_of? Array
hash.map{|i| convert_to_class(i)}
else
hash
end
end
# convert plural class names to singular... if there are class names that end in 's'
# then we will have to code in an exception for this class.
def singular(txt)
parts = txt.split('_')
if (parts.length>1) && (parts[-1]=="array")
return parts[0..-2].join('_')
end
return txt[0..-2] if txt[-1].chr == 's'
txt
end
def array?(txt)
(parts.length>1) && (parts[-1]=="array")
end
end #Handler
end #Blix
|
realbite/blix
|
lib/blix/core/json_rpc_parser.rb
|
Ruby
|
apache-2.0
| 6,698 |
package org.docksidestage.app.web.es.product;
public class EsProductAddForm {
public String productDescription;
public String productCategoryCode;
public String productHandleCode;
public String productName;
public Integer regularPrice;
public String productStatusCode;
}
|
dbflute-example/dbflute-example-with-non-rdb
|
src/main/java/org/docksidestage/app/web/es/product/EsProductAddForm.java
|
Java
|
apache-2.0
| 298 |
using UnityEngine;
using System.Collections;
public class Wander : MonoBehaviour
{
private Vector3 tarPos;
public float movementSpeed = 5.0f;
private float rotSpeed = 2.0f;
private float minX, maxX, minZ, maxZ;
public float wanderRadius = 30.0f;
// Use this for initialization
void Start ()
{
minX = -wanderRadius;
maxX = wanderRadius;
minZ = -wanderRadius;
maxZ = wanderRadius;
//Get Wander Position
GetNextPosition();
}
// Update is called once per frame
void Update ()
{
if(Vector3.Distance(tarPos, transform.position) <= 5.0f)
GetNextPosition();
Quaternion tarRot = Quaternion.LookRotation(tarPos - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, tarRot, rotSpeed * Time.deltaTime);
transform.Translate(new Vector3(0, 0, movementSpeed * Time.deltaTime));
}
void GetNextPosition()
{
tarPos = new Vector3(Random.Range(minX, maxX), 0.5f, Random.Range(minZ, maxZ));
}
}
|
Guityyo/minerparty
|
Assets/_Scripts/AIWandering/Wander.cs
|
C#
|
apache-2.0
| 1,056 |
/*
* 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.inspector2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/inspector2-2020-06-08/GetMember" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetMemberResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Details of the retrieved member account.
* </p>
*/
private Member member;
/**
* <p>
* Details of the retrieved member account.
* </p>
*
* @param member
* Details of the retrieved member account.
*/
public void setMember(Member member) {
this.member = member;
}
/**
* <p>
* Details of the retrieved member account.
* </p>
*
* @return Details of the retrieved member account.
*/
public Member getMember() {
return this.member;
}
/**
* <p>
* Details of the retrieved member account.
* </p>
*
* @param member
* Details of the retrieved member account.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetMemberResult withMember(Member member) {
setMember(member);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getMember() != null)
sb.append("Member: ").append(getMember());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetMemberResult == false)
return false;
GetMemberResult other = (GetMemberResult) obj;
if (other.getMember() == null ^ this.getMember() == null)
return false;
if (other.getMember() != null && other.getMember().equals(this.getMember()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getMember() == null) ? 0 : getMember().hashCode());
return hashCode;
}
@Override
public GetMemberResult clone() {
try {
return (GetMemberResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-inspector2/src/main/java/com/amazonaws/services/inspector2/model/GetMemberResult.java
|
Java
|
apache-2.0
| 3,656 |
package com.ecrm.DAO;
import org.springframework.stereotype.Repository;
/**
* Created by Htang on 7/10/2015.
*/
@Repository
public interface ScheduleConfigDAO {
}
|
tranquang9a1/ECRM
|
App/ECRM/src/main/java/com/ecrm/DAO/ScheduleConfigDAO.java
|
Java
|
apache-2.0
| 177 |
package clarifai
// Response is a universal Clarifai API response object.
type Response struct {
Status *ServiceStatus `json:"status,omitempty"`
Outputs []*Output `json:"outputs,omitempty"`
Input *Input `json:"input,omitempty"` // Request for one input.
Inputs []*Input `json:"inputs,omitempty"`
Hits []*Hit `json:"hits,omitempty"` // Search hits.
Model *Model `json:"model,omitempty"`
Models []*Model `json:"models,omitempty"`
ModelVersion *ModelVersion `json:"model_version,omitempty"`
ModelVersions []*ModelVersion `json:"model_versions,omitempty"`
}
|
mpmlj/clarifai-client-go
|
response.go
|
GO
|
apache-2.0
| 667 |
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.actions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.syntax.Label;
import com.google.devtools.build.lib.util.StringUtil;
import java.util.Set;
/**
* A mutable action graph. Implementations of this interface must be thread-safe.
*/
public interface MutableActionGraph extends ActionGraph {
/**
* Attempts to register the action. If any of the action's outputs already has a generating
* action, and the two actions are not compatible, then an {@link ActionConflictException} is
* thrown. The internal data structure may be partially modified when that happens; it is not
* guaranteed that all potential conflicts are detected, but at least one of them is.
*
* <p>For example, take three actions A, B, and C, where A creates outputs a and b, B creates just
* b, and C creates c and b. There are two potential conflicts in this case, between A and B, and
* between B and C. Depending on the ordering of calls to this method and the ordering of outputs
* in the action output lists, either one or two conflicts are detected: if B is registered first,
* then both conflicts are detected; if either A or C is registered first, then only one conflict
* is detected.
*/
void registerAction(Action action) throws ActionConflictException;
/**
* Removes an action from this action graph if it is present.
*
* <p>Throws {@link IllegalStateException} if one of the outputs of the action is in fact
* generated by a different {@link Action} instance (even if they are sharable).
*/
void unregisterAction(Action action);
/**
* Clear the action graph.
*/
void clear();
/**
* This exception is thrown when a conflict between actions is detected. It contains information
* about the artifact for which the conflict is found, and data about the two conflicting actions
* and their owners.
*/
public static final class ActionConflictException extends Exception {
private final Artifact artifact;
private final Action previousAction;
private final Action attemptedAction;
public ActionConflictException(Artifact artifact, Action previousAction,
Action attemptedAction) {
super("for " + artifact);
this.artifact = artifact;
this.previousAction = previousAction;
this.attemptedAction = attemptedAction;
}
public Artifact getArtifact() {
return artifact;
}
public void reportTo(EventHandler eventListener) {
String msg = "file '" + artifact.prettyPrint()
+ "' is generated by these conflicting actions:\n" +
suffix(attemptedAction, previousAction);
eventListener.handle(Event.error(msg));
}
private void addStringDetail(StringBuilder sb, String key, String valueA, String valueB) {
valueA = valueA != null ? valueA : "(null)";
valueB = valueB != null ? valueB : "(null)";
sb.append(key).append(": ").append(valueA);
if (!valueA.equals(valueB)) {
sb.append(", ").append(valueB);
}
sb.append("\n");
}
private void addListDetail(StringBuilder sb, String key,
Iterable<Artifact> valueA, Iterable<Artifact> valueB) {
Set<Artifact> setA = ImmutableSet.copyOf(valueA);
Set<Artifact> setB = ImmutableSet.copyOf(valueB);
SetView<Artifact> diffA = Sets.difference(setA, setB);
SetView<Artifact> diffB = Sets.difference(setB, setA);
sb.append(key).append(": ");
if (diffA.isEmpty() && diffB.isEmpty()) {
sb.append("are equal");
} else {
if (!diffA.isEmpty() && !diffB.isEmpty()) {
sb.append("attempted action contains artifacts not in previous action and "
+ "previous action contains artifacts not in attempted action: "
+ diffA + ", " + diffB);
} else if (!diffA.isEmpty()) {
sb.append("attempted action contains artifacts not in previous action: ");
sb.append(StringUtil.joinEnglishList(diffA, "and"));
} else if (!diffB.isEmpty()) {
sb.append("previous action contains artifacts not in attempted action: ");
sb.append(StringUtil.joinEnglishList(diffB, "and"));
}
}
sb.append("\n");
}
// See also Actions.canBeShared()
private String suffix(Action a, Action b) {
// Note: the error message reveals to users the names of intermediate files that are not
// documented in the BUILD language. This error-reporting logic is rather elaborate but it
// does help to diagnose some tricky situations.
StringBuilder sb = new StringBuilder();
ActionOwner aOwner = a.getOwner();
ActionOwner bOwner = b.getOwner();
boolean aNull = aOwner == null;
boolean bNull = bOwner == null;
addStringDetail(sb, "Label", aNull ? null : Label.print(aOwner.getLabel()),
bNull ? null : Label.print(bOwner.getLabel()));
addStringDetail(sb, "RuleClass", aNull ? null : aOwner.getTargetKind(),
bNull ? null : bOwner.getTargetKind());
addStringDetail(sb, "Configuration", aNull ? null : aOwner.getConfigurationName(),
bNull ? null : bOwner.getConfigurationName());
addStringDetail(sb, "Mnemonic", a.getMnemonic(), b.getMnemonic());
addStringDetail(sb, "Progress message", a.getProgressMessage(), b.getProgressMessage());
addListDetail(sb, "MandatoryInputs", a.getMandatoryInputs(), b.getMandatoryInputs());
addListDetail(sb, "Outputs", a.getOutputs(), b.getOutputs());
return sb.toString();
}
}
}
|
rzagabe/bazel
|
src/main/java/com/google/devtools/build/lib/actions/MutableActionGraph.java
|
Java
|
apache-2.0
| 6,415 |
package com.taoswork.tallycheck.general.solution.threading;
import com.taoswork.tallycheck.general.solution.quickinterface.IValueMaker;
/**
* Created by Gao Yuan on 2015/8/16.
*/
public class ThreadLocalHelper {
public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type, final IValueMaker<T> valueMaker) {
ThreadLocal<T> result = new ThreadLocal<T>() {
@Override
protected T initialValue() {
if(valueMaker != null){
return valueMaker.make();
}
return super.initialValue();
}
};
return result;
}
public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type, final boolean createInitialValue) {
IValueMaker<T> valueMaker = createInitialValue ? new IValueMaker<T>() {
@Override
public T make() {
T obj = null;
try {
obj = type.newInstance();
} catch (InstantiationException exp) {
throw new RuntimeException(exp);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return obj;
}
} : null;
return createThreadLocal(type, valueMaker);
}
public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type) {
return createThreadLocal(type, true);
}
}
|
tallycheck/general
|
general-solution/src/main/java/com/taoswork/tallycheck/general/solution/threading/ThreadLocalHelper.java
|
Java
|
apache-2.0
| 1,473 |
#!/usr/bin/env ruby
# INSTALL
# sudo gem install sinatra liquid
# RUN
# ruby examples/sinatra/buzz_api.rb
root_dir = File.expand_path("../../..", __FILE__)
lib_dir = File.expand_path("./lib", root_dir)
$LOAD_PATH.unshift(lib_dir)
$LOAD_PATH.uniq!
require 'rubygems'
begin
gem 'rack', '= 1.2.0'
require 'rack'
rescue LoadError
STDERR.puts "Missing dependencies."
STDERR.puts "sudo gem install rack -v 1.2.0"
exit(1)
end
begin
require 'sinatra'
require 'liquid'
require 'signet/oauth_1/client'
require 'google/api_client'
rescue LoadError
STDERR.puts "Missing dependencies."
STDERR.puts "sudo gem install sinatra liquid signet google-api-client"
exit(1)
end
enable :sessions
CSS = <<-CSS
/* http://meyerweb.com/eric/tools/css/reset/ */
/* v1.0 | 20080212 */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* End Reset */
body {
color: #555555;
background-color: #ffffff;
font-family: 'Helvetica', 'Arial', sans-serif;
font-size: 18px;
line-height: 27px;
padding: 27px 72px;
}
p {
margin-bottom: 27px;
}
h1 {
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'Helvetica', 'Arial', sans-serif;
font-size: 36px;
line-height: 54px;
margin-bottom: 0px;
}
h2 {
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
font-size: 14px;
line-height: 27px;
margin-top: 0px;
margin-bottom: 54px;
letter-spacing: 0.1em;
text-transform: none;
text-shadow: rgba(204, 204, 204, 0.75) 0px 1px 0px;
}
#output h3 {
font-style: normal;
font-variant: normal;
font-weight: bold;
font-size: 18px;
line-height: 27px;
margin: 27px 0px;
}
#output h3:first-child {
margin-top: 0px;
}
ul, ol, dl {
margin-bottom: 27px;
}
li {
margin: 0px 0px;
}
form {
float: left;
display: block;
}
form label, form input, form textarea {
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
display: block;
}
form label {
margin-bottom: 5px;
}
form input {
width: 300px;
font-size: 14px;
padding: 5px;
}
form textarea {
height: 150px;
min-height: 150px;
width: 300px;
min-width: 300px;
max-width: 300px;
}
#output {
font-family: 'Monaco', 'Andale Mono', 'Consolas', 'Inconsolata', 'Courier New', monospace;
display: inline-block;
margin-left: 27px;
padding: 27px;
border: 1px dotted #555555;
width: 1120px;
max-width: 100%;
min-height: 600px;
}
#output pre {
overflow: auto;
}
a {
color: #000000;
text-decoration: none;
border-bottom: 1px dotted rgba(112, 56, 56, 0.0);
}
a:hover {
-webkit-transition: all 0.3s linear;
color: #703838;
border-bottom: 1px dotted rgba(112, 56, 56, 1.0);
}
p a {
border-bottom: 1px dotted rgba(0, 0, 0, 1.0);
}
h1, h2 {
color: #000000;
}
h3, h4, h5, h6 {
color: #333333;
}
.block {
display: block;
}
button {
margin-bottom: 72px;
padding: 7px 11px;
font-size: 14px;
}
CSS
JAVASCRIPT = <<-JAVASCRIPT
var uriTimeout = null;
$(document).ready(function () {
$('#output').hide();
var rpcName = $('#rpc-name').text().trim();
var serviceId = $('#service-id').text().trim();
var getParameters = function() {
var parameters = {};
var fields = $('.parameter').parents('li');
for (var i = 0; i < fields.length; i++) {
var input = $(fields[i]).find('input');
var label = $(fields[i]).find('label');
if (input.val() && input.val() != "") {
parameters[label.text()] = input.val();
}
}
return parameters;
}
var updateOutput = function (event) {
var request = $('#request').text().trim();
var response = $('#response').text().trim();
if (request != '' || response != '') {
$('#output').show();
} else {
$('#output').hide();
}
}
var handleUri = function (event) {
updateOutput(event);
if (uriTimeout) {
clearTimeout(uriTimeout);
}
uriTimeout = setTimeout(function () {
$.ajax({
"url": "/template/" + serviceId + "/" + rpcName + "/",
"data": getParameters(),
"dataType": "text",
"ifModified": true,
"success": function (data, textStatus, xhr) {
updateOutput(event);
if (textStatus == 'success') {
$('#uri-template').html(data);
if (uriTimeout) {
clearTimeout(uriTimeout);
}
}
}
});
}, 350);
}
var getResponse = function (event) {
$.ajax({
"url": "/response/" + serviceId + "/" + rpcName + "/",
"type": "POST",
"data": getParameters(),
"dataType": "html",
"ifModified": true,
"success": function (data, textStatus, xhr) {
if (textStatus == 'success') {
$('#response').text(data);
}
updateOutput(event);
}
});
}
var getRequest = function (event) {
$.ajax({
"url": "/request/" + serviceId + "/" + rpcName + "/",
"type": "GET",
"data": getParameters(),
"dataType": "html",
"ifModified": true,
"success": function (data, textStatus, xhr) {
if (textStatus == 'success') {
$('#request').text(data);
updateOutput(event);
getResponse(event);
}
}
});
}
var transmit = function (event) {
$('#request').html('');
$('#response').html('');
handleUri(event);
updateOutput(event);
getRequest(event);
}
$('form').submit(function (event) { event.preventDefault(); });
$('button').click(transmit);
$('.parameter').keyup(handleUri);
$('.parameter').blur(handleUri);
});
JAVASCRIPT
def client
@client ||= Google::APIClient.new(
:service => 'buzz',
:authorization => Signet::OAuth1::Client.new(
:temporary_credential_uri =>
'https://www.google.com/accounts/OAuthGetRequestToken',
:authorization_uri =>
'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken',
:token_credential_uri =>
'https://www.google.com/accounts/OAuthGetAccessToken',
:client_credential_key => 'anonymous',
:client_credential_secret => 'anonymous'
)
)
end
def service(service_name, service_version)
unless service_version
service_version = client.latest_service_version(service_name).version
end
client.discovered_service(service_name, service_version)
end
get '/template/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
uri = Addressable::URI.parse(
method.uri_template.partial_expand(parameters).pattern
)
template_variables = method.uri_template.variables
query_parameters = method.normalize_parameters(parameters).reject do |k, v|
template_variables.include?(k)
end
if query_parameters.size > 0
uri.query_values = (uri.query_values || {}).merge(query_parameters)
end
# Normalization is necessary because of undesirable percent-escaping
# during URI template expansion
return uri.normalize.to_s.gsub('%7B', '{').gsub('%7D', '}')
end
get '/request/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
body = ''
request = client.generate_request(
method, parameters.merge("pp" => "1"), body, [], {:signed => false}
)
method, uri, headers, body = request
merged_body = StringIO.new
body.each do |chunk|
merged_body << chunk
end
merged_body.rewind
<<-REQUEST.strip
#{method} #{uri} HTTP/1.1
#{(headers.map { |k,v| "#{k}: #{v}" }).join('\n')}
#{merged_body.string}
REQUEST
end
post '/response/:service/:method/' do
require 'rack/utils'
service_name, service_version = params[:service].split("-", 2)
method = service(service_name, service_version).to_h[params[:method].to_s]
parameters = method.parameters.inject({}) do |accu, parameter|
accu[parameter] = params[parameter.to_sym] if params[parameter.to_sym]
accu
end
body = ''
response = client.execute(
method, parameters.merge("pp" => "1"), body, [], {:signed => false}
)
status, headers, body = response
status_message = Rack::Utils::HTTP_STATUS_CODES[status.to_i]
merged_body = StringIO.new
body.each do |chunk|
merged_body << chunk
end
merged_body.rewind
<<-RESPONSE.strip
#{status} #{status_message}
#{(headers.map { |k,v| "#{k}: #{v}" }).join("\n")}
#{merged_body.string}
RESPONSE
end
get '/explore/:service/' do
service_name, service_version = params[:service].split("-", 2)
service_version = service(service_name, service_version).version
variables = {
"css" => CSS,
"service_name" => service_name,
"service_version" => service_version,
"methods" => service(service_name, service_version).to_h.keys.sort
}
Liquid::Template.parse(<<-HTML).render(variables)
<!DOCTYPE html>
<html>
<head>
<title>{{service_name}}</title>
<style type="text/css">
{{css}}
</style>
</head>
<body>
<h1>{{service_name}}</h1>
<ul>
{% for method in methods %}
<li>
<a href="/explore/{{service_name}}-{{service_version}}/{{method}}/">
{{method}}
</a>
</li>
{% endfor %}
</ul>
</body>
</html>
HTML
end
get '/explore/:service/:method/' do
service_name, service_version = params[:service].split("-", 2)
service_version = service(service_name, service_version).version
method = service(service_name, service_version).to_h[params[:method].to_s]
variables = {
"css" => CSS,
"javascript" => JAVASCRIPT,
"http_method" => (method.description['httpMethod'] || 'GET'),
"service_name" => service_name,
"service_version" => service_version,
"method" => params[:method].to_s,
"required_parameters" =>
method.required_parameters,
"optional_parameters" =>
method.optional_parameters.sort,
"template" => method.uri_template.pattern
}
Liquid::Template.parse(<<-HTML).render(variables)
<!DOCTYPE html>
<html>
<head>
<title>{{service_name}} - {{method}}</title>
<style type="text/css">
{{css}}
</style>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
type="text/javascript">
</script>
<script type="text/javascript">
{{javascript}}
</script>
</head>
<body>
<h3 id="service-id">
<a href="/explore/{{service_name}}-{{service_version}}/">
{{service_name}}-{{service_version}}
</a>
</h3>
<h1 id="rpc-name">{{method}}</h1>
<h2>{{http_method}} <span id="uri-template">{{template}}</span></h2>
<form>
<ul>
{% for parameter in required_parameters %}
<li>
<label for="param-{{parameter}}">{{parameter}}</label>
<input id="param-{{parameter}}" name="param-{{parameter}}"
class="parameter" type="text" />
</li>
{% endfor %}
{% for parameter in optional_parameters %}
<li>
<label for="param-{{parameter}}">{{parameter}}</label>
<input id="param-{{parameter}}" name="param-{{parameter}}"
class="parameter" type="text" />
</li>
{% endfor %}
{% if http_method != 'GET' %}
<li>
<label for="http-body">body</label>
<textarea id="http-body" name="http-body"></textarea>
</li>
{% endif %}
</ul>
<button>Transmit</button>
</form>
<div id="output">
<h3>Request</h3>
<pre id="request"></pre>
<h3>Response</h3>
<pre id="response"></pre>
</div>
</body>
</html>
HTML
end
get '/favicon.ico' do
require 'httpadapter'
HTTPAdapter.transmit(
['GET', 'http://www.google.com/favicon.ico', [], ['']],
HTTPAdapter::NetHTTPRequestAdapter
)
end
get '/' do
redirect '/explore/buzz/'
end
|
jeroenvandijk/google-api-ruby-client
|
examples/sinatra/explorer.rb
|
Ruby
|
apache-2.0
| 13,332 |
<?php
class Faq_model extends CI_Model{
public $_table='faq';
public $_topics='faq_topics';
function __construct() {
parent::__construct();
}
public function get_all_admin(){
return $this->db->select('f.*,ft.faqTopics')->from($this->_table.' f')->join($this->_topics.' ft','f.faqTopicsId=ft.faqTopicsId')->get()->result();
}
function get_details($faqId){
return $this->db->select('f.*,ft.faqTopics')->from($this->_table.' f')->join($this->_topics.' ft','f.faqTopicsId=ft.faqTopicsId')->where('f.faqId',$faqId)->get()->result();
}
public function add($dataArr){
$this->db->insert($this->_table,$dataArr);
return $this->db->insert_id();
}
public function edit($DataArr,$faqId){
$this->db->where('faqId',$faqId);
$this->db->update($this->_table,$DataArr);
//echo $this->db->last_query();die;
return TRUE;
}
public function change_status($faqId,$status){
$this->db->where('faqId',$faqId);
$this->db->update($this->_table,array('status'=>$status));
return TRUE;
}
public function delete($faqId){
$this->db->delete($this->_table, array('faqId' => $faqId));
return TRUE;
}
public function get_all($type){
$this->db->select('*')->from($this->_table)->where('status',1)->where('type',$type);
return $this->db->get()->result();
}
function get_all_admin_topics(){
return $this->db->get($this->_topics)->result();
}
function get_all_active_topic(){
return $this->db->get_where($this->_topics,array('status'=>1))->result();
}
public function add_topics($dataArr){
$this->db->insert($this->_topics,$dataArr);
return $this->db->insert_id();
}
public function edit_topics($DataArr,$faqTopicsId){
$this->db->where('faqTopicsId',$faqTopicsId);
$this->db->update($this->_topics,$DataArr);
//echo $this->db->last_query();die;
return TRUE;
}
public function change_status_topics($faqTopicsId,$status){
$this->db->where('faqTopicsId',$faqTopicsId);
$this->db->update($this->_topics,array('status'=>$status));
return TRUE;
}
public function delete_topics($faqTopicsId){
$this->db->delete($this->_topics, array('faqTopicsId' => $faqTopicsId));
return TRUE;
}
function check_faq_topics_exist($faqTopics,$faqTopicsType){
$rs=$this->db->from($this->_topics)->where('faqTopics',$faqTopics)->where('faqTopicsType',$faqTopicsType)->get()->result();
if(count($rs)>0){
return TRUE;
}else{
return FALSE;
}
}
function get_topics_by_type($type){
return $this->db->get_where($this->_topics,array('faqTopicsType'=>$type))->result();
}
}
|
kousik/tidiit
|
models/faq_model.php
|
PHP
|
apache-2.0
| 2,958 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Component } from 'react';
import Radium from 'radium';
import PropTypes from 'prop-types';
import Immutable from 'immutable';
import classNames from 'classnames';
import DragColumnMenu from 'components/DragComponents/DragColumnMenu';
import ColumnDragItem from 'utils/ColumnDragItem';
import { base, inner, leftBorder, fullHeight, contentPadding } from '@app/uiTheme/less/Aggregate/AggregateContent.less';
import ColumnDragArea from './components/ColumnDragArea';
import MeasureDragArea, { MEASURE_DRAG_AREA_TEXT } from './components/MeasureDragArea';
export const NOT_SUPPORTED_TYPES = new Set(['MAP', 'LIST', 'STRUCT']);
@Radium
class AggregateContent extends Component {
static propTypes = {
fields: PropTypes.object,
canSelectMeasure: PropTypes.bool,
canUseFieldAsBothDimensionAndMeasure: PropTypes.bool,
allColumns: PropTypes.instanceOf(Immutable.List),
handleDragStart: PropTypes.func,
onDragEnd: PropTypes.func,
onDrop: PropTypes.func,
handleMeasureChange: PropTypes.func,
dragType: PropTypes.string,
path: PropTypes.string,
isDragInProgress: PropTypes.bool,
style: PropTypes.object,
dragItem: PropTypes.instanceOf(ColumnDragItem),
className: PropTypes.string,
canAlter: PropTypes.any
};
static defaultProps = {
allColumns: Immutable.List(),
canSelectMeasure: true,
canUseFieldAsBothDimensionAndMeasure: true
};
disabledColumnNames = undefined;
constructor(props) {
super(props);
this.receiveProps(props, {});
}
componentWillReceiveProps(nextProps) {
this.receiveProps(nextProps, this.props);
}
receiveProps(nextProps, oldProps) {
// disabledColumnNames is wholly derived from these props, so only recalculate it when one of them has changed
const propKeys = ['allColumns', 'fields', 'canSelectMeasure', 'canUseFieldAsBothDimensionAndMeasure'];
if (propKeys.some((key) => nextProps[key] !== oldProps[key])) {
this.disabledColumnNames = this.getDisabledColumnNames(nextProps);
}
}
getDisabledColumnNames(props) {
const {
allColumns, fields, canSelectMeasure, canUseFieldAsBothDimensionAndMeasure
} = props;
const dimensionColumnNames = Immutable.Set(fields.columnsDimensions.map(col => col.column.value));
const measuresColumnNames = Immutable.Set(fields.columnsMeasures.map(col => col.column.value));
const columnsInEither = dimensionColumnNames.concat(measuresColumnNames);
const columnsInBoth = dimensionColumnNames.intersect(measuresColumnNames);
const disabledColumns = allColumns.filter(
(column) =>
NOT_SUPPORTED_TYPES.has(column.get('type')) ||
(!canSelectMeasure && columnsInBoth.has(column.get('name'))) ||
(!canUseFieldAsBothDimensionAndMeasure && columnsInEither.has(column.get('name')))
);
return Immutable.Set(disabledColumns.map((column) => column.get('name')));
}
render() {
const {
allColumns, onDrop, fields, dragType, isDragInProgress, dragItem,
handleDragStart, onDragEnd, canUseFieldAsBothDimensionAndMeasure,
className, canAlter
} = this.props;
const commonDragAreaProps = {
allColumns,
disabledColumnNames: this.disabledColumnNames,
handleDragStart,
onDragEnd,
onDrop,
dragType,
isDragInProgress,
dragItem,
canUseFieldAsBothDimensionAndMeasure
};
const measurementCls = classNames(['aggregate-measurement', fullHeight]);
return (
<div className={classNames(['aggregate-content', base, className])} style={this.props.style}>
<div className={inner}>
<DragColumnMenu
items={allColumns}
className={fullHeight}
disabledColumnNames={this.disabledColumnNames}
columnType='column'
handleDragStart={handleDragStart}
onDragEnd={onDragEnd}
dragType={dragType}
name={`${this.props.path} (${la('Current')})`}
canAlter={canAlter}
/>
</div>
<div className={leftBorder}>
<ColumnDragArea
className={classNames(['aggregate-dimension', fullHeight])}
dragContentCls={contentPadding}
{...commonDragAreaProps}
columnsField={fields.columnsDimensions}
canAlter={canAlter}
/>
</div>
<div className={leftBorder}>
{
this.props.canSelectMeasure ?
<MeasureDragArea
dragContentCls={contentPadding}
className={measurementCls}
{...commonDragAreaProps}
columnsField={fields.columnsMeasures}/> :
<ColumnDragArea
dragContentCls={contentPadding}
className={measurementCls}
{...commonDragAreaProps}
dragOrigin='measures'
dragAreaText={MEASURE_DRAG_AREA_TEXT}
columnsField={fields.columnsMeasures}
canAlter={canAlter}
/>
}
</div>
</div>
);
}
}
export default AggregateContent;
|
dremio/dremio-oss
|
dac/ui/src/components/Aggregate/AggregateContent.js
|
JavaScript
|
apache-2.0
| 5,729 |
import { Component } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.component.html',
styleUrls: ['home.component.css'],
})
export class HomeComponent implements OnInit {
constructor(meta: Meta, title: Title) {
title.setTitle('etcd Labs');
meta.addTags([
{ name: 'author', content: 'etcd'},
{ name: 'keywords', content: 'etcd, etcd demo, etcd setting, etcd cluster, etcd install'},
{ name: 'description', content: 'This is etcd demo, install guides!' }
]);
}
ngOnInit(): void {
}
}
|
gyuho/etcdlabs
|
frontend/app/home/home.component.ts
|
TypeScript
|
apache-2.0
| 654 |
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"errors"
"fmt"
"encoding/binary"
"encoding/hex"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/bccsp/factory"
"github.com/hyperledger/fabric/common/crypto"
"github.com/hyperledger/fabric/common/util"
"github.com/hyperledger/fabric/core/chaincode/platforms"
"github.com/hyperledger/fabric/protos/common"
"github.com/hyperledger/fabric/protos/peer"
)
// GetChaincodeInvocationSpec get the ChaincodeInvocationSpec from the proposal
func GetChaincodeInvocationSpec(prop *peer.Proposal) (*peer.ChaincodeInvocationSpec, error) {
txhdr := &common.Header{}
err := proto.Unmarshal(prop.Header, txhdr)
if err != nil {
return nil, err
}
ccPropPayload := &peer.ChaincodeProposalPayload{}
err = proto.Unmarshal(prop.Payload, ccPropPayload)
if err != nil {
return nil, err
}
cis := &peer.ChaincodeInvocationSpec{}
err = proto.Unmarshal(ccPropPayload.Input, cis)
if err != nil {
return nil, err
}
return cis, nil
}
// GetChaincodeProposalContext returns creator and transient
func GetChaincodeProposalContext(prop *peer.Proposal) ([]byte, map[string][]byte, error) {
if prop == nil {
return nil, nil, fmt.Errorf("Proposal is nil")
}
if len(prop.Header) == 0 {
return nil, nil, fmt.Errorf("Proposal's header is nil")
}
if len(prop.Payload) == 0 {
return nil, nil, fmt.Errorf("Proposal's payload is nil")
}
//// get back the header
hdr, err := GetHeader(prop.Header)
if err != nil {
return nil, nil, fmt.Errorf("Could not extract the header from the proposal: %s", err)
}
if hdr == nil {
return nil, nil, fmt.Errorf("Unmarshalled header is nil")
}
chdr, err := UnmarshalChannelHeader(hdr.ChannelHeader)
if err != nil {
return nil, nil, fmt.Errorf("Could not extract the channel header from the proposal: %s", err)
}
if common.HeaderType(chdr.Type) != common.HeaderType_ENDORSER_TRANSACTION &&
common.HeaderType(chdr.Type) != common.HeaderType_CONFIG {
return nil, nil, fmt.Errorf("Invalid proposal type expected ENDORSER_TRANSACTION or CONFIG. Was: %d", chdr.Type)
}
shdr, err := GetSignatureHeader(hdr.SignatureHeader)
if err != nil {
return nil, nil, fmt.Errorf("Could not extract the signature header from the proposal: %s", err)
}
ccPropPayload := &peer.ChaincodeProposalPayload{}
err = proto.Unmarshal(prop.Payload, ccPropPayload)
if err != nil {
return nil, nil, err
}
return shdr.Creator, ccPropPayload.TransientMap, nil
}
// GetHeader Get Header from bytes
func GetHeader(bytes []byte) (*common.Header, error) {
hdr := &common.Header{}
err := proto.Unmarshal(bytes, hdr)
if err != nil {
return nil, err
}
return hdr, nil
}
// GetNonce returns the nonce used in Proposal
func GetNonce(prop *peer.Proposal) ([]byte, error) {
// get back the header
hdr, err := GetHeader(prop.Header)
if err != nil {
return nil, fmt.Errorf("Could not extract the header from the proposal: %s", err)
}
chdr, err := UnmarshalChannelHeader(hdr.ChannelHeader)
if err != nil {
return nil, fmt.Errorf("Could not extract the channel header from the proposal: %s", err)
}
shdr, err := GetSignatureHeader(hdr.SignatureHeader)
if err != nil {
return nil, fmt.Errorf("Could not extract the signature header from the proposal: %s", err)
}
if common.HeaderType(chdr.Type) != common.HeaderType_ENDORSER_TRANSACTION &&
common.HeaderType(chdr.Type) != common.HeaderType_CONFIG {
return nil, fmt.Errorf("Invalid proposal type expected ENDORSER_TRANSACTION or CONFIG. Was: %d", chdr.Type)
}
if hdr.SignatureHeader == nil {
return nil, errors.New("Invalid signature header. It must be different from nil.")
}
ccPropPayload := &peer.ChaincodeProposalPayload{}
err = proto.Unmarshal(prop.Payload, ccPropPayload)
if err != nil {
return nil, err
}
return shdr.Nonce, nil
}
// GetChaincodeHeaderExtension get chaincode header extension given header
func GetChaincodeHeaderExtension(hdr *common.Header) (*peer.ChaincodeHeaderExtension, error) {
chdr, err := UnmarshalChannelHeader(hdr.ChannelHeader)
if err != nil {
return nil, err
}
chaincodeHdrExt := &peer.ChaincodeHeaderExtension{}
err = proto.Unmarshal(chdr.Extension, chaincodeHdrExt)
if err != nil {
return nil, err
}
return chaincodeHdrExt, nil
}
// GetProposalResponse given proposal in bytes
func GetProposalResponse(prBytes []byte) (*peer.ProposalResponse, error) {
proposalResponse := &peer.ProposalResponse{}
err := proto.Unmarshal(prBytes, proposalResponse)
if err != nil {
return nil, err
}
return proposalResponse, nil
}
// GetChaincodeDeploymentSpec returns a ChaincodeDeploymentSpec given args
func GetChaincodeDeploymentSpec(code []byte) (*peer.ChaincodeDeploymentSpec, error) {
cds := &peer.ChaincodeDeploymentSpec{}
err := proto.Unmarshal(code, cds)
if err != nil {
return nil, err
}
// FAB-2122: Validate the CDS according to platform specific requirements
platform, err := platforms.Find(cds.ChaincodeSpec.Type)
if err != nil {
return nil, err
}
err = platform.ValidateDeploymentSpec(cds)
if err != nil {
return nil, err
}
return cds, nil
}
// GetChaincodeAction gets the ChaincodeAction given chaicnode action bytes
func GetChaincodeAction(caBytes []byte) (*peer.ChaincodeAction, error) {
chaincodeAction := &peer.ChaincodeAction{}
err := proto.Unmarshal(caBytes, chaincodeAction)
if err != nil {
return nil, err
}
return chaincodeAction, nil
}
// GetResponse gets the Response given response bytes
func GetResponse(resBytes []byte) (*peer.Response, error) {
response := &peer.Response{}
err := proto.Unmarshal(resBytes, response)
if err != nil {
return nil, err
}
return response, nil
}
// GetChaincodeEvents gets the ChaincodeEvents given chaicnode event bytes
func GetChaincodeEvents(eBytes []byte) (*peer.ChaincodeEvent, error) {
chaincodeEvent := &peer.ChaincodeEvent{}
err := proto.Unmarshal(eBytes, chaincodeEvent)
if err != nil {
return nil, err
}
return chaincodeEvent, nil
}
// GetProposalResponsePayload gets the proposal response payload
func GetProposalResponsePayload(prpBytes []byte) (*peer.ProposalResponsePayload, error) {
prp := &peer.ProposalResponsePayload{}
err := proto.Unmarshal(prpBytes, prp)
if err != nil {
return nil, err
}
return prp, nil
}
// GetProposal returns a Proposal message from its bytes
func GetProposal(propBytes []byte) (*peer.Proposal, error) {
prop := &peer.Proposal{}
err := proto.Unmarshal(propBytes, prop)
if err != nil {
return nil, err
}
return prop, nil
}
// GetPayload Get Payload from Envelope message
func GetPayload(e *common.Envelope) (*common.Payload, error) {
payload := &common.Payload{}
err := proto.Unmarshal(e.Payload, payload)
if err != nil {
return nil, err
}
return payload, nil
}
// GetTransaction Get Transaction from bytes
func GetTransaction(txBytes []byte) (*peer.Transaction, error) {
tx := &peer.Transaction{}
err := proto.Unmarshal(txBytes, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// GetChaincodeActionPayload Get ChaincodeActionPayload from bytes
func GetChaincodeActionPayload(capBytes []byte) (*peer.ChaincodeActionPayload, error) {
cap := &peer.ChaincodeActionPayload{}
err := proto.Unmarshal(capBytes, cap)
if err != nil {
return nil, err
}
return cap, nil
}
// GetChaincodeProposalPayload Get ChaincodeProposalPayload from bytes
func GetChaincodeProposalPayload(bytes []byte) (*peer.ChaincodeProposalPayload, error) {
cpp := &peer.ChaincodeProposalPayload{}
err := proto.Unmarshal(bytes, cpp)
if err != nil {
return nil, err
}
return cpp, nil
}
// GetSignatureHeader Get SignatureHeader from bytes
func GetSignatureHeader(bytes []byte) (*common.SignatureHeader, error) {
sh := &common.SignatureHeader{}
err := proto.Unmarshal(bytes, sh)
if err != nil {
return nil, err
}
return sh, nil
}
// GetSignaturePolicyEnvelope returns a SignaturePolicyEnvelope from bytes
func GetSignaturePolicyEnvelope(bytes []byte) (*common.SignaturePolicyEnvelope, error) {
p := &common.SignaturePolicyEnvelope{}
err := proto.Unmarshal(bytes, p)
if err != nil {
return nil, err
}
return p, nil
}
// CreateChaincodeProposal creates a proposal from given input.
// It returns the proposal and the transaction id associated to the proposal
func CreateChaincodeProposal(typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, creator []byte) (*peer.Proposal, string, error) {
return CreateChaincodeProposalWithTransient(typ, chainID, cis, creator, nil)
}
// CreateChaincodeProposalWithTransient creates a proposal from given input
// It returns the proposal and the transaction id associated to the proposal
func CreateChaincodeProposalWithTransient(typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) {
// generate a random nonce
nonce, err := crypto.GetRandomNonce()
if err != nil {
return nil, "", err
}
// compute txid
txid, err := ComputeProposalTxID(nonce, creator)
if err != nil {
return nil, "", err
}
return CreateChaincodeProposalWithTxIDNonceAndTransient(txid, typ, chainID, cis, nonce, creator, transientMap)
}
// CreateChaincodeProposalWithTxIDNonceAndTransient creates a proposal from given input
func CreateChaincodeProposalWithTxIDNonceAndTransient(txid string, typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, nonce, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) {
ccHdrExt := &peer.ChaincodeHeaderExtension{ChaincodeId: cis.ChaincodeSpec.ChaincodeId}
ccHdrExtBytes, err := proto.Marshal(ccHdrExt)
if err != nil {
return nil, "", err
}
cisBytes, err := proto.Marshal(cis)
if err != nil {
return nil, "", err
}
ccPropPayload := &peer.ChaincodeProposalPayload{Input: cisBytes, TransientMap: transientMap}
ccPropPayloadBytes, err := proto.Marshal(ccPropPayload)
if err != nil {
return nil, "", err
}
// TODO: epoch is now set to zero. This must be changed once we
// get a more appropriate mechanism to handle it in.
var epoch uint64 = 0
timestamp := util.CreateUtcTimestamp()
hdr := &common.Header{ChannelHeader: MarshalOrPanic(&common.ChannelHeader{
Type: int32(typ),
TxId: txid,
Timestamp: timestamp,
ChannelId: chainID,
Extension: ccHdrExtBytes,
Epoch: epoch}),
SignatureHeader: MarshalOrPanic(&common.SignatureHeader{Nonce: nonce, Creator: creator})}
hdrBytes, err := proto.Marshal(hdr)
if err != nil {
return nil, "", err
}
return &peer.Proposal{Header: hdrBytes, Payload: ccPropPayloadBytes}, txid, nil
}
// GetBytesProposalResponsePayload gets proposal response payload
func GetBytesProposalResponsePayload(hash []byte, response *peer.Response, result []byte, event []byte, ccid *peer.ChaincodeID) ([]byte, error) {
cAct := &peer.ChaincodeAction{Events: event, Results: result, Response: response, ChaincodeId: ccid}
cActBytes, err := proto.Marshal(cAct)
if err != nil {
return nil, err
}
prp := &peer.ProposalResponsePayload{Extension: cActBytes, ProposalHash: hash}
prpBytes, err := proto.Marshal(prp)
if err != nil {
return nil, err
}
return prpBytes, nil
}
// GetBytesChaincodeProposalPayload gets the chaincode proposal payload
func GetBytesChaincodeProposalPayload(cpp *peer.ChaincodeProposalPayload) ([]byte, error) {
cppBytes, err := proto.Marshal(cpp)
if err != nil {
return nil, err
}
return cppBytes, nil
}
// GetBytesResponse gets the bytes of Response
func GetBytesResponse(res *peer.Response) ([]byte, error) {
resBytes, err := proto.Marshal(res)
if err != nil {
return nil, err
}
return resBytes, nil
}
// GetBytesChaincodeEvent gets the bytes of ChaincodeEvent
func GetBytesChaincodeEvent(event *peer.ChaincodeEvent) ([]byte, error) {
eventBytes, err := proto.Marshal(event)
if err != nil {
return nil, err
}
return eventBytes, nil
}
// GetBytesChaincodeActionPayload get the bytes of ChaincodeActionPayload from the message
func GetBytesChaincodeActionPayload(cap *peer.ChaincodeActionPayload) ([]byte, error) {
capBytes, err := proto.Marshal(cap)
if err != nil {
return nil, err
}
return capBytes, nil
}
// GetBytesProposalResponse gets propoal bytes response
func GetBytesProposalResponse(pr *peer.ProposalResponse) ([]byte, error) {
respBytes, err := proto.Marshal(pr)
if err != nil {
return nil, err
}
return respBytes, nil
}
// GetBytesProposal returns the bytes of a proposal message
func GetBytesProposal(prop *peer.Proposal) ([]byte, error) {
propBytes, err := proto.Marshal(prop)
if err != nil {
return nil, err
}
return propBytes, nil
}
// GetBytesHeader get the bytes of Header from the message
func GetBytesHeader(hdr *common.Header) ([]byte, error) {
bytes, err := proto.Marshal(hdr)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesSignatureHeader get the bytes of SignatureHeader from the message
func GetBytesSignatureHeader(hdr *common.SignatureHeader) ([]byte, error) {
bytes, err := proto.Marshal(hdr)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesTransaction get the bytes of Transaction from the message
func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) {
bytes, err := proto.Marshal(tx)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesPayload get the bytes of Payload from the message
func GetBytesPayload(payl *common.Payload) ([]byte, error) {
bytes, err := proto.Marshal(payl)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetBytesEnvelope get the bytes of Envelope from the message
func GetBytesEnvelope(env *common.Envelope) ([]byte, error) {
bytes, err := proto.Marshal(env)
if err != nil {
return nil, err
}
return bytes, nil
}
// GetActionFromEnvelope extracts a ChaincodeAction message from a serialized Envelope
func GetActionFromEnvelope(envBytes []byte) (*peer.ChaincodeAction, error) {
env, err := GetEnvelopeFromBlock(envBytes)
if err != nil {
return nil, err
}
payl, err := GetPayload(env)
if err != nil {
return nil, err
}
tx, err := GetTransaction(payl.Data)
if err != nil {
return nil, err
}
if len(tx.Actions) == 0 {
return nil, fmt.Errorf("At least one TransactionAction is required")
}
_, respPayload, err := GetPayloads(tx.Actions[0])
return respPayload, err
}
// CreateProposalFromCIS returns a proposal given a serialized identity and a ChaincodeInvocationSpec
func CreateProposalFromCIS(typ common.HeaderType, chainID string, cis *peer.ChaincodeInvocationSpec, creator []byte) (*peer.Proposal, string, error) {
return CreateChaincodeProposal(typ, chainID, cis, creator)
}
// CreateInstallProposalFromCDS returns a install proposal given a serialized identity and a ChaincodeDeploymentSpec
func CreateInstallProposalFromCDS(ccpack proto.Message, creator []byte) (*peer.Proposal, string, error) {
return createProposalFromCDS("", ccpack, creator, nil, nil, nil, "install")
}
// CreateDeployProposalFromCDS returns a deploy proposal given a serialized identity and a ChaincodeDeploymentSpec
func CreateDeployProposalFromCDS(chainID string, cds *peer.ChaincodeDeploymentSpec, creator []byte, policy []byte, escc []byte, vscc []byte) (*peer.Proposal, string, error) {
return createProposalFromCDS(chainID, cds, creator, policy, escc, vscc, "deploy")
}
// CreateUpgradeProposalFromCDS returns a upgrade proposal given a serialized identity and a ChaincodeDeploymentSpec
func CreateUpgradeProposalFromCDS(chainID string, cds *peer.ChaincodeDeploymentSpec, creator []byte, policy []byte, escc []byte, vscc []byte) (*peer.Proposal, string, error) {
return createProposalFromCDS(chainID, cds, creator, policy, escc, vscc, "upgrade")
}
// createProposalFromCDS returns a deploy or upgrade proposal given a serialized identity and a ChaincodeDeploymentSpec
func createProposalFromCDS(chainID string, msg proto.Message, creator []byte, policy []byte, escc []byte, vscc []byte, propType string) (*peer.Proposal, string, error) {
//in the new mode, cds will be nil, "deploy" and "upgrade" are instantiates.
var ccinp *peer.ChaincodeInput
var b []byte
var err error
if msg != nil {
b, err = proto.Marshal(msg)
if err != nil {
return nil, "", err
}
}
switch propType {
case "deploy":
fallthrough
case "upgrade":
cds, ok := msg.(*peer.ChaincodeDeploymentSpec)
if !ok || cds == nil {
return nil, "", fmt.Errorf("invalid message for creating lifecycle chaincode proposal from")
}
ccinp = &peer.ChaincodeInput{Args: [][]byte{[]byte(propType), []byte(chainID), b, policy, escc, vscc}}
case "install":
ccinp = &peer.ChaincodeInput{Args: [][]byte{[]byte(propType), b}}
}
//wrap the deployment in an invocation spec to lscc...
lsccSpec := &peer.ChaincodeInvocationSpec{
ChaincodeSpec: &peer.ChaincodeSpec{
Type: peer.ChaincodeSpec_GOLANG,
ChaincodeId: &peer.ChaincodeID{Name: "lscc"},
Input: ccinp}}
//...and get the proposal for it
return CreateProposalFromCIS(common.HeaderType_ENDORSER_TRANSACTION, chainID, lsccSpec, creator)
}
// ComputeProposalTxID computes TxID as the Hash computed
// over the concatenation of nonce and creator.
func ComputeProposalTxID(nonce, creator []byte) (string, error) {
// TODO: Get the Hash function to be used from
// channel configuration
digest, err := factory.GetDefault().Hash(
append(nonce, creator...),
&bccsp.SHA256Opts{})
if err != nil {
return "", err
}
return hex.EncodeToString(digest), nil
}
// CheckProposalTxID checks that txid is equal to the Hash computed
// over the concatenation of nonce and creator.
func CheckProposalTxID(txid string, nonce, creator []byte) error {
computedTxID, err := ComputeProposalTxID(nonce, creator)
if err != nil {
return fmt.Errorf("Failed computing target TXID for comparison [%s]", err)
}
if txid != computedTxID {
return fmt.Errorf("Transaction is not valid. Got [%s], expected [%s]", txid, computedTxID)
}
return nil
}
// ComputeProposalBinding computes the binding of a proposal
func ComputeProposalBinding(proposal *peer.Proposal) ([]byte, error) {
if proposal == nil {
return nil, fmt.Errorf("Porposal is nil")
}
if len(proposal.Header) == 0 {
return nil, fmt.Errorf("Proposal's Header is nil")
}
h, err := GetHeader(proposal.Header)
if err != nil {
return nil, err
}
chdr, err := UnmarshalChannelHeader(h.ChannelHeader)
if err != nil {
return nil, err
}
shdr, err := GetSignatureHeader(h.SignatureHeader)
if err != nil {
return nil, err
}
return computeProposalBindingInternal(shdr.Nonce, shdr.Creator, chdr.Epoch)
}
func computeProposalBindingInternal(nonce, creator []byte, epoch uint64) ([]byte, error) {
epochBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(epochBytes, epoch)
// TODO: add to genesis block the hash function used for the binding computation.
digest, err := factory.GetDefault().Hash(
append(append(nonce, creator...), epochBytes...),
&bccsp.SHA256Opts{})
if err != nil {
return nil, err
}
return digest, nil
}
|
mffrench/fabric
|
protos/utils/proputils.go
|
GO
|
apache-2.0
| 19,622 |
package spring.store;
import java.util.List;
/**
* Created by Andrey on 02.02.2018.
*/
public interface Storage <T>{
void add(User user);
List<T> getAll();
}
|
AVBaranov/abaranov
|
chapter_011/src/main/java/spring/store/Storage.java
|
Java
|
apache-2.0
| 170 |
/*
* Java port of Bullet (c) 2008 Martin Dvorak <jezek2@advel.cz>
*
* Bullet Continuous Collision Detection and Physics Library
* Copyright (c) 2003-2008 Erwin Coumans http://www.bulletphysics.com/
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
package org.gearvrf.bulletphysics.dynamics.constraintsolver;
import javax.vecmath.Matrix3f;
import javax.vecmath.Vector3f;
import org.gearvrf.bulletphysics.dynamics.RigidBody;
import org.gearvrf.bulletphysics.linearmath.Transform;
import org.gearvrf.bulletphysics.linearmath.VectorUtil;
import org.gearvrf.bulletphysics.stack.Stack;
/**
* Point to point constraint between two rigid bodies each with a pivot point that
* descibes the "ballsocket" location in local space.
*
* @author jezek2
*/
public class Point2PointConstraint extends TypedConstraint {
private final JacobianEntry[] jac = new JacobianEntry[]/*[3]*/ { new JacobianEntry(), new JacobianEntry(), new JacobianEntry() }; // 3 orthogonal linear constraints
private final Vector3f pivotInA = new Vector3f();
private final Vector3f pivotInB = new Vector3f();
public ConstraintSetting setting = new ConstraintSetting();
public Point2PointConstraint() {
super(TypedConstraintType.POINT2POINT_CONSTRAINT_TYPE);
}
public Point2PointConstraint(RigidBody rbA, RigidBody rbB, Vector3f pivotInA, Vector3f pivotInB) {
super(TypedConstraintType.POINT2POINT_CONSTRAINT_TYPE, rbA, rbB);
this.pivotInA.set(pivotInA);
this.pivotInB.set(pivotInB);
}
public Point2PointConstraint(RigidBody rbA, Vector3f pivotInA) {
super(TypedConstraintType.POINT2POINT_CONSTRAINT_TYPE, rbA);
this.pivotInA.set(pivotInA);
this.pivotInB.set(pivotInA);
rbA.getCenterOfMassTransform(Stack.alloc(Transform.class)).transform(this.pivotInB);
}
@Override
public void buildJacobian() {
appliedImpulse = 0f;
Vector3f normal = Stack.alloc(Vector3f.class);
normal.set(0f, 0f, 0f);
Matrix3f tmpMat1 = Stack.alloc(Matrix3f.class);
Matrix3f tmpMat2 = Stack.alloc(Matrix3f.class);
Vector3f tmp1 = Stack.alloc(Vector3f.class);
Vector3f tmp2 = Stack.alloc(Vector3f.class);
Vector3f tmpVec = Stack.alloc(Vector3f.class);
Transform centerOfMassA = rbA.getCenterOfMassTransform(Stack.alloc(Transform.class));
Transform centerOfMassB = rbB.getCenterOfMassTransform(Stack.alloc(Transform.class));
for (int i = 0; i < 3; i++) {
VectorUtil.setCoord(normal, i, 1f);
tmpMat1.transpose(centerOfMassA.basis);
tmpMat2.transpose(centerOfMassB.basis);
tmp1.set(pivotInA);
centerOfMassA.transform(tmp1);
tmp1.sub(rbA.getCenterOfMassPosition(tmpVec));
tmp2.set(pivotInB);
centerOfMassB.transform(tmp2);
tmp2.sub(rbB.getCenterOfMassPosition(tmpVec));
jac[i].init(
tmpMat1,
tmpMat2,
tmp1,
tmp2,
normal,
rbA.getInvInertiaDiagLocal(Stack.alloc(Vector3f.class)),
rbA.getInvMass(),
rbB.getInvInertiaDiagLocal(Stack.alloc(Vector3f.class)),
rbB.getInvMass());
VectorUtil.setCoord(normal, i, 0f);
}
}
@Override
public void solveConstraint(float timeStep) {
Vector3f tmp = Stack.alloc(Vector3f.class);
Vector3f tmp2 = Stack.alloc(Vector3f.class);
Vector3f tmpVec = Stack.alloc(Vector3f.class);
Transform centerOfMassA = rbA.getCenterOfMassTransform(Stack.alloc(Transform.class));
Transform centerOfMassB = rbB.getCenterOfMassTransform(Stack.alloc(Transform.class));
Vector3f pivotAInW = Stack.alloc(pivotInA);
centerOfMassA.transform(pivotAInW);
Vector3f pivotBInW = Stack.alloc(pivotInB);
centerOfMassB.transform(pivotBInW);
Vector3f normal = Stack.alloc(Vector3f.class);
normal.set(0f, 0f, 0f);
//btVector3 angvelA = m_rbA.getCenterOfMassTransform().getBasis().transpose() * m_rbA.getAngularVelocity();
//btVector3 angvelB = m_rbB.getCenterOfMassTransform().getBasis().transpose() * m_rbB.getAngularVelocity();
for (int i = 0; i < 3; i++) {
VectorUtil.setCoord(normal, i, 1f);
float jacDiagABInv = 1f / jac[i].getDiagonal();
Vector3f rel_pos1 = Stack.alloc(Vector3f.class);
rel_pos1.sub(pivotAInW, rbA.getCenterOfMassPosition(tmpVec));
Vector3f rel_pos2 = Stack.alloc(Vector3f.class);
rel_pos2.sub(pivotBInW, rbB.getCenterOfMassPosition(tmpVec));
// this jacobian entry could be re-used for all iterations
Vector3f vel1 = rbA.getVelocityInLocalPoint(rel_pos1, Stack.alloc(Vector3f.class));
Vector3f vel2 = rbB.getVelocityInLocalPoint(rel_pos2, Stack.alloc(Vector3f.class));
Vector3f vel = Stack.alloc(Vector3f.class);
vel.sub(vel1, vel2);
float rel_vel;
rel_vel = normal.dot(vel);
/*
//velocity error (first order error)
btScalar rel_vel = m_jac[i].getRelativeVelocity(m_rbA.getLinearVelocity(),angvelA,
m_rbB.getLinearVelocity(),angvelB);
*/
// positional error (zeroth order error)
tmp.sub(pivotAInW, pivotBInW);
float depth = -tmp.dot(normal); //this is the error projected on the normal
float impulse = depth * setting.tau / timeStep * jacDiagABInv - setting.damping * rel_vel * jacDiagABInv;
float impulseClamp = setting.impulseClamp;
if (impulseClamp > 0f) {
if (impulse < -impulseClamp) {
impulse = -impulseClamp;
}
if (impulse > impulseClamp) {
impulse = impulseClamp;
}
}
appliedImpulse += impulse;
Vector3f impulse_vector = Stack.alloc(Vector3f.class);
impulse_vector.scale(impulse, normal);
tmp.sub(pivotAInW, rbA.getCenterOfMassPosition(tmpVec));
rbA.applyImpulse(impulse_vector, tmp);
tmp.negate(impulse_vector);
tmp2.sub(pivotBInW, rbB.getCenterOfMassPosition(tmpVec));
rbB.applyImpulse(tmp, tmp2);
VectorUtil.setCoord(normal, i, 0f);
}
}
public void updateRHS(float timeStep) {
}
public void setPivotA(Vector3f pivotA) {
pivotInA.set(pivotA);
}
public void setPivotB(Vector3f pivotB) {
pivotInB.set(pivotB);
}
public Vector3f getPivotInA(Vector3f out) {
out.set(pivotInA);
return out;
}
public Vector3f getPivotInB(Vector3f out) {
out.set(pivotInB);
return out;
}
////////////////////////////////////////////////////////////////////////////
public static class ConstraintSetting {
public float tau = 0.3f;
public float damping = 1f;
public float impulseClamp = 0f;
}
}
|
danke-sra/GearVRf
|
GVRf/Framework/src/org/gearvrf/bulletphysics/dynamics/constraintsolver/Point2PointConstraint.java
|
Java
|
apache-2.0
| 7,029 |
/**
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* 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.jboss.arquillian.warp.client.proxy;
import java.lang.annotation.Annotation;
import java.net.URL;
import org.jboss.arquillian.container.test.impl.enricher.resource.URLResourceProvider;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
import org.jboss.arquillian.warp.utils.URLUtils;
/**
* Provides the proxy URL instead of real URL.
*
* Stores the mapping between real URL and proxy URL in {@link URLMapping}.
*
* @author Lukas Fryc
*
*/
public class ProxyURLProvider implements ResourceProvider {
@Inject
Instance<ServiceLoader> serviceLoader;
@Inject
Instance<URLMapping> mapping;
@Inject
Instance<ProxyHolder> proxyHolder;
@Inject
Instance<Injector> injector;
URLResourceProvider urlResourceProvider = new URLResourceProvider();
@Override
public boolean canProvide(Class<?> type) {
return URL.class.isAssignableFrom(type);
}
@Override
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
injector.get().inject(urlResourceProvider);
URL realUrl = (URL) urlResourceProvider.lookup(resource, qualifiers);
if ("http".equals(realUrl.getProtocol())) {
return getProxyUrl(realUrl);
} else {
return realUrl;
}
}
private URL getProxyUrl(URL realUrl) {
URL baseRealUrl = URLUtils.getUrlBase(realUrl);
URL baseProxyUrl = mapping.get().getProxyURL(baseRealUrl);
URL proxyUrl = URLUtils.buildUrl(baseProxyUrl, realUrl.getPath());
proxyHolder.get().startProxyForUrl(baseProxyUrl, baseRealUrl);
return proxyUrl;
}
}
|
aslakknutsen/arquillian-extension-warp
|
impl/src/main/java/org/jboss/arquillian/warp/client/proxy/ProxyURLProvider.java
|
Java
|
apache-2.0
| 2,711 |
/*
* 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.ignite.examples.ml.tutorial;
import java.io.FileNotFoundException;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.ml.dataset.feature.extractor.Vectorizer;
import org.apache.ignite.ml.dataset.feature.extractor.impl.DummyVectorizer;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.preprocessing.Preprocessor;
import org.apache.ignite.ml.preprocessing.imputing.ImputerTrainer;
import org.apache.ignite.ml.selection.scoring.evaluator.Evaluator;
import org.apache.ignite.ml.selection.scoring.metric.classification.Accuracy;
import org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer;
import org.apache.ignite.ml.tree.DecisionTreeNode;
/**
* Usage of {@link ImputerTrainer} to fill missed data ({@code Double.NaN}) values in the chosen columns.
* <p>
* Code in this example launches Ignite grid and fills the cache with test data (based on Titanic passengers data).</p>
* <p>
* After that it defines preprocessors that extract features from an upstream data and
* <a href="https://en.wikipedia.org/wiki/Imputation_(statistics)">impute</a> missing values.</p>
* <p>
* Then, it trains the model based on the processed data using decision tree classification.</p>
* <p>
* Finally, this example uses {@link Evaluator} functionality to compute metrics from predictions.</p>
*/
public class Step_2_Imputing {
/** Run example. */
public static void main(String[] args) {
System.out.println();
System.out.println(">>> Tutorial step 2 (imputing) example started.");
try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
try {
IgniteCache<Integer, Vector> dataCache = TitanicUtils.readPassengers(ignite);
final Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>(0, 5, 6).labeled(1);
Preprocessor<Integer, Vector> imputingPreprocessor = new ImputerTrainer<Integer, Vector>()
.fit(ignite,
dataCache,
vectorizer // "pclass", "sibsp", "parch"
);
DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(5, 0);
// Train decision tree model.
DecisionTreeNode mdl = trainer.fit(
ignite,
dataCache,
vectorizer
);
System.out.println("\n>>> Trained model: " + mdl);
double accuracy = Evaluator.evaluate(
dataCache,
mdl,
imputingPreprocessor,
new Accuracy<>()
);
System.out.println("\n>>> Accuracy " + accuracy);
System.out.println("\n>>> Test Error " + (1 - accuracy));
System.out.println(">>> Tutorial step 2 (imputing) example completed.");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
|
ilantukh/ignite
|
examples/src/main/java/org/apache/ignite/examples/ml/tutorial/Step_2_Imputing.java
|
Java
|
apache-2.0
| 3,986 |
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class FeedbackResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
*
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'subject' => $this->subject,
'user_id' => $this->user_id,
'description' => $this->description,
'created_at' => optional($this->created_at)->toDateTimeString(),
'author' => new UserResource($this->owner),
];
}
}
|
voten-co/voten
|
app/Http/Resources/FeedbackResource.php
|
PHP
|
apache-2.0
| 656 |
/*
Copyright ONECHAIN 2017 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var StompServer=require('stomp-broker-js')
var stompServer
function init(http){
stompServer=new StompServer({server:http})
}
module.exports.init=init
module.exports.stomp=function () {
return stompServer
}
|
onechain/fabric-explorer
|
socket/websocketserver.js
|
JavaScript
|
apache-2.0
| 801 |
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
/* separation_stats.cc
Jeremy Barnes, 14 June 2011
Copyright (c) 2011 mldb.ai inc. All rights reserved.
*/
#include "separation_stats.h"
#include "mldb/arch/exception.h"
#include "mldb/base/exc_assert.h"
#include <boost/utility.hpp>
#include "mldb/vfs/filter_streams.h"
using namespace std;
namespace MLDB {
/*****************************************************************************/
/* BINARY STATS */
/*****************************************************************************/
double
BinaryStats::
rocAreaSince(const BinaryStats & other) const
{
double tp1 = other.truePositiveRate(), fp1 = other.falsePositiveRate();
double tp2 = truePositiveRate(), fp2 = falsePositiveRate();
double result = (fp2 - fp1) * (tp1 + tp2) * 0.5;
//cerr << "tp1 = " << tp1 << " tp2 = " << tp2 << " fp1 = " << fp1
// << " fp2 = " << fp2 << " area = " << result << endl;
return result;
}
void
BinaryStats::
add(const BinaryStats & other, double weight)
{
auto addCounts = [&] ( Array2D & local,
const Array2D & other,
float w)
{
local[0][0] += w * other[0][0];
local[0][1] += w * other[0][1];
local[1][0] += w * other[1][0];
local[1][1] += w * other[1][1];
};
addCounts(counts, other.counts, weight);
addCounts(unweighted_counts, other.unweighted_counts, 1);
threshold += weight * other.threshold;
}
Json::Value
BinaryStats::
toJson() const
{
Json::Value result;
result["population"]["included"] = includedPopulation();
result["population"]["excluded"] = excludedPopulation();
result["pr"]["accuracy"] = accuracy();
result["pr"]["precision"] = precision();
result["pr"]["recall"] = recall();
result["pr"]["f1Score"] = f();
result["mcc"] = mcc();
result["gain"] = gain();
result["counts"]["truePositives"] = truePositives();
result["counts"]["falsePositives"] = falsePositives();
result["counts"]["trueNegatives"] = trueNegatives();
result["counts"]["falseNegatives"] = falseNegatives();
result["threshold"] = threshold;
return result;
}
/*****************************************************************************/
/* SCORED STATS */
/*****************************************************************************/
ScoredStats::
ScoredStats()
: auc(1.0), isSorted(true)
{
}
BinaryStats
ScoredStats::
atThreshold(float threshold) const
{
struct FindThreshold {
bool operator () (const BinaryStats & e1, const BinaryStats & e2) const
{
return e1.threshold > e2.threshold;
}
bool operator () (const BinaryStats & e1, float e2) const
{
return e1.threshold > e2;
}
bool operator () (float e1, const BinaryStats & e2) const
{
return e1 > e2.threshold;
}
};
if (!std::is_sorted(stats.begin(), stats.end(), FindThreshold()))
throw Exception("stats not sorted on input");
if (stats.empty())
throw Exception("stats is empty");
// Lower bound means strictly above
auto lower
= std::lower_bound(stats.begin(), stats.end(), threshold,
FindThreshold());
if (lower == stats.end())
return stats.back();
return *lower;
}
BinaryStats
ScoredStats::
atPercentile(float percentile) const
{
struct FindPercentile {
bool operator () (const BinaryStats & e1, const BinaryStats & e2) const
{
return e1.proportionOfPopulation() < e2.proportionOfPopulation();
}
bool operator () (const BinaryStats & e1, float e2) const
{
return e1.proportionOfPopulation() < e2;
}
bool operator () (float e1, const BinaryStats & e2) const
{
return e1 < e2.proportionOfPopulation();
}
};
for (unsigned i = 1; i < stats.size(); ++i) {
if (stats[i -1].proportionOfPopulation() > stats[i].proportionOfPopulation()) {
cerr << "i = " << i << endl;
cerr << "prev = " << stats[i - 1].toJson() << endl;
cerr << "ours = " << stats[i].toJson() << endl;
throw MLDB::Exception("really not sorted on input");
}
}
if (!std::is_sorted(stats.begin(), stats.end(), FindPercentile()))
throw Exception("stats not sorted on input");
if (stats.empty())
throw Exception("stats is empty");
// Lower bound means strictly above
auto it
= std::lower_bound(stats.begin(), stats.end(), percentile,
FindPercentile());
if (it == stats.begin())
return *it;
if (it == stats.end())
return stats.back();
BinaryStats upper = *it, lower = *std::prev(it);
// Do an interpolation
double atUpper = upper.proportionOfPopulation(),
atLower = lower.proportionOfPopulation(),
range = atUpper - atLower;
ExcAssertLessEqual(percentile, atUpper);
ExcAssertGreaterEqual(percentile, atLower);
ExcAssertGreater(range, 0);
double weight1 = (atUpper - percentile) / range;
double weight2 = (percentile - atLower) / range;
//cerr << "atUpper = " << atUpper << " atLower = " << atLower
// << " range = " << range << " weight1 = " << weight1
// << " weight2 = " << weight2 << endl;
BinaryStats result;
result.add(upper, weight2);
result.add(lower, weight1);
//cerr << "result prop = " << result.proportionOfPopulation() << endl;
return result;
}
void
ScoredStats::
sort()
{
// Go from highest to lowest score
std::sort(entries.begin(), entries.end());
isSorted = true;
}
void
ScoredStats::
calculate()
{
BinaryStats current;
for (unsigned i = 0; i < entries.size(); ++i)
current.counts[entries[i].label][false] += entries[i].weight;
if (!isSorted)
sort();
bestF = current;
bestMcc = current;
double totalAuc = 0.0;
stats.clear();
// take the all point
stats.push_back(BinaryStats(current, INFINITY));
for (unsigned i = 0; i < entries.size(); ++i) {
const ScoredStats::ScoredEntry & entry = entries[i];
if (i > 0 && entries[i - 1].score != entry.score) {
totalAuc += current.rocAreaSince(stats.back());
stats.push_back
(BinaryStats(current, entries[i - 1].score, entry.key));
if (current.f() > bestF.f())
bestF = stats.back();
if (current.mcc() > bestMcc.mcc())
bestMcc = stats.back();
if (current.specificity() > bestSpecificity.specificity())
bestSpecificity = stats.back();
#if 0
cerr << "entry " << i << ": score " << entries[i - 1].score
<< " p " << current.precision() << " r " << current.recall()
<< " f " << current.f() << " mcc " << current.mcc() << endl;
#endif
}
bool label = entry.label;
// We transfer from a false positive to a true negative, or a
// true positive to a false negative
double weight = entry.weight;
current.counts[label][false] -= weight;
current.counts[label][true] += weight;
current.unweighted_counts[label][false] -= 1;
current.unweighted_counts[label][true] += 1;
}
totalAuc += current.rocAreaSince(stats.back());
if (!entries.empty())
stats.push_back(BinaryStats(current, entries.back().score));
auc = totalAuc;
}
void
ScoredStats::
add(const ScoredStats & other)
{
if (!isSorted)
throw MLDB::Exception("attempt to add to non-sorted separation stats");
if (!other.isSorted)
throw MLDB::Exception("attempt to add non-sorted separation stats");
size_t split = entries.size();
entries.insert(entries.end(), other.entries.begin(), other.entries.end());
std::inplace_merge(entries.begin(), entries.begin() + split,
entries.end());
// If we had already calculated, we recalculate
if (!stats.empty())
calculate();
}
void
ScoredStats::
dumpRocCurveJs(std::ostream & stream) const
{
if (stats.empty())
throw MLDB::Exception("can't dump ROC curve without calling calculate()");
stream << "this.data = {" << endl;
stream << MLDB::format(" \"aroc\": %8.05f , ", auc) << endl;
stream << " \"model\":{";
for(unsigned i = 0; i < stats.size(); ++i) {
const BinaryStats & x = stats[i];
stream << MLDB::format("\n \"%8.05f\": { ", x.threshold);
stream << MLDB::format("\n tpr : %8.05f,", x.recall());
stream << MLDB::format("\n accuracy : %8.05f,", x.accuracy());
stream << MLDB::format("\n precision : %8.05f,", x.precision());
stream << MLDB::format("\n fscore : %8.05f,", x.f());
stream << MLDB::format("\n fpr : %8.05f,", x.falsePositiveRate());
stream << MLDB::format("\n tp : %8.05f,", x.truePositives());
stream << MLDB::format("\n fp : %8.05f,", x.falsePositives());
stream << MLDB::format("\n fn : %8.05f,", x.falseNegatives());
stream << MLDB::format("\n tn : %8.05f,", x.trueNegatives());
stream << MLDB::format("}");
stream << ",";
}
stream << "\n}";
stream << "};";
}
void
ScoredStats::
saveRocCurveJs(const std::string & filename) const
{
filter_ostream stream(filename);
dumpRocCurveJs(stream);
}
Json::Value
ScoredStats::
getRocCurveJson() const
{
if (stats.empty())
throw MLDB::Exception("can't dump ROC curve without calling calculate()");
Json::Value modelJs;
for(unsigned i = 0; i < stats.size(); ++i) {
const BinaryStats & x = stats[i];
modelJs[MLDB::format("%8.05f", x.threshold)] = x.toJson();
}
Json::Value js;
js["aroc"] = auc;
js["model"] = modelJs;
js["bestF1Score"] = bestF.toJson();
js["bestMcc"] = bestMcc.toJson();
return js;
}
void
ScoredStats::
saveRocCurveJson(const std::string & filename) const
{
filter_ostream stream(filename);
stream << getRocCurveJson().toStyledString() << endl;
}
Json::Value
ScoredStats::
toJson() const
{
Json::Value result;
result["auc"] = auc;
result["bestF1Score"] = bestF.toJson();
result["bestMcc"] = bestMcc.toJson();
return result;
}
} // namespace MLDB
|
mldbai/mldb
|
plugins/jml/separation_stats.cc
|
C++
|
apache-2.0
| 10,625 |
/*jslint devel: true */
/*global Titanium, module */
(function (Ti) {
"use strict";
var style = {
win: {
backgroundColor: "#FFFFFF",
layout: "vertical"
},
btn: {
top: 44,
title: "Get GeoHash!"
},
label: {
top: 22,
color: "#666666",
font: {
fontFamily: "monospace"
}
},
map: {
top: 22,
mapType: Ti.Map.STANDARD_TYPE,
animate: true,
regionFit: true
},
extend: function (target, append) {
var key;
for (key in append) {
if (append.hasOwnProperty(key)) {
target[key] = append[key];
}
}
return target;
}
};
module.exports = style;
}(Titanium));
|
ryugoo/TiGeoHash
|
Resources/style/app.style.js
|
JavaScript
|
apache-2.0
| 898 |
package com.junitlet.rule;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import com.junitlet.rule.LoggingRule.Phase;
public class LoggingRuleTest {
@Rule
public final LoggingRule<Logger> javaUtilLogger =
new LoggingRuleBuilder<Logger>().
with(Logger.class).
log(Phase.starting, "info").
log(Phase.succeeded, "info").
log(Phase.failed, "severe").
build();
private static List<String> logMessages = new ArrayList<>();
private static Handler javaUtilLoggerHandler = new Handler() {
@Override
public void publish(LogRecord record) {
logMessages.add(record.getMessage());
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
};
@BeforeClass
public static void logSetup() {
Logger.getLogger(LoggingRuleTest.class.getName()).addHandler(javaUtilLoggerHandler);
}
@Test
public void test1() {
assertTrue(true);
}
@Test
public void test2() {
assertTrue(true);
}
@AfterClass
public static void logCheck() {
Logger.getLogger(LoggingRuleTest.class.getName()).removeHandler(javaUtilLoggerHandler);
assertTrue(logMessages.get(0).matches(".*test1.*is starting"));
assertTrue(logMessages.get(1).matches(".*test1.*is succeeded"));
assertTrue(logMessages.get(2).matches(".*test2.*is starting"));
assertTrue(logMessages.get(3).matches(".*test2.*is succeeded"));
}
}
|
alexradzin/JUnitlet
|
src/test/java/com/junitlet/rule/LoggingRuleTest.java
|
Java
|
apache-2.0
| 1,672 |
/*
* Copyright (C) 2017 Google 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 com.google.caliper.runner.worker;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Scope;
/** Scope annotation for per-{@link Worker} bindings, which should be unique per worker instance. */
@Target({TYPE, METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Scope
public @interface WorkerScoped {}
|
google/caliper
|
caliper-runner/src/main/java/com/google/caliper/runner/worker/WorkerScoped.java
|
Java
|
apache-2.0
| 1,098 |
package org.egorlitvinenko.certification.oca.book1.assessment.Q3;
/**
* Created by Egor Litvinenko on 19.01.17.
*/
public interface HasTail {
int getTailLength();
}
|
egorlitvinenko/JavaLearning
|
src/org/egorlitvinenko/certification/oca/book1/assessment/Q3/HasTail.java
|
Java
|
apache-2.0
| 172 |
'''
This module provides some handle-related functions
that are needed across various modules of the
pyhandle library.
'''
from __future__ import absolute_import
import base64
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import quote
from . import handleexceptions
from . import util
def remove_index_from_handle(handle_with_index):
'''
Returns index and handle separately, in a tuple.
:handle_with_index: The handle string with an index (e.g.
500:prefix/suffix)
:return: index and handle as a tuple, where index is integer.
'''
split = handle_with_index.split(':')
if len(split) == 2:
split[0] = int(split[0])
return split
elif len(split) == 1:
return (None, handle_with_index)
elif len(split) > 2:
raise handleexceptions.HandleSyntaxError(
msg='Too many colons',
handle=handle_with_index,
expected_syntax='index:prefix/suffix')
def check_handle_syntax(string):
'''
Checks the syntax of a handle without an index (are prefix
and suffix there, are there too many slashes?).
:string: The handle without index, as string prefix/suffix.
:raise: :exc:`~pyhandle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
'''
expected = 'prefix/suffix'
try:
arr = string.split('/')
except AttributeError:
raise handleexceptions.HandleSyntaxError(msg='The provided handle is None', expected_syntax=expected)
if len(arr) < 2:
msg = 'No slash'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[0]) == 0:
msg = 'Empty prefix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[1]) == 0:
msg = 'Empty suffix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if ':' in string:
check_handle_syntax_with_index(string, base_already_checked=True)
return True
def check_handle_syntax_with_index(string, base_already_checked=False):
'''
Checks the syntax of a handle with an index (is index there, is it an
integer?), and of the handle itself.
:string: The handle with index, as string index:prefix/suffix.
:raise: :exc:`~pyhandle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
'''
expected = 'index:prefix/suffix'
try:
arr = string.split(':')
except AttributeError:
raise handleexceptions.HandleSyntaxError(msg='The provided handle is None.', expected_syntax=expected)
if len(arr) > 2:
msg = 'Too many colons'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
elif len(arr) < 2:
msg = 'No colon'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
try:
int(arr[0])
except ValueError:
msg = 'Index is not an integer'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if not base_already_checked:
check_handle_syntax(string)
return True
def create_authentication_string(username, password):
'''
Creates an authentication string from the username and password.
:username: Username.
:password: Password.
:return: The encoded string.
'''
username_utf8 = username.encode('utf-8')
userpw_utf8 = password.encode('utf-8').decode('utf-8')
username_perc = quote(username_utf8)
authinfostring = username_perc + ':' + userpw_utf8
authinfostring_base64 = base64.b64encode(authinfostring.encode('utf-8')).decode('utf-8')
return authinfostring_base64
def make_request_log_message(**args):
'''
Creates a string containing all relevant information
about a request made to the Handle System, for
logging purposes.
:handle: The handle that the request is about.
:url: The url the request is sent to.
:headers: The headers sent along with the request.
:verify: Boolean parameter passed to the requests
module (https verification).
:resp: The request's response.
:op: The library operation during which the request
was sent.
:payload: Optional. The payload sent with the request.
:return: A formatted string.
'''
mandatory_args = ['op', 'handle', 'url', 'headers', 'verify', 'resp']
optional_args = ['payload']
util.check_presence_of_mandatory_args(args, mandatory_args)
util.add_missing_optional_args_with_value_none(args, optional_args)
space = '\n '
message = ''
message += '\n'+args['op']+' '+args['handle']
message += space+'URL: '+args['url']
message += space+'HEADERS: '+str(args['headers'])
message += space+'VERIFY: '+str(args['verify'])
if 'payload' in args.keys():
message += space+'PAYLOAD:'+space+str(args['payload'])
message += space+'RESPONSECODE: '+str(args['resp'].status_code)
message += space+'RESPONSE:'+space+str(args['resp'].content)
return message
|
EUDAT-B2SAFE/PYHANDLE
|
pyhandle/utilhandle.py
|
Python
|
apache-2.0
| 5,268 |
/*
* 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.cloudformation.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* The output for the <a>GetTemplateSummary</a> action.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/GetTemplateSummary" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetTemplateSummaryResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ParameterDeclaration> parameters;
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*/
private String description;
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> capabilities;
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*/
private String capabilitiesReason;
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> resourceTypes;
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*/
private String version;
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*/
private String metadata;
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> declaredTransforms;
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary> resourceIdentifierSummaries;
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*
* @return A list of parameter declarations that describe various properties for each parameter.
*/
public java.util.List<ParameterDeclaration> getParameters() {
if (parameters == null) {
parameters = new com.amazonaws.internal.SdkInternalList<ParameterDeclaration>();
}
return parameters;
}
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*
* @param parameters
* A list of parameter declarations that describe various properties for each parameter.
*/
public void setParameters(java.util.Collection<ParameterDeclaration> parameters) {
if (parameters == null) {
this.parameters = null;
return;
}
this.parameters = new com.amazonaws.internal.SdkInternalList<ParameterDeclaration>(parameters);
}
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setParameters(java.util.Collection)} or {@link #withParameters(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param parameters
* A list of parameter declarations that describe various properties for each parameter.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withParameters(ParameterDeclaration... parameters) {
if (this.parameters == null) {
setParameters(new com.amazonaws.internal.SdkInternalList<ParameterDeclaration>(parameters.length));
}
for (ParameterDeclaration ele : parameters) {
this.parameters.add(ele);
}
return this;
}
/**
* <p>
* A list of parameter declarations that describe various properties for each parameter.
* </p>
*
* @param parameters
* A list of parameter declarations that describe various properties for each parameter.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withParameters(java.util.Collection<ParameterDeclaration> parameters) {
setParameters(parameters);
return this;
}
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*
* @param description
* The value that's defined in the <code>Description</code> property of the template.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*
* @return The value that's defined in the <code>Description</code> property of the template.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The value that's defined in the <code>Description</code> property of the template.
* </p>
*
* @param description
* The value that's defined in the <code>Description</code> property of the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @return The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use
* the <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return
* an <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @see Capability
*/
public java.util.List<String> getCapabilities() {
if (capabilities == null) {
capabilities = new com.amazonaws.internal.SdkInternalList<String>();
}
return capabilities;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @see Capability
*/
public void setCapabilities(java.util.Collection<String> capabilities) {
if (capabilities == null) {
this.capabilities = null;
return;
}
this.capabilities = new com.amazonaws.internal.SdkInternalList<String>(capabilities);
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setCapabilities(java.util.Collection)} or {@link #withCapabilities(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Capability
*/
public GetTemplateSummaryResult withCapabilities(String... capabilities) {
if (this.capabilities == null) {
setCapabilities(new com.amazonaws.internal.SdkInternalList<String>(capabilities.length));
}
for (String ele : capabilities) {
this.capabilities.add(ele);
}
return this;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Capability
*/
public GetTemplateSummaryResult withCapabilities(java.util.Collection<String> capabilities) {
setCapabilities(capabilities);
return this;
}
/**
* <p>
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.
* </p>
* <p>
* For more information, see <a
* href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* </p>
*
* @param capabilities
* The capabilities found within the template. If your template contains IAM resources, you must specify the
* <code>CAPABILITY_IAM</code> or <code>CAPABILITY_NAMED_IAM</code> value for this parameter when you use the
* <a>CreateStack</a> or <a>UpdateStack</a> actions with your template; otherwise, those actions return an
* <code>InsufficientCapabilities</code> error.</p>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities"
* >Acknowledging IAM Resources in CloudFormation Templates</a>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Capability
*/
public GetTemplateSummaryResult withCapabilities(Capability... capabilities) {
com.amazonaws.internal.SdkInternalList<String> capabilitiesCopy = new com.amazonaws.internal.SdkInternalList<String>(capabilities.length);
for (Capability value : capabilities) {
capabilitiesCopy.add(value.toString());
}
if (getCapabilities() == null) {
setCapabilities(capabilitiesCopy);
} else {
getCapabilities().addAll(capabilitiesCopy);
}
return this;
}
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*
* @param capabilitiesReason
* The list of resources that generated the values in the <code>Capabilities</code> response element.
*/
public void setCapabilitiesReason(String capabilitiesReason) {
this.capabilitiesReason = capabilitiesReason;
}
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*
* @return The list of resources that generated the values in the <code>Capabilities</code> response element.
*/
public String getCapabilitiesReason() {
return this.capabilitiesReason;
}
/**
* <p>
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* </p>
*
* @param capabilitiesReason
* The list of resources that generated the values in the <code>Capabilities</code> response element.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withCapabilitiesReason(String capabilitiesReason) {
setCapabilitiesReason(capabilitiesReason);
return this;
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*
* @return A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
*/
public java.util.List<String> getResourceTypes() {
if (resourceTypes == null) {
resourceTypes = new com.amazonaws.internal.SdkInternalList<String>();
}
return resourceTypes;
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*
* @param resourceTypes
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
*/
public void setResourceTypes(java.util.Collection<String> resourceTypes) {
if (resourceTypes == null) {
this.resourceTypes = null;
return;
}
this.resourceTypes = new com.amazonaws.internal.SdkInternalList<String>(resourceTypes);
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setResourceTypes(java.util.Collection)} or {@link #withResourceTypes(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param resourceTypes
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceTypes(String... resourceTypes) {
if (this.resourceTypes == null) {
setResourceTypes(new com.amazonaws.internal.SdkInternalList<String>(resourceTypes.length));
}
for (String ele : resourceTypes) {
this.resourceTypes.add(ele);
}
return this;
}
/**
* <p>
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and <code>Custom::MyCustomInstance</code>.
* </p>
*
* @param resourceTypes
* A list of all the template resource types that are defined in the template, such as
* <code>AWS::EC2::Instance</code>, <code>AWS::Dynamo::Table</code>, and
* <code>Custom::MyCustomInstance</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceTypes(java.util.Collection<String> resourceTypes) {
setResourceTypes(resourceTypes);
return this;
}
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*
* @param version
* The Amazon Web Services template format version, which identifies the capabilities of the template.
*/
public void setVersion(String version) {
this.version = version;
}
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*
* @return The Amazon Web Services template format version, which identifies the capabilities of the template.
*/
public String getVersion() {
return this.version;
}
/**
* <p>
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* </p>
*
* @param version
* The Amazon Web Services template format version, which identifies the capabilities of the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withVersion(String version) {
setVersion(version);
return this;
}
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*
* @param metadata
* The value that's defined for the <code>Metadata</code> property of the template.
*/
public void setMetadata(String metadata) {
this.metadata = metadata;
}
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*
* @return The value that's defined for the <code>Metadata</code> property of the template.
*/
public String getMetadata() {
return this.metadata;
}
/**
* <p>
* The value that's defined for the <code>Metadata</code> property of the template.
* </p>
*
* @param metadata
* The value that's defined for the <code>Metadata</code> property of the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withMetadata(String metadata) {
setMetadata(metadata);
return this;
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*
* @return A list of the transforms that are declared in the template.
*/
public java.util.List<String> getDeclaredTransforms() {
if (declaredTransforms == null) {
declaredTransforms = new com.amazonaws.internal.SdkInternalList<String>();
}
return declaredTransforms;
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*
* @param declaredTransforms
* A list of the transforms that are declared in the template.
*/
public void setDeclaredTransforms(java.util.Collection<String> declaredTransforms) {
if (declaredTransforms == null) {
this.declaredTransforms = null;
return;
}
this.declaredTransforms = new com.amazonaws.internal.SdkInternalList<String>(declaredTransforms);
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setDeclaredTransforms(java.util.Collection)} or {@link #withDeclaredTransforms(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param declaredTransforms
* A list of the transforms that are declared in the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withDeclaredTransforms(String... declaredTransforms) {
if (this.declaredTransforms == null) {
setDeclaredTransforms(new com.amazonaws.internal.SdkInternalList<String>(declaredTransforms.length));
}
for (String ele : declaredTransforms) {
this.declaredTransforms.add(ele);
}
return this;
}
/**
* <p>
* A list of the transforms that are declared in the template.
* </p>
*
* @param declaredTransforms
* A list of the transforms that are declared in the template.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withDeclaredTransforms(java.util.Collection<String> declaredTransforms) {
setDeclaredTransforms(declaredTransforms);
return this;
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*
* @return A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
*/
public java.util.List<ResourceIdentifierSummary> getResourceIdentifierSummaries() {
if (resourceIdentifierSummaries == null) {
resourceIdentifierSummaries = new com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary>();
}
return resourceIdentifierSummaries;
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*
* @param resourceIdentifierSummaries
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
*/
public void setResourceIdentifierSummaries(java.util.Collection<ResourceIdentifierSummary> resourceIdentifierSummaries) {
if (resourceIdentifierSummaries == null) {
this.resourceIdentifierSummaries = null;
return;
}
this.resourceIdentifierSummaries = new com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary>(resourceIdentifierSummaries);
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setResourceIdentifierSummaries(java.util.Collection)} or
* {@link #withResourceIdentifierSummaries(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param resourceIdentifierSummaries
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceIdentifierSummaries(ResourceIdentifierSummary... resourceIdentifierSummaries) {
if (this.resourceIdentifierSummaries == null) {
setResourceIdentifierSummaries(new com.amazonaws.internal.SdkInternalList<ResourceIdentifierSummary>(resourceIdentifierSummaries.length));
}
for (ResourceIdentifierSummary ele : resourceIdentifierSummaries) {
this.resourceIdentifierSummaries.add(ele);
}
return this;
}
/**
* <p>
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* </p>
*
* @param resourceIdentifierSummaries
* A list of resource identifier summaries that describe the target resources of an import operation and the
* properties you can provide during the import to identify the target resources. For example,
* <code>BucketName</code> is a possible identifier property for an <code>AWS::S3::Bucket</code> resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetTemplateSummaryResult withResourceIdentifierSummaries(java.util.Collection<ResourceIdentifierSummary> resourceIdentifierSummaries) {
setResourceIdentifierSummaries(resourceIdentifierSummaries);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getParameters() != null)
sb.append("Parameters: ").append(getParameters()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getCapabilities() != null)
sb.append("Capabilities: ").append(getCapabilities()).append(",");
if (getCapabilitiesReason() != null)
sb.append("CapabilitiesReason: ").append(getCapabilitiesReason()).append(",");
if (getResourceTypes() != null)
sb.append("ResourceTypes: ").append(getResourceTypes()).append(",");
if (getVersion() != null)
sb.append("Version: ").append(getVersion()).append(",");
if (getMetadata() != null)
sb.append("Metadata: ").append(getMetadata()).append(",");
if (getDeclaredTransforms() != null)
sb.append("DeclaredTransforms: ").append(getDeclaredTransforms()).append(",");
if (getResourceIdentifierSummaries() != null)
sb.append("ResourceIdentifierSummaries: ").append(getResourceIdentifierSummaries());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetTemplateSummaryResult == false)
return false;
GetTemplateSummaryResult other = (GetTemplateSummaryResult) obj;
if (other.getParameters() == null ^ this.getParameters() == null)
return false;
if (other.getParameters() != null && other.getParameters().equals(this.getParameters()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getCapabilities() == null ^ this.getCapabilities() == null)
return false;
if (other.getCapabilities() != null && other.getCapabilities().equals(this.getCapabilities()) == false)
return false;
if (other.getCapabilitiesReason() == null ^ this.getCapabilitiesReason() == null)
return false;
if (other.getCapabilitiesReason() != null && other.getCapabilitiesReason().equals(this.getCapabilitiesReason()) == false)
return false;
if (other.getResourceTypes() == null ^ this.getResourceTypes() == null)
return false;
if (other.getResourceTypes() != null && other.getResourceTypes().equals(this.getResourceTypes()) == false)
return false;
if (other.getVersion() == null ^ this.getVersion() == null)
return false;
if (other.getVersion() != null && other.getVersion().equals(this.getVersion()) == false)
return false;
if (other.getMetadata() == null ^ this.getMetadata() == null)
return false;
if (other.getMetadata() != null && other.getMetadata().equals(this.getMetadata()) == false)
return false;
if (other.getDeclaredTransforms() == null ^ this.getDeclaredTransforms() == null)
return false;
if (other.getDeclaredTransforms() != null && other.getDeclaredTransforms().equals(this.getDeclaredTransforms()) == false)
return false;
if (other.getResourceIdentifierSummaries() == null ^ this.getResourceIdentifierSummaries() == null)
return false;
if (other.getResourceIdentifierSummaries() != null && other.getResourceIdentifierSummaries().equals(this.getResourceIdentifierSummaries()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getParameters() == null) ? 0 : getParameters().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getCapabilities() == null) ? 0 : getCapabilities().hashCode());
hashCode = prime * hashCode + ((getCapabilitiesReason() == null) ? 0 : getCapabilitiesReason().hashCode());
hashCode = prime * hashCode + ((getResourceTypes() == null) ? 0 : getResourceTypes().hashCode());
hashCode = prime * hashCode + ((getVersion() == null) ? 0 : getVersion().hashCode());
hashCode = prime * hashCode + ((getMetadata() == null) ? 0 : getMetadata().hashCode());
hashCode = prime * hashCode + ((getDeclaredTransforms() == null) ? 0 : getDeclaredTransforms().hashCode());
hashCode = prime * hashCode + ((getResourceIdentifierSummaries() == null) ? 0 : getResourceIdentifierSummaries().hashCode());
return hashCode;
}
@Override
public GetTemplateSummaryResult clone() {
try {
return (GetTemplateSummaryResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-cloudformation/src/main/java/com/amazonaws/services/cloudformation/model/GetTemplateSummaryResult.java
|
Java
|
apache-2.0
| 36,945 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Microsoft.AspNetCore.Mvc.Diagnostics;
namespace Microsoft.AspNetCore.Mvc.RazorPages
{
internal static class MvcRazorPagesDiagnosticListenerExtensions
{
public static void BeforeHandlerMethod(
this DiagnosticListener diagnosticListener,
ActionContext actionContext,
HandlerMethodDescriptor handlerMethodDescriptor,
IReadOnlyDictionary<string, object?> arguments,
object instance)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(actionContext != null);
Debug.Assert(handlerMethodDescriptor != null);
Debug.Assert(arguments != null);
Debug.Assert(instance != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeHandlerMethodImpl(diagnosticListener, actionContext, handlerMethodDescriptor, arguments, instance);
}
}
private static void BeforeHandlerMethodImpl(DiagnosticListener diagnosticListener, ActionContext actionContext, HandlerMethodDescriptor handlerMethodDescriptor, IReadOnlyDictionary<string, object?> arguments, object instance)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforeHandlerMethodEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforeHandlerMethodEventData.EventName,
new BeforeHandlerMethodEventData(
actionContext,
arguments,
handlerMethodDescriptor,
instance
));
}
}
public static void AfterHandlerMethod(
this DiagnosticListener diagnosticListener,
ActionContext actionContext,
HandlerMethodDescriptor handlerMethodDescriptor,
IReadOnlyDictionary<string, object?> arguments,
object instance,
IActionResult? result)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(actionContext != null);
Debug.Assert(handlerMethodDescriptor != null);
Debug.Assert(arguments != null);
Debug.Assert(instance != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterHandlerMethodImpl(diagnosticListener, actionContext, handlerMethodDescriptor, arguments, instance, result);
}
}
private static void AfterHandlerMethodImpl(DiagnosticListener diagnosticListener, ActionContext actionContext, HandlerMethodDescriptor handlerMethodDescriptor, IReadOnlyDictionary<string, object?> arguments, object instance, IActionResult? result)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterHandlerMethodEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterHandlerMethodEventData.EventName,
new AfterHandlerMethodEventData(
actionContext,
arguments,
handlerMethodDescriptor,
instance,
result
));
}
}
public static void BeforeOnPageHandlerExecution(
this DiagnosticListener diagnosticListener,
PageHandlerExecutingContext handlerExecutionContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutionContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerExecutionImpl(diagnosticListener, handlerExecutionContext, filter);
}
}
private static void BeforeOnPageHandlerExecutionImpl(DiagnosticListener diagnosticListener, PageHandlerExecutingContext handlerExecutionContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerExecutionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerExecutionEventData.EventName,
new BeforePageFilterOnPageHandlerExecutionEventData(
handlerExecutionContext.ActionDescriptor,
handlerExecutionContext,
filter
));
}
}
public static void AfterOnPageHandlerExecution(
this DiagnosticListener diagnosticListener,
PageHandlerExecutedContext handlerExecutedContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerExecutionImpl(diagnosticListener, handlerExecutedContext, filter);
}
}
private static void AfterOnPageHandlerExecutionImpl(DiagnosticListener diagnosticListener, PageHandlerExecutedContext handlerExecutedContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerExecutionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerExecutionEventData.EventName,
new AfterPageFilterOnPageHandlerExecutionEventData(
handlerExecutedContext.ActionDescriptor,
handlerExecutedContext,
filter
));
}
}
public static void BeforeOnPageHandlerExecuting(
this DiagnosticListener diagnosticListener,
PageHandlerExecutingContext handlerExecutingContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutingContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerExecutingImpl(diagnosticListener, handlerExecutingContext, filter);
}
}
private static void BeforeOnPageHandlerExecutingImpl(DiagnosticListener diagnosticListener, PageHandlerExecutingContext handlerExecutingContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerExecutingEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerExecutingEventData.EventName,
new BeforePageFilterOnPageHandlerExecutingEventData(
handlerExecutingContext.ActionDescriptor,
handlerExecutingContext,
filter
));
}
}
public static void AfterOnPageHandlerExecuting(
this DiagnosticListener diagnosticListener,
PageHandlerExecutingContext handlerExecutingContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutingContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerExecutingImpl(diagnosticListener, handlerExecutingContext, filter);
}
}
private static void AfterOnPageHandlerExecutingImpl(DiagnosticListener diagnosticListener, PageHandlerExecutingContext handlerExecutingContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerExecutingEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerExecutingEventData.EventName,
new AfterPageFilterOnPageHandlerExecutingEventData(
handlerExecutingContext.ActionDescriptor,
handlerExecutingContext,
filter
));
}
}
public static void BeforeOnPageHandlerExecuted(
this DiagnosticListener diagnosticListener,
PageHandlerExecutedContext handlerExecutedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerExecutedImpl(diagnosticListener, handlerExecutedContext, filter);
}
}
private static void BeforeOnPageHandlerExecutedImpl(DiagnosticListener diagnosticListener, PageHandlerExecutedContext handlerExecutedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerExecutedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerExecutedEventData.EventName,
new BeforePageFilterOnPageHandlerExecutedEventData(
handlerExecutedContext.ActionDescriptor,
handlerExecutedContext,
filter
));
}
}
public static void AfterOnPageHandlerExecuted(
this DiagnosticListener diagnosticListener,
PageHandlerExecutedContext handlerExecutedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerExecutedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerExecutedImpl(diagnosticListener, handlerExecutedContext, filter);
}
}
private static void AfterOnPageHandlerExecutedImpl(DiagnosticListener diagnosticListener, PageHandlerExecutedContext handlerExecutedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerExecutedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerExecutedEventData.EventName,
new AfterPageFilterOnPageHandlerExecutedEventData(
handlerExecutedContext.ActionDescriptor,
handlerExecutedContext,
filter
));
}
}
public static void BeforeOnPageHandlerSelection(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerSelectionImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void BeforeOnPageHandlerSelectionImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerSelectionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerSelectionEventData.EventName,
new BeforePageFilterOnPageHandlerSelectionEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
public static void AfterOnPageHandlerSelection(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IAsyncPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerSelectionImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void AfterOnPageHandlerSelectionImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IAsyncPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerSelectionEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerSelectionEventData.EventName,
new AfterPageFilterOnPageHandlerSelectionEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
public static void BeforeOnPageHandlerSelected(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
BeforeOnPageHandlerSelectedImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void BeforeOnPageHandlerSelectedImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.BeforePageFilterOnPageHandlerSelectedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.BeforePageFilterOnPageHandlerSelectedEventData.EventName,
new BeforePageFilterOnPageHandlerSelectedEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
public static void AfterOnPageHandlerSelected(
this DiagnosticListener diagnosticListener,
PageHandlerSelectedContext handlerSelectedContext,
IPageFilter filter)
{
Debug.Assert(diagnosticListener != null);
Debug.Assert(handlerSelectedContext != null);
Debug.Assert(filter != null);
// Inlinable fast-path check if Diagnositcs is enabled
if (diagnosticListener.IsEnabled())
{
AfterOnPageHandlerSelectedImpl(diagnosticListener, handlerSelectedContext, filter);
}
}
private static void AfterOnPageHandlerSelectedImpl(DiagnosticListener diagnosticListener, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter)
{
if (diagnosticListener.IsEnabled(Diagnostics.AfterPageFilterOnPageHandlerSelectedEventData.EventName))
{
diagnosticListener.Write(
Diagnostics.AfterPageFilterOnPageHandlerSelectedEventData.EventName,
new AfterPageFilterOnPageHandlerSelectedEventData(
handlerSelectedContext.ActionDescriptor,
handlerSelectedContext,
filter
));
}
}
}
}
|
aspnet/AspNetCore
|
src/Mvc/Mvc.RazorPages/src/MvcRazorPagesDiagnosticListenerExtensions.cs
|
C#
|
apache-2.0
| 17,096 |
from __future__ import absolute_import, division, print_function, unicode_literals
from amaascore.market_data.eod_price import EODPrice
from amaascore.market_data.fx_rate import FXRate
from amaascore.market_data.curve import Curve
from amaascore.market_data.corporate_action import CorporateAction
def json_to_eod_price(json_eod_price):
eod_price = EODPrice(**json_eod_price)
return eod_price
def json_to_fx_rate(json_fx_rate):
fx_rate = FXRate(**json_fx_rate)
return fx_rate
def json_to_curve(json_curve):
curve = Curve(**json_curve)
return curve
def json_to_corporate_action(json_corporate_action):
corporate_action = CorporateAction(**json_corporate_action)
return corporate_action
|
amaas-fintech/amaas-core-sdk-python
|
amaascore/market_data/utils.py
|
Python
|
apache-2.0
| 723 |
/*
* Copyright (c) jiucheng.org
*/
package org.jiucheng.web;
import java.lang.reflect.Method;
public class Ctrl {
private String route;
private Method method;
private RequestType requestType;
private String beanName;
private String handlerBeanName;
public void setRoute(String route) {
this.route = route;
}
public String getRoute() {
return route;
}
public Method getMethod() {
return method;
}
public void setRequestType(RequestType requestType) {
this.requestType = requestType;
}
public RequestType getRequestType() {
return requestType;
}
public void setMethod(Method method) {
this.method = method;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public String getHandlerBeanName() {
return handlerBeanName;
}
public void setHandlerBeanName(String handlerBeanName) {
this.handlerBeanName = handlerBeanName;
}
}
|
AnEgg/DragonYun
|
src/org/jiucheng/web/Ctrl.java
|
Java
|
apache-2.0
| 1,114 |
# -------------------------------------------------------------------------- #
# Copyright 2002-2020, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
require 'one_helper'
class OneDatastoreHelper < OpenNebulaHelper::OneHelper
DATASTORE = {
:name => "datastore",
:short => "-d id|name",
:large => "--datastore id|name" ,
:description => "Selects the datastore",
:format => String,
:proc => lambda { |o, options|
OpenNebulaHelper.rname_to_id(o, "DATASTORE")
}
}
def self.rname
"DATASTORE"
end
def self.conf_file
"onedatastore.yaml"
end
def format_pool(options)
config_file = self.class.table_conf
table = CLIHelper::ShowTable.new(config_file, self) do
column :ID, "ONE identifier for the Datastore", :size=>4 do |d|
d["ID"]
end
column :USER, "Username of the Datastore owner", :left,
:size=>10 do |d|
helper.user_name(d, options)
end
column :GROUP, "Group of the Datastore", :left,
:size=>10 do |d|
helper.group_name(d, options)
end
column :NAME, "Name of the Datastore", :left, :size=>13 do |d|
d["NAME"]
end
column :SIZE, "Datastore total size", :size =>10 do |d|
shared = d['TEMPLATE']['SHARED']
if shared != nil && shared.upcase == 'NO'
"-"
else
OpenNebulaHelper.unit_to_str(d['TOTAL_MB'].to_i, {}, 'M')
end
end
column :AVAIL, "Datastore free size", :left, :size =>5 do |d|
if d['TOTAL_MB'].to_i == 0
"-"
else
"#{((d['FREE_MB'].to_f/d['TOTAL_MB'].to_f) * 100).round()}%"
end
end
column :CLUSTERS, "Cluster IDs", :left, :size=>12 do |d|
OpenNebulaHelper.clusters_str(d["CLUSTERS"]["ID"])
end
column :IMAGES, "Number of Images", :size=>6 do |d|
if d["IMAGES"]["ID"].nil?
"0"
else
[d["IMAGES"]["ID"]].flatten.size
end
end
column :TYPE, "Datastore type", :left, :size=>4 do |d|
type = OpenNebula::Datastore::DATASTORE_TYPES[d["TYPE"].to_i]
OpenNebula::Datastore::SHORT_DATASTORE_TYPES[type]
end
column :DS, "Datastore driver", :left, :size=>7 do |d|
d["DS_MAD"]
end
column :TM, "Transfer driver", :left, :size=>7 do |d|
d["TM_MAD"]
end
column :STAT, "State of the Datastore", :left, :size=>3 do |d|
state = OpenNebula::Datastore::DATASTORE_STATES[d["STATE"].to_i]
OpenNebula::Datastore::SHORT_DATASTORE_STATES[state]
end
default :ID, :USER, :GROUP, :NAME, :SIZE, :AVAIL, :CLUSTERS, :IMAGES,
:TYPE, :DS, :TM, :STAT
end
table
end
private
def factory(id=nil)
if id
OpenNebula::Datastore.new_with_id(id, @client)
else
xml=OpenNebula::Datastore.build_xml
OpenNebula::Datastore.new(xml, @client)
end
end
def factory_pool(user_flag=-2)
OpenNebula::DatastorePool.new(@client)
end
def format_resource(datastore, options = {})
str="%-15s: %-20s"
str_h1="%-80s"
CLIHelper.print_header(str_h1 % "DATASTORE #{datastore['ID']} INFORMATION")
puts str % ["ID", datastore.id.to_s]
puts str % ["NAME", datastore.name]
puts str % ["USER", datastore['UNAME']]
puts str % ["GROUP", datastore['GNAME']]
puts str % ["CLUSTERS",
OpenNebulaHelper.clusters_str(datastore.retrieve_elements("CLUSTERS/ID"))]
puts str % ["TYPE", datastore.type_str]
puts str % ["DS_MAD", datastore['DS_MAD']]
puts str % ["TM_MAD", datastore['TM_MAD']]
puts str % ["BASE PATH",datastore['BASE_PATH']]
puts str % ["DISK_TYPE",Image::DISK_TYPES[datastore['DISK_TYPE'].to_i]]
puts str % ["STATE", datastore.state_str]
puts
CLIHelper.print_header(str_h1 % "DATASTORE CAPACITY", false)
shared = datastore['TEMPLATE/SHARED']
local = shared != nil && shared.upcase == 'NO'
limit_mb = datastore['TEMPLATE/LIMIT_MB']
puts str % ["TOTAL:", local ? '-' : OpenNebulaHelper.unit_to_str(datastore['TOTAL_MB'].to_i, {},'M')]
puts str % ["FREE:", local ? '-' : OpenNebulaHelper.unit_to_str(datastore['FREE_MB'].to_i, {},'M')]
puts str % ["USED: ", local ? '-' : OpenNebulaHelper.unit_to_str(datastore['USED_MB'].to_i, {},'M')]
puts str % ["LIMIT:", local || limit_mb.nil? ? '-' : OpenNebulaHelper.unit_to_str(limit_mb.to_i, {},'M')]
puts
CLIHelper.print_header(str_h1 % "PERMISSIONS",false)
["OWNER", "GROUP", "OTHER"].each { |e|
mask = "---"
mask[0] = "u" if datastore["PERMISSIONS/#{e}_U"] == "1"
mask[1] = "m" if datastore["PERMISSIONS/#{e}_M"] == "1"
mask[2] = "a" if datastore["PERMISSIONS/#{e}_A"] == "1"
puts str % [e, mask]
}
puts
CLIHelper.print_header(str_h1 % "DATASTORE TEMPLATE", false)
puts datastore.template_str
puts
CLIHelper.print_header("%-15s" % "IMAGES")
datastore.img_ids.each do |id|
puts "%-15s" % [id]
end
end
end
|
baby-gnu/one
|
src/cli/one_helper/onedatastore_helper.rb
|
Ruby
|
apache-2.0
| 6,796 |
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import {plotData} from './index';
const statusElement = document.getElementById('status');
const timeSpanSelect = document.getElementById('time-span');
const selectSeries1 = document.getElementById('data-series-1');
const selectSeries2 = document.getElementById('data-series-2');
const dataNormalizedCheckbox = document.getElementById('data-normalized');
const dateTimeRangeSpan = document.getElementById('date-time-range');
const dataPrevButton = document.getElementById('data-prev');
const dataNextButton = document.getElementById('data-next');
const dataScatterCheckbox = document.getElementById('data-scatter');
export function logStatus(message) {
statusElement.innerText = message;
}
export function populateSelects(dataObj) {
const columnNames = ['None'].concat(dataObj.getDataColumnNames());
for (const selectSeries of [selectSeries1, selectSeries2]) {
while (selectSeries.firstChild) {
selectSeries.removeChild(selectSeries.firstChild);
}
console.log(columnNames);
for (const name of columnNames) {
const option = document.createElement('option');
option.setAttribute('value', name);
option.textContent = name;
selectSeries.appendChild(option);
}
}
if (columnNames.indexOf('T (degC)') !== -1) {
selectSeries1.value = 'T (degC)';
}
if (columnNames.indexOf('p (mbar)') !== -1) {
selectSeries2.value = 'p (mbar)';
}
timeSpanSelect.value = 'week';
dataNormalizedCheckbox.checked = true;
}
export const TIME_SPAN_RANGE_MAP = {
hour: 6,
day: 6 * 24,
week: 6 * 24 * 7,
tenDays: 6 * 24 * 10,
month: 6 * 24 * 30,
year: 6 * 24 * 365,
full: null
};
export const TIME_SPAN_STRIDE_MAP = {
day: 1,
week: 1,
tenDays: 6,
month: 6,
year: 6 * 6,
full: 6 * 24
};
export let currBeginIndex = 0;
export function updateDateTimeRangeSpan(jenaWeatherData) {
const timeSpan = timeSpanSelect.value;
const currEndIndex = currBeginIndex + TIME_SPAN_RANGE_MAP[timeSpan];
const begin =
new Date(jenaWeatherData.getTime(currBeginIndex)).toLocaleDateString();
const end =
new Date(jenaWeatherData.getTime(currEndIndex)).toLocaleDateString();
dateTimeRangeSpan.textContent = `${begin} - ${end}`;
}
export function updateScatterCheckbox() {
const series1 = selectSeries1.value;
const series2 = selectSeries2.value;
dataScatterCheckbox.disabled = series1 === 'None' || series2 === 'None';
}
dataPrevButton.addEventListener('click', () => {
const timeSpan = timeSpanSelect.value;
currBeginIndex -= Math.round(TIME_SPAN_RANGE_MAP[timeSpan] / 8);
if (currBeginIndex >= 0) {
plotData();
} else {
currBeginIndex = 0;
}
});
dataNextButton.addEventListener('click', () => {
const timeSpan = timeSpanSelect.value;
currBeginIndex += Math.round(TIME_SPAN_RANGE_MAP[timeSpan] / 8);
plotData();
});
timeSpanSelect.addEventListener('change', () => {
plotData();
});
selectSeries1.addEventListener('change', plotData);
selectSeries2.addEventListener('change', plotData);
dataNormalizedCheckbox.addEventListener('change', plotData);
dataScatterCheckbox.addEventListener('change', plotData);
export function getDataVizOptions() {
return {
timeSpan: timeSpanSelect.value,
series1: selectSeries1.value,
series2: selectSeries2.value,
normalize: dataNormalizedCheckbox.checked,
scatter: dataScatterCheckbox.checked
};
}
|
tensorflow/tfjs-examples
|
jena-weather/ui.js
|
JavaScript
|
apache-2.0
| 4,072 |
/**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.huntering.common.entity.search.utils;
import com.google.common.collect.Lists;
import com.huntering.common.entity.search.SearchOperator;
import com.huntering.common.entity.search.Searchable;
import com.huntering.common.entity.search.exception.InvalidSearchPropertyException;
import com.huntering.common.entity.search.exception.InvalidSearchValueException;
import com.huntering.common.entity.search.exception.SearchException;
import com.huntering.common.entity.search.filter.AndCondition;
import com.huntering.common.entity.search.filter.Condition;
import com.huntering.common.entity.search.filter.OrCondition;
import com.huntering.common.entity.search.filter.SearchFilter;
import com.huntering.common.utils.SpringUtils;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-1-15 上午11:46
* <p>Version: 1.0
*/
public final class SearchableConvertUtils {
private static volatile ConversionService conversionService;
/**
* 设置用于类型转换的conversionService
* 把如下代码放入spring配置文件即可
* <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
* <property name="staticMethod"
* value="com.huntering.common.entity.search.utils.SearchableConvertUtils.setConversionService"/>
* <property name="arguments" ref="conversionService"/>
* </bean>
*
* @param conversionService
*/
public static void setConversionService(ConversionService conversionService) {
SearchableConvertUtils.conversionService = conversionService;
}
public static ConversionService getConversionService() {
if (conversionService == null) {
synchronized (SearchableConvertUtils.class) {
if (conversionService == null) {
try {
conversionService = SpringUtils.getBean(ConversionService.class);
} catch (Exception e) {
throw new SearchException("conversionService is null, " +
"search param convert must use conversionService. " +
"please see [com.huntering.common.entity.search.utils." +
"SearchableConvertUtils#setConversionService]");
}
}
}
}
return conversionService;
}
/**
* @param search 查询条件
* @param entityClass 实体类型
* @param <T>
*/
public static <T> void convertSearchValueToEntityValue(final Searchable search, final Class<T> entityClass) {
if (search.isConverted()) {
return;
}
Collection<SearchFilter> searchFilters = search.getSearchFilters();
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(entityClass);
beanWrapper.setAutoGrowNestedPaths(true);
beanWrapper.setConversionService(getConversionService());
for (SearchFilter searchFilter : searchFilters) {
convertSearchValueToEntityValue(beanWrapper, searchFilter);
}
}
private static void convertSearchValueToEntityValue(BeanWrapperImpl beanWrapper, SearchFilter searchFilter) {
if (searchFilter instanceof Condition) {
Condition condition = (Condition) searchFilter;
convert(beanWrapper, condition);
return;
}
if (searchFilter instanceof OrCondition) {
for (SearchFilter orFilter : ((OrCondition) searchFilter).getOrFilters()) {
convertSearchValueToEntityValue(beanWrapper, orFilter);
}
return;
}
if (searchFilter instanceof AndCondition) {
for (SearchFilter andFilter : ((AndCondition) searchFilter).getAndFilters()) {
convertSearchValueToEntityValue(beanWrapper, andFilter);
}
return;
}
}
private static void convert(BeanWrapperImpl beanWrapper, Condition condition) {
String searchProperty = condition.getSearchProperty();
//自定义的也不转换
if (condition.getOperator() == SearchOperator.custom) {
return;
}
//一元运算符不需要计算
if (condition.isUnaryFilter()) {
return;
}
String entityProperty = condition.getEntityProperty();
Object value = condition.getValue();
Object newValue = null;
boolean isCollection = value instanceof Collection;
boolean isArray = value != null && value.getClass().isArray();
if (isCollection || isArray) {
List<Object> list = Lists.newArrayList();
if (isCollection) {
list.addAll((Collection) value);
} else {
list = Lists.newArrayList(CollectionUtils.arrayToList(value));
}
int length = list.size();
for (int i = 0; i < length; i++) {
list.set(i, getConvertedValue(beanWrapper, searchProperty, entityProperty, list.get(i)));
}
newValue = list;
} else {
newValue = getConvertedValue(beanWrapper, searchProperty, entityProperty, value);
}
condition.setValue(newValue);
}
private static Object getConvertedValue(
final BeanWrapperImpl beanWrapper,
final String searchProperty,
final String entityProperty,
final Object value) {
Object newValue;
try {
beanWrapper.setPropertyValue(entityProperty, value);
newValue = beanWrapper.getPropertyValue(entityProperty);
} catch (InvalidPropertyException e) {
throw new InvalidSearchPropertyException(searchProperty, entityProperty, e);
} catch (Exception e) {
throw new InvalidSearchValueException(searchProperty, entityProperty, value, e);
}
return newValue;
}
/* public static <T> void convertSearchValueToEntityValue(SearchRequest search, Class<T> domainClass) {
List<Condition> searchFilters = search.getSearchFilters();
for (Condition searchFilter : searchFilters) {
String property = searchFilter.getSearchProperty();
Class<? extends Comparable> targetPropertyType = getPropertyType(domainClass, property);
Object value = searchFilter.getValue();
Comparable newValue = convert(value, targetPropertyType);
searchFilter.setValue(newValue);
}
}*/
/*
private static <T> Class getPropertyType(Class<T> domainClass, String property) {
String[] names = StringUtils.split(property, ".");
Class<?> clazz = null;
for (String name : names) {
if (clazz == null) {
clazz = BeanUtils.findPropertyType(name, ArrayUtils.toArray(domainClass));
} else {
clazz = BeanUtils.findPropertyType(name, ArrayUtils.toArray(clazz));
}
}
return clazz;
}*/
/*
public static <S, T> T convert(S sourceValue, Class<T> targetClass) {
ConversionService conversionService = getConversionService();
if (!conversionService.canConvert(sourceValue.getClass(), targetClass)) {
throw new IllegalArgumentException(
"search param can not convert value:[" + sourceValue + "] to target type:[" + targetClass + "]");
}
return conversionService.convert(sourceValue, targetClass);
}
*/
}
|
xiuxin/Huntering
|
common/src/main/java/com/huntering/common/entity/search/utils/SearchableConvertUtils.java
|
Java
|
apache-2.0
| 7,912 |
/*
* Copyright (c) 2021 Citrix Systems, 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 appfw
/**
* Configuration for xml error page resource.
*/
type Appfwxmlerrorpage struct {
/**
* Indicates name of the imported xml error page to be removed.
*/
Name string `json:"name,omitempty"`
/**
* URL (protocol, host, path, and name) for the location at which to store the imported XML error object.
NOTE: The import fails if the object to be imported is on an HTTPS server that requires client certificate authentication for access.
*/
Src string `json:"src,omitempty"`
/**
* Any comments to preserve information about the XML error object.
*/
Comment string `json:"comment,omitempty"`
/**
* Overwrite any existing XML error object of the same name.
*/
Overwrite bool `json:"overwrite,omitempty"`
//------- Read only Parameter ---------;
Response string `json:"response,omitempty"`
}
|
citrix/terraform-provider-netscaler
|
vendor/github.com/citrix/adc-nitro-go/resource/config/appfw/appfwxmlerrorpage.go
|
GO
|
apache-2.0
| 1,434 |
package com.action.jdxchxjs.ch03.stack_1;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wuyunfeng on 2017/9/21.
*/
public class MyStack {
private List list = new ArrayList();
public synchronized void pubsh(){
try {
if (list.size() == 1){
this.wait();
}
list.add("anyString=" + Math.random());
this.notify();
System.out.println("push=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized String pop(){
String returnValue = "";
try {
if (list.size() == 0){
System.out.println("pop 操作中的:" + Thread.currentThread().getName()
+ " 线程呈wait状态");
this.wait();
}
returnValue = "" + list.get(0);
list.remove(0);
this.notify();
System.out.println("pop=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
}
|
pearpai/java_action
|
src/main/java/com/action/jdxchxjs/ch03/stack_1/MyStack.java
|
Java
|
apache-2.0
| 1,139 |
package com.huawei.esdk.demo.autogen;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for BroadInfoEx complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BroadInfoEx">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="directBroad" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="recordBroad" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="directBroadStatus" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="recordBroadStatus" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BroadInfoEx", propOrder = {
"directBroad",
"recordBroad",
"directBroadStatus",
"recordBroadStatus"
})
public class BroadInfoEx {
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer directBroad;
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer recordBroad;
@XmlElement(type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer directBroadStatus;
@XmlElement(type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "int")
protected Integer recordBroadStatus;
/**
* Gets the value of the directBroad property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getDirectBroad() {
return directBroad;
}
/**
* Sets the value of the directBroad property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDirectBroad(Integer value) {
this.directBroad = value;
}
/**
* Gets the value of the recordBroad property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getRecordBroad() {
return recordBroad;
}
/**
* Sets the value of the recordBroad property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRecordBroad(Integer value) {
this.recordBroad = value;
}
/**
* Gets the value of the directBroadStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getDirectBroadStatus() {
return directBroadStatus;
}
/**
* Sets the value of the directBroadStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDirectBroadStatus(Integer value) {
this.directBroadStatus = value;
}
/**
* Gets the value of the recordBroadStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getRecordBroadStatus() {
return recordBroadStatus;
}
/**
* Sets the value of the recordBroadStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRecordBroadStatus(Integer value) {
this.recordBroadStatus = value;
}
}
|
eSDK/esdk_tp_native_java
|
test/demo/eSDK_TP_Demo_BS_Java/src/com/huawei/esdk/demo/autogen/BroadInfoEx.java
|
Java
|
apache-2.0
| 4,017 |
var dir_0c96b3d0fc842fbb51d7afc18d90cdec =
[
[ "design", "dir_b39402054b6f29d8059088b0004b64ee.html", "dir_b39402054b6f29d8059088b0004b64ee" ],
[ "v4", "dir_b1530cc8b78b2d9923632461f396c71c.html", "dir_b1530cc8b78b2d9923632461f396c71c" ],
[ "v7", "dir_94bdcc46f12b2beb2dba250b68a1fa32.html", "dir_94bdcc46f12b2beb2dba250b68a1fa32" ]
];
|
feedhenry/fh-dotnet-sdk
|
Documentations/html/dir_0c96b3d0fc842fbb51d7afc18d90cdec.js
|
JavaScript
|
apache-2.0
| 347 |
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google 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 org.openqa.selenium.remote.server;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.selenium.remote.server.handler.AddConfig;
import org.openqa.selenium.remote.server.handler.AddCookie;
import org.openqa.selenium.remote.server.handler.CaptureScreenshot;
import org.openqa.selenium.remote.server.handler.ChangeUrl;
import org.openqa.selenium.remote.server.handler.ClearElement;
import org.openqa.selenium.remote.server.handler.ClickElement;
import org.openqa.selenium.remote.server.handler.CloseWindow;
import org.openqa.selenium.remote.server.handler.DeleteCookie;
import org.openqa.selenium.remote.server.handler.DeleteNamedCookie;
import org.openqa.selenium.remote.server.handler.DeleteSession;
import org.openqa.selenium.remote.server.handler.DescribeElement;
import org.openqa.selenium.remote.server.handler.DragElement;
import org.openqa.selenium.remote.server.handler.ExecuteScript;
import org.openqa.selenium.remote.server.handler.FindActiveElement;
import org.openqa.selenium.remote.server.handler.FindChildElement;
import org.openqa.selenium.remote.server.handler.FindChildElements;
import org.openqa.selenium.remote.server.handler.FindElement;
import org.openqa.selenium.remote.server.handler.FindElements;
import org.openqa.selenium.remote.server.handler.GetAllCookies;
import org.openqa.selenium.remote.server.handler.GetAllWindowHandles;
import org.openqa.selenium.remote.server.handler.GetCssProperty;
import org.openqa.selenium.remote.server.handler.GetCurrentUrl;
import org.openqa.selenium.remote.server.handler.GetCurrentWindowHandle;
import org.openqa.selenium.remote.server.handler.GetElementAttribute;
import org.openqa.selenium.remote.server.handler.GetElementDisplayed;
import org.openqa.selenium.remote.server.handler.GetElementEnabled;
import org.openqa.selenium.remote.server.handler.GetElementLocation;
import org.openqa.selenium.remote.server.handler.GetElementSelected;
import org.openqa.selenium.remote.server.handler.GetElementSize;
import org.openqa.selenium.remote.server.handler.GetElementText;
import org.openqa.selenium.remote.server.handler.GetElementValue;
import org.openqa.selenium.remote.server.handler.GetMouseSpeed;
import org.openqa.selenium.remote.server.handler.GetPageSource;
import org.openqa.selenium.remote.server.handler.GetSessionCapabilities;
import org.openqa.selenium.remote.server.handler.GetTagName;
import org.openqa.selenium.remote.server.handler.GetTitle;
import org.openqa.selenium.remote.server.handler.GoBack;
import org.openqa.selenium.remote.server.handler.GoForward;
import org.openqa.selenium.remote.server.handler.HoverOverElement;
import org.openqa.selenium.remote.server.handler.NewSession;
import org.openqa.selenium.remote.server.handler.RefreshPage;
import org.openqa.selenium.remote.server.handler.SendKeys;
import org.openqa.selenium.remote.server.handler.SetElementSelected;
import org.openqa.selenium.remote.server.handler.SetMouseSpeed;
import org.openqa.selenium.remote.server.handler.SubmitElement;
import org.openqa.selenium.remote.server.handler.SwitchToFrame;
import org.openqa.selenium.remote.server.handler.SwitchToWindow;
import org.openqa.selenium.remote.server.handler.ToggleElement;
import org.openqa.selenium.remote.server.handler.ElementEquality;
import org.openqa.selenium.remote.server.renderer.EmptyResult;
import org.openqa.selenium.remote.server.renderer.ForwardResult;
import org.openqa.selenium.remote.server.renderer.JsonErrorExceptionResult;
import org.openqa.selenium.remote.server.renderer.JsonResult;
import org.openqa.selenium.remote.server.renderer.RedirectResult;
import org.openqa.selenium.remote.server.rest.Handler;
import org.openqa.selenium.remote.server.rest.ResultConfig;
import org.openqa.selenium.remote.server.rest.ResultType;
import org.openqa.selenium.remote.server.rest.UrlMapper;
public class DriverServlet extends HttpServlet {
private UrlMapper getMapper;
private UrlMapper postMapper;
private UrlMapper deleteMapper;
@Override
public void init() throws ServletException {
super.init();
DriverSessions driverSessions = new DriverSessions();
ServletLogTo logger = new ServletLogTo();
setupMappings(driverSessions, logger);
}
private void setupMappings(DriverSessions driverSessions, ServletLogTo logger) {
getMapper = new UrlMapper(driverSessions, logger);
postMapper = new UrlMapper(driverSessions, logger);
deleteMapper = new UrlMapper(driverSessions, logger);
getMapper.addGlobalHandler(ResultType.EXCEPTION,
new JsonErrorExceptionResult(":exception", ":response"));
postMapper.addGlobalHandler(ResultType.EXCEPTION,
new JsonErrorExceptionResult(":exception", ":response"));
deleteMapper.addGlobalHandler(ResultType.EXCEPTION,
new JsonErrorExceptionResult(":exception", ":response"));
postMapper.bind("/config/drivers", AddConfig.class).on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session", NewSession.class)
.on(ResultType.SUCCESS, new RedirectResult("/session/:sessionId"));
getMapper.bind("/session/:sessionId", GetSessionCapabilities.class)
.on(ResultType.SUCCESS, new ForwardResult("/WEB-INF/views/sessionCapabilities.jsp"))
.on(ResultType.SUCCESS, new JsonResult(":response"), "application/json");
deleteMapper.bind("/session/:sessionId", DeleteSession.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/window_handle", GetCurrentWindowHandle.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/window_handles", GetAllWindowHandles.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/url", ChangeUrl.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/url", GetCurrentUrl.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/forward", GoForward.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/back", GoBack.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/refresh", RefreshPage.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/execute", ExecuteScript.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/source", GetPageSource.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/screenshot", CaptureScreenshot.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/title", GetTitle.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element", FindElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id", DescribeElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/elements", FindElements.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/active", FindActiveElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/element", FindChildElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/elements", FindChildElements.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/click", ClickElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/text", GetElementText.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/submit", SubmitElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/element/:id/value", SendKeys.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/value", GetElementValue.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/name", GetTagName.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/clear", ClearElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/selected", GetElementSelected.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/selected", SetElementSelected.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/element/:id/toggle", ToggleElement.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/enabled", GetElementEnabled.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/displayed", GetElementDisplayed.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/location", GetElementLocation.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/size", GetElementSize.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/css/:propertyName", GetCssProperty.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/element/:id/hover", HoverOverElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/element/:id/drag", DragElement.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/element/:id/attribute/:name", GetElementAttribute.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/element/:id/equals/:other", ElementEquality.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
getMapper.bind("/session/:sessionId/cookie", GetAllCookies.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/cookie", AddCookie.class)
.on(ResultType.SUCCESS, new EmptyResult());
deleteMapper.bind("/session/:sessionId/cookie", DeleteCookie.class)
.on(ResultType.SUCCESS, new EmptyResult());
deleteMapper.bind("/session/:sessionId/cookie/:name", DeleteNamedCookie.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/frame", SwitchToFrame.class)
.on(ResultType.SUCCESS, new EmptyResult());
postMapper.bind("/session/:sessionId/window", SwitchToWindow.class)
.on(ResultType.SUCCESS, new EmptyResult());
deleteMapper.bind("/session/:sessionId/window", CloseWindow.class)
.on(ResultType.SUCCESS, new EmptyResult());
getMapper.bind("/session/:sessionId/speed", GetMouseSpeed.class)
.on(ResultType.SUCCESS, new JsonResult(":response"));
postMapper.bind("/session/:sessionId/speed", SetMouseSpeed.class)
.on(ResultType.SUCCESS, new EmptyResult());
}
protected ResultConfig addNewGetMapping(String path, Class<? extends Handler> implementationClass) {
return getMapper.bind(path, implementationClass);
}
protected ResultConfig addNewPostMapping(String path, Class<? extends Handler> implementationClass) {
return postMapper.bind(path, implementationClass);
}
protected ResultConfig addNewDeleteMapping(String path, Class<? extends Handler> implementationClass) {
return deleteMapper.bind(path, implementationClass);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(getMapper, request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(postMapper, request, response);
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(deleteMapper, request, response);
}
protected void handleRequest(UrlMapper mapper, HttpServletRequest request,
HttpServletResponse response)
throws ServletException {
try {
ResultConfig config = mapper.getConfig(request.getPathInfo());
if (config == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else {
config.handle(request.getPathInfo(), request, response);
}
} catch (Exception e) {
log("Fatal, unhandled exception: " + request.getPathInfo() + ": " + e);
throw new ServletException(e);
}
}
private class ServletLogTo implements LogTo {
public void log(String message) {
DriverServlet.this.log(message);
}
}
}
|
mogotest/selenium
|
remote/server/src/java/org/openqa/selenium/remote/server/DriverServlet.java
|
Java
|
apache-2.0
| 14,199 |
/*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
*
* 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.apache.harmony.rmi.internal.runtime;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.rmi.server.RMIClassLoader;
import java.rmi.server.RMIClassLoaderSpi;
import java.util.Arrays;
import java.util.HashMap;
import org.apache.harmony.rmi.internal.utils.Pair;
import org.apache.harmony.rmi.internal.utils.PropertiesReader;
/**
* This is the default RMI implementation of the
* {@link java.rmi.server.RMIClassLoaderSpi} interface. The implementation of
* these method it is specified in the
* {@link RMIClassLoader}
* API.
*
* @author Gustavo Petri
*
*/
public class RMIDefaultClassLoaderSpi extends RMIClassLoaderSpi {
/**
* A <code>String</code> that serves as a cache fot the codebaseProp
* property.
*/
private String codebaseProp;
/**
* A flag that represents the unexistence of a <code>SecurityManager</code>.
*/
private boolean noSecurityManager;
/**
* The actual <code>SecurityManager</code> instance of the class.
*/
private SecurityManager securityManager;
/**
* This is a mapping between pairs of sorted codebase Strings and
* <code>ClassLoader</code> instances to <code>WeakReferences</code> to
* the <code>URLClassLoader</code> cached in this table.
*/
private HashMap<Pair<String, ClassLoader>, WeakReference<URLClassLoader>> classLoaderMap;
/**
* Constructs a default {@link java.rmi.server.RMIClassLoaderSpi}
* instance and it initializes the private variables.
*/
public RMIDefaultClassLoaderSpi() {
super();
codebaseProp = PropertiesReader.readString("java.rmi.server.codebase");
securityManager = System.getSecurityManager();
if (securityManager == null) {
noSecurityManager = true;
} else {
noSecurityManager = false;
}
classLoaderMap =
new HashMap<Pair<String, ClassLoader>, WeakReference<URLClassLoader>>();
}
@Override
/**
* Should construct a Proxy Class that implements all the interfaces passed
* as parameter.
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @param interfaces
* a array of <code>Strings</code> interfaces
* @param defaultLoader
* responsible for loading classes
* @return a Proxy Class that implements all the interfaces
* @throws MalformedURLException
* no legal protocol could be found in a specification string
* @throws ClassNotFoundException
* if there is no Classloader for the specified interfaces
*/
public final Class<?> loadProxyClass(String codebase, String[] interfaces,
ClassLoader defaultLoader) throws MalformedURLException,
ClassNotFoundException {
Class<?>[] interfaceClasses = new Class[interfaces.length];
ClassLoader notPublicClassloader = null;
for (int i = 0; i < interfaces.length; i++) {
interfaceClasses[i] = loadClass(codebase, interfaces[i],
defaultLoader);
int modifier = interfaceClasses[i].getModifiers();
if (!Modifier.isPublic(modifier)) {
if (notPublicClassloader == null) {
notPublicClassloader = interfaceClasses[i].getClassLoader();
} else if (!notPublicClassloader.equals(interfaceClasses[i]
.getClassLoader())) {
throw new LinkageError(
"There is no Classloader for the specified interfaces");
}
}
}
if (notPublicClassloader != null) {
try {
return Proxy.getProxyClass(notPublicClassloader,
interfaceClasses);
} catch (Exception e) {
throw new LinkageError(
"There is no Classloader for the specified interfaces");
}
}
try {
ClassLoader cl = getClassLoader(codebase);
return Proxy.getProxyClass(cl, interfaceClasses);
} catch (IllegalArgumentException e) {
try {
return Proxy.getProxyClass(defaultLoader, interfaceClasses);
} catch (IllegalArgumentException e1) {
throw new ClassNotFoundException(
"There is no Classloader for the specified interfaces",
e);
}
}
}
@Override
/**
* Specified in the
* {@link java.rmi.server.RMIClassLoader#getDefaultProviderInstance} Method.
* Returns the
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* which has loaded the Class.
*
* @param cl
* the specified Class
* @return the
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* which has loaded the Class.
*/
public final String getClassAnnotation(Class cl) {
java.lang.ClassLoader classLoader = cl.getClassLoader();
String codebase =
PropertiesReader.readString("java.rmi.server.codebase");
if (classLoader == null) {
return codebase;
}
java.lang.ClassLoader cLoader = classLoader;
while (cLoader != null) {
if (ClassLoader.getSystemClassLoader().equals(classLoader)) {
return codebase;
}
if (cl != null) {
cLoader = cLoader.getParent();
}
}
if (classLoader instanceof URLClassLoader
&& !ClassLoader.getSystemClassLoader().equals(classLoader)) {
try {
URL urls[] = ((URLClassLoader) classLoader).getURLs();
String ret = null;
/*
* FIXME HARD: Check Permissions: If the URLClassLoader was
* created by this provider to service an invocation of its
* loadClass or loadProxyClass methods, then no permissions are
* required to get the associated codebase string. If it is an
* arbitrary other URLClassLoader instance, then if there is a
* security manager, its checkPermission method will be invoked
* once for each URL returned by the getURLs method, with the
* permission returned by invoking
* openConnection().getPermission() on each URL
*/
if (urls != null) {
for (URL url : urls) {
if (ret == null) {
ret = new String(url.toExternalForm());
} else {
ret += " " + url.toExternalForm();
}
}
}
return ret;
} catch (SecurityException e) {
return codebase;
}
}
return codebase;
}
@Override
/**
* Specified in the {@link java.rmi.server.RMIClassLoader#loadClass(String)}
* Method. It loads the class directly.
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @param name
* of the class.
* @param defaultLoader
* responsible for loading classes
* @return a Proxy Class
* @throws MalformedURLException
* no legal protocol could be found in a specification string
* @throws ClassNotFoundException
* if there is no Classloader for the specified interfaces
*/
public final Class<?> loadClass(String codebase, String name,
ClassLoader defaultLoader) throws MalformedURLException,
ClassNotFoundException {
Class<?> ret;
if (defaultLoader != null) {
try {
ret = Class.forName(name, false, defaultLoader);
} catch (ClassNotFoundException e) {
try {
ret = Class.forName(name, false, getClassLoader(codebase));
} catch (SecurityException e1) {
ret = Class.forName(name, false, Thread.currentThread()
.getContextClassLoader());
}
}
} else {
try {
ret = Class.forName(name, false, getClassLoader(codebase));
} catch (SecurityException e1) {
ret = Class.forName(name, false, Thread.currentThread()
.getContextClassLoader());
}
}
return ret;
}
@Override
/**
* Specified in the
* {@link java.rmi.server.RMIClassLoader#getClassLoader(String)} Method.
* Returns the corresponding
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* to the codebase
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @return the corresponding
* {@link <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html"><code>ClassLoader</code></a>}
* @throws MalformedURLException
* no legal protocol could be found in a specification string
*/
public final ClassLoader getClassLoader(String codebase)
throws MalformedURLException {
if (!noSecurityManager) {
securityManager.checkPermission(
new RuntimePermission("getClassLoader"));
} else {
return Thread.currentThread().getContextClassLoader();
}
return getClassLoaderFromCodebase(codebase);
}
/**
* Specified in the {@link java.rmi.server.RMIClassLoader}.
*
* @param codebase
* a <code>String</code> that represent the specified directory
* @return the corresponding
* {@link ClassLoader}
* @throws MalformedURLException
* no legal protocol could be found in a specification string
*/
private final ClassLoader getClassLoaderFromCodebase(String codebase)
throws MalformedURLException {
ClassLoader classLoader = null;
String tempCodebase = (codebase == null) ? codebaseProp : codebase;
/*
* The API Specification always assumes that the property
* java.rmi.server.codebase is correctly setted, and it does not specify
* what to do when returns null. In this case we always return
* Thread.currentThread().getContextClassLoader();
*/
if (tempCodebase == null) {
return Thread.currentThread().getContextClassLoader();
}
tempCodebase = sortURLs(tempCodebase);
Pair<String, ClassLoader> key = new Pair<String, ClassLoader>(
tempCodebase, Thread.currentThread().getContextClassLoader());
if (classLoaderMap.containsKey(key)) {
classLoader = classLoaderMap.get(key).get();
}
if (classLoader == null) {
URL[] urls = getURLs(codebase);
if (urls == null) {
return null;
}
for (URL url : urls) {
try {
securityManager.checkPermission(url.openConnection()
.getPermission());
} catch (IOException e) {
throw new SecurityException(e);
}
}
classLoader = new URLClassLoader(urls);
classLoaderMap.put(key, new WeakReference<URLClassLoader>(
(URLClassLoader) classLoader));
}
return classLoader;
}
/**
* Takes a <EM>space separated</EM> list of URL's as a String, and sorts
* it. For that purpose the String must be parsed.
*
* @param urls
* a list of URL's
* @return an alphabetic order list of URL's
*/
private final static String sortURLs(String urls) {
String ret = null;
if (urls != null) {
String[] codebaseSplit = urls.split("( )+");
if (codebaseSplit.length > 0) {
ret = new String();
Arrays.sort(codebaseSplit);
for (String url : codebaseSplit) {
ret += url + " ";
}
}
}
return ret;
}
/**
* Takes a <EM>space separated</EM> list of URL's as a <code>String</code>,
* and returns an array of URL's.
*
* @param urls
* a list of URL's as a <code>String</code>
* @return an array of URL's
* @throws MalformedURLException
* no legal protocol could be found in a specification string
*/
private final static URL[] getURLs(String urls) throws MalformedURLException {
URL[] realURLs = null;
if (urls == null) {
return realURLs;
}
String[] codebaseSplit = urls.split("( )+");
if (codebaseSplit.length > 0) {
realURLs = new URL[codebaseSplit.length];
for (int i = 0; i < codebaseSplit.length; i++) {
realURLs[i] = new URL(codebaseSplit[i]);
}
}
return realURLs;
}
}
|
freeVM/freeVM
|
enhanced/archive/classlib/modules/rmi2.1.4/src/main/java/org/apache/harmony/rmi/internal/runtime/RMIDefaultClassLoaderSpi.java
|
Java
|
apache-2.0
| 14,748 |
package com.squeezer.designpatterns.abstractfactory;
public class ProductA1 implements AbstractProductA {
@Override
public void display() {
System.out.println("Product A 1 display");
}
}
|
Squeezer-software/java-design-patterns
|
src/com/squeezer/designpatterns/abstractfactory/ProductA1.java
|
Java
|
apache-2.0
| 211 |
package com.example.reference;
import arez.annotations.ArezComponent;
import arez.annotations.LinkType;
import arez.annotations.Observable;
import arez.annotations.Reference;
import arez.annotations.ReferenceId;
@ArezComponent
abstract class LazyLoadObservableReferenceModel
{
@Reference( load = LinkType.LAZY )
abstract MyEntity getMyEntity();
@ReferenceId
@Observable
abstract int getMyEntityId();
abstract void setMyEntityId( int id );
static class MyEntity
{
}
}
|
realityforge/arez
|
processor/src/test/fixtures/input/com/example/reference/LazyLoadObservableReferenceModel.java
|
Java
|
apache-2.0
| 490 |
package advisor
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"encoding/json"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
"github.com/Azure/go-autorest/autorest/to"
"github.com/satori/go.uuid"
"net/http"
)
// Category enumerates the values for category.
type Category string
const (
// Cost ...
Cost Category = "Cost"
// HighAvailability ...
HighAvailability Category = "HighAvailability"
// Performance ...
Performance Category = "Performance"
// Security ...
Security Category = "Security"
)
// PossibleCategoryValues returns an array of possible values for the Category const type.
func PossibleCategoryValues() []Category {
return []Category{Cost, HighAvailability, Performance, Security}
}
// Impact enumerates the values for impact.
type Impact string
const (
// High ...
High Impact = "High"
// Low ...
Low Impact = "Low"
// Medium ...
Medium Impact = "Medium"
)
// PossibleImpactValues returns an array of possible values for the Impact const type.
func PossibleImpactValues() []Impact {
return []Impact{High, Low, Medium}
}
// Risk enumerates the values for risk.
type Risk string
const (
// Error ...
Error Risk = "Error"
// None ...
None Risk = "None"
// Warning ...
Warning Risk = "Warning"
)
// PossibleRiskValues returns an array of possible values for the Risk const type.
func PossibleRiskValues() []Risk {
return []Risk{Error, None, Warning}
}
// ARMErrorResponseBody ARM error response body.
type ARMErrorResponseBody struct {
autorest.Response `json:"-"`
// Message - Gets or sets the string that describes the error in detail and provides debugging information.
Message *string `json:"message,omitempty"`
// Code - Gets or sets the string that can be used to programmatically identify the error.
Code *string `json:"code,omitempty"`
}
// ConfigData the Advisor configuration data structure.
type ConfigData struct {
// ID - The resource Id of the configuration resource.
ID *string `json:"id,omitempty"`
// Type - The type of the configuration resource.
Type *string `json:"type,omitempty"`
// Name - The name of the configuration resource.
Name *string `json:"name,omitempty"`
// Properties - The list of property name/value pairs.
Properties *ConfigDataProperties `json:"properties,omitempty"`
}
// ConfigDataProperties the list of property name/value pairs.
type ConfigDataProperties struct {
// AdditionalProperties - Unmatched properties from the message are deserialized this collection
AdditionalProperties map[string]interface{} `json:""`
// Exclude - Exclude the resource from Advisor evaluations. Valid values: False (default) or True.
Exclude *bool `json:"exclude,omitempty"`
// LowCPUThreshold - Minimum percentage threshold for Advisor low CPU utilization evaluation. Valid only for subscriptions. Valid values: 5 (default), 10, 15 or 20.
LowCPUThreshold *string `json:"low_cpu_threshold,omitempty"`
}
// MarshalJSON is the custom marshaler for ConfigDataProperties.
func (cd ConfigDataProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if cd.Exclude != nil {
objectMap["exclude"] = cd.Exclude
}
if cd.LowCPUThreshold != nil {
objectMap["low_cpu_threshold"] = cd.LowCPUThreshold
}
for k, v := range cd.AdditionalProperties {
objectMap[k] = v
}
return json.Marshal(objectMap)
}
// ConfigurationListResult the list of Advisor configurations.
type ConfigurationListResult struct {
autorest.Response `json:"-"`
// Value - The list of configurations.
Value *[]ConfigData `json:"value,omitempty"`
// NextLink - The link used to get the next page of configurations.
NextLink *string `json:"nextLink,omitempty"`
}
// ConfigurationListResultIterator provides access to a complete listing of ConfigData values.
type ConfigurationListResultIterator struct {
i int
page ConfigurationListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *ConfigurationListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter ConfigurationListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter ConfigurationListResultIterator) Response() ConfigurationListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter ConfigurationListResultIterator) Value() ConfigData {
if !iter.page.NotDone() {
return ConfigData{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (clr ConfigurationListResult) IsEmpty() bool {
return clr.Value == nil || len(*clr.Value) == 0
}
// configurationListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (clr ConfigurationListResult) configurationListResultPreparer() (*http.Request, error) {
if clr.NextLink == nil || len(to.String(clr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(clr.NextLink)))
}
// ConfigurationListResultPage contains a page of ConfigData values.
type ConfigurationListResultPage struct {
fn func(ConfigurationListResult) (ConfigurationListResult, error)
clr ConfigurationListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *ConfigurationListResultPage) Next() error {
next, err := page.fn(page.clr)
if err != nil {
return err
}
page.clr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page ConfigurationListResultPage) NotDone() bool {
return !page.clr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page ConfigurationListResultPage) Response() ConfigurationListResult {
return page.clr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page ConfigurationListResultPage) Values() []ConfigData {
if page.clr.IsEmpty() {
return nil
}
return *page.clr.Value
}
// OperationDisplayInfo the operation supported by Advisor.
type OperationDisplayInfo struct {
// Description - The description of the operation.
Description *string `json:"description,omitempty"`
// Operation - The action that users can perform, based on their permission level.
Operation *string `json:"operation,omitempty"`
// Provider - Service provider: Microsoft Advisor.
Provider *string `json:"provider,omitempty"`
// Resource - Resource on which the operation is performed.
Resource *string `json:"resource,omitempty"`
}
// OperationEntity the operation supported by Advisor.
type OperationEntity struct {
// Name - Operation name: {provider}/{resource}/{operation}.
Name *string `json:"name,omitempty"`
// Display - The operation supported by Advisor.
Display *OperationDisplayInfo `json:"display,omitempty"`
}
// OperationEntityListResult the list of Advisor operations.
type OperationEntityListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of operations.
NextLink *string `json:"nextLink,omitempty"`
// Value - The list of operations.
Value *[]OperationEntity `json:"value,omitempty"`
}
// OperationEntityListResultIterator provides access to a complete listing of OperationEntity values.
type OperationEntityListResultIterator struct {
i int
page OperationEntityListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *OperationEntityListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter OperationEntityListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter OperationEntityListResultIterator) Response() OperationEntityListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter OperationEntityListResultIterator) Value() OperationEntity {
if !iter.page.NotDone() {
return OperationEntity{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (oelr OperationEntityListResult) IsEmpty() bool {
return oelr.Value == nil || len(*oelr.Value) == 0
}
// operationEntityListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (oelr OperationEntityListResult) operationEntityListResultPreparer() (*http.Request, error) {
if oelr.NextLink == nil || len(to.String(oelr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(oelr.NextLink)))
}
// OperationEntityListResultPage contains a page of OperationEntity values.
type OperationEntityListResultPage struct {
fn func(OperationEntityListResult) (OperationEntityListResult, error)
oelr OperationEntityListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *OperationEntityListResultPage) Next() error {
next, err := page.fn(page.oelr)
if err != nil {
return err
}
page.oelr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page OperationEntityListResultPage) NotDone() bool {
return !page.oelr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page OperationEntityListResultPage) Response() OperationEntityListResult {
return page.oelr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page OperationEntityListResultPage) Values() []OperationEntity {
if page.oelr.IsEmpty() {
return nil
}
return *page.oelr.Value
}
// RecommendationProperties the properties of the recommendation.
type RecommendationProperties struct {
// Category - The category of the recommendation. Possible values include: 'HighAvailability', 'Security', 'Performance', 'Cost'
Category Category `json:"category,omitempty"`
// Impact - The business impact of the recommendation. Possible values include: 'High', 'Medium', 'Low'
Impact Impact `json:"impact,omitempty"`
// ImpactedField - The resource type identified by Advisor.
ImpactedField *string `json:"impactedField,omitempty"`
// ImpactedValue - The resource identified by Advisor.
ImpactedValue *string `json:"impactedValue,omitempty"`
// LastUpdated - The most recent time that Advisor checked the validity of the recommendation.
LastUpdated *date.Time `json:"lastUpdated,omitempty"`
// Metadata - The recommendation metadata.
Metadata map[string]interface{} `json:"metadata"`
// RecommendationTypeID - The recommendation-type GUID.
RecommendationTypeID *string `json:"recommendationTypeId,omitempty"`
// Risk - The potential risk of not implementing the recommendation. Possible values include: 'Error', 'Warning', 'None'
Risk Risk `json:"risk,omitempty"`
// ShortDescription - A summary of the recommendation.
ShortDescription *ShortDescription `json:"shortDescription,omitempty"`
// SuppressionIds - The list of snoozed and dismissed rules for the recommendation.
SuppressionIds *[]uuid.UUID `json:"suppressionIds,omitempty"`
}
// MarshalJSON is the custom marshaler for RecommendationProperties.
func (rp RecommendationProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rp.Category != "" {
objectMap["category"] = rp.Category
}
if rp.Impact != "" {
objectMap["impact"] = rp.Impact
}
if rp.ImpactedField != nil {
objectMap["impactedField"] = rp.ImpactedField
}
if rp.ImpactedValue != nil {
objectMap["impactedValue"] = rp.ImpactedValue
}
if rp.LastUpdated != nil {
objectMap["lastUpdated"] = rp.LastUpdated
}
if rp.Metadata != nil {
objectMap["metadata"] = rp.Metadata
}
if rp.RecommendationTypeID != nil {
objectMap["recommendationTypeId"] = rp.RecommendationTypeID
}
if rp.Risk != "" {
objectMap["risk"] = rp.Risk
}
if rp.ShortDescription != nil {
objectMap["shortDescription"] = rp.ShortDescription
}
if rp.SuppressionIds != nil {
objectMap["suppressionIds"] = rp.SuppressionIds
}
return json.Marshal(objectMap)
}
// Resource an Azure resource.
type Resource struct {
// ID - The resource ID.
ID *string `json:"id,omitempty"`
// Name - The name of the resource.
Name *string `json:"name,omitempty"`
// Type - The type of the resource.
Type *string `json:"type,omitempty"`
}
// ResourceRecommendationBase advisor Recommendation.
type ResourceRecommendationBase struct {
autorest.Response `json:"-"`
// RecommendationProperties - The properties of the recommendation.
*RecommendationProperties `json:"properties,omitempty"`
// ID - The resource ID.
ID *string `json:"id,omitempty"`
// Name - The name of the resource.
Name *string `json:"name,omitempty"`
// Type - The type of the resource.
Type *string `json:"type,omitempty"`
}
// MarshalJSON is the custom marshaler for ResourceRecommendationBase.
func (rrb ResourceRecommendationBase) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rrb.RecommendationProperties != nil {
objectMap["properties"] = rrb.RecommendationProperties
}
if rrb.ID != nil {
objectMap["id"] = rrb.ID
}
if rrb.Name != nil {
objectMap["name"] = rrb.Name
}
if rrb.Type != nil {
objectMap["type"] = rrb.Type
}
return json.Marshal(objectMap)
}
// UnmarshalJSON is the custom unmarshaler for ResourceRecommendationBase struct.
func (rrb *ResourceRecommendationBase) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
for k, v := range m {
switch k {
case "properties":
if v != nil {
var recommendationProperties RecommendationProperties
err = json.Unmarshal(*v, &recommendationProperties)
if err != nil {
return err
}
rrb.RecommendationProperties = &recommendationProperties
}
case "id":
if v != nil {
var ID string
err = json.Unmarshal(*v, &ID)
if err != nil {
return err
}
rrb.ID = &ID
}
case "name":
if v != nil {
var name string
err = json.Unmarshal(*v, &name)
if err != nil {
return err
}
rrb.Name = &name
}
case "type":
if v != nil {
var typeVar string
err = json.Unmarshal(*v, &typeVar)
if err != nil {
return err
}
rrb.Type = &typeVar
}
}
}
return nil
}
// ResourceRecommendationBaseListResult the list of Advisor recommendations.
type ResourceRecommendationBaseListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of recommendations.
NextLink *string `json:"nextLink,omitempty"`
// Value - The list of recommendations.
Value *[]ResourceRecommendationBase `json:"value,omitempty"`
}
// ResourceRecommendationBaseListResultIterator provides access to a complete listing of ResourceRecommendationBase
// values.
type ResourceRecommendationBaseListResultIterator struct {
i int
page ResourceRecommendationBaseListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *ResourceRecommendationBaseListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter ResourceRecommendationBaseListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter ResourceRecommendationBaseListResultIterator) Response() ResourceRecommendationBaseListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter ResourceRecommendationBaseListResultIterator) Value() ResourceRecommendationBase {
if !iter.page.NotDone() {
return ResourceRecommendationBase{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (rrblr ResourceRecommendationBaseListResult) IsEmpty() bool {
return rrblr.Value == nil || len(*rrblr.Value) == 0
}
// resourceRecommendationBaseListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (rrblr ResourceRecommendationBaseListResult) resourceRecommendationBaseListResultPreparer() (*http.Request, error) {
if rrblr.NextLink == nil || len(to.String(rrblr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(rrblr.NextLink)))
}
// ResourceRecommendationBaseListResultPage contains a page of ResourceRecommendationBase values.
type ResourceRecommendationBaseListResultPage struct {
fn func(ResourceRecommendationBaseListResult) (ResourceRecommendationBaseListResult, error)
rrblr ResourceRecommendationBaseListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *ResourceRecommendationBaseListResultPage) Next() error {
next, err := page.fn(page.rrblr)
if err != nil {
return err
}
page.rrblr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page ResourceRecommendationBaseListResultPage) NotDone() bool {
return !page.rrblr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page ResourceRecommendationBaseListResultPage) Response() ResourceRecommendationBaseListResult {
return page.rrblr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page ResourceRecommendationBaseListResultPage) Values() []ResourceRecommendationBase {
if page.rrblr.IsEmpty() {
return nil
}
return *page.rrblr.Value
}
// ShortDescription a summary of the recommendation.
type ShortDescription struct {
// Problem - The issue or opportunity identified by the recommendation.
Problem *string `json:"problem,omitempty"`
// Solution - The remediation action suggested by the recommendation.
Solution *string `json:"solution,omitempty"`
}
// SuppressionContract the details of the snoozed or dismissed rule; for example, the duration, name, and GUID
// associated with the rule.
type SuppressionContract struct {
autorest.Response `json:"-"`
// SuppressionProperties - The properties of the suppression.
*SuppressionProperties `json:"properties,omitempty"`
// ID - The resource ID.
ID *string `json:"id,omitempty"`
// Name - The name of the resource.
Name *string `json:"name,omitempty"`
// Type - The type of the resource.
Type *string `json:"type,omitempty"`
}
// MarshalJSON is the custom marshaler for SuppressionContract.
func (sc SuppressionContract) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if sc.SuppressionProperties != nil {
objectMap["properties"] = sc.SuppressionProperties
}
if sc.ID != nil {
objectMap["id"] = sc.ID
}
if sc.Name != nil {
objectMap["name"] = sc.Name
}
if sc.Type != nil {
objectMap["type"] = sc.Type
}
return json.Marshal(objectMap)
}
// UnmarshalJSON is the custom unmarshaler for SuppressionContract struct.
func (sc *SuppressionContract) UnmarshalJSON(body []byte) error {
var m map[string]*json.RawMessage
err := json.Unmarshal(body, &m)
if err != nil {
return err
}
for k, v := range m {
switch k {
case "properties":
if v != nil {
var suppressionProperties SuppressionProperties
err = json.Unmarshal(*v, &suppressionProperties)
if err != nil {
return err
}
sc.SuppressionProperties = &suppressionProperties
}
case "id":
if v != nil {
var ID string
err = json.Unmarshal(*v, &ID)
if err != nil {
return err
}
sc.ID = &ID
}
case "name":
if v != nil {
var name string
err = json.Unmarshal(*v, &name)
if err != nil {
return err
}
sc.Name = &name
}
case "type":
if v != nil {
var typeVar string
err = json.Unmarshal(*v, &typeVar)
if err != nil {
return err
}
sc.Type = &typeVar
}
}
}
return nil
}
// SuppressionContractListResult the list of Advisor suppressions.
type SuppressionContractListResult struct {
autorest.Response `json:"-"`
// NextLink - The link used to get the next page of suppressions.
NextLink *string `json:"nextLink,omitempty"`
// Value - The list of suppressions.
Value *[]SuppressionContract `json:"value,omitempty"`
}
// SuppressionContractListResultIterator provides access to a complete listing of SuppressionContract values.
type SuppressionContractListResultIterator struct {
i int
page SuppressionContractListResultPage
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *SuppressionContractListResultIterator) Next() error {
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err := iter.page.Next()
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter SuppressionContractListResultIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter SuppressionContractListResultIterator) Response() SuppressionContractListResult {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter SuppressionContractListResultIterator) Value() SuppressionContract {
if !iter.page.NotDone() {
return SuppressionContract{}
}
return iter.page.Values()[iter.i]
}
// IsEmpty returns true if the ListResult contains no values.
func (sclr SuppressionContractListResult) IsEmpty() bool {
return sclr.Value == nil || len(*sclr.Value) == 0
}
// suppressionContractListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (sclr SuppressionContractListResult) suppressionContractListResultPreparer() (*http.Request, error) {
if sclr.NextLink == nil || len(to.String(sclr.NextLink)) < 1 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(sclr.NextLink)))
}
// SuppressionContractListResultPage contains a page of SuppressionContract values.
type SuppressionContractListResultPage struct {
fn func(SuppressionContractListResult) (SuppressionContractListResult, error)
sclr SuppressionContractListResult
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *SuppressionContractListResultPage) Next() error {
next, err := page.fn(page.sclr)
if err != nil {
return err
}
page.sclr = next
return nil
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page SuppressionContractListResultPage) NotDone() bool {
return !page.sclr.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page SuppressionContractListResultPage) Response() SuppressionContractListResult {
return page.sclr
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page SuppressionContractListResultPage) Values() []SuppressionContract {
if page.sclr.IsEmpty() {
return nil
}
return *page.sclr.Value
}
// SuppressionProperties the properties of the suppression.
type SuppressionProperties struct {
// SuppressionID - The GUID of the suppression.
SuppressionID *string `json:"suppressionId,omitempty"`
// TTL - The duration for which the suppression is valid.
TTL *string `json:"ttl,omitempty"`
}
|
linzhaoming/origin
|
vendor/github.com/Azure/azure-sdk-for-go/services/advisor/mgmt/2017-04-19/advisor/models.go
|
GO
|
apache-2.0
| 25,984 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.vebo.dados.mapeamento;
/**
*
* @author mohfus
*/
public enum MovimentacaoEstoqueEnum {
ENTRADA,
RETIRADA;
}
|
diegobqb/veboMaven
|
src/main/java/br/com/vebo/dados/mapeamento/MovimentacaoEstoqueEnum.java
|
Java
|
apache-2.0
| 236 |
import * as should from 'should';
import 'should-http';
import 'should-sinon';
import '../lib/asserts';
import * as nock from 'nock';
import * as sinon from 'sinon';
import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import * as debugLib from 'debug';
import * as path from 'path';
import { Environments } from 'bitgo';
import { coroutine as co } from 'bluebird';
import { SSL_OP_NO_TLSv1 } from 'constants';
import { TlsConfigurationError, NodeEnvironmentError } from '../../src/errors';
nock.disableNetConnect();
import {
app as expressApp,
startup,
createServer,
createBaseUri,
prepareIpc,
} from '../../src/expressApp';
import * as clientRoutes from '../../src/clientRoutes';
describe('Bitgo Express', function () {
describe('server initialization', function () {
const validPrvJSON =
'{"61f039aad587c2000745c687373e0fa9":"xprv9s21ZrQH143K3EuPWCBuqnWxydaQV6et9htQige4EswvcHKEzNmkVmwTwKoadyHzJYppuADB7Us7AbaNLToNvoFoSxuWqndQRYtnNy5DUY2"}';
it('should require NODE_ENV to be production when running against prod env', function () {
const envStub = sinon.stub(process, 'env').value({ NODE_ENV: 'production' });
try {
(() => expressApp({
env: 'prod',
bind: 'localhost',
} as any)).should.not.throw();
process.env.NODE_ENV = 'dev';
(() => expressApp({
env: 'prod',
bind: 'localhost',
} as any)).should.throw(NodeEnvironmentError);
} finally {
envStub.restore();
}
});
it('should disable NODE_ENV check if disableenvcheck argument is given', function () {
const envStub = sinon.stub(process, 'env').value({ NODE_ENV: 'dev' });
try {
(() => expressApp({
env: 'prod',
bind: 'localhost',
disableEnvCheck: true,
} as any)).should.not.throw();
} finally {
envStub.restore();
}
});
it('should require TLS for prod env when listening on external interfaces', function () {
const args: any = {
env: 'prod',
bind: '1',
disableEnvCheck: true,
disableSSL: false,
crtPath: undefined as string | undefined,
keyPath: undefined as string | undefined,
};
(() => expressApp(args)).should.throw(TlsConfigurationError);
args.bind = 'localhost';
(() => expressApp(args)).should.not.throw();
args.bind = '1';
args.env = 'test';
(() => expressApp(args)).should.not.throw();
args.disableSSL = true;
args.env = 'prod';
(() => expressApp(args)).should.not.throw();
delete args.disableSSL;
args.crtPath = '/tmp/cert.pem';
(() => expressApp(args)).should.throw(TlsConfigurationError);
delete args.crtPath;
args.keyPath = '/tmp/key.pem';
(() => expressApp(args)).should.throw(TlsConfigurationError);
});
it('should require both keypath and crtpath when using TLS, but TLS is not required', function () {
const args: any = {
env: 'test',
bind: '1',
keyPath: '/tmp/key.pem',
crtPath: undefined as string | undefined,
};
(() => expressApp(args)).should.throw(TlsConfigurationError);
delete args.keyPath;
args.crtPath = '/tmp/cert.pem';
(() => expressApp(args)).should.throw(TlsConfigurationError);
});
it('should create an http server when not using TLS', co(function *() {
const createServerStub = sinon.stub(http, 'createServer');
const args: any = {
env: 'prod',
bind: 'localhost',
};
createServer(args, null as any);
createServerStub.should.be.calledOnce();
createServerStub.restore();
}));
it('should create an https server when using TLS', co(function *() {
const createServerStub = sinon.stub(https, 'createServer');
const readFileAsyncStub = sinon.stub(fs.promises, 'readFile' as any)
.onFirstCall().resolves('key')
.onSecondCall().resolves('cert');
const args: any = {
env: 'prod',
bind: '1.2.3.4',
crtPath: '/tmp/crt.pem',
keyPath: '/tmp/key.pem',
};
yield createServer(args, null as any);
https.createServer.should.be.calledOnce();
https.createServer.should.be.calledWith({ secureOptions: SSL_OP_NO_TLSv1, key: 'key', cert: 'cert' });
createServerStub.restore();
readFileAsyncStub.restore();
}));
it('should output basic information upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
};
startup(args, 'base')();
logStub.should.have.callCount(3);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.restore();
});
it('should output custom root uri information upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
customRootUri: 'customuri',
};
startup(args, 'base')();
logStub.should.have.callCount(4);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.should.have.been.calledWith(`Custom root URI: ${args.customRootUri}`);
logStub.restore();
});
it('should output custom bitcoin network information upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
customBitcoinNetwork: 'customnetwork',
};
startup(args, 'base')();
logStub.should.have.callCount(4);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.should.have.been.calledWith(`Custom bitcoin network: ${args.customBitcoinNetwork}`);
logStub.restore();
});
it('should output signer mode upon server startup', () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
signerMode: 'signerMode',
};
startup(args, 'base')();
logStub.should.have.callCount(4);
logStub.should.have.been.calledWith('BitGo-Express running');
logStub.should.have.been.calledWith(`Environment: ${args.env}`);
logStub.should.have.been.calledWith('Base URI: base');
logStub.should.have.been.calledWith(`External signer mode: ${args.signerMode}`);
logStub.restore();
});
it('should create http base URIs', () => {
const args: any = {
bind: '1',
port: 2,
};
createBaseUri(args).should.equal(`http://${args.bind}:${args.port}`);
args.port = 80;
createBaseUri(args).should.equal(`http://${args.bind}`);
args.port = 443;
createBaseUri(args).should.equal(`http://${args.bind}:443`);
});
it('should create https base URIs', () => {
const args: any = {
bind: '6',
port: 8,
keyPath: '3',
crtPath: '4',
};
createBaseUri(args).should.equal(`https://${args.bind}:${args.port}`);
args.port = 80;
createBaseUri(args).should.equal(`https://${args.bind}:80`);
args.port = 443;
createBaseUri(args).should.equal(`https://${args.bind}`);
});
it('should set up logging with a logfile', () => {
const resolveSpy = sinon.spy(path, 'resolve');
const createWriteStreamSpy = sinon.spy(fs, 'createWriteStream');
const logStub = sinon.stub(console, 'log');
const args: any = {
logFile: '/dev/null',
disableProxy: true,
};
expressApp(args);
path.resolve.should.have.been.calledWith(args.logFile);
fs.createWriteStream.should.have.been.calledOnceWith(args.logFile, { flags: 'a' });
logStub.should.have.been.calledOnceWith(`Log location: ${args.logFile}`);
resolveSpy.restore();
createWriteStreamSpy.restore();
logStub.restore();
});
it('should enable specified debug namespaces', () => {
const enableStub = sinon.stub(debugLib, 'enable');
const args: any = {
debugNamespace: ['a', 'b'],
disableProxy: true,
};
expressApp(args);
enableStub.should.have.been.calledTwice();
enableStub.should.have.been.calledWith(args.debugNamespace[0]);
enableStub.should.have.been.calledWith(args.debugNamespace[1]);
enableStub.restore();
});
it('should configure a custom root URI', () => {
const args: any = {
customRootUri: 'customroot',
env: undefined as string | undefined,
};
expressApp(args);
should(args.env).equal('custom');
Environments.custom.uri.should.equal(args.customRootUri);
});
it('should configure a custom bitcoin network', () => {
const args: any = {
customBitcoinNetwork: 'custombitcoinnetwork',
env: undefined as string | undefined,
};
expressApp(args);
should(args.env).equal('custom');
Environments.custom.network.should.equal(args.customBitcoinNetwork);
});
it('should fail if IPC option is used on windows', async () => {
const platformStub = sinon.stub(process, 'platform').value('win32');
await prepareIpc('testipc').should.be.rejectedWith(/^IPC option is not supported on platform/);
platformStub.restore();
});
it('should not remove the IPC socket if it doesn\'t exist', async () => {
const statStub = sinon.stub(fs, 'statSync').throws({ code: 'ENOENT' });
const unlinkStub = sinon.stub(fs, 'unlinkSync');
await prepareIpc('testipc').should.be.resolved();
unlinkStub.notCalled.should.be.true();
statStub.restore();
unlinkStub.restore();
});
it('should remove the socket before binding if IPC socket exists and is a socket', async () => {
const statStub = sinon.stub(fs, 'statSync').returns(
{ isSocket: () => true } as unknown as fs.Stats,
);
const unlinkStub = sinon.stub(fs, 'unlinkSync');
await prepareIpc('testipc').should.be.resolved();
unlinkStub.calledWithExactly('testipc').should.be.true();
unlinkStub.calledOnce.should.be.true();
statStub.restore();
unlinkStub.restore();
});
it('should fail if IPC socket is not actually a socket', async () => {
const statStub = sinon.stub(fs, 'statSync').returns(
{ isSocket: () => false } as unknown as fs.Stats,
);
const unlinkStub = sinon.stub(fs, 'unlinkSync');
await prepareIpc('testipc').should.be.rejectedWith(/IPC socket is not actually a socket/);
unlinkStub.notCalled.should.be.true();
statStub.restore();
unlinkStub.restore();
});
it('should print the IPC socket path on startup', async () => {
const logStub = sinon.stub(console, 'log');
const args: any = {
env: 'test',
customRootUri: 'customuri',
ipc: 'expressIPC',
};
startup(args, 'base')();
logStub.should.have.been.calledWith('IPC path: expressIPC');
logStub.restore();
});
it('should only call setupAPIRoutes when running in regular mode', () => {
const args: any = {
env: 'test',
signerMode: undefined,
};
const apiStub = sinon.stub(clientRoutes, 'setupAPIRoutes');
const signerStub = sinon.stub(clientRoutes, 'setupSigningRoutes');
expressApp(args);
apiStub.should.have.been.calledOnce();
signerStub.called.should.be.false();
apiStub.restore();
signerStub.restore();
});
it('should only call setupSigningRoutes when running in signer mode', () => {
const args: any = {
env: 'test',
signerMode: 'signerMode',
signerFileSystemPath: 'signerFileSystemPath',
};
const apiStub = sinon.stub(clientRoutes, 'setupAPIRoutes');
const signerStub = sinon.stub(clientRoutes, 'setupSigningRoutes');
const readFileStub = sinon.stub(fs, 'readFileSync').returns(validPrvJSON);
expressApp(args);
signerStub.should.have.been.calledOnce();
apiStub.called.should.be.false();
apiStub.restore();
signerStub.restore();
readFileStub.restore();
});
it('should require a signerFileSystemPath and signerMode are both set when running in signer mode', function () {
const args: any = {
env: 'test',
signerMode: 'signerMode',
signerFileSystemPath: undefined,
};
(() => expressApp(args)).should.throw({
name: 'ExternalSignerConfigError',
message: 'signerMode and signerFileSystemPath must both be set in order to run in external signing mode.'
});
args.signerMode = undefined;
args.signerFileSystemPath = 'signerFileSystemPath';
(() => expressApp(args)).should.throw({
name: 'ExternalSignerConfigError',
message: 'signerMode and signerFileSystemPath must both be set in order to run in external signing mode.'
});
const readFileStub = sinon.stub(fs, 'readFileSync').returns(validPrvJSON);
args.signerMode = 'signerMode';
(() => expressApp(args)).should.not.throw();
readFileStub.restore();
});
it('should require that an externalSignerUrl and signerMode are not both set', function () {
const args: any = {
env: 'test',
signerMode: 'signerMode',
externalSignerUrl: 'externalSignerUrl',
};
(() => expressApp(args)).should.throw({
name: 'ExternalSignerConfigError',
message: 'signerMode or signerFileSystemPath is set, but externalSignerUrl is also set.'
});
args.signerMode = undefined;
(() => expressApp(args)).should.not.throw();
});
it('should require that an signerFileSystemPath contains a parsable json', function () {
const args: any = {
env: 'test',
signerMode: 'signerMode',
signerFileSystemPath: 'invalidSignerFileSystemPath',
};
(() => expressApp(args)).should.throw();
const invalidPrv = '{"invalid json"}';
const readInvalidStub = sinon.stub(fs, 'readFileSync').returns(invalidPrv);
(() => expressApp(args)).should.throw();
readInvalidStub.restore();
const readValidStub = sinon.stub(fs, 'readFileSync').returns(validPrvJSON);
(() => expressApp(args)).should.not.throw();
readValidStub.restore();
});
});
});
|
BitGo/BitGoJS
|
modules/express/test/unit/bitgoExpress.ts
|
TypeScript
|
apache-2.0
| 14,766 |
package requirements_test
import (
"cf/models"
. "cf/requirements"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
testassert "testhelpers/assert"
testconfig "testhelpers/configuration"
testterm "testhelpers/terminal"
)
var _ = Describe("Testing with ginkgo", func() {
It("TestSpaceRequirement", func() {
ui := new(testterm.FakeUI)
org := models.OrganizationFields{}
org.Name = "my-org"
org.Guid = "my-org-guid"
space := models.SpaceFields{}
space.Name = "my-space"
space.Guid = "my-space-guid"
config := testconfig.NewRepositoryWithDefaults()
req := NewTargetedSpaceRequirement(ui, config)
success := req.Execute()
Expect(success).To(BeTrue())
config.SetSpaceFields(models.SpaceFields{})
testassert.AssertPanic(testterm.FailedWasCalled, func() {
NewTargetedSpaceRequirement(ui, config).Execute()
})
testassert.SliceContains(ui.Outputs, testassert.Lines{
{"FAILED"},
{"No space targeted"},
})
ui.ClearOutputs()
config.SetOrganizationFields(models.OrganizationFields{})
testassert.AssertPanic(testterm.FailedWasCalled, func() {
NewTargetedSpaceRequirement(ui, config).Execute()
})
testassert.SliceContains(ui.Outputs, testassert.Lines{
{"FAILED"},
{"No org and space targeted"},
})
})
})
|
nimbus-cloud/cli
|
src/cf/requirements/targeted_space_test.go
|
GO
|
apache-2.0
| 1,273 |
package com.github.mfursov.w7.page.signin;
import com.github.mfursov.w7.Context;
import com.github.mfursov.w7.Mounts;
import com.github.mfursov.w7.annotation.MountPath;
import com.github.mfursov.w7.component.CaptchaField;
import com.github.mfursov.w7.component.Feedback;
import com.github.mfursov.w7.component.RefreshCaptchaLink;
import com.github.mfursov.w7.db.dbi.UsersDbi;
import com.github.mfursov.w7.model.User;
import com.github.mfursov.w7.model.VerificationRecord;
import com.github.mfursov.w7.model.VerificationRecordType;
import com.github.mfursov.w7.page.BasePage;
import com.github.mfursov.w7.util.MailClient;
import com.github.mfursov.w7.util.UserSessionUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.util.MapModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import static java.util.Collections.singletonMap;
/**
*/
@MountPath("/password/restore")
public class ForgotPasswordPage extends BasePage {
private static final Logger log = LoggerFactory.getLogger(ForgotPasswordPage.class);
public ForgotPasswordPage() {
UserSessionUtils.redirectToHomeIfSignedIn();
Feedback feedback = new Feedback("feedback");
add(feedback);
Form form = new Form("reset_from");
add(form);
CaptchaField captchaField = new CaptchaField("captcha_value");
TextField<String> loginOrEmailField = new TextField<>("login_or_email_field", Model.of(""));
form.add(captchaField);
form.add(loginOrEmailField);
Image captchaImage = new NonCachingImage("captcha_image", captchaField.getCaptchaImageResource());
captchaImage.setOutputMarkupId(true);
form.add(captchaImage);
form.add(new RefreshCaptchaLink("change_captcha", captchaField, captchaImage));
form.add(new AjaxSubmitLink("submit", form) {
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
feedback.reset(target);
String captcha = captchaField.getUserText();
if (!captchaField.getOriginalText().equals(captcha)) {
feedback.errorKey("error_invalid_captcha_code");
return;
}
UsersDbi dao = Context.getUsersDbi();
String loginOrEmail = loginOrEmailField.getModelObject();
User user = dao.getUserByLoginOrEmail(loginOrEmail);
if (user == null) {
user = dao.getUserByEmail(loginOrEmail);
}
if (user == null) {
feedback.errorKey("error_user_not_found");
return;
}
VerificationRecord resetRequest = new VerificationRecord(user, VerificationRecordType.PasswordReset, "");
Context.getUsersDbi().createVerificationRecord(resetRequest);
feedback.infoKey("info_password_reset_info_was_sent", new MapModel<>(singletonMap("email", user.email)));
sendEmail(user, resetRequest);
}
});
}
private void sendEmail(User user, VerificationRecord resetRequest) {
try {
MailClient.sendMail(user.email, getString("info_password_reset_email_subject"),
getString("info_password_reset_email_body", new MapModel<>(new HashMap<String, String>() {{
put("username", user.login);
put("link", Mounts.urlFor(ResetPasswordPage.class) + "?" + ResetPasswordPage.HASH_PARAM + "=" + resetRequest.hash);
}})));
} catch (IOException e) {
log.error("", e);
//todo:
}
}
}
|
mfursov/wicket7template
|
src/main/java/com/github/mfursov/w7/page/signin/ForgotPasswordPage.java
|
Java
|
apache-2.0
| 4,068 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LoveCalculator.java
*
* Created on 2011-11-24, 9:27:40
*/
package pb.text;
/**
* @author maqiang
*/
public class LoveCalculator extends javax.swing.JFrame
{
/**
* 域(私有)<br>
* 名称: dp<br>
* 描述: 日期处理对象<br>
*/
private DateProcessor dp;
/**
* 域()<br>
* 名称: <br>
* 描述: <br>
*/
private String curDate;
private String knowDate;
private String loveDate;
private String marryDate;
/** Creates new form LoveCalculator */
public LoveCalculator()
{
initComponents();
this.dp=new DateProcessor();
this.curDate=this.dp.getCurrent();
this.knowDate="2001-09-10";
this.loveDate="2002-02-24";
this.marryDate="2011-03-22";
this.currentDateField.setText(curDate);
this.knowDateField.setText(this.knowDate);
this.loveDateField.setText(this.loveDate);
this.marryDateField.setText(this.marryDate);
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
loveDateLabel=new javax.swing.JLabel();
loveDateField=new javax.swing.JTextField();
marryDateField=new javax.swing.JTextField();
marryDateLabel=new javax.swing.JLabel();
currentDateLabel=new javax.swing.JLabel();
currentDateField=new javax.swing.JTextField();
loveTimeField=new javax.swing.JTextField();
loveTimeLabel=new javax.swing.JLabel();
marryTimeLabel=new javax.swing.JLabel();
marryTimeField=new javax.swing.JTextField();
calculateButton=new javax.swing.JButton();
knowDateField=new javax.swing.JTextField();
knowDateLabel=new javax.swing.JLabel();
knowTimeLabel=new javax.swing.JLabel();
knowTimeField=new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("爱情计算器");
setBackground(new java.awt.Color(255,255,255));
loveDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveDateLabel.setText("恋爱日期:");
loveDateField.setEditable(false);
loveDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryDateField.setEditable(false);
marryDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryDateLabel.setText("结婚日期:");
currentDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
currentDateLabel.setText("当前日期:");
currentDateField.setEditable(false);
currentDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveTimeField.setEditable(false);
loveTimeField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveTimeLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
loveTimeLabel.setText("恋爱时间:");
marryTimeLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
marryTimeLabel.setText("结婚时间:");
marryTimeField.setEditable(false);
marryTimeField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
calculateButton.setText("计算");
calculateButton.addMouseListener(
new java.awt.event.MouseAdapter()
{
public void mouseClicked(java.awt.event.MouseEvent evt)
{
calculateButtonMouseClicked(evt);
}
}
);
knowDateField.setEditable(false);
knowDateField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
knowDateLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
knowDateLabel.setText("结识日期:");
knowTimeLabel.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
knowTimeLabel.setText("结识时间:");
knowTimeField.setEditable(false);
knowTimeField.setFont(new java.awt.Font("微软雅黑",0,14)); // NOI18N
javax.swing.GroupLayout layout=new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addContainerGap()
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.TRAILING
)
.addComponent(marryTimeLabel)
.addComponent(loveTimeLabel)
.addComponent(knowTimeLabel)
.addComponent(currentDateLabel)
.addComponent(marryDateLabel)
)
.addComponent(loveDateLabel)
.addComponent(knowDateLabel)
)
.addGap(10,10,10)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(calculateButton)
.addComponent(
marryTimeField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
.addComponent(
knowTimeField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
.addComponent(
knowDateField,javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,194,Short.MAX_VALUE
)
.addComponent(
loveDateField,javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE,194,Short.MAX_VALUE
)
.addComponent(
marryDateField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
.addComponent(
currentDateField,javax.swing.GroupLayout.DEFAULT_SIZE,
194,Short.MAX_VALUE
)
.addComponent(
loveTimeField,javax.swing.GroupLayout.DEFAULT_SIZE,194,
Short.MAX_VALUE
)
)
.addContainerGap()
)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,layout.createSequentialGroup()
.addContainerGap(29,Short.MAX_VALUE)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
knowDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(knowDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
loveDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(loveDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
marryDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(marryDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
currentDateField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(currentDateLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
knowTimeField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(knowTimeLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
loveTimeField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(loveTimeLabel)
)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(
marryTimeField,javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE
)
.addComponent(marryTimeLabel)
)
.addGap(14,14,14)
.addComponent(calculateButton)
.addContainerGap()
)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void calculateButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_calculateButtonMouseClicked
{//GEN-HEADEREND:event_calculateButtonMouseClicked
// TODO add your handling code here:
this.knowTimeField.setText(this.calculateDate(curDate,this.knowDate));
this.loveTimeField.setText(this.calculateDate(curDate,this.loveDate));
this.marryTimeField.setText(this.calculateDate(curDate,this.marryDate));
}//GEN-LAST:event_calculateButtonMouseClicked
private String calculateDate(String currentDate,String oldDate)
{
String result="";
int first=4;
int last=7;
//计算年
int cur=Integer.parseInt(currentDate.substring(0,first));
int old=Integer.parseInt(oldDate.substring(0,first));
int diff=cur-old;
result+=(diff<1)?"":(diff+"年");
//计算月
cur=Integer.parseInt(currentDate.substring(first+1,last));
old=Integer.parseInt(oldDate.substring(first+1,last));
diff=cur-old;
result+=(diff<1)?"":(diff+"个月");
//计算天
cur=Integer.parseInt(currentDate.substring(last+1));
old=Integer.parseInt(oldDate.substring(last+1));
diff=cur-old;
result+=(diff<1)?"":(diff+"天");
return result;
}
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch(ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
catch(InstantiationException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
catch(IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
catch(javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(LoveCalculator.class.getName())
.log(java.util.logging.Level.SEVERE,null,ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(
new Runnable()
{
public void run()
{
new LoveCalculator().setVisible(true);
}
}
);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton calculateButton;
private javax.swing.JTextField currentDateField;
private javax.swing.JLabel currentDateLabel;
private javax.swing.JTextField knowDateField;
private javax.swing.JLabel knowDateLabel;
private javax.swing.JTextField knowTimeField;
private javax.swing.JLabel knowTimeLabel;
private javax.swing.JTextField loveDateField;
private javax.swing.JLabel loveDateLabel;
private javax.swing.JTextField loveTimeField;
private javax.swing.JLabel loveTimeLabel;
private javax.swing.JTextField marryDateField;
private javax.swing.JLabel marryDateLabel;
private javax.swing.JTextField marryTimeField;
private javax.swing.JLabel marryTimeLabel;
// End of variables declaration//GEN-END:variables
}
|
ProteanBear/ProteanBear_Java
|
source/PbJExpress/test/pb/text/LoveCalculator.java
|
Java
|
apache-2.0
| 19,881 |
package com.uwetrottmann.shopr.context.algorithm;
import android.database.Cursor;
import android.util.Log;
import com.uwetrottmann.shopr.ShoprApp;
import com.uwetrottmann.shopr.algorithm.model.Item;
import com.uwetrottmann.shopr.context.model.Company;
import com.uwetrottmann.shopr.context.model.DayOfTheWeek;
import com.uwetrottmann.shopr.context.model.DistanceMetric;
import com.uwetrottmann.shopr.context.model.ItemSelectedContext;
import com.uwetrottmann.shopr.context.model.ScenarioContext;
import com.uwetrottmann.shopr.context.model.Temperature;
import com.uwetrottmann.shopr.context.model.TimeOfTheDay;
import com.uwetrottmann.shopr.context.model.Weather;
import com.uwetrottmann.shopr.provider.ShoprContract;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by yannick on 17.02.15.
*
* In this class the post-filtering of the recommended cases is done. We will retrieve several different
* items from the recommendation algorithm. Based on the current active context and the contexts in which these items
* were selected, there is going to be a re-ordered list of the top x items.
*/
public class ContextualPostFiltering {
/*
* This variable can be between 0 and 1.
* It states the distance of items, that were not selected in any context, to the currently
* active context. Meaning that if you set 0.5 here, all items that were not selected yet, are
* going to get a distance of 0.5 Therefore you can influence the exploration/exploitation parameter.
*/
private static final double DISTANCE_OF_NON_SELECTED_ITEMS = 0.6;
private static final double THRESHOLD_FREQUENTLY_USED_ITEMS = 0.3; // Items that are selected in more than this numbers times of cases
private static final double IMPROVEMENT_FREQUENTLY_USED_ITEMS = 0.2; // will get a bonus in distance of this
private static String[] sSelectionColumns = new String[]{ShoprContract.ContextItemRelation.REF_ITEM_ID, ShoprContract.ContextItemRelation.CONTEXT_TIME, ShoprContract.ContextItemRelation.CONTEXT_DAY, ShoprContract.ContextItemRelation.CONTEXT_TEMPERATURE, ShoprContract.ContextItemRelation.CONTEXT_HUMIDITY, ShoprContract.ContextItemRelation.CONTEXT_COMPANY};
/**
* This method shall postFilter the provided item set of the case base in order to return better recommendations.
* Therefore it takes a list of current preferred items by the algorithm and searches for contexts in which this item
* was selected. It then checks these contexts with the current context and compares them based on the context's distance metric.
*
* @param currentRecommendation the current recommendations as set by the algorithm
* @param numberOfRecommendations the number of recommendations that should be outputted
* @return an updated list with only the number of items that should be outputted.
*/
public static List<Item> postFilterItems(List<Item> currentRecommendation, int numberOfRecommendations){
List<Item> updatedRecommendation = new ArrayList<Item>();
//Updates the items, such that we can see in which contexts these items were selected
retrieveContextInformationForItems(currentRecommendation);
ScenarioContext scenarioContext = ScenarioContext.getInstance();
//Check that we have a scenario (real test)
if (scenarioContext.isSet()) {
int contexts = 0;
//For each item: Calculate the distances
for (Item item : currentRecommendation) {
//Get the context for the item
ItemSelectedContext itemContext = item.getItemContext();
Map<DistanceMetric, Integer> distanceMetrics = itemContext.getContextsForItem(); //Get the contexts for the item
int overallContextsSet = 0; // The number of context factors which are set for this item
double overallItemDistance = 0; // The overall distance after summation of all factors without dividing
for (DistanceMetric metric : distanceMetrics.keySet()) { //For each metric for the item
int times = distanceMetrics.get(metric);
overallContextsSet += times;
//Multiply the distance with its weight, as they should not have their full weight
overallItemDistance = overallItemDistance + getDistance(times, metric, scenarioContext) * metric.getWeight();
} // End for each metric within the contexts of a item
// Set the distance to the current context
// Items that were not selected in any context are the very far away and will first of all be attached to the end, afterwards they will get the median.
if (overallItemDistance != 0 || overallContextsSet != 0){
overallItemDistance = overallItemDistance / overallContextsSet;
}
item.setDistanceToContext(itemContext.normalizeDistance(overallItemDistance));
//The variable times selected states how often this item was (overall) selected. This is necessary,
// because we might want to improve the scores for products that are very frequently selected.
item.setTimesSelected(overallContextsSet / ItemSelectedContext.getNumberOfDifferentContextFactors());
contexts = contexts + item.getTimesSelected();
} // End for each item
adjustDistances(contexts, currentRecommendation);
//The maximum distance for a product is 1 and the minimum 0 (closest).
//We want the closest items to be at the top of the list (screen)
Collections.sort(currentRecommendation, new DistanceComparator());
} //End check for scenario
int i = 1;
for (Item item : currentRecommendation){
if (updatedRecommendation.size() < numberOfRecommendations) {
updatedRecommendation.add(item);
Log.d("Distance " + i++, "" + item.getDistanceToContext() + " " + item);
} else {
break;
}
}
return updatedRecommendation;
}
/**
* This method returns the distance of this scenario context compared to the context in which the
* item has been selected.
* @param timesSelected the times in which the item has been selected in this context
* @param metric the distance metric to check
* @param scenarioContext the current scenario context
* @return the distance of the metric to the scenario multiplied by the times it was selected
*/
private static double getDistance(int timesSelected, DistanceMetric metric, ScenarioContext scenarioContext){
double distance;
if (metric.isMetricWithEuclideanDistance()){
// The -1 makes sure that we can have 1 as a distance, as when min is 0 and max 5, the number of items is 6, but should be 5 for the maximum distance.
distance = getAdaptedEuclideanDistance(scenarioContext.getMetric(metric).currentOrdinal(), metric.currentOrdinal(), metric.numberOfItems() - 1.0);
distance = timesSelected * distance;
} else {
distance = timesSelected * metric.distanceToContext(scenarioContext);
}
return distance;
}
/**
* This method adjusts the distances for over-performing articles as well as for articles
* that do not sell at all.
* @param contexts the number of times an item was (successfully) recommended
* @param currentRecommendation the list of current recommendations.
*/
private static void adjustDistances(int contexts, List<Item> currentRecommendation){
if (contexts > 0) {
for (Item item : currentRecommendation) {
//Improve items that are very frequently selected
if ( (item.getTimesSelected() / contexts) > THRESHOLD_FREQUENTLY_USED_ITEMS) {
item.setDistanceToContext(item.getDistanceToContext() * (1 - IMPROVEMENT_FREQUENTLY_USED_ITEMS));
}
//Items that were never selected.
if (item.getTimesSelected() == 0){
item.setDistanceToContext(DISTANCE_OF_NON_SELECTED_ITEMS); // Set the distance for items that were not selected in any context
}
}
}
}
/**
* Updates the items and sets the context scenarios in which these items have been selected.
* @param currentRecommendation A list of items, that shall be part of the current recommendation cycle.
*/
private static void retrieveContextInformationForItems(List<Item> currentRecommendation){
for (Item item : currentRecommendation){
//Set a new context for the item(s)
ItemSelectedContext itemContext = new ItemSelectedContext();
item.setItemContext(itemContext);
//Query the database
String selectionString = ShoprContract.ContextItemRelation.REF_ITEM_ID + " = " + item.id();
Cursor query = ShoprApp.getContext().getContentResolver().query(ShoprContract.ContextItemRelation.CONTENT_URI,
sSelectionColumns, selectionString, null, null);
//Move the information from the database into the data structure
if (query != null){
while (query.moveToNext()){
itemContext.increaseDistanceMetric(TimeOfTheDay.getTimeOfTheDay(query.getInt(1)));
itemContext.increaseDistanceMetric(DayOfTheWeek.getDayOfTheWeek(query.getInt(2)));
itemContext.increaseDistanceMetric(Temperature.getTemperature(query.getInt(3)));
itemContext.increaseDistanceMetric(Weather.getWeather(query.getInt(4)));
itemContext.increaseDistanceMetric(Company.getCompany(query.getInt(5)));
}
query.close();
}
// Log.d("Item Context: ", ""+ itemContext);
}
}
/**
* This method returns the adapted euclidean distance as described in the HEOM
* @param p the value for the coordinate of the first object
* @param q the value for the coordinate of the second object
* @param range the difference between the highest and the lowest number in the range
* @return a double with the distance
*/
private static double getAdaptedEuclideanDistance(double p, double q, double range){
double result = ( p - q ) / range;
result = Math.pow(result, 2); // square it
return Math.sqrt(result);
}
}
|
Nicksteal/ShopR
|
Android/Shopr/src/main/java/com/uwetrottmann/shopr/context/algorithm/ContextualPostFiltering.java
|
Java
|
apache-2.0
| 10,688 |
/*
* Copyright (c) 2010, www.wojilu.com. All rights reserved.
*/
using System;
using System.Collections;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Apps.Content.Interface;
using wojilu.Apps.Content.Domain;
using wojilu.Common.Feeds.Service;
using wojilu.Common.Feeds.Domain;
using wojilu.Apps.Content.Service;
using wojilu.Web.Controller.Content.Utils;
namespace wojilu.Web.Controller.Content.Binder {
public class MyShareBinderController : ControllerBase, ISectionBinder {
public FeedService feedService { get; set; }
public IContentCustomTemplateService ctService { get; set; }
public MyShareBinderController() {
feedService = new FeedService();
ctService = new ContentCustomTemplateService();
}
public void Bind( ContentSection section, IList serviceData ) {
TemplateUtil.loadTemplate( this, section, ctService );
IBlock block = getBlock( "list" );
foreach (Share share in serviceData) {
String creatorInfo = string.Format( "<a href='{0}'>{1}</a>", Link.ToMember( share.Creator ), share.Creator.Name );
block.Set( "share.Title", feedService.GetHtmlValue( share.TitleTemplate, share.TitleData, creatorInfo ) );
block.Set( "share.Created", cvt.ToTimeString( share.Created ) );
block.Set( "share.DataTypeImg", strUtil.Join( sys.Path.Img, "/app/s/" + typeof( Share ).FullName + ".gif" ) );
block.Bind( "share", share );
block.Next();
}
}
}
}
|
songboriceboy/cnblogsbywojilu
|
wojilu.Controller/Content/Binder/MyShareBinderController.cs
|
C#
|
apache-2.0
| 1,649 |
/*
* Copyright (C) 2015 The Minium 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 minium.web.internal.drivers;
import static com.google.common.base.MoreObjects.toStringHelper;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
public class WindowWebDriver extends BaseDocumentWebDriver {
private static final Logger LOGGER = LoggerFactory.getLogger(WindowWebDriver.class);
private final String windowHandle;
public WindowWebDriver(WebDriver webDriver) {
this(webDriver, null);
}
public WindowWebDriver(WebDriver webDriver, String windowHandle) {
super(webDriver);
this.windowHandle = windowHandle == null ? webDriver.getWindowHandle() : windowHandle;
}
@Override
public void ensureSwitch() {
webDriver.switchTo().window(windowHandle);
LOGGER.trace("Switched to window {}", windowHandle);
}
@Override
public boolean isClosed() {
return !getWindowHandles().contains(windowHandle);
}
@Override
public String toString() {
return toStringHelper(WindowWebDriver.class.getSimpleName())
.addValue(windowHandle)
.toString();
}
@Override
public int hashCode() {
return Objects.hashCode(super.hashCode(), windowHandle);
}
@Override
public boolean equals(Object obj) {
return obj != null && obj.getClass() == WindowWebDriver.class && equalFields((WindowWebDriver) obj);
}
protected boolean equalFields(WindowWebDriver obj) {
return super.equalFields(obj) && Objects.equal(windowHandle, obj.windowHandle);
}
}
|
viltgroup/minium
|
minium-webelements/src/main/java/minium/web/internal/drivers/WindowWebDriver.java
|
Java
|
apache-2.0
| 2,217 |
package stroom.util.validation;
import stroom.util.shared.validation.IsSubsetOf;
import stroom.util.shared.validation.IsSubsetOfValidator;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintValidatorContext;
public class IsSubsetOfValidatorImpl implements IsSubsetOfValidator {
private Set<String> allowedValues;
@Override
public void initialize(IsSubsetOf constraintAnnotation) {
allowedValues = new HashSet<>(Arrays.asList(constraintAnnotation.allowedValues()));
}
/**
* Implements the validation logic.
* The state of {@code value} must not be altered.
* <p>
* This method can be accessed concurrently, thread-safety must be ensured
* by the implementation.
*
* @param values object to validate
* @param context context in which the constraint is evaluated
* @return {@code false} if {@code value} does not pass the constraint
*/
@Override
public boolean isValid(final Collection<String> values,
final ConstraintValidatorContext context) {
boolean result = true;
if (values != null && !values.isEmpty()) {
final Set<String> invalidValues = new HashSet<>(values);
invalidValues.removeAll(allowedValues);
if (!invalidValues.isEmpty()) {
// We want the exception details in the message so bin the default constraint
// violation and make a new one.
final String plural = invalidValues.size() > 1
? "s"
: "";
final String msg = "Set contains invalid value"
+ plural
+ " ["
+ String.join(",", invalidValues) + "]";
context.disableDefaultConstraintViolation();
context
.buildConstraintViolationWithTemplate(msg)
.addConstraintViolation();
result = false;
}
}
return result;
}
}
|
gchq/stroom
|
stroom-util/src/main/java/stroom/util/validation/IsSubsetOfValidatorImpl.java
|
Java
|
apache-2.0
| 2,147 |
/*
* Copyright 2016 VOPEN.CN
*
* 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 xyz.vopen.mysql.binlog.network.protocol.command;
import xyz.vopen.mysql.binlog.nio.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author <a href="mailto:cinc.jan@gmail.com">CiNC</a>
*/
public class DumpBinaryLogCommand implements Command {
private long serverId;
private String binlogFilename;
private long binlogPosition;
public DumpBinaryLogCommand (long serverId, String binlogFilename, long binlogPosition) {
this.serverId = serverId;
this.binlogFilename = binlogFilename;
this.binlogPosition = binlogPosition;
}
@SuppressWarnings("resource")
@Override
public byte[] toByteArray () throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
buffer.writeInteger(CommandType.BINLOG_DUMP.ordinal(), 1);
buffer.writeLong(this.binlogPosition, 4);
buffer.writeInteger(0, 2); // flag
buffer.writeLong(this.serverId, 4);
buffer.writeString(this.binlogFilename);
return buffer.toByteArray();
}
}
|
ivetech/binlog-mysql
|
src/main/java/xyz/vopen/mysql/binlog/network/protocol/command/DumpBinaryLogCommand.java
|
Java
|
apache-2.0
| 1,645 |
<?php
namespace SocioChat\DAO;
use Core\DAO\DAOBase;
use Core\Utils\DbQueryHelper;
use SocioChat\Clients\User;
class NameChangeDAO extends DAOBase
{
const USER_ID = 'user_id';
const OLD_NAME = 'old_name';
const DATE_CHANGE = 'date_change';
public function __construct()
{
parent::__construct(
[
self::USER_ID,
self::OLD_NAME,
self::DATE_CHANGE,
]
);
$this->dbTable = 'name_change_history';
}
public function getName()
{
return $this[self::OLD_NAME];
}
public function getDateRaw()
{
return $this[self::DATE_CHANGE];
}
public function getDate()
{
return strtotime($this[self::DATE_CHANGE]);
}
public function getUserId()
{
return strtotime($this[self::USER_ID]);
}
public function setUser(User $user)
{
$this[self::USER_ID] = $user->getId();
$this[self::OLD_NAME] = $user->getProperties()->getName();
$this[self::DATE_CHANGE] = DbQueryHelper::timestamp2date();
return $this;
}
/**
* @param User $user
* @return $this
*/
public function getLastByUser(User $user)
{
$list = $this->getListByQuery(
"SELECT * FROM {$this->dbTable} WHERE " . self::USER_ID . " = :user_id ORDER BY " . self::DATE_CHANGE . " DESC LIMIT 1",
['user_id' => $user->getId()]);
return !empty($list) ? $list[0] : null;
}
/**
* @param string $name
* @return $this
*/
public function getLastByName($name)
{
$list = $this->getListByQuery(
"SELECT * FROM {$this->dbTable} WHERE " . self::OLD_NAME . " = :oldname ORDER BY " . self::DATE_CHANGE . " ASC LIMIT 1",
['oldname' => $name]);
return !empty($list) ? $list[0] : null;
}
public function getHistoryByUserId($userId)
{
return $this->getListByQuery(
"SELECT * FROM {$this->dbTable} WHERE " . self::USER_ID . " = :user_id ORDER BY " . self::DATE_CHANGE . " DESC",
['user_id' => $userId]);
}
public function dropByUserId($id)
{
$this->db->exec("DELETE FROM {$this->dbTable} WHERE " . self::USER_ID . " = :0", [$id]);
}
protected function getForeignProperties()
{
return [];
}
}
|
kryoz/sociochat
|
src/SocioChat/DAO/NameChangeDAO.php
|
PHP
|
apache-2.0
| 2,379 |
/* Copyright© 2000 - 2022 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/
import mapboxgl from 'mapbox-gl';
import { ServiceBase } from './ServiceBase';
import '../core/Base';
import { ImageService as CommonMatchImageService } from '@supermap/iclient-common';
/**
* @class mapboxgl.supermap.ImageService
* @version 10.2.0
* @constructs mapboxgl.supermap.ImageService
* @classdesc 影像服务类
* @category iServer Image
* @example
* mapboxgl.supermap.ImageService(url,options)
* .getCollections(function(result){
* //doSomething
* })
* @param {string} url - 服务地址。例如: http://{ip}:{port}/iserver/{imageservice-imageserviceName}/restjsr/
* @param {Object} options - 参数。
* @param {string} [options.proxy] - 服务代理地址。
* @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。
* @param {boolean} [options.crossOrigin] - 是否允许跨域请求。
* @param {Object} [options.headers] - 请求头。
* @extends {mapboxgl.supermap.ServiceBase}
*/
export class ImageService extends ServiceBase {
constructor(url, options) {
super(url, options);
}
/**
* @function mapboxgl.supermap.ImageService.prototype.getCollections
* @description 返回当前影像服务中的影像集合列表(Collections)。
* @param {RequestCallback} callback - 请求结果的回调函数。
*/
getCollections(callback) {
var me = this;
var ImageService = new CommonMatchImageService(this.url, {
proxy: me.options.proxy,
withCredentials: me.options.withCredentials,
crossOrigin: me.options.crossOrigin,
headers: me.options.headers,
eventListeners: {
scope: me,
processCompleted: callback,
processFailed: callback
}
});
ImageService.getCollections();
}
/**
* @function mapboxgl.supermap.ImageService.prototype.getCollectionByID
* @description ID值等于`collectionId`参数值的影像集合(Collection)。 ID值用于在服务中唯一标识该影像集合。
* @param {string} collectionId 影像集合(Collection)的ID,在一个影像服务中唯一标识影像集合。
* @param {RequestCallback} callback - 请求结果的回调函数。
*/
getCollectionByID(collectionId, callback) {
var me = this;
var ImageService = new CommonMatchImageService(me.url, {
proxy: me.options.proxy,
withCredentials: me.options.withCredentials,
crossOrigin: me.options.crossOrigin,
headers: me.options.headers,
eventListeners: {
scope: me,
processCompleted: callback,
processFailed: callback
}
});
ImageService.getCollectionByID(collectionId);
}
/**
* @function mapboxgl.supermap.ImageService.prototype.search
* @description 查询与过滤条件匹配的影像数据。
* @param {SuperMap.ImageSearchParameter} [itemSearch] 查询参数
* @param {RequestCallback} callback - 请求结果的回调函数。
*/
search(itemSearch, callback) {
var me = this;
var ImageService = new CommonMatchImageService(me.url, {
proxy: me.options.proxy,
withCredentials: me.options.withCredentials,
crossOrigin: me.options.crossOrigin,
headers: me.options.headers,
eventListeners: {
scope: me,
processCompleted: callback,
processFailed: callback
}
});
ImageService.search(itemSearch);
}
}
mapboxgl.supermap.ImageService = ImageService;
|
SuperMap/iClient9
|
src/mapboxgl/services/ImageService.js
|
JavaScript
|
apache-2.0
| 3,968 |
'use strict';
/* Services that are used to interact with the backend. */
var eventManServices = angular.module('eventManServices', ['ngResource']);
/* Modify, in place, an object to convert datetime. */
function convert_dates(obj) {
angular.forEach(['begin_date', 'end_date', 'ticket_sales_begin_date', 'ticket_sales_end_date'], function(key, key_idx) {
if (!obj[key]) {
return;
}
obj[key] = obj[key].getTime();
});
return obj;
}
eventManServices.factory('Event', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('events/:id', {id: '@_id'}, {
all: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
angular.forEach(data.events || [], function(event_, event_idx) {
convert_dates(event_);
});
return data.events;
}
},
get: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
convert_dates(data);
// strip empty keys.
angular.forEach(data.tickets || [], function(ticket, ticket_idx) {
angular.forEach(ticket, function(value, key) {
if (value === "") {
delete ticket[key];
}
});
});
return data;
}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
convert_dates(data);
return data;
}
},
group_persons: {
method: 'GET',
url: 'events/:id/group_persons',
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
return data.persons || [];
}
}
});
}]
);
eventManServices.factory('EventTicket', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('events/:id/tickets', {event_id: '@event_id', ticket_id: '@_id'}, {
all: {
method: 'GET',
url: '/tickets',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
return data.tickets;
}
},
get: {
method: 'GET',
url: 'events/:id/tickets/:ticket_id',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.ticket;
}
},
add: {
method: 'POST',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
url: 'events/:event_id/tickets',
params: {uuid: $rootScope.app_uuid},
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.ticket;
}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
url: 'events/:event_id/tickets/:ticket_id',
params: {uuid: $rootScope.app_uuid},
transformResponse: function(data, headers) {
if (data.error) {
return data;
}
return angular.fromJson(data);
}
},
'delete': {
method: 'DELETE',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
url: 'events/:event_id/tickets/:ticket_id',
params: {uuid: $rootScope.app_uuid},
transformResponse: function(data, headers) {
return angular.fromJson(data);
}
}
});
}]
);
eventManServices.factory('Setting', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('settings/', {}, {
query: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.settings;
}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler}
}
});
}]
);
eventManServices.factory('Info', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('info/', {}, {
get: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.info || {};
}
}
});
}]
);
eventManServices.factory('EbAPI', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('ebapi/', {}, {
apiImport: {
method: 'POST',
interceptor: {responseError: $rootScope.errorHandler},
isArray: false,
transformResponse: function(data, headers) {
return angular.fromJson(data);
}
}
});
}]
);
eventManServices.factory('User', ['$resource', '$rootScope',
function($resource, $rootScope) {
return $resource('users/:id', {id: '@_id'}, {
all: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
isArray: true,
transformResponse: function(data, headers) {
data = angular.fromJson(data);
if (data.error) {
return data;
}
return data.users;
}
},
get: {
method: 'GET',
interceptor: {responseError: $rootScope.errorHandler},
transformResponse: function(data, headers) {
return angular.fromJson(data);
}
},
add: {
method: 'POST',
interceptor: {responseError: $rootScope.errorHandler}
},
update: {
method: 'PUT',
interceptor: {responseError: $rootScope.errorHandler}
},
login: {
method: 'POST',
url: '/login',
interceptor: {responseError: $rootScope.errorHandler}
},
logout: {
method: 'GET',
url: '/logout',
interceptor: {responseError: $rootScope.errorHandler}
}
});
}]
);
/* WebSocket collection used to update the list of tickets of an Event. */
eventManApp.factory('EventUpdates', ['$websocket', '$location', '$log', '$rootScope',
function($websocket, $location, $log, $rootScope) {
var dataStream = null;
var data = {};
var methods = {
data: data,
close: function() {
$log.debug('close WebSocket connection');
dataStream.close();
},
open: function() {
var proto = $location.protocol() == 'https' ? 'wss' : 'ws';
var url = proto + '://' + $location.host() + ':' + $location.port() +
'/ws/' + $location.path() + '/updates?uuid=' + $rootScope.app_uuid;
$log.debug('open WebSocket connection to ' + url);
//dataStream && dataStream.close();
dataStream = $websocket(url);
dataStream.onMessage(function(message) {
$log.debug('EventUpdates message received');
data.update = angular.fromJson(message.data);
});
}
};
return methods;
}]
);
|
raspibo/eventman
|
angular_app/js/services.js
|
JavaScript
|
apache-2.0
| 9,665 |
/**
* Copyright 2011-2017 Asakusa Framework 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 com.asakusafw.directio.hive.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.asakusafw.directio.hive.info.TableInfo;
/**
* Hive table annotation.
* @since 0.7.0
* @version 0.8.1
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HiveTable {
/**
* The table schema providers.
*/
Class<? extends TableInfo.Provider>[] value();
}
|
cocoatomo/asakusafw
|
hive-project/asakusa-hive-info/src/main/java/com/asakusafw/directio/hive/annotation/HiveTable.java
|
Java
|
apache-2.0
| 1,243 |
/*
Copyright (c) 2014 (Jonathan Q. Bo)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package bq.jpa.demo.lifecycle.domain;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.PostPersist;
import javax.persistence.PrePersist;
/**
* <b> </b>
*
* <p> </p>
*
* @author Jonathan Q. Bo (jonathan.q.bo@gmail.com)
*
* Created at Feb 10, 2014 9:18:29 PM
*
*/
@Entity(name="jpa_lifecycle_contract")
@DiscriminatorValue("contract")
@EntityListeners(ContractEmployeeListener.class)
public class ContractEmployee extends Employee{
private int dailyRate;
private int term;
@PrePersist
public void prePersit(){
System.out.println(ContractEmployee.class.getName() + " prePersist");
}
@PostPersist
public void postPersist(){
System.out.println(ContractEmployee.class.getName() + " postPersist");
}
public int getDailyRate() {
return dailyRate;
}
public void setDailyRate(int dailyRate) {
this.dailyRate = dailyRate;
}
public int getTerm() {
return term;
}
public void setTerm(int term) {
this.term = term;
}
}
|
jonathanqbo/jpa
|
src/main/java/bq/jpa/demo/lifecycle/domain/ContractEmployee.java
|
Java
|
apache-2.0
| 2,171 |
package godebug
import (
"regexp"
"strconv"
"strings"
)
func getFileDetails(stack string) (string, int) { // file name, line that called godebug.Break(), and a "preview line" to begin from
re, _ := regexp.Compile(`(?m)^(.*?)(:)(\d+)`)
res := re.FindAllStringSubmatch(stack, -1)
fn := strings.Trim(res[1][1], " \r\n\t")
breakLine, _ := strconv.Atoi(res[1][3])
return fn, breakLine
}
|
simon-whitehead/go-debug
|
utils.go
|
GO
|
apache-2.0
| 393 |
package org.zstack.header.network.service;
import org.zstack.header.vm.VmNicInventory;
/**
* Created by yaohua.wu on 8/14/2019.
*/
public interface VirtualRouterAfterDetachNicExtensionPoint {
void afterDetachNic(VmNicInventory nic);
}
|
AlanJager/zstack
|
header/src/main/java/org/zstack/header/network/service/VirtualRouterAfterDetachNicExtensionPoint.java
|
Java
|
apache-2.0
| 243 |
#
# Author:: Jake Vanderdray <jvanderdray@customink.com>
# Cookbook Name:: nagios
# Recipe:: pagerduty
#
# Copyright 2011, CustomInk 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
#
# 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 "libwww-perl" do
case node["platform"]
when "redhat", "centos", "scientific", "fedora", "suse", "amazon"
package_name "perl-libwww-perl"
when "debian","ubuntu"
package_name "libwww-perl"
when "arch"
package_name "libwww-perl"
end
action :install
end
package "libcrypt-ssleay-perl" do
case node["platform"]
when "redhat", "centos", "scientific", "fedora", "suse", "amazon"
package_name "perl-Crypt-SSLeay"
when "debian","ubuntu"
package_name "libcrypt-ssleay-perl"
when "arch"
package_name "libcrypt-ssleay-perl"
end
action :install
end
# need to support
# multi-region VPC and non VPC for our not fully VPC prod env
# multi-region VPC for private clouds (currently single region, but could become multi sometime)
api_key = ''
if node['instance_role'] == 'vagrant'
api_key = "test"
else
# we really only want to do this for prod
region = node['ec2']['region']
# if its private only, its VPC so tack that on
unless node['cloud']['public_ipv4'].nil?
region = "#{region}-nonvpc"
end
key_bag = data_bag_item('pager_duty', node['app_environment'])
api_key = key_bag['keys'][region]
end
template "/etc/nagios3/conf.d/pagerduty_nagios.cfg" do
owner "nagios"
group "nagios"
mode 0644
source "pagerduty_nagios.cfg.erb"
variables :api_key => api_key
end
remote_file "#{node['nagios']['plugin_dir']}/pagerduty_nagios.pl" do
owner "root"
group "root"
mode 0755
source "https://raw.github.com/PagerDuty/pagerduty-nagios-pl/master/pagerduty_nagios.pl"
action :create_if_missing
end
cron "Flush Pagerduty" do
user "nagios"
command "#{node['nagios']['plugin_dir']}/pagerduty_nagios.pl flush"
minute "*"
hour "*"
day "*"
month "*"
weekday "*"
action :create
end
|
Tealium/nagios
|
recipes/pagerduty.rb
|
Ruby
|
apache-2.0
| 2,473 |
/*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core.stubs;
import java.util.ArrayList;
import java.util.List;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.ClosedState;
import com.adaptris.core.ComponentState;
import com.adaptris.core.CoreException;
import com.adaptris.core.InitialisedState;
import com.adaptris.core.ProduceException;
import com.adaptris.core.ProduceOnlyProducerImp;
import com.adaptris.core.StartedState;
import com.adaptris.core.StateManagedComponent;
import com.adaptris.core.StoppedState;
import com.adaptris.interlok.util.Args;
/**
* <p>
* Mock implementation of <code>AdaptrisMessageProducer</code> for testing.
* Produces messages to a List which can be retrieved, thus allowing messages to
* be verified as split, etc., etc.
* </p>
*/
public class MockMessageProducer extends ProduceOnlyProducerImp implements
StateManagedComponent, MessageCounter {
private transient List<AdaptrisMessage> producedMessages;
private transient ComponentState state = ClosedState.getInstance();
public MockMessageProducer() {
producedMessages = new ArrayList<AdaptrisMessage>();
}
@Override
protected void doProduce(AdaptrisMessage msg, String endpoint) throws ProduceException {
Args.notNull(msg, "message");
producedMessages.add(msg);
}
@Override
public void prepare() throws CoreException {
}
/**
* <p>
* Returns the internal store of produced messages.
* </p>
*
* @return the internal store of produced messages
*/
@Override
public List<AdaptrisMessage> getMessages() {
return producedMessages;
}
@Override
public int messageCount() {
return producedMessages.size();
}
@Override
public void init() throws CoreException {
state = InitialisedState.getInstance();
}
@Override
public void start() throws CoreException {
state = StartedState.getInstance();
}
@Override
public void stop() {
state = StoppedState.getInstance();
}
@Override
public void close() {
state = ClosedState.getInstance();
}
@Override
public void changeState(ComponentState newState) {
state = newState;
}
@Override
public String getUniqueId() {
// TODO Auto-generated method stub
return null;
}
@Override
public void requestClose() {
state.requestClose(this);
}
@Override
public void requestInit() throws CoreException {
state.requestInit(this);
}
@Override
public void requestStart() throws CoreException {
state.requestStart(this);
}
@Override
public void requestStop() {
state.requestStop(this);
}
@Override
public ComponentState retrieveComponentState() {
return state;
}
@Override
public String endpoint(AdaptrisMessage msg) throws ProduceException {
return null;
}
}
|
adaptris/interlok
|
interlok-core/src/test/java/com/adaptris/core/stubs/MockMessageProducer.java
|
Java
|
apache-2.0
| 3,368 |
package crawler;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws SQLException, IOException, PropertyVetoException, InterruptedException
{
DatabaseManager MyDB=new DatabaseManager();//Create DB Object
Scanner sc =new Scanner(System.in);
BufferedReader consolereader = new BufferedReader (new InputStreamReader(System.in));
int X;
String InputRURL="";//RURL stands for restricted URL
do{//First Option List
//to store the user choice
System.out.println("Enter:\n1. to Add Restircted URLS \n2. to Start Crawling/Indexing \n3. to Reset Data \n4. to Exit \n>>");
X=sc.nextInt();
//Add Restricted URLs
if(X==1)
{
System.out.println("Enter a URL to Restrict:");
InputRURL=consolereader.readLine();
if(!MyDB.CheckRURL(InputRURL))//to make sure that that URL has not been added to the restricted URLs already
{
MyDB.AddRURL(InputRURL);
}
else
{
System.out.println("URL is Already Restricted");
}
}
//Reset data
else if(X==3)
{//Confirmation Check
System.out.println("Are You Sure You Want To Reset All Data (Enter 'reset' to confirm):");
if(consolereader.readLine().equals("reset"))
{
int MaxDownloadedID =MyDB.GetMaxDownloadedID();
try{
for(int i=1;i<=MaxDownloadedID;i++)
{
File file = new File(i+".html");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}
}catch(Exception e){
e.printStackTrace();
}
MyDB.ResetDB();
System.out.println("Data Reseted");
}
else
{
System.out.println("Reset Aborted");
}
}
else if (X==4)
{
return;
}
}while(X!=2);
//Start crawling/indexing
System.out.println("Enter the Number of Crawler Threads (20 Max): ");
int ThreadNumber=sc.nextInt();
MyDB.AddSeeds();
//Run Crawlers
Thread[] CThreadArray=new Thread[ThreadNumber];
Thread[] IThreadArray=new Thread[20];
for(int i =0;i<ThreadNumber;i++)
{//Start Crawler Threads And Name Them
CThreadArray[i] = new Crawler(MyDB);
CThreadArray[i].setName ("Crawler "+ i);
}
for(int i=0;i<20;i++)
{
IThreadArray[i] =new Indexer(MyDB);
IThreadArray[i].setName("Indexer"+ i);
}
//System.out.println("Enter the 1 to Recrawl, 2 to Stop the Crawler \n>>");
for(int i =0;i<ThreadNumber;i++)
{//Start Crawler Threads And Name Them
CThreadArray[i].start();
}
for(int i=0;i<20;i++)
{
IThreadArray[i].start();
}
//Start Indexer Thread
do{//Second Option List (Available After Running The Crawlers)
System.out.println("Enter the 1 to Recrawl, 2 to Stop the Crawler \n>>");
X=sc.nextInt();
if(X==1)
{
MyDB.Recrawl();
System.out.println("Recrawling Successful");
}
else if (X==2)
{//Interrupt All Threads
System.out.println("Terminating Threads...Please Wait");
for(int i =0;i<ThreadNumber;i++)
{
CThreadArray[i].interrupt();
}
for(int i=0;i<20;i++)
{
IThreadArray[i].interrupt();
}
for(int i =0;i<ThreadNumber;i++)
{
CThreadArray[i].join();
}
for(int i=0;i<20;i++)
{
IThreadArray[i].join();
}
}
}while(X!=2);
System.out.println("Main Thread Terminated..");
}
// public static void main(String[] args) throws SQLException, IOException, PropertyVetoException, InterruptedException
// {
// DatabaseManager MyDB=new DatabaseManager();//Create DB Object
// Ranker R=new Ranker(MyDB,1);
// String W="gggfgfgfyfyfuhjhi game";
// ArrayList<URStruct> List=R.GetURLRankings(W);
//
// for(int i=0;i<List.size();i++)
// {
// System.out.println("URL: "+List.get(i).URL+" IF: "+List.get(i).IR);
// }
// }
// public static void main(String[] args) throws SQLException, IOException, PropertyVetoException, InterruptedException
// {
// DatabaseManager MyDB=new DatabaseManager();
// Scanner sc =new Scanner(System.in);
// BufferedReader consolereader = new BufferedReader (new InputStreamReader(System.in));
//
// String Word=consolereader.readLine();
// QueryProcessor QP = new QueryProcessor(Word,MyDB,1);
// ArrayList<ResultStruct> PTemp=new ArrayList<ResultStruct>();
// PTemp=QP.ProcessQuery(Word);
// if(PTemp==null)
// {
// System.out.println("Phrase Not Found");
// return;
// }
// for(int i=0;i<PTemp.size();i++)
// {
// System.out.println(PTemp.get(i).UID+" "+PTemp.get(i).URL+" "+PTemp.get(i).Rating);
// }
////System.out.println(QP.Stem("Footballers"));
// }
}
|
MAnbar/SearchEngine
|
Crawler/src/crawler/Main.java
|
Java
|
apache-2.0
| 5,900 |
"use strict";
var samples = {};
module.exports = samples;
samples.valid_0 = {
"address": "xde@sjdu.com",
"type": "work place"
};
samples.valid_1 = {
"address": "xde@sjdu.com"
};
samples.invalid_0 = {};
samples.invalid_1 = {
"address": "xde@sjdu.com",
"type": "work place",
"other": "na"
};
|
amida-tech/blue-button-model
|
test/samples/unit/cda_email.js
|
JavaScript
|
apache-2.0
| 320 |
#if WINDOWS_UWP
namespace io.nodekit.NKScripting.Engines.Chakra
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
/// <summary>
/// Native interfaces.
/// </summary>
public static class Native
{
/// <summary>
/// Throws if a native method returns an error code.
/// </summary>
/// <param name="error">The error.</param>
internal static void ThrowIfError(JavaScriptErrorCode error)
{
if (error != JavaScriptErrorCode.NoError)
{
switch (error)
{
case JavaScriptErrorCode.InvalidArgument:
throw new JavaScriptUsageException(error, "Invalid argument.");
case JavaScriptErrorCode.NullArgument:
throw new JavaScriptUsageException(error, "Null argument.");
case JavaScriptErrorCode.NoCurrentContext:
throw new JavaScriptUsageException(error, "No current context.");
case JavaScriptErrorCode.InExceptionState:
throw new JavaScriptUsageException(error, "Runtime is in exception state.");
case JavaScriptErrorCode.NotImplemented:
throw new JavaScriptUsageException(error, "Method is not implemented.");
case JavaScriptErrorCode.WrongThread:
throw new JavaScriptUsageException(error, "Runtime is active on another thread.");
case JavaScriptErrorCode.RuntimeInUse:
throw new JavaScriptUsageException(error, "Runtime is in use.");
case JavaScriptErrorCode.BadSerializedScript:
throw new JavaScriptUsageException(error, "Bad serialized script.");
case JavaScriptErrorCode.InDisabledState:
throw new JavaScriptUsageException(error, "Runtime is disabled.");
case JavaScriptErrorCode.CannotDisableExecution:
throw new JavaScriptUsageException(error, "Cannot disable execution.");
case JavaScriptErrorCode.AlreadyDebuggingContext:
throw new JavaScriptUsageException(error, "Context is already in debug mode.");
case JavaScriptErrorCode.HeapEnumInProgress:
throw new JavaScriptUsageException(error, "Heap enumeration is in progress.");
case JavaScriptErrorCode.ArgumentNotObject:
throw new JavaScriptUsageException(error, "Argument is not an object.");
case JavaScriptErrorCode.InProfileCallback:
throw new JavaScriptUsageException(error, "In a profile callback.");
case JavaScriptErrorCode.InThreadServiceCallback:
throw new JavaScriptUsageException(error, "In a thread service callback.");
case JavaScriptErrorCode.CannotSerializeDebugScript:
throw new JavaScriptUsageException(error, "Cannot serialize a debug script.");
case JavaScriptErrorCode.AlreadyProfilingContext:
throw new JavaScriptUsageException(error, "Already profiling this context.");
case JavaScriptErrorCode.IdleNotEnabled:
throw new JavaScriptUsageException(error, "Idle is not enabled.");
case JavaScriptErrorCode.OutOfMemory:
throw new JavaScriptEngineException(error, "Out of memory.");
case JavaScriptErrorCode.ScriptException:
{
JavaScriptValue errorObject;
JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);
if (innerError != JavaScriptErrorCode.NoError)
{
throw new JavaScriptFatalException(innerError);
}
throw new JavaScriptScriptException(error, errorObject, "Script threw an exception.");
}
case JavaScriptErrorCode.ScriptCompile:
{
JavaScriptValue errorObject;
JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);
if (innerError != JavaScriptErrorCode.NoError)
{
throw new JavaScriptFatalException(innerError);
}
throw new JavaScriptScriptException(error, errorObject, "Compile error.");
}
case JavaScriptErrorCode.ScriptTerminated:
throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Script was terminated.");
case JavaScriptErrorCode.ScriptEvalDisabled:
throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Eval of strings is disabled in this runtime.");
case JavaScriptErrorCode.Fatal:
throw new JavaScriptFatalException(error);
default:
throw new JavaScriptFatalException(error);
}
}
}
const string DllName = "Chakra.dll";
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateRuntime(JavaScriptRuntimeAttributes attributes, JavaScriptThreadServiceCallback threadService, out JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCollectGarbage(JavaScriptRuntime handle);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDisposeRuntime(JavaScriptRuntime handle);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetRuntimeMemoryUsage(JavaScriptRuntime runtime, out UIntPtr memoryUsage);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetRuntimeMemoryLimit(JavaScriptRuntime runtime, out UIntPtr memoryLimit);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetRuntimeMemoryLimit(JavaScriptRuntime runtime, UIntPtr memoryLimit);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetRuntimeMemoryAllocationCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptMemoryAllocationCallback allocationCallback);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetRuntimeBeforeCollectCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptBeforeCollectCallback beforeCollectCallback);
[DllImport(DllName, EntryPoint = "JsAddRef")]
internal static extern JavaScriptErrorCode JsContextAddRef(JavaScriptContext reference, out uint count);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsAddRef(JavaScriptValue reference, out uint count);
[DllImport(DllName, EntryPoint = "JsRelease")]
internal static extern JavaScriptErrorCode JsContextRelease(JavaScriptContext reference, out uint count);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsRelease(JavaScriptValue reference, out uint count);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateContext(JavaScriptRuntime runtime, out JavaScriptContext newContext);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetCurrentContext(out JavaScriptContext currentContext);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetCurrentContext(JavaScriptContext context);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetRuntime(JavaScriptContext context, out JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsStartDebugging();
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsIdle(out uint nextIdleTick);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsParseScript(string script, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsRunScript(string script, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsSerializeScript(string script, byte[] buffer, ref ulong bufferSize);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsParseSerializedScript(string script, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsRunSerializedScript(string script, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsGetPropertyIdFromName(string name, out JavaScriptPropertyId propertyId);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsGetPropertyNameFromId(JavaScriptPropertyId propertyId, out string name);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetUndefinedValue(out JavaScriptValue undefinedValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetNullValue(out JavaScriptValue nullValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetTrueValue(out JavaScriptValue trueValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetFalseValue(out JavaScriptValue falseValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsBoolToBoolean(bool value, out JavaScriptValue booleanValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsBooleanToBool(JavaScriptValue booleanValue, out bool boolValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToBoolean(JavaScriptValue value, out JavaScriptValue booleanValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetValueType(JavaScriptValue value, out JavaScriptValueType type);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDoubleToNumber(double doubleValue, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsIntToNumber(int intValue, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsNumberToDouble(JavaScriptValue value, out double doubleValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToNumber(JavaScriptValue value, out JavaScriptValue numberValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetStringLength(JavaScriptValue sringValue, out int length);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsPointerToString(string value, UIntPtr stringLength, out JavaScriptValue stringValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsStringToPointer(JavaScriptValue value, out IntPtr stringValue, out UIntPtr stringLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToString(JavaScriptValue value, out JavaScriptValue stringValue);
[DllImport(DllName)]
#pragma warning disable CS0618 // Type or member is obsolete
internal static extern JavaScriptErrorCode JsVariantToValue([MarshalAs(UnmanagedType.Struct)] ref object var, out JavaScriptValue value);
#pragma warning restore CS0618 // Type or member is obsolete
[DllImport(DllName)]
#pragma warning disable CS0618 // Type or member is obsolete
internal static extern JavaScriptErrorCode JsValueToVariant(JavaScriptValue obj, [MarshalAs(UnmanagedType.Struct)] out object var);
#pragma warning restore CS0618 // Type or member is obsolete
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetGlobalObject(out JavaScriptValue globalObject);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateObject(out JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateExternalObject(IntPtr data, JavaScriptObjectFinalizeCallback finalizeCallback, out JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToObject(JavaScriptValue value, out JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetPrototype(JavaScriptValue obj, out JavaScriptValue prototypeObject);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetPrototype(JavaScriptValue obj, JavaScriptValue prototypeObject);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetExtensionAllowed(JavaScriptValue obj, out bool value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsPreventExtension(JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetOwnPropertyDescriptor(JavaScriptValue obj, JavaScriptPropertyId propertyId, out JavaScriptValue propertyDescriptor);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetOwnPropertyNames(JavaScriptValue obj, out JavaScriptValue propertyNames);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, JavaScriptValue value, bool useStrictRules);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, out bool hasProperty);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDeleteProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, bool useStrictRules, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDefineProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, JavaScriptValue propertyDescriptor, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasIndexedProperty(JavaScriptValue obj, JavaScriptValue index, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetIndexedProperty(JavaScriptValue obj, JavaScriptValue index, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetIndexedProperty(JavaScriptValue obj, JavaScriptValue index, JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDeleteIndexedProperty(JavaScriptValue obj, JavaScriptValue index);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsEquals(JavaScriptValue obj1, JavaScriptValue obj2, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsStrictEquals(JavaScriptValue obj1, JavaScriptValue obj2, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasExternalData(JavaScriptValue obj, out bool value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetExternalData(JavaScriptValue obj, out IntPtr externalData);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetExternalData(JavaScriptValue obj, IntPtr externalData);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateArray(uint length, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCallFunction(JavaScriptValue function, JavaScriptValue[] arguments, ushort argumentCount, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConstructObject(JavaScriptValue function, JavaScriptValue[] arguments, ushort argumentCount, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateFunction(JavaScriptNativeFunction nativeFunction, IntPtr externalData, out JavaScriptValue function);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateRangeError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateReferenceError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateSyntaxError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateTypeError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateURIError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasException(out bool hasException);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetAndClearException(out JavaScriptValue exception);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetException(JavaScriptValue exception);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDisableRuntimeExecution(JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsEnableRuntimeExecution(JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsIsRuntimeExecutionDisabled(JavaScriptRuntime runtime, out bool isDisabled);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetObjectBeforeCollectCallback(JavaScriptValue reference, IntPtr callbackState, JavaScriptObjectBeforeCollectCallback beforeCollectCallback);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateNamedFunction(JavaScriptValue name, JavaScriptNativeFunction nativeFunction, IntPtr callbackState, out JavaScriptValue function);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsProjectWinRTNamespace(string namespaceName);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsInspectableToObject([MarshalAs(UnmanagedType.IInspectable)] System.Object inspectable, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetProjectionEnqueueCallback(JavaScriptProjectionEnqueueCallback projectionEnqueueCallback, IntPtr context);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetPromiseContinuationCallback(JavaScriptPromiseContinuationCallback promiseContinuationCallback, IntPtr callbackState);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateArrayBuffer(uint byteLength, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateTypedArray(JavaScriptTypedArrayType arrayType, JavaScriptValue arrayBuffer, uint byteOffset,
uint elementLength, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateDataView(JavaScriptValue arrayBuffer, uint byteOffset, uint byteOffsetLength, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetArrayBufferStorage(JavaScriptValue arrayBuffer, out byte[] buffer, out uint bufferLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetTypedArrayStorage(JavaScriptValue typedArray, out byte[] buffer, out uint bufferLength, out JavaScriptTypedArrayType arrayType, out int elementSize);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetDataViewStorage(JavaScriptValue dataView, out byte[] buffer, out uint bufferLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetPropertyIdType(JavaScriptPropertyId propertyId, out JavaSciptPropertyIdType propertyIdType);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateSymbol(JavaScriptValue description, out JavaScriptValue symbol);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetSymbolFromPropertyId(JavaScriptPropertyId propertyId, out JavaScriptValue symbol);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetPropertyIdFromSymbol(JavaScriptValue symbol, out JavaScriptPropertyId propertyId);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetOwnPropertySymbols(JavaScriptValue obj, out JavaScriptValue propertySymbols);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsNumberToInt(JavaScriptValue value, out int intValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetIndexedPropertiesToExternalData(JavaScriptValue obj, IntPtr data, JavaScriptTypedArrayType arrayType, uint elementLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetIndexedPropertiesExternalData(JavaScriptValue obj, IntPtr data, out JavaScriptTypedArrayType arrayType, out uint elementLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasIndexedPropertiesExternalData(JavaScriptValue obj, out bool value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsInstanceOf(JavaScriptValue obj, JavaScriptValue constructor, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateExternalArrayBuffer(IntPtr data, uint byteLength, JavaScriptObjectFinalizeCallback finalizeCallback, IntPtr callbackState, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetTypedArrayInfo(JavaScriptValue typedArray, out JavaScriptTypedArrayType arrayType, out JavaScriptValue arrayBuffer, out uint byteOffset, out uint byteLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetContextOfObject(JavaScriptValue obj, out JavaScriptContext context);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetContextData(JavaScriptContext context, out IntPtr data);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetContextData(JavaScriptContext context, IntPtr data);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsParseSerializedScriptWithCallback(JavaScriptSerializedScriptLoadSourceCallback scriptLoadCallback,
JavaScriptSerializedScriptUnloadCallback scriptUnloadCallback, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsRunSerializedScriptWithCallback(JavaScriptSerializedScriptLoadSourceCallback scriptLoadCallback,
JavaScriptSerializedScriptUnloadCallback scriptUnloadCallback, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
}
}
#endif
|
nodekit-io/nodekit-windows
|
src/nodekit/NKScripting/common/engines/chakra/Engine/Native_uwp.cs
|
C#
|
apache-2.0
| 24,924 |
package me.vilsol.nmswrapper.wraps.unparsed;
import me.vilsol.nmswrapper.NMSWrapper;
import me.vilsol.nmswrapper.reflections.ReflectiveClass;
import me.vilsol.nmswrapper.reflections.ReflectiveMethod;
import me.vilsol.nmswrapper.wraps.NMSWrap;
import org.bukkit.command.CommandSender;
@ReflectiveClass(name = "CommandBlockListenerAbstract")
public class NMSCommandBlockListenerAbstract extends NMSWrap implements NMSICommandListener {
public NMSCommandBlockListenerAbstract(Object nmsObject){
super(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#a(net.minecraft.server.v1_9_R1.EntityHuman)
*/
@ReflectiveMethod(name = "a", types = {NMSEntityHuman.class})
public boolean a(NMSEntityHuman entityHuman){
return (boolean) NMSWrapper.getInstance().exec(nmsObject, entityHuman);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#b(net.minecraft.server.v1_9_R1.IChatBaseComponent)
*/
@ReflectiveMethod(name = "b", types = {NMSIChatBaseComponent.class})
public void b(NMSIChatBaseComponent iChatBaseComponent){
NMSWrapper.getInstance().exec(nmsObject, iChatBaseComponent);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#executeCommand(net.minecraft.server.v1_9_R1.ICommandListener, org.bukkit.command.CommandSender, java.lang.String)
*/
@ReflectiveMethod(name = "executeCommand", types = {NMSICommandListener.class, CommandSender.class, String.class})
public int executeCommand(NMSICommandListener iCommandListener, CommandSender commandSender, String s){
return (int) NMSWrapper.getInstance().exec(nmsObject, iCommandListener, commandSender, s);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getCommand()
*/
@ReflectiveMethod(name = "getCommand", types = {})
public String getCommand(){
return (String) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getName()
*/
@ReflectiveMethod(name = "getName", types = {})
public String getName(){
return (String) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getScoreboardDisplayName()
*/
@ReflectiveMethod(name = "getScoreboardDisplayName", types = {})
public NMSIChatBaseComponent getScoreboardDisplayName(){
return (NMSIChatBaseComponent) NMSWrapper.getInstance().createApplicableObject(NMSWrapper.getInstance().exec(nmsObject));
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getSendCommandFeedback()
*/
@ReflectiveMethod(name = "getSendCommandFeedback", types = {})
public boolean getSendCommandFeedback(){
return (boolean) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#h()
*/
@ReflectiveMethod(name = "h", types = {})
public void h(){
NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#j()
*/
@ReflectiveMethod(name = "j", types = {})
public int j(){
return (int) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#k()
*/
@ReflectiveMethod(name = "k", types = {})
public NMSIChatBaseComponent k(){
return (NMSIChatBaseComponent) NMSWrapper.getInstance().createApplicableObject(NMSWrapper.getInstance().exec(nmsObject));
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#m()
*/
@ReflectiveMethod(name = "m", types = {})
public boolean m(){
return (boolean) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#n()
*/
@ReflectiveMethod(name = "n", types = {})
public NMSCommandObjectiveExecutor n(){
return new NMSCommandObjectiveExecutor(NMSWrapper.getInstance().exec(nmsObject));
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#sendMessage(net.minecraft.server.v1_9_R1.IChatBaseComponent)
*/
@ReflectiveMethod(name = "sendMessage", types = {NMSIChatBaseComponent.class})
public void sendMessage(NMSIChatBaseComponent iChatBaseComponent){
NMSWrapper.getInstance().exec(nmsObject, iChatBaseComponent);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#setCommand(java.lang.String)
*/
@ReflectiveMethod(name = "setCommand", types = {String.class})
public void setCommand(String s){
NMSWrapper.getInstance().exec(nmsObject, s);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#setName(java.lang.String)
*/
@ReflectiveMethod(name = "setName", types = {String.class})
public void setName(String s){
NMSWrapper.getInstance().exec(nmsObject, s);
}
}
|
Vilsol/NMSWrapper
|
src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSCommandBlockListenerAbstract.java
|
Java
|
apache-2.0
| 5,334 |
/*
* 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.phoenix.compile;
import java.sql.ParameterMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.cache.ServerCacheClient.ServerCache;
import org.apache.phoenix.compile.GroupByCompiler.GroupBy;
import org.apache.phoenix.compile.OrderByCompiler.OrderBy;
import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
import org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.execute.AggregatePlan;
import org.apache.phoenix.execute.BaseQueryPlan;
import org.apache.phoenix.execute.MutationState;
import org.apache.phoenix.filter.SkipScanFilter;
import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.index.IndexMetaDataCacheClient;
import org.apache.phoenix.index.PhoenixIndexCodec;
import org.apache.phoenix.iterate.ResultIterator;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixResultSet;
import org.apache.phoenix.jdbc.PhoenixStatement;
import org.apache.phoenix.optimize.QueryOptimizer;
import org.apache.phoenix.parse.AliasedNode;
import org.apache.phoenix.parse.DeleteStatement;
import org.apache.phoenix.parse.HintNode;
import org.apache.phoenix.parse.HintNode.Hint;
import org.apache.phoenix.parse.NamedTableNode;
import org.apache.phoenix.parse.ParseNode;
import org.apache.phoenix.parse.ParseNodeFactory;
import org.apache.phoenix.parse.SelectStatement;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.KeyRange;
import org.apache.phoenix.query.QueryConstants;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.MetaDataClient;
import org.apache.phoenix.schema.MetaDataEntityNotFoundException;
import org.apache.phoenix.schema.PColumn;
import org.apache.phoenix.schema.PIndexState;
import org.apache.phoenix.schema.PName;
import org.apache.phoenix.schema.PRow;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.PTableKey;
import org.apache.phoenix.schema.PTableType;
import org.apache.phoenix.schema.ReadOnlyTableException;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.TableRef;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.util.MetaDataUtil;
import org.apache.phoenix.util.ScanUtil;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.sun.istack.NotNull;
public class DeleteCompiler {
private static ParseNodeFactory FACTORY = new ParseNodeFactory();
private final PhoenixStatement statement;
public DeleteCompiler(PhoenixStatement statement) {
this.statement = statement;
}
private static MutationState deleteRows(PhoenixStatement statement, TableRef targetTableRef, TableRef indexTableRef, ResultIterator iterator, RowProjector projector, TableRef sourceTableRef) throws SQLException {
PTable table = targetTableRef.getTable();
PhoenixConnection connection = statement.getConnection();
PName tenantId = connection.getTenantId();
byte[] tenantIdBytes = null;
if (tenantId != null) {
tenantId = ScanUtil.padTenantIdIfNecessary(table.getRowKeySchema(), table.getBucketNum() != null, tenantId);
tenantIdBytes = tenantId.getBytes();
}
final boolean isAutoCommit = connection.getAutoCommit();
ConnectionQueryServices services = connection.getQueryServices();
final int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
final int batchSize = Math.min(connection.getMutateBatchSize(), maxSize);
Map<ImmutableBytesPtr,Map<PColumn,byte[]>> mutations = Maps.newHashMapWithExpectedSize(batchSize);
Map<ImmutableBytesPtr,Map<PColumn,byte[]>> indexMutations = null;
// If indexTableRef is set, we're deleting the rows from both the index table and
// the data table through a single query to save executing an additional one.
if (indexTableRef != null) {
indexMutations = Maps.newHashMapWithExpectedSize(batchSize);
}
try {
List<PColumn> pkColumns = table.getPKColumns();
boolean isMultiTenant = table.isMultiTenant() && tenantIdBytes != null;
boolean isSharedViewIndex = table.getViewIndexId() != null;
int offset = (table.getBucketNum() == null ? 0 : 1);
byte[][] values = new byte[pkColumns.size()][];
if (isMultiTenant) {
values[offset++] = tenantIdBytes;
}
if (isSharedViewIndex) {
values[offset++] = MetaDataUtil.getViewIndexIdDataType().toBytes(table.getViewIndexId());
}
PhoenixResultSet rs = new PhoenixResultSet(iterator, projector, statement);
int rowCount = 0;
while (rs.next()) {
ImmutableBytesPtr ptr = new ImmutableBytesPtr(); // allocate new as this is a key in a Map
// Use tuple directly, as projector would not have all the PK columns from
// our index table inside of our projection. Since the tables are equal,
// there's no transation required.
if (sourceTableRef.equals(targetTableRef)) {
rs.getCurrentRow().getKey(ptr);
} else {
for (int i = offset; i < values.length; i++) {
byte[] byteValue = rs.getBytes(i+1-offset);
// The ResultSet.getBytes() call will have inverted it - we need to invert it back.
// TODO: consider going under the hood and just getting the bytes
if (pkColumns.get(i).getSortOrder() == SortOrder.DESC) {
byte[] tempByteValue = Arrays.copyOf(byteValue, byteValue.length);
byteValue = SortOrder.invert(byteValue, 0, tempByteValue, 0, byteValue.length);
}
values[i] = byteValue;
}
table.newKey(ptr, values);
}
mutations.put(ptr, PRow.DELETE_MARKER);
if (indexTableRef != null) {
ImmutableBytesPtr indexPtr = new ImmutableBytesPtr(); // allocate new as this is a key in a Map
rs.getCurrentRow().getKey(indexPtr);
indexMutations.put(indexPtr, PRow.DELETE_MARKER);
}
if (mutations.size() > maxSize) {
throw new IllegalArgumentException("MutationState size of " + mutations.size() + " is bigger than max allowed size of " + maxSize);
}
rowCount++;
// Commit a batch if auto commit is true and we're at our batch size
if (isAutoCommit && rowCount % batchSize == 0) {
MutationState state = new MutationState(targetTableRef, mutations, 0, maxSize, connection);
connection.getMutationState().join(state);
if (indexTableRef != null) {
MutationState indexState = new MutationState(indexTableRef, indexMutations, 0, maxSize, connection);
connection.getMutationState().join(indexState);
}
connection.commit();
mutations.clear();
if (indexMutations != null) {
indexMutations.clear();
}
}
}
// If auto commit is true, this last batch will be committed upon return
int nCommittedRows = rowCount / batchSize * batchSize;
MutationState state = new MutationState(targetTableRef, mutations, nCommittedRows, maxSize, connection);
if (indexTableRef != null) {
// To prevent the counting of these index rows, we have a negative for remainingRows.
MutationState indexState = new MutationState(indexTableRef, indexMutations, 0, maxSize, connection);
state.join(indexState);
}
return state;
} finally {
iterator.close();
}
}
private static class DeletingParallelIteratorFactory extends MutatingParallelIteratorFactory {
private RowProjector projector;
private TableRef targetTableRef;
private TableRef indexTableRef;
private TableRef sourceTableRef;
private DeletingParallelIteratorFactory(PhoenixConnection connection) {
super(connection);
}
@Override
protected MutationState mutate(StatementContext context, ResultIterator iterator, PhoenixConnection connection) throws SQLException {
PhoenixStatement statement = new PhoenixStatement(connection);
return deleteRows(statement, targetTableRef, indexTableRef, iterator, projector, sourceTableRef);
}
public void setTargetTableRef(TableRef tableRef) {
this.targetTableRef = tableRef;
}
public void setSourceTableRef(TableRef tableRef) {
this.sourceTableRef = tableRef;
}
public void setRowProjector(RowProjector projector) {
this.projector = projector;
}
public void setIndexTargetTableRef(TableRef indexTableRef) {
this.indexTableRef = indexTableRef;
}
}
private Set<PTable> getNonDisabledImmutableIndexes(TableRef tableRef) {
PTable table = tableRef.getTable();
if (table.isImmutableRows() && !table.getIndexes().isEmpty()) {
Set<PTable> nonDisabledIndexes = Sets.newHashSetWithExpectedSize(table.getIndexes().size());
for (PTable index : table.getIndexes()) {
if (index.getIndexState() != PIndexState.DISABLE) {
nonDisabledIndexes.add(index);
}
}
return nonDisabledIndexes;
}
return Collections.emptySet();
}
private class MultiDeleteMutationPlan implements MutationPlan {
private final List<MutationPlan> plans;
private final MutationPlan firstPlan;
public MultiDeleteMutationPlan(@NotNull List<MutationPlan> plans) {
Preconditions.checkArgument(!plans.isEmpty());
this.plans = plans;
this.firstPlan = plans.get(0);
}
@Override
public StatementContext getContext() {
return firstPlan.getContext();
}
@Override
public ParameterMetaData getParameterMetaData() {
return firstPlan.getParameterMetaData();
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
return firstPlan.getExplainPlan();
}
@Override
public PhoenixConnection getConnection() {
return firstPlan.getConnection();
}
@Override
public MutationState execute() throws SQLException {
MutationState state = firstPlan.execute();
for (MutationPlan plan : plans.subList(1, plans.size())) {
plan.execute();
}
return state;
}
}
public MutationPlan compile(DeleteStatement delete) throws SQLException {
final PhoenixConnection connection = statement.getConnection();
final boolean isAutoCommit = connection.getAutoCommit();
final boolean hasLimit = delete.getLimit() != null;
final ConnectionQueryServices services = connection.getQueryServices();
List<QueryPlan> queryPlans;
NamedTableNode tableNode = delete.getTable();
String tableName = tableNode.getName().getTableName();
String schemaName = tableNode.getName().getSchemaName();
boolean retryOnce = !isAutoCommit;
TableRef tableRefToBe;
boolean noQueryReqd = false;
boolean runOnServer = false;
SelectStatement select = null;
Set<PTable> immutableIndex = Collections.emptySet();
DeletingParallelIteratorFactory parallelIteratorFactory = null;
while (true) {
try {
ColumnResolver resolver = FromCompiler.getResolverForMutation(delete, connection);
tableRefToBe = resolver.getTables().get(0);
PTable table = tableRefToBe.getTable();
if (table.getType() == PTableType.VIEW && table.getViewType().isReadOnly()) {
throw new ReadOnlyTableException(table.getSchemaName().getString(),table.getTableName().getString());
}
immutableIndex = getNonDisabledImmutableIndexes(tableRefToBe);
boolean mayHaveImmutableIndexes = !immutableIndex.isEmpty();
noQueryReqd = !hasLimit;
runOnServer = isAutoCommit && noQueryReqd;
HintNode hint = delete.getHint();
if (runOnServer && !delete.getHint().hasHint(Hint.USE_INDEX_OVER_DATA_TABLE)) {
hint = HintNode.create(hint, Hint.USE_DATA_OVER_INDEX_TABLE);
}
List<AliasedNode> aliasedNodes = Lists.newArrayListWithExpectedSize(table.getPKColumns().size());
boolean isSalted = table.getBucketNum() != null;
boolean isMultiTenant = connection.getTenantId() != null && table.isMultiTenant();
boolean isSharedViewIndex = table.getViewIndexId() != null;
for (int i = (isSalted ? 1 : 0) + (isMultiTenant ? 1 : 0) + (isSharedViewIndex ? 1 : 0); i < table.getPKColumns().size(); i++) {
PColumn column = table.getPKColumns().get(i);
aliasedNodes.add(FACTORY.aliasedNode(null, FACTORY.column(null, '"' + column.getName().getString() + '"', null)));
}
select = FACTORY.select(
delete.getTable(),
hint, false, aliasedNodes, delete.getWhere(),
Collections.<ParseNode>emptyList(), null,
delete.getOrderBy(), delete.getLimit(),
delete.getBindCount(), false, false, Collections.<SelectStatement>emptyList());
select = StatementNormalizer.normalize(select, resolver);
SelectStatement transformedSelect = SubqueryRewriter.transform(select, resolver, connection);
if (transformedSelect != select) {
resolver = FromCompiler.getResolverForQuery(transformedSelect, connection);
select = StatementNormalizer.normalize(transformedSelect, resolver);
}
parallelIteratorFactory = hasLimit ? null : new DeletingParallelIteratorFactory(connection);
QueryOptimizer optimizer = new QueryOptimizer(services);
queryPlans = Lists.newArrayList(mayHaveImmutableIndexes
? optimizer.getApplicablePlans(statement, select, resolver, Collections.<PColumn>emptyList(), parallelIteratorFactory)
: optimizer.getBestPlan(statement, select, resolver, Collections.<PColumn>emptyList(), parallelIteratorFactory));
if (mayHaveImmutableIndexes) { // FIXME: this is ugly
// Lookup the table being deleted from in the cache, as it's possible that the
// optimizer updated the cache if it found indexes that were out of date.
// If the index was marked as disabled, it should not be in the list
// of immutable indexes.
table = connection.getMetaDataCache().getTable(new PTableKey(table.getTenantId(), table.getName().getString()));
tableRefToBe.setTable(table);
immutableIndex = getNonDisabledImmutableIndexes(tableRefToBe);
}
} catch (MetaDataEntityNotFoundException e) {
// Catch column/column family not found exception, as our meta data may
// be out of sync. Update the cache once and retry if we were out of sync.
// Otherwise throw, as we'll just get the same error next time.
if (retryOnce) {
retryOnce = false;
MetaDataMutationResult result = new MetaDataClient(connection).updateCache(schemaName, tableName);
if (result.wasUpdated()) {
continue;
}
}
throw e;
}
break;
}
final boolean hasImmutableIndexes = !immutableIndex.isEmpty();
// tableRefs is parallel with queryPlans
TableRef[] tableRefs = new TableRef[hasImmutableIndexes ? immutableIndex.size() : 1];
if (hasImmutableIndexes) {
int i = 0;
Iterator<QueryPlan> plans = queryPlans.iterator();
while (plans.hasNext()) {
QueryPlan plan = plans.next();
PTable table = plan.getTableRef().getTable();
if (table.getType() == PTableType.INDEX) { // index plans
tableRefs[i++] = plan.getTableRef();
immutableIndex.remove(table);
} else { // data plan
/*
* If we have immutable indexes that we need to maintain, don't execute the data plan
* as we can save a query by piggy-backing on any of the other index queries, since the
* PK columns that we need are always in each index row.
*/
plans.remove();
}
}
/*
* If we have any immutable indexes remaining, then that means that the plan for that index got filtered out
* because it could not be executed. This would occur if a column in the where clause is not found in the
* immutable index.
*/
if (!immutableIndex.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.INVALID_FILTER_ON_IMMUTABLE_ROWS).setSchemaName(tableRefToBe.getTable().getSchemaName().getString())
.setTableName(tableRefToBe.getTable().getTableName().getString()).build().buildException();
}
}
// Make sure the first plan is targeting deletion from the data table
// In the case of an immutable index, we'll also delete from the index.
tableRefs[0] = tableRefToBe;
/*
* Create a mutationPlan for each queryPlan. One plan will be for the deletion of the rows
* from the data table, while the others will be for deleting rows from immutable indexes.
*/
List<MutationPlan> mutationPlans = Lists.newArrayListWithExpectedSize(tableRefs.length);
for (int i = 0; i < tableRefs.length; i++) {
final TableRef tableRef = tableRefs[i];
final QueryPlan plan = queryPlans.get(i);
if (!plan.getTableRef().equals(tableRef) || !(plan instanceof BaseQueryPlan)) {
runOnServer = false;
noQueryReqd = false; // FIXME: why set this to false in this case?
}
final int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
final StatementContext context = plan.getContext();
// If we're doing a query for a set of rows with no where clause, then we don't need to contact the server at all.
// A simple check of the none existence of a where clause in the parse node is not sufficient, as the where clause
// may have been optimized out. Instead, we check that there's a single SkipScanFilter
if (noQueryReqd
&& (!context.getScan().hasFilter()
|| context.getScan().getFilter() instanceof SkipScanFilter)
&& context.getScanRanges().isPointLookup()) {
mutationPlans.add(new MutationPlan() {
@Override
public ParameterMetaData getParameterMetaData() {
return context.getBindManager().getParameterMetaData();
}
@Override
public MutationState execute() {
// We have a point lookup, so we know we have a simple set of fully qualified
// keys for our ranges
ScanRanges ranges = context.getScanRanges();
Iterator<KeyRange> iterator = ranges.getPointLookupKeyIterator();
Map<ImmutableBytesPtr,Map<PColumn,byte[]>> mutation = Maps.newHashMapWithExpectedSize(ranges.getPointLookupCount());
while (iterator.hasNext()) {
mutation.put(new ImmutableBytesPtr(iterator.next().getLowerRange()), PRow.DELETE_MARKER);
}
return new MutationState(tableRef, mutation, 0, maxSize, connection);
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
return new ExplainPlan(Collections.singletonList("DELETE SINGLE ROW"));
}
@Override
public PhoenixConnection getConnection() {
return connection;
}
@Override
public StatementContext getContext() {
return context;
}
});
} else if (runOnServer) {
// TODO: better abstraction
Scan scan = context.getScan();
scan.setAttribute(BaseScannerRegionObserver.DELETE_AGG, QueryConstants.TRUE);
// Build an ungrouped aggregate query: select COUNT(*) from <table> where <where>
// The coprocessor will delete each row returned from the scan
// Ignoring ORDER BY, since with auto commit on and no limit makes no difference
SelectStatement aggSelect = SelectStatement.create(SelectStatement.COUNT_ONE, delete.getHint());
final RowProjector projector = ProjectionCompiler.compile(context, aggSelect, GroupBy.EMPTY_GROUP_BY);
final QueryPlan aggPlan = new AggregatePlan(context, select, tableRef, projector, null, OrderBy.EMPTY_ORDER_BY, null, GroupBy.EMPTY_GROUP_BY, null);
mutationPlans.add(new MutationPlan() {
@Override
public PhoenixConnection getConnection() {
return connection;
}
@Override
public ParameterMetaData getParameterMetaData() {
return context.getBindManager().getParameterMetaData();
}
@Override
public StatementContext getContext() {
return context;
}
@Override
public MutationState execute() throws SQLException {
// TODO: share this block of code with UPSERT SELECT
ImmutableBytesWritable ptr = context.getTempPtr();
tableRef.getTable().getIndexMaintainers(ptr, context.getConnection());
ServerCache cache = null;
try {
if (ptr.getLength() > 0) {
IndexMetaDataCacheClient client = new IndexMetaDataCacheClient(connection, tableRef);
cache = client.addIndexMetadataCache(context.getScanRanges(), ptr);
byte[] uuidValue = cache.getId();
context.getScan().setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
}
ResultIterator iterator = aggPlan.iterator();
try {
Tuple row = iterator.next();
final long mutationCount = (Long)projector.getColumnProjector(0).getValue(row, PLong.INSTANCE, ptr);
return new MutationState(maxSize, connection) {
@Override
public long getUpdateCount() {
return mutationCount;
}
};
} finally {
iterator.close();
}
} finally {
if (cache != null) {
cache.close();
}
}
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
List<String> queryPlanSteps = aggPlan.getExplainPlan().getPlanSteps();
List<String> planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1);
planSteps.add("DELETE ROWS");
planSteps.addAll(queryPlanSteps);
return new ExplainPlan(planSteps);
}
});
} else {
final boolean deleteFromImmutableIndexToo = hasImmutableIndexes && !plan.getTableRef().equals(tableRef);
if (parallelIteratorFactory != null) {
parallelIteratorFactory.setRowProjector(plan.getProjector());
parallelIteratorFactory.setTargetTableRef(tableRef);
parallelIteratorFactory.setSourceTableRef(plan.getTableRef());
parallelIteratorFactory.setIndexTargetTableRef(deleteFromImmutableIndexToo ? plan.getTableRef() : null);
}
mutationPlans.add( new MutationPlan() {
@Override
public PhoenixConnection getConnection() {
return connection;
}
@Override
public ParameterMetaData getParameterMetaData() {
return context.getBindManager().getParameterMetaData();
}
@Override
public StatementContext getContext() {
return context;
}
@Override
public MutationState execute() throws SQLException {
ResultIterator iterator = plan.iterator();
if (!hasLimit) {
Tuple tuple;
long totalRowCount = 0;
while ((tuple=iterator.next()) != null) {// Runs query
Cell kv = tuple.getValue(0);
totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault());
}
// Return total number of rows that have been delete. In the case of auto commit being off
// the mutations will all be in the mutation state of the current connection.
return new MutationState(maxSize, connection, totalRowCount);
} else {
return deleteRows(statement, tableRef, deleteFromImmutableIndexToo ? plan.getTableRef() : null, iterator, plan.getProjector(), plan.getTableRef());
}
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
List<String> queryPlanSteps = plan.getExplainPlan().getPlanSteps();
List<String> planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1);
planSteps.add("DELETE ROWS");
planSteps.addAll(queryPlanSteps);
return new ExplainPlan(planSteps);
}
});
}
}
return mutationPlans.size() == 1 ? mutationPlans.get(0) : new MultiDeleteMutationPlan(mutationPlans);
}
}
|
glammedia/phoenix
|
phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java
|
Java
|
apache-2.0
| 30,200 |
/**
* define global constant
*
* Created by Shiro on 16/12/20.
*/
const NAV = [
{name: 'Home', link: '/index'},
{name: 'Editor', link: '/editor'},
{name: 'Project', link: '/project', children: [
{name: 'RMSP', link: '/project/rmsp'},
{name: 'test', link: '/project/'},
{name: 'test', link: '/project/'}
]},
{name: 'Css', link: '/css'}
];
export {NAV};
const TITLEMAP = {
login: '登录'
};
export {TITLEMAP};
const MAP = {
sex: ['女', '男'],
zodiac: [
{zh: '鼠', emoji: '🐹'},
{zh: '牛', emoji: '🐮'},
{zh: '虎', emoji: '🐯'},
{zh: '兔', emoji: '🐰'},
{zh: '龙', emoji: '🐲'},
{zh: '蛇', emoji: '🐍'},
{zh: '马', emoji: '🦄'},
{zh: '羊', emoji: '🐑'},
{zh: '猴', emoji: '🐒'},
{zh: '鸡', emoji: '🐣'},
{zh: '狗', emoji: '🐶'},
{zh: '猪', emoji: '🐷'}
],
constellation: [
{zh: '白羊座', emoji: '♈'},
{zh: '金牛座', emoji: '♉'},
{zh: '双子座', emoji: '♊'},
{zh: '巨蟹座', emoji: '♋'},
{zh: '狮子座', emoji: '♌'},
{zh: '处女座', emoji: '♍'},
{zh: '天秤座', emoji: '♎'},
{zh: '天蝎座', emoji: '♏'},
{zh: '射手座', emoji: '♐'},
{zh: '摩羯座', emoji: '♑'},
{zh: '水瓶座', emoji: '♒'},
{zh: '双鱼座', emoji: '♓'}
]
};
export {MAP}
|
supershiro/Cancer
|
src/libs/const.js
|
JavaScript
|
apache-2.0
| 1,357 |
/**
* Copyright 2015 Steffen Kremp
*
* 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.pictura.servlet;
import java.net.HttpURLConnection;
import javax.servlet.http.HttpServletResponse;
/**
* A handler to provide cache control directives for the value of the HTTP
* response header.
* <p>
* For example, to set a general max-age of 60 seconds, the implementation looks
* like:
*
* <pre>
* public class DefaultCacheControlHandler implements CacheControlHandler {
*
* public String getDirective(String path) {
* if (path != null) {
* return "public, max-age=60";
* }
* return null;
* }
*
* }
* </pre>
*
* @author Steffen Kremp
*
* @since 1.0
*/
public interface CacheControlHandler {
/**
* Gets the cache control directive for the specified resource path. If
* there is no directive available for the requested resource, the method
* returns <code>null</code>. Also a directive will only set in cases of an
* {@link HttpServletResponse#SC_OK} status code.
* <p>
* If the resource is located on a remote server and the used
* {@link RequestProcessor} uses an {@link HttpURLConnection} to fetch the
* resource the origin cache control header will be overwritten with the
* directive by this implementation, however not if there was no custom
* directive found.
* </p>
* <p>
* If the directive contains a <code>max-age</code>, the value of the
* maximum age is also used to calculate and set the <code>Expires</code>
* header, where the value of the expiration date is <code>System.currentTimeMillis() +
* (max-age * 1000)</code>.
* </p>
*
* @param path The resource path.
*
* @return The cache control directive or <code>null</code> if there was no
* directive found for the given resource path.
*/
public String getDirective(String path);
}
|
skremp/pictura-io
|
servlet/src/main/java/io/pictura/servlet/CacheControlHandler.java
|
Java
|
apache-2.0
| 2,439 |
/**
* Copyright (C) 2009 GIP RECIA http://www.recia.fr
* @Author (C) 2009 GIP RECIA <contact@recia.fr>
* @Contributor (C) 2009 SOPRA http://www.sopragroup.com/
* @Contributor (C) 2011 Pierre Legay <pierre.legay@recia.fr>
*
* 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.
*/
/*
* 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 javax.faces.event;
import java.util.EventListener;
/**
* see Javadoc of <a href="http://java.sun.com/j2ee/javaserverfaces/1.1_01/docs/api/index.html">JSF Specification</a>
*
* @author Thomas Spiegl (latest modification by $Author: grantsmith $)
* @version $Revision: 472558 $ $Date: 2006-11-08 18:36:53 +0100 (Mi, 08 Nov 2006) $
*/
public interface FacesListener
extends EventListener
{
}
|
GIP-RECIA/esco-grouper-ui
|
ext/bundles/myfaces-api/src/main/java/javax/faces/event/FacesListener.java
|
Java
|
apache-2.0
| 2,038 |
<?php
/**
* This file is part of the Patterns package.
*
* Copyright (c) 2013-2016 Pierre Cassat <me@e-piwi.fr> and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*
* The source code of this package is available online at
* <http://github.com/atelierspierrot/patterns>.
*/
namespace Patterns\Interfaces;
/**
* A simple interface to manage a set of options
*
* @author piwi <me@e-piwi.fr>
*/
interface OptionableInterface
{
/**
* Set an array of options
* @param array $options
*/
public function setOptions(array $options);
/**
* Set the value of a specific option
* @param string $name
* @param mixed $value
*/
public function setOption($name, $value);
/**
* Get the array of options
* @return array
*/
public function getOptions();
/**
* Get the value of a specific option
* @param string $name
* @param mixed $default
* @return mixed
*/
public function getOption($name, $default = null);
}
|
atelierspierrot/patterns
|
src/Patterns/Interfaces/OptionableInterface.php
|
PHP
|
apache-2.0
| 1,567 |
import fs from 'fs';
import path from 'path';
import { expect } from 'chai';
import sinon from 'sinon';
import { factory } from '@stryker-mutator/test-helpers';
import * as utils from '@stryker-mutator/util';
import type { Config } from '@jest/types';
import { CustomJestConfigLoader } from '../../../src/config-loaders/custom-jest-config-loader';
import { createJestRunnerOptionsWithStrykerOptions } from '../../helpers/producers';
import { JestRunnerOptionsWithStrykerOptions } from '../../../src/jest-runner-options-with-stryker-options';
describe(CustomJestConfigLoader.name, () => {
let sut: CustomJestConfigLoader;
const projectRoot = process.cwd();
let readFileSyncStub: sinon.SinonStub;
let fileExistsSyncStub: sinon.SinonStub;
let requireStub: sinon.SinonStub;
let readConfig: Config.InitialOptions;
let options: JestRunnerOptionsWithStrykerOptions;
beforeEach(() => {
readFileSyncStub = sinon.stub(fs, 'readFileSync');
fileExistsSyncStub = sinon.stub(fs, 'existsSync');
requireStub = sinon.stub(utils, 'requireResolve');
readConfig = { testMatch: ['exampleJestConfigValue'] };
readFileSyncStub.callsFake(() => `{ "jest": ${JSON.stringify(readConfig)}}`);
requireStub.returns(readConfig);
options = createJestRunnerOptionsWithStrykerOptions();
sut = new CustomJestConfigLoader(factory.logger(), options);
});
it('should load the Jest configuration from the jest.config.js', () => {
fileExistsSyncStub.returns(true);
const config = sut.loadConfig();
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.js'));
expect(config).to.deep.contains(readConfig);
});
it('should set the rootDir when no rootDir was configured jest.config.js', () => {
fileExistsSyncStub.returns(true);
const config = sut.loadConfig();
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.js'));
expect(config).to.deep.contains({ rootDir: projectRoot });
});
it('should override the rootDir when a rootDir was configured jest.config.js', () => {
readConfig.rootDir = 'lib';
fileExistsSyncStub.returns(true);
const config = sut.loadConfig();
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.js'));
expect(config).to.deep.contains({ rootDir: path.resolve(projectRoot, 'lib') });
});
it('should allow users to configure a jest.config.json file as "configFile"', () => {
// Arrange
fileExistsSyncStub.returns(true);
options.jest.configFile = path.resolve(projectRoot, 'jest.config.json');
// Act
const config = sut.loadConfig();
// Assert
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.json'));
expect(config).to.deep.contain(readConfig);
});
it('should allow users to configure a package.json file as "configFile"', () => {
// Arrange
fileExistsSyncStub
.withArgs(path.resolve(projectRoot, 'jest.config.js'))
.returns(false)
.withArgs(path.resolve(projectRoot, 'package.json'))
.returns(true);
options.jest.configFile = path.resolve(projectRoot, 'package.json');
// Act
const config = sut.loadConfig();
// Assert
expect(readFileSyncStub).calledWith(path.join(projectRoot, 'package.json'), 'utf8');
expect(config).to.deep.contain(readConfig);
});
it("should fail when configured jest.config.js file doesn't exist", () => {
const expectedError = new Error("File doesn't exist");
fileExistsSyncStub.returns(false);
requireStub.throws(expectedError);
options.jest.configFile = 'my-custom-jest.config.js';
expect(sut.loadConfig.bind(sut)).throws(expectedError);
});
it("should fail when configured package.json file doesn't exist", () => {
const expectedError = new Error("File doesn't exist");
fileExistsSyncStub.returns(false);
readFileSyncStub.throws(expectedError);
options.jest.configFile = 'client/package.json';
expect(sut.loadConfig.bind(sut)).throws(expectedError);
});
it('should fallback and load the Jest configuration from the package.json when jest.config.js is not present in the project', () => {
// Arrange
fileExistsSyncStub
.withArgs(path.resolve(projectRoot, 'jest.config.js'))
.returns(false)
.withArgs(path.resolve(projectRoot, 'package.json'))
.returns(true);
// Act
const config = sut.loadConfig();
// Assert
expect(readFileSyncStub).calledWith(path.join(projectRoot, 'package.json'), 'utf8');
expect(config).to.deep.contain(readConfig);
});
it('should set the rootDir when reading config from package.json', () => {
// Arrange
options.jest.configFile = 'client/package.json';
fileExistsSyncStub
.withArgs(path.resolve(projectRoot, 'jest.config.js'))
.returns(false)
.withArgs(path.resolve(projectRoot, 'client', 'package.json'))
.returns(true);
// Act
const config = sut.loadConfig();
// Assert
expect(readFileSyncStub).calledWith(path.join(projectRoot, 'client', 'package.json'), 'utf8');
expect(config).to.deep.contain(readConfig);
});
it('should load the default Jest configuration if there is no package.json config or jest.config.js', () => {
requireStub.throws(Error('ENOENT: no such file or directory, open package.json'));
readFileSyncStub.returns('{ }'); // note, no `jest` key here!
const config = sut.loadConfig();
expect(config).to.deep.equal({});
});
});
|
stryker-mutator/stryker
|
packages/jest-runner/test/unit/config-loaders/custom-config-loader.spec.ts
|
TypeScript
|
apache-2.0
| 5,452 |
package com.xinjian.winner.di.qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import javax.inject.Qualifier;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by codeest on 2017/2/26.
*/
@Qualifier
@Documented
@Retention(RUNTIME)
public @interface VtexUrl {
}
|
lixinjian/MyFirstWinner
|
app/src/main/java/com/xinjian/winner/di/qualifier/VtexUrl.java
|
Java
|
apache-2.0
| 334 |
/*
* MinIO Cloud Storage, (C) 2016-2020 MinIO, 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 cmd
import (
"net/http"
"github.com/gorilla/mux"
xhttp "github.com/minio/minio/cmd/http"
)
func newHTTPServerFn() *xhttp.Server {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
return globalHTTPServer
}
func newObjectLayerWithoutSafeModeFn() ObjectLayer {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
return globalObjectAPI
}
func newObjectLayerFn() ObjectLayer {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
if globalSafeMode {
return nil
}
return globalObjectAPI
}
func newCachedObjectLayerFn() CacheObjectLayer {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
if globalSafeMode {
return nil
}
return globalCacheObjectAPI
}
// objectAPIHandler implements and provides http handlers for S3 API.
type objectAPIHandlers struct {
ObjectAPI func() ObjectLayer
CacheAPI func() CacheObjectLayer
// Returns true of handlers should interpret encryption.
EncryptionEnabled func() bool
// Returns true if handlers allow SSE-KMS encryption headers.
AllowSSEKMS func() bool
}
// registerAPIRouter - registers S3 compatible APIs.
func registerAPIRouter(router *mux.Router, encryptionEnabled, allowSSEKMS bool) {
// Initialize API.
api := objectAPIHandlers{
ObjectAPI: newObjectLayerFn,
CacheAPI: newCachedObjectLayerFn,
EncryptionEnabled: func() bool {
return encryptionEnabled
},
AllowSSEKMS: func() bool {
return allowSSEKMS
},
}
// API Router
apiRouter := router.PathPrefix(SlashSeparator).Subrouter()
var routers []*mux.Router
for _, domainName := range globalDomainNames {
routers = append(routers, apiRouter.Host("{bucket:.+}."+domainName).Subrouter())
routers = append(routers, apiRouter.Host("{bucket:.+}."+domainName+":{port:.*}").Subrouter())
}
routers = append(routers, apiRouter.PathPrefix("/{bucket}").Subrouter())
for _, bucket := range routers {
// Object operations
// HeadObject
bucket.Methods(http.MethodHead).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("headobject", httpTraceAll(api.HeadObjectHandler))))
// CopyObjectPart
bucket.Methods(http.MethodPut).Path("/{object:.+}").HeadersRegexp(xhttp.AmzCopySource, ".*?(\\/|%2F).*?").HandlerFunc(maxClients(collectAPIStats("copyobjectpart", httpTraceAll(api.CopyObjectPartHandler)))).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
// PutObjectPart
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectpart", httpTraceHdrs(api.PutObjectPartHandler)))).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
// ListObjectParts
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("listobjectparts", httpTraceAll(api.ListObjectPartsHandler)))).Queries("uploadId", "{uploadId:.*}")
// CompleteMultipartUpload
bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("completemutipartupload", httpTraceAll(api.CompleteMultipartUploadHandler)))).Queries("uploadId", "{uploadId:.*}")
// NewMultipartUpload
bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("newmultipartupload", httpTraceAll(api.NewMultipartUploadHandler)))).Queries("uploads", "")
// AbortMultipartUpload
bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("abortmultipartupload", httpTraceAll(api.AbortMultipartUploadHandler)))).Queries("uploadId", "{uploadId:.*}")
// GetObjectACL - this is a dummy call.
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjectacl", httpTraceHdrs(api.GetObjectACLHandler)))).Queries("acl", "")
// PutObjectACL - this is a dummy call.
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectacl", httpTraceHdrs(api.PutObjectACLHandler)))).Queries("acl", "")
// GetObjectTagging
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjecttagging", httpTraceHdrs(api.GetObjectTaggingHandler)))).Queries("tagging", "")
// PutObjectTagging
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjecttagging", httpTraceHdrs(api.PutObjectTaggingHandler)))).Queries("tagging", "")
// DeleteObjectTagging
bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("deleteobjecttagging", httpTraceHdrs(api.DeleteObjectTaggingHandler)))).Queries("tagging", "")
// SelectObjectContent
bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("selectobjectcontent", httpTraceHdrs(api.SelectObjectContentHandler)))).Queries("select", "").Queries("select-type", "2")
// GetObjectRetention
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjectretention", httpTraceAll(api.GetObjectRetentionHandler)))).Queries("retention", "")
// GetObjectLegalHold
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjectlegalhold", httpTraceAll(api.GetObjectLegalHoldHandler)))).Queries("legal-hold", "")
// GetObject
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobject", httpTraceHdrs(api.GetObjectHandler))))
// CopyObject
bucket.Methods(http.MethodPut).Path("/{object:.+}").HeadersRegexp(xhttp.AmzCopySource, ".*?(\\/|%2F).*?").HandlerFunc(maxClients(collectAPIStats("copyobject", httpTraceAll(api.CopyObjectHandler))))
// PutObjectRetention
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectretention", httpTraceAll(api.PutObjectRetentionHandler)))).Queries("retention", "")
// PutObjectLegalHold
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectlegalhold", httpTraceAll(api.PutObjectLegalHoldHandler)))).Queries("legal-hold", "")
// PutObject
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobject", httpTraceHdrs(api.PutObjectHandler))))
// DeleteObject
bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("deleteobject", httpTraceAll(api.DeleteObjectHandler))))
/// Bucket operations
// GetBucketLocation
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlocation", httpTraceAll(api.GetBucketLocationHandler)))).Queries("location", "")
// GetBucketPolicy
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketpolicy", httpTraceAll(api.GetBucketPolicyHandler)))).Queries("policy", "")
// GetBucketLifecycle
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlifecycle", httpTraceAll(api.GetBucketLifecycleHandler)))).Queries("lifecycle", "")
// GetBucketEncryption
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketencryption", httpTraceAll(api.GetBucketEncryptionHandler)))).Queries("encryption", "")
// Dummy Bucket Calls
// GetBucketACL -- this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketacl", httpTraceAll(api.GetBucketACLHandler)))).Queries("acl", "")
// PutBucketACL -- this is a dummy call.
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketacl", httpTraceAll(api.PutBucketACLHandler)))).Queries("acl", "")
// GetBucketCors - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketcors", httpTraceAll(api.GetBucketCorsHandler)))).Queries("cors", "")
// GetBucketWebsiteHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketwebsite", httpTraceAll(api.GetBucketWebsiteHandler)))).Queries("website", "")
// GetBucketAccelerateHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketaccelerate", httpTraceAll(api.GetBucketAccelerateHandler)))).Queries("accelerate", "")
// GetBucketRequestPaymentHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketrequestpayment", httpTraceAll(api.GetBucketRequestPaymentHandler)))).Queries("requestPayment", "")
// GetBucketLoggingHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlogging", httpTraceAll(api.GetBucketLoggingHandler)))).Queries("logging", "")
// GetBucketLifecycleHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlifecycle", httpTraceAll(api.GetBucketLifecycleHandler)))).Queries("lifecycle", "")
// GetBucketReplicationHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketreplication", httpTraceAll(api.GetBucketReplicationHandler)))).Queries("replication", "")
// GetBucketTaggingHandler
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbuckettagging", httpTraceAll(api.GetBucketTaggingHandler)))).Queries("tagging", "")
//DeleteBucketWebsiteHandler
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketwebsite", httpTraceAll(api.DeleteBucketWebsiteHandler)))).Queries("website", "")
// DeleteBucketTaggingHandler
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebuckettagging", httpTraceAll(api.DeleteBucketTaggingHandler)))).Queries("tagging", "")
// GetBucketObjectLockConfig
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketobjectlockconfiguration", httpTraceAll(api.GetBucketObjectLockConfigHandler)))).Queries("object-lock", "")
// GetBucketVersioning
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketversioning", httpTraceAll(api.GetBucketVersioningHandler)))).Queries("versioning", "")
// GetBucketNotification
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketnotification", httpTraceAll(api.GetBucketNotificationHandler)))).Queries("notification", "")
// ListenBucketNotification
bucket.Methods(http.MethodGet).HandlerFunc(collectAPIStats("listenbucketnotification", httpTraceAll(api.ListenBucketNotificationHandler))).Queries("events", "{events:.*}")
// ListMultipartUploads
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listmultipartuploads", httpTraceAll(api.ListMultipartUploadsHandler)))).Queries("uploads", "")
// ListObjectsV2M
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listobjectsv2M", httpTraceAll(api.ListObjectsV2MHandler)))).Queries("list-type", "2", "metadata", "true")
// ListObjectsV2
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listobjectsv2", httpTraceAll(api.ListObjectsV2Handler)))).Queries("list-type", "2")
// ListBucketVersions
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listbucketversions", httpTraceAll(api.ListBucketObjectVersionsHandler)))).Queries("versions", "")
// ListObjectsV1 (Legacy)
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listobjectsv1", httpTraceAll(api.ListObjectsV1Handler))))
// PutBucketLifecycle
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketlifecycle", httpTraceAll(api.PutBucketLifecycleHandler)))).Queries("lifecycle", "")
// PutBucketEncryption
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketencryption", httpTraceAll(api.PutBucketEncryptionHandler)))).Queries("encryption", "")
// PutBucketPolicy
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketpolicy", httpTraceAll(api.PutBucketPolicyHandler)))).Queries("policy", "")
// PutBucketObjectLockConfig
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketobjectlockconfig", httpTraceAll(api.PutBucketObjectLockConfigHandler)))).Queries("object-lock", "")
// PutBucketTaggingHandler
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbuckettagging", httpTraceAll(api.PutBucketTaggingHandler)))).Queries("tagging", "")
// PutBucketVersioning
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketversioning", httpTraceAll(api.PutBucketVersioningHandler)))).Queries("versioning", "")
// PutBucketNotification
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketnotification", httpTraceAll(api.PutBucketNotificationHandler)))).Queries("notification", "")
// PutBucket
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucket", httpTraceAll(api.PutBucketHandler))))
// HeadBucket
bucket.Methods(http.MethodHead).HandlerFunc(
maxClients(collectAPIStats("headbucket", httpTraceAll(api.HeadBucketHandler))))
// PostPolicy
bucket.Methods(http.MethodPost).HeadersRegexp(xhttp.ContentType, "multipart/form-data*").HandlerFunc(
maxClients(collectAPIStats("postpolicybucket", httpTraceHdrs(api.PostPolicyBucketHandler))))
// DeleteMultipleObjects
bucket.Methods(http.MethodPost).HandlerFunc(
maxClients(collectAPIStats("deletemultipleobjects", httpTraceAll(api.DeleteMultipleObjectsHandler)))).Queries("delete", "")
// DeleteBucketPolicy
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketpolicy", httpTraceAll(api.DeleteBucketPolicyHandler)))).Queries("policy", "")
// DeleteBucketLifecycle
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketlifecycle", httpTraceAll(api.DeleteBucketLifecycleHandler)))).Queries("lifecycle", "")
// DeleteBucketEncryption
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketencryption", httpTraceAll(api.DeleteBucketEncryptionHandler)))).Queries("encryption", "")
// DeleteBucket
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucket", httpTraceAll(api.DeleteBucketHandler))))
}
/// Root operation
// ListBuckets
apiRouter.Methods(http.MethodGet).Path(SlashSeparator).HandlerFunc(
maxClients(collectAPIStats("listbuckets", httpTraceAll(api.ListBucketsHandler))))
// S3 browser with signature v4 adds '//' for ListBuckets request, so rather
// than failing with UnknownAPIRequest we simply handle it for now.
apiRouter.Methods(http.MethodGet).Path(SlashSeparator + SlashSeparator).HandlerFunc(
maxClients(collectAPIStats("listbuckets", httpTraceAll(api.ListBucketsHandler))))
// If none of the routes match add default error handler routes
apiRouter.NotFoundHandler = http.HandlerFunc(collectAPIStats("notfound", httpTraceAll(errorResponseHandler)))
apiRouter.MethodNotAllowedHandler = http.HandlerFunc(collectAPIStats("methodnotallowed", httpTraceAll(errorResponseHandler)))
}
|
harshavardhana/minio
|
cmd/api-router.go
|
GO
|
apache-2.0
| 15,882 |
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import ru.stqa.pft.addressbook.model.ContactData;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ВВС on 14.04.2017.
*/
public class ContactHelper extends HelperBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void fillContactForm(ContactData contactData/*, boolean creation*/) {
type(By.name("firstname"), contactData.getFirstname());
type(By.name("lastname"), contactData.getLastname());
type(By.name("address"), contactData.getAddress());
type(By.name("home"), contactData.getHome());
type(By.name("email"), contactData.getEmail());
/*
if (creation) {
new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
} else {
Assert.assertFalse(isElementPresent(By.name("new_group")));
}
*/
}
//Метод, нажимающий на кнопку подтверждения создания объекта
public void submitCreateContact() {
click(By.name("submit"));
}
//Метод, проверяющий наличие кнопки редактирования объекта
public boolean xpathIsPresent() {
try {
wd.findElement(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
//Метод, проверяющий наличие кнопки редактирования контакта. Если таковой нет, то метод создает новый контакт
public void editContactButton(ContactData contact){
if( ! xpathIsPresent() == true){
goToAddNewContactPage();
fillContactForm(contact);
submitCreateContact();
new NavigationHelper(wd).goToHome();
}
}
public void clickEditContact(int index) {
if (index < 0) {
click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
} else {
click(By.xpath("//table[@id='maintable']/tbody/tr[" + (index+2) + "]/td[8]/a/img"));
}
}
public void updateContactButton() {
if (isElementPresent(By.tagName("h1"))
&& wd.findElement(By.tagName("h1")).getText().equals("Edit / add address book entry")
&& isElementPresent(By.name("update"))) {
return;
}
click(By.name("update"));
}
public boolean elementIsPresent() {
try {
wd.findElement(By.name("selected[]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void selectContactButton(ContactData contact) {
if (! elementIsPresent() == true) {
goToAddNewContactPage();
fillContactForm(contact);
submitCreateContact();
new NavigationHelper(wd).goToHome();
}
}
public void clickDeleteContact(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
}
public void deleteContactButton () {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
}
public void goToAddNewContactPage() {
if (isElementPresent(By.tagName("h1"))
&& wd.findElement(By.tagName("h1")).getText().equals("Edit / add address book entry")
&& (isElementPresent(By.name("submit")))) {
return;
}
click(By.linkText("add new"));
}
//Метод, который высчитывает кол-во контактов в тестах создания и удаления контактов
public int getContactCount() {
return wd.findElements(By.name("selected[]")).size();
}
//Метод, который высчитывает кол-во контактов в тесте модификации контактов
public int getContactCountXpath() {
int m = 0;
for (int i = 2; i < 10; i++) {
int y = wd.findElements(By.xpath("//table[@id='maintable']/tbody/tr[" + i + "]/td[8]/a/img")).size();
m = m + y;
}
return m;
}
public List<ContactData> getContactList() {
List<ContactData> contacts = new ArrayList<ContactData>();
int size = wd.findElements(By.name("selected[]")).size();
for (int i = 2; i < (size + 2); i++){
List<WebElement> elements = wd.findElements(By.xpath("//*[@id=\"maintable\"]/tbody/tr[" + i + "]"));
for (WebElement element : elements){
String firstname = element.findElement(By.xpath("//*[@id=\"maintable\"]/tbody/tr[" + i + "]/td[3]")).getText();
String lastname = element.findElement(By.xpath("//*[@id=\"maintable\"]/tbody/tr[" + i + "]/td[2]")).getText();
int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value"));
ContactData contact = new ContactData(id, firstname, lastname, null );
contacts.add(contact);
}
}
return contacts;
}
}
|
VVSilinenko/java_first
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
|
Java
|
apache-2.0
| 5,422 |
package org.jtheque.modules.impl;
/*
* Copyright JTheque (Baptiste Wicht)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.jtheque.modules.ModuleDescription;
import org.jtheque.modules.Repository;
import org.jtheque.utils.annotations.Immutable;
import org.jtheque.utils.bean.InternationalString;
import org.jtheque.utils.collections.CollectionUtils;
import java.util.Collection;
/**
* A module repository.
*
* @author Baptiste Wicht
*/
@Immutable
final class RepositoryImpl implements Repository {
private final InternationalString title;
private final String application;
private final Collection<ModuleDescription> modules;
/**
* Create a new RepositoryImpl.
*
* @param title The title of the repository.
* @param application The application of the repository.
* @param modules The modules of the repository.
*/
RepositoryImpl(InternationalString title, String application, Collection<ModuleDescription> modules) {
super();
this.title = title;
this.application = application;
this.modules = CollectionUtils.protectedCopy(modules);
}
@Override
public String getApplication() {
return application;
}
@Override
public Collection<ModuleDescription> getModules() {
return modules;
}
@Override
public InternationalString getTitle() {
return title;
}
@Override
public String toString() {
return "Repository{" +
"title=" + title +
", application='" + application + '\'' +
", modules=" + modules +
'}';
}
}
|
wichtounet/jtheque-core
|
jtheque-modules/src/main/java/org/jtheque/modules/impl/RepositoryImpl.java
|
Java
|
apache-2.0
| 2,249 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.organizations.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.organizations.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DisablePolicyTypeRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DisablePolicyTypeRequestProtocolMarshaller implements Marshaller<Request<DisablePolicyTypeRequest>, DisablePolicyTypeRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AWSOrganizationsV20161128.DisablePolicyType").serviceName("AWSOrganizations").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DisablePolicyTypeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DisablePolicyTypeRequest> marshall(DisablePolicyTypeRequest disablePolicyTypeRequest) {
if (disablePolicyTypeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DisablePolicyTypeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
disablePolicyTypeRequest);
protocolMarshaller.startMarshalling();
DisablePolicyTypeRequestMarshaller.getInstance().marshall(disablePolicyTypeRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-organizations/src/main/java/com/amazonaws/services/organizations/model/transform/DisablePolicyTypeRequestProtocolMarshaller.java
|
Java
|
apache-2.0
| 2,748 |
/*
* Copyright (c) 2011-2020, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.demonstrations.imageprocessing;
import boofcv.abst.distort.FDistort;
import boofcv.alg.interpolate.InterpolationType;
import boofcv.gui.DemonstrationBase;
import boofcv.gui.image.ImagePanel;
import boofcv.gui.image.ScaleOptions;
import boofcv.io.UtilIO;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.border.BorderType;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Scales an image using the specified interpolation method.
*
* @author Peter Abeles
*/
public class DemonstrationInterpolateScaleApp<T extends ImageBase<T>>
extends DemonstrationBase implements ItemListener, ComponentListener
{
private final T latestImage;
private final T scaledImage;
private final ImagePanel panel = new ImagePanel();
private final JComboBox combo = new JComboBox();
private volatile InterpolationType interpType = InterpolationType.values()[0];
public DemonstrationInterpolateScaleApp(List<String> examples , ImageType<T> imageType ) {
super(examples, imageType);
panel.setScaling(ScaleOptions.NONE);
latestImage = imageType.createImage(1,1);
scaledImage = imageType.createImage(1,1);
for( InterpolationType type : InterpolationType.values() ) {
combo.addItem( type.toString() );
}
combo.addItemListener(this);
menuBar.add(combo);
panel.addComponentListener(this);
add(BorderLayout.CENTER, panel);
}
@Override
public void processImage(int sourceID, long frameID, BufferedImage buffered, ImageBase input) {
synchronized (latestImage) {
latestImage.setTo((T)input);
applyScaling();
}
}
private void applyScaling() {
scaledImage.reshape(panel.getWidth(), panel.getHeight());
if( scaledImage.width <= 0 || scaledImage.height <= 0 ) {
return;
}
if( latestImage.width != 0 && latestImage.height != 0 ) {
new FDistort(latestImage, scaledImage).interp(interpType).border(BorderType.EXTENDED).scale().apply();
BufferedImage out = ConvertBufferedImage.convertTo(scaledImage, null, true);
panel.setImageUI(out);
panel.repaint();
}
}
@Override
public void itemStateChanged(ItemEvent e) {
interpType = InterpolationType.values()[ combo.getSelectedIndex() ];
synchronized (latestImage) {
applyScaling();
}
}
@Override
public void componentResized(ComponentEvent e) {
synchronized (latestImage) {
if( inputMethod == InputMethod.IMAGE )
applyScaling();
}
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
public static void main( String[] args ) {
ImageType type = ImageType.pl(3,GrayF32.class);
// ImageType type = ImageType.pl(3,GrayU8.class);
// ImageType type = ImageType.single(GrayU8.class);
// ImageType type = ImageType.il(3, InterleavedF32.class);
List<String> examples = new ArrayList<>();
examples.add( UtilIO.pathExample("eye01.jpg") );
examples.add( UtilIO.pathExample("small_sunflower.jpg"));
DemonstrationInterpolateScaleApp app = new DemonstrationInterpolateScaleApp(examples,type);
app.setPreferredSize(new Dimension(500,500));
app.openFile(new File(examples.get(0)));
app.display("Interpolation Enlarge");
}
}
|
lessthanoptimal/BoofCV
|
demonstrations/src/main/java/boofcv/demonstrations/imageprocessing/DemonstrationInterpolateScaleApp.java
|
Java
|
apache-2.0
| 4,261 |
package org.genericsystem.reactor.contextproperties;
import org.genericsystem.reactor.Context;
import org.genericsystem.reactor.HtmlDomNode;
import org.genericsystem.reactor.Tag;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
public interface StylesDefaults extends MapStringDefaults {
public static final String STYLES = "styles";
<T> T getInheritedContextAttribute(String propertyName, Context[] model, Tag[] tag);
default ObservableMap<String, String> getDomNodeStyles(Context model) {
return getDomNodeMap(model, STYLES, HtmlDomNode::getStylesListener);
}
default void inheritStyle(Context context, String styleName) {
Context[] modelArray = new Context[] { context };
Tag[] tagArray = new Tag[] { (Tag) this };
ObservableMap<String, String> ancestorStyles = getInheritedContextAttribute(STYLES, modelArray, tagArray);
while (ancestorStyles != null)
if (ancestorStyles.containsKey(styleName)) {
ObservableMap<String, String> styles = getDomNodeStyles(context);
styles.put(styleName, ancestorStyles.get(styleName));
ancestorStyles.addListener((MapChangeListener<String, String>) c -> {
if (c.getKey().equals(styleName)) {
if (c.wasRemoved())
styles.remove(styleName);
if (c.wasAdded())
styles.put(styleName, c.getValueAdded());
}
});
break;
} else
ancestorStyles = getInheritedContextAttribute(STYLES, modelArray, tagArray);
}
default void inheritStyle(String styleName) {
addPrefixBinding(context -> inheritStyle(context, styleName));
}
}
|
genericsystem/genericsystem2015
|
gs-reactor/src/main/java/org/genericsystem/reactor/contextproperties/StylesDefaults.java
|
Java
|
apache-2.0
| 1,576 |
#include <assert.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <regex>
#include <sstream>
#include <sys/epoll.h>
#include "bcc_syms.h"
#include "perf_reader.h"
#include "bpforc.h"
#include "bpftrace.h"
#include "attached_probe.h"
#include "triggers.h"
namespace bpftrace {
int BPFtrace::add_probe(ast::Probe &p)
{
for (auto attach_point : *p.attach_points)
{
if (attach_point->provider == "BEGIN")
{
Probe probe;
probe.path = "/proc/self/exe";
probe.attach_point = "BEGIN_trigger";
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = p.name();
special_probes_.push_back(probe);
continue;
}
else if (attach_point->provider == "END")
{
Probe probe;
probe.path = "/proc/self/exe";
probe.attach_point = "END_trigger";
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = p.name();
special_probes_.push_back(probe);
continue;
}
std::vector<std::string> attach_funcs;
if (attach_point->func.find("*") != std::string::npos ||
attach_point->func.find("[") != std::string::npos &&
attach_point->func.find("]") != std::string::npos)
{
std::string file_name;
switch (probetype(attach_point->provider))
{
case ProbeType::kprobe:
case ProbeType::kretprobe:
file_name = "/sys/kernel/debug/tracing/available_filter_functions";
break;
case ProbeType::tracepoint:
file_name = "/sys/kernel/debug/tracing/available_events";
break;
default:
std::cerr << "Wildcard matches aren't available on probe type '"
<< attach_point->provider << "'" << std::endl;
return 1;
}
auto matches = find_wildcard_matches(attach_point->target,
attach_point->func,
file_name);
attach_funcs.insert(attach_funcs.end(), matches.begin(), matches.end());
}
else
{
attach_funcs.push_back(attach_point->func);
}
for (auto func : attach_funcs)
{
Probe probe;
probe.path = attach_point->target;
probe.attach_point = func;
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = attach_point->name(func);
probe.freq = attach_point->freq;
probes_.push_back(probe);
}
}
return 0;
}
std::set<std::string> BPFtrace::find_wildcard_matches(const std::string &prefix, const std::string &func, const std::string &file_name)
{
// Turn glob into a regex
auto regex_str = "(" + std::regex_replace(func, std::regex("\\*"), "[^\\s]*") + ")";
if (prefix != "")
regex_str = prefix + ":" + regex_str;
regex_str = "^" + regex_str;
std::regex func_regex(regex_str);
std::smatch match;
std::ifstream file(file_name);
if (file.fail())
{
std::cerr << strerror(errno) << ": " << file_name << std::endl;
return std::set<std::string>();
}
std::string line;
std::set<std::string> matches;
while (std::getline(file, line))
{
if (std::regex_search(line, match, func_regex))
{
assert(match.size() == 2);
matches.insert(match[1]);
}
}
return matches;
}
int BPFtrace::num_probes() const
{
return special_probes_.size() + probes_.size();
}
void perf_event_printer(void *cb_cookie, void *data, int size)
{
auto bpftrace = static_cast<BPFtrace*>(cb_cookie);
auto printf_id = *static_cast<uint64_t*>(data);
auto arg_data = static_cast<uint8_t*>(data) + sizeof(uint64_t);
auto fmt = std::get<0>(bpftrace->printf_args_[printf_id]).c_str();
auto args = std::get<1>(bpftrace->printf_args_[printf_id]);
std::vector<uint64_t> arg_values;
std::vector<std::unique_ptr<char>> resolved_symbols;
for (auto arg : args)
{
switch (arg.type)
{
case Type::integer:
arg_values.push_back(*(uint64_t*)arg_data);
break;
case Type::string:
arg_values.push_back((uint64_t)arg_data);
break;
case Type::sym:
resolved_symbols.emplace_back(strdup(
bpftrace->resolve_sym(*(uint64_t*)arg_data).c_str()));
arg_values.push_back((uint64_t)resolved_symbols.back().get());
break;
case Type::usym:
resolved_symbols.emplace_back(strdup(
bpftrace->resolve_usym(*(uint64_t*)arg_data).c_str()));
arg_values.push_back((uint64_t)resolved_symbols.back().get());
break;
default:
abort();
}
arg_data += arg.size;
}
switch (args.size())
{
case 0:
printf(fmt);
break;
case 1:
printf(fmt, arg_values.at(0));
break;
case 2:
printf(fmt, arg_values.at(0), arg_values.at(1));
break;
case 3:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2));
break;
case 4:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3));
break;
case 5:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3), arg_values.at(4));
break;
case 6:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3), arg_values.at(4), arg_values.at(5));
break;
default:
abort();
}
}
void perf_event_lost(void *cb_cookie, uint64_t lost)
{
printf("Lost %lu events\n", lost);
}
std::unique_ptr<AttachedProbe> BPFtrace::attach_probe(Probe &probe, const BpfOrc &bpforc)
{
auto func = bpforc.sections_.find("s_" + probe.prog_name);
if (func == bpforc.sections_.end())
{
std::cerr << "Code not generated for probe: " << probe.name << std::endl;
return nullptr;
}
try
{
return std::make_unique<AttachedProbe>(probe, func->second);
}
catch (std::runtime_error e)
{
std::cerr << e.what() << std::endl;
}
return nullptr;
}
int BPFtrace::run(std::unique_ptr<BpfOrc> bpforc)
{
for (Probe &probe : special_probes_)
{
auto attached_probe = attach_probe(probe, *bpforc.get());
if (attached_probe == nullptr)
return -1;
special_attached_probes_.push_back(std::move(attached_probe));
}
int epollfd = setup_perf_events();
if (epollfd < 0)
return epollfd;
BEGIN_trigger();
for (Probe &probe : probes_)
{
auto attached_probe = attach_probe(probe, *bpforc.get());
if (attached_probe == nullptr)
return -1;
attached_probes_.push_back(std::move(attached_probe));
}
poll_perf_events(epollfd);
attached_probes_.clear();
END_trigger();
poll_perf_events(epollfd, 100);
special_attached_probes_.clear();
return 0;
}
int BPFtrace::setup_perf_events()
{
int epollfd = epoll_create1(EPOLL_CLOEXEC);
if (epollfd == -1)
{
std::cerr << "Failed to create epollfd" << std::endl;
return -1;
}
std::vector<int> cpus = ebpf::get_online_cpus();
online_cpus_ = cpus.size();
for (int cpu : cpus)
{
int page_cnt = 8;
void *reader = bpf_open_perf_buffer(&perf_event_printer, &perf_event_lost, this, -1, cpu, page_cnt);
if (reader == nullptr)
{
std::cerr << "Failed to open perf buffer" << std::endl;
return -1;
}
struct epoll_event ev = {};
ev.events = EPOLLIN;
ev.data.ptr = reader;
int reader_fd = perf_reader_fd((perf_reader*)reader);
bpf_update_elem(perf_event_map_->mapfd_, &cpu, &reader_fd, 0);
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reader_fd, &ev) == -1)
{
std::cerr << "Failed to add perf reader to epoll" << std::endl;
return -1;
}
}
return epollfd;
}
void BPFtrace::poll_perf_events(int epollfd, int timeout)
{
auto events = std::vector<struct epoll_event>(online_cpus_);
while (true)
{
int ready = epoll_wait(epollfd, events.data(), online_cpus_, timeout);
if (ready <= 0)
{
return;
}
for (int i=0; i<ready; i++)
{
perf_reader_event_read((perf_reader*)events[i].data.ptr);
}
}
return;
}
int BPFtrace::print_maps()
{
for(auto &mapmap : maps_)
{
IMap &map = *mapmap.second.get();
int err;
if (map.type_.type == Type::quantize)
err = print_map_quantize(map);
else
err = print_map(map);
if (err)
return err;
}
return 0;
}
int BPFtrace::print_map(IMap &map)
{
std::vector<uint8_t> old_key;
try
{
old_key = find_empty_key(map, map.key_.size());
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);
std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> values_by_key;
while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0)
{
int value_size = map.type_.size;
if (map.type_.type == Type::count)
value_size *= ncpus_;
auto value = std::vector<uint8_t>(value_size);
int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data());
if (err)
{
std::cerr << "Error looking up elem: " << err << std::endl;
return -1;
}
values_by_key.push_back({key, value});
old_key = key;
}
if (map.type_.type == Type::count)
{
std::sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return reduce_value(a.second, ncpus_) < reduce_value(b.second, ncpus_);
});
}
else
{
sort_by_key(map.key_.args_, values_by_key);
};
for (auto &pair : values_by_key)
{
auto key = pair.first;
auto value = pair.second;
std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": ";
if (map.type_.type == Type::stack)
std::cout << get_stack(*(uint32_t*)value.data(), false, 8);
else if (map.type_.type == Type::ustack)
std::cout << get_stack(*(uint32_t*)value.data(), true, 8);
else if (map.type_.type == Type::sym)
std::cout << resolve_sym(*(uintptr_t*)value.data());
else if (map.type_.type == Type::usym)
std::cout << resolve_usym(*(uintptr_t*)value.data());
else if (map.type_.type == Type::string)
std::cout << value.data() << std::endl;
else if (map.type_.type == Type::count)
std::cout << reduce_value(value, ncpus_) << std::endl;
else
std::cout << *(int64_t*)value.data() << std::endl;
}
std::cout << std::endl;
return 0;
}
int BPFtrace::print_map_quantize(IMap &map)
{
// A quantize-map adds an extra 8 bytes onto the end of its key for storing
// the bucket number.
// e.g. A map defined as: @x[1, 2] = @quantize(3);
// would actually be stored with the key: [1, 2, 3]
std::vector<uint8_t> old_key;
try
{
old_key = find_empty_key(map, map.key_.size() + 8);
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);
std::map<std::vector<uint8_t>, std::vector<uint64_t>> values_by_key;
while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0)
{
auto key_prefix = std::vector<uint8_t>(map.key_.size());
int bucket = key.at(map.key_.size());
for (size_t i=0; i<map.key_.size(); i++)
key_prefix.at(i) = key.at(i);
int value_size = map.type_.size * ncpus_;
auto value = std::vector<uint8_t>(value_size);
int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data());
if (err)
{
std::cerr << "Error looking up elem: " << err << std::endl;
return -1;
}
if (values_by_key.find(key_prefix) == values_by_key.end())
{
// New key - create a list of buckets for it
values_by_key[key_prefix] = std::vector<uint64_t>(65);
}
values_by_key[key_prefix].at(bucket) = reduce_value(value, ncpus_);
old_key = key;
}
// Sort based on sum of counts in all buckets
std::vector<std::pair<std::vector<uint8_t>, uint64_t>> total_counts_by_key;
for (auto &map_elem : values_by_key)
{
int sum = 0;
for (size_t i=0; i<map_elem.second.size(); i++)
{
sum += map_elem.second.at(i);
}
total_counts_by_key.push_back({map_elem.first, sum});
}
std::sort(total_counts_by_key.begin(), total_counts_by_key.end(), [&](auto &a, auto &b)
{
return a.second < b.second;
});
for (auto &key_count : total_counts_by_key)
{
auto &key = key_count.first;
auto &value = values_by_key[key];
std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": " << std::endl;
print_quantize(value);
std::cout << std::endl;
}
return 0;
}
int BPFtrace::print_quantize(const std::vector<uint64_t> &values) const
{
int max_index = -1;
int max_value = 0;
for (size_t i = 0; i < values.size(); i++)
{
int v = values.at(i);
if (v != 0)
max_index = i;
if (v > max_value)
max_value = v;
}
if (max_index == -1)
return 0;
for (int i = 0; i <= max_index; i++)
{
std::ostringstream header;
if (i == 0)
{
header << "[0, 1]";
}
else
{
header << "[" << quantize_index_label(i);
header << ", " << quantize_index_label(i+1) << ")";
}
int max_width = 52;
int bar_width = values.at(i)/(float)max_value*max_width;
std::string bar(bar_width, '@');
std::cout << std::setw(16) << std::left << header.str()
<< std::setw(8) << std::right << values.at(i)
<< " |" << std::setw(max_width) << std::left << bar << "|"
<< std::endl;
}
return 0;
}
std::string BPFtrace::quantize_index_label(int power)
{
char suffix = '\0';
if (power >= 40)
{
suffix = 'T';
power -= 40;
}
else if (power >= 30)
{
suffix = 'G';
power -= 30;
}
else if (power >= 20)
{
suffix = 'M';
power -= 20;
}
else if (power >= 10)
{
suffix = 'k';
power -= 10;
}
std::ostringstream label;
label << (1<<power);
if (suffix)
label << suffix;
return label.str();
}
uint64_t BPFtrace::reduce_value(const std::vector<uint8_t> &value, int ncpus)
{
uint64_t sum = 0;
for (int i=0; i<ncpus; i++)
{
sum += *(uint64_t*)(value.data() + i*sizeof(uint64_t*));
}
return sum;
}
std::vector<uint8_t> BPFtrace::find_empty_key(IMap &map, size_t size) const
{
if (size == 0) size = 8;
auto key = std::vector<uint8_t>(size);
int value_size = map.type_.size;
if (map.type_.type == Type::count || map.type_.type == Type::quantize)
value_size *= ncpus_;
auto value = std::vector<uint8_t>(value_size);
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
for (auto &elem : key) elem = 0xff;
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
for (auto &elem : key) elem = 0x55;
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
throw std::runtime_error("Could not find empty key");
}
std::string BPFtrace::get_stack(uint32_t stackid, bool ustack, int indent)
{
auto stack_trace = std::vector<uint64_t>(MAX_STACK_SIZE);
int err = bpf_lookup_elem(stackid_map_->mapfd_, &stackid, stack_trace.data());
if (err)
{
std::cerr << "Error looking up stack id " << stackid << ": " << err << std::endl;
return "";
}
std::ostringstream stack;
std::string padding(indent, ' ');
stack << "\n";
for (auto &addr : stack_trace)
{
if (addr == 0)
break;
if (!ustack)
stack << padding << resolve_sym(addr, true) << std::endl;
else
stack << padding << resolve_usym(addr) << std::endl;
}
return stack.str();
}
std::string BPFtrace::resolve_sym(uintptr_t addr, bool show_offset)
{
struct bcc_symbol sym;
std::ostringstream symbol;
if (ksyms_.resolve_addr(addr, &sym))
{
symbol << sym.name;
if (show_offset)
symbol << "+" << sym.offset;
}
else
{
symbol << (void*)addr;
}
return symbol.str();
}
std::string BPFtrace::resolve_usym(uintptr_t addr) const
{
// TODO
std::ostringstream symbol;
symbol << (void*)addr;
return symbol.str();
}
void BPFtrace::sort_by_key(std::vector<SizedType> key_args,
std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> &values_by_key)
{
int arg_offset = 0;
for (auto arg : key_args)
{
arg_offset += arg.size;
}
// Sort the key arguments in reverse order so the results are sorted by
// the first argument first, then the second, etc.
for (size_t i=key_args.size(); i-- > 0; )
{
auto arg = key_args.at(i);
arg_offset -= arg.size;
if (arg.type == Type::integer)
{
if (arg.size == 8)
{
std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return *(uint64_t*)(a.first.data() + arg_offset) < *(uint64_t*)(b.first.data() + arg_offset);
});
}
else
abort();
}
else if (arg.type == Type::string)
{
std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return strncmp((char*)(a.first.data() + arg_offset),
(char*)(b.first.data() + arg_offset),
STRING_SIZE) < 0;
});
}
// Other types don't get sorted
}
}
} // namespace bpftrace
|
ajor/bpftrace
|
src/bpftrace.cpp
|
C++
|
apache-2.0
| 17,280 |
/*
* Copyright 2012 GitHub 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 com.github.zion.ui.gist;
import com.github.zion.core.ResourcePager;
import com.github.zion.core.gist.GistPager;
import org.eclipse.egit.github.core.Gist;
import org.eclipse.egit.github.core.client.PageIterator;
/**
* Fragment to display a list of Gists
*/
public class StarredGistsFragment extends GistsFragment {
@Override
protected ResourcePager<Gist> createPager() {
return new GistPager(store) {
@Override
public PageIterator<Gist> createIterator(int page, int size) {
return service.pageStarredGists(page, size);
}
};
}
}
|
DeLaSalleUniversity-Manila/ForkHub-macexcel
|
app/src/main/java/com/github/zion/ui/gist/StarredGistsFragment.java
|
Java
|
apache-2.0
| 1,214 |
/*
* Copyright 2014 Red Hat, 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.
*/
// This is a generated file. Not intended for manual editing.
package com.intellij.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.lang.yang.psi.YangTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.psi.*;
public class YangPrefixStmtImpl extends ASTWrapperPsiElement implements YangPrefixStmt {
public YangPrefixStmtImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof YangVisitor) ((YangVisitor)visitor).visitPrefixStmt(this);
else super.accept(visitor);
}
@Override
@NotNull
public YangStmtend getStmtend() {
return findNotNullChildByClass(YangStmtend.class);
}
@Override
@NotNull
public YangString getString() {
return findNotNullChildByClass(YangString.class);
}
}
|
dave-tucker/intellij-yang
|
gen/com/intellij/lang/psi/impl/YangPrefixStmtImpl.java
|
Java
|
apache-2.0
| 1,626 |
// 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.cloud.storage.upload.params;
import com.cloud.hypervisor.Hypervisor;
import java.util.Map;
public abstract class UploadParamsBase implements UploadParams {
private boolean isIso;
private long userId;
private String name;
private String displayText;
private Integer bits;
private boolean passwordEnabled;
private boolean requiresHVM;
private boolean isPublic;
private boolean featured;
private boolean isExtractable;
private String format;
private Long guestOSId;
private Long zoneId;
private Hypervisor.HypervisorType hypervisorType;
private String checksum;
private boolean bootable;
private String templateTag;
private long templateOwnerId;
private Map details;
private boolean sshkeyEnabled;
private boolean isDynamicallyScalable;
private boolean isRoutingType;
UploadParamsBase(long userId, String name, String displayText,
Integer bits, boolean passwordEnabled, boolean requiresHVM,
boolean isPublic, boolean featured,
boolean isExtractable, String format, Long guestOSId,
Long zoneId, Hypervisor.HypervisorType hypervisorType, String checksum,
String templateTag, long templateOwnerId,
Map details, boolean sshkeyEnabled,
boolean isDynamicallyScalable, boolean isRoutingType) {
this.userId = userId;
this.name = name;
this.displayText = displayText;
this.bits = bits;
this.passwordEnabled = passwordEnabled;
this.requiresHVM = requiresHVM;
this.isPublic = isPublic;
this.featured = featured;
this.isExtractable = isExtractable;
this.format = format;
this.guestOSId = guestOSId;
this.zoneId = zoneId;
this.hypervisorType = hypervisorType;
this.checksum = checksum;
this.templateTag = templateTag;
this.templateOwnerId = templateOwnerId;
this.details = details;
this.sshkeyEnabled = sshkeyEnabled;
this.isDynamicallyScalable = isDynamicallyScalable;
this.isRoutingType = isRoutingType;
}
UploadParamsBase(long userId, String name, String displayText, boolean isPublic, boolean isFeatured,
boolean isExtractable, Long osTypeId, Long zoneId, boolean bootable, long ownerId) {
this.userId = userId;
this.name = name;
this.displayText = displayText;
this.isPublic = isPublic;
this.featured = isFeatured;
this.isExtractable = isExtractable;
this.guestOSId = osTypeId;
this.zoneId = zoneId;
this.bootable = bootable;
this.templateOwnerId = ownerId;
}
@Override
public boolean isIso() {
return isIso;
}
@Override
public long getUserId() {
return userId;
}
@Override
public String getName() {
return name;
}
@Override
public String getDisplayText() {
return displayText;
}
@Override
public Integer getBits() {
return bits;
}
@Override
public boolean isPasswordEnabled() {
return passwordEnabled;
}
@Override
public boolean requiresHVM() {
return requiresHVM;
}
@Override
public String getUrl() {
return null;
}
@Override
public boolean isPublic() {
return isPublic;
}
@Override
public boolean isFeatured() {
return featured;
}
@Override
public boolean isExtractable() {
return isExtractable;
}
@Override
public String getFormat() {
return format;
}
@Override
public Long getGuestOSId() {
return guestOSId;
}
@Override
public Long getZoneId() {
return zoneId;
}
@Override
public Hypervisor.HypervisorType getHypervisorType() {
return hypervisorType;
}
@Override
public String getChecksum() {
return checksum;
}
@Override
public boolean isBootable() {
return bootable;
}
@Override
public String getTemplateTag() {
return templateTag;
}
@Override
public long getTemplateOwnerId() {
return templateOwnerId;
}
@Override
public Map getDetails() {
return details;
}
@Override
public boolean isSshKeyEnabled() {
return sshkeyEnabled;
}
@Override
public String getImageStoreUuid() {
return null;
}
@Override
public boolean isDynamicallyScalable() {
return isDynamicallyScalable;
}
@Override
public boolean isRoutingType() {
return isRoutingType;
}
@Override
public boolean isDirectDownload() {
return false;
}
void setIso(boolean iso) {
isIso = iso;
}
void setBootable(boolean bootable) {
this.bootable = bootable;
}
void setBits(Integer bits) {
this.bits = bits;
}
void setFormat(String format) {
this.format = format;
}
void setRequiresHVM(boolean requiresHVM) {
this.requiresHVM = requiresHVM;
}
void setHypervisorType(Hypervisor.HypervisorType hypervisorType) {
this.hypervisorType = hypervisorType;
}
}
|
DaanHoogland/cloudstack
|
server/src/main/java/com/cloud/storage/upload/params/UploadParamsBase.java
|
Java
|
apache-2.0
| 6,233 |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.RabbitMqTransport
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Logging;
/// <summary>
/// Creates an IHostnameSelector which sequentially chooses the next host name from the provided list based on index
/// </summary>
public class SequentialHostnameSelector :
IRabbitMqHostNameSelector
{
static readonly ILog _log = Logger.Get<SequentialHostnameSelector>();
string _lastHost;
int _nextHostIndex;
public SequentialHostnameSelector()
{
_nextHostIndex = 0;
_lastHost = "";
}
public string NextFrom(IList<string> options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
if (options.All(string.IsNullOrWhiteSpace))
throw new ArgumentException("There must be at least one host to use a hostname selector.", nameof(options));
do
{
_lastHost = options[_nextHostIndex % options.Count];
}
while (string.IsNullOrWhiteSpace(_lastHost));
if (_log.IsDebugEnabled)
_log.Debug($"Returning next host: {_lastHost}");
Interlocked.Increment(ref _nextHostIndex);
return _lastHost;
}
public string LastHost => _lastHost;
}
}
|
jsmale/MassTransit
|
src/MassTransit.RabbitMqTransport/SequentialHostnameSelector.cs
|
C#
|
apache-2.0
| 2,154 |
package com.neustar.ultraservice.schema.v01;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for HeaderRule complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="HeaderRule">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* <attribute name="headerField" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="matchCriteria" use="required" type="{http://schema.ultraservice.neustar.com/v01/}MatchCriteria" />
* <attribute name="headerValue" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="caseInsensitive" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HeaderRule")
public class HeaderRule {
@XmlAttribute(name = "headerField", required = true)
protected String headerField;
@XmlAttribute(name = "matchCriteria", required = true)
protected MatchCriteria matchCriteria;
@XmlAttribute(name = "headerValue", required = true)
protected String headerValue;
@XmlAttribute(name = "caseInsensitive", required = true)
protected boolean caseInsensitive;
/**
* Gets the value of the headerField property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHeaderField() {
return headerField;
}
/**
* Sets the value of the headerField property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHeaderField(String value) {
this.headerField = value;
}
/**
* Gets the value of the matchCriteria property.
*
* @return
* possible object is
* {@link MatchCriteria }
*
*/
public MatchCriteria getMatchCriteria() {
return matchCriteria;
}
/**
* Sets the value of the matchCriteria property.
*
* @param value
* allowed object is
* {@link MatchCriteria }
*
*/
public void setMatchCriteria(MatchCriteria value) {
this.matchCriteria = value;
}
/**
* Gets the value of the headerValue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHeaderValue() {
return headerValue;
}
/**
* Sets the value of the headerValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHeaderValue(String value) {
this.headerValue = value;
}
/**
* Gets the value of the caseInsensitive property.
*
*/
public boolean isCaseInsensitive() {
return caseInsensitive;
}
/**
* Sets the value of the caseInsensitive property.
*
*/
public void setCaseInsensitive(boolean value) {
this.caseInsensitive = value;
}
}
|
ultradns/ultra-java-api
|
src/main/java/com/neustar/ultraservice/schema/v01/HeaderRule.java
|
Java
|
apache-2.0
| 3,436 |
# Copyright 2011 OpenStack Foundation
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 Grid Dynamics
# Copyright 2011 Eldar Nugaev, Kirill Shileev, Ilya Alekseyev
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import webob
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import compute
from nova.compute import utils as compute_utils
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova import network
from nova.openstack.common import log as logging
from nova.openstack.common import uuidutils
LOG = logging.getLogger(__name__)
authorize = extensions.extension_authorizer('compute', 'floating_ips')
def make_float_ip(elem):
elem.set('id')
elem.set('ip')
elem.set('pool')
elem.set('fixed_ip')
elem.set('instance_id')
class FloatingIPTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('floating_ip',
selector='floating_ip')
make_float_ip(root)
return xmlutil.MasterTemplate(root, 1)
class FloatingIPsTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('floating_ips')
elem = xmlutil.SubTemplateElement(root, 'floating_ip',
selector='floating_ips')
make_float_ip(elem)
return xmlutil.MasterTemplate(root, 1)
def _translate_floating_ip_view(floating_ip):
result = {
'id': floating_ip['id'],
'ip': floating_ip['address'],
'pool': floating_ip['pool'],
}
try:
result['fixed_ip'] = floating_ip['fixed_ip']['address']
except (TypeError, KeyError, AttributeError):
result['fixed_ip'] = None
try:
result['instance_id'] = floating_ip['fixed_ip']['instance_uuid']
except (TypeError, KeyError, AttributeError):
result['instance_id'] = None
return {'floating_ip': result}
def _translate_floating_ips_view(floating_ips):
return {'floating_ips': [_translate_floating_ip_view(ip)['floating_ip']
for ip in floating_ips]}
def get_instance_by_floating_ip_addr(self, context, address):
snagiibfa = self.network_api.get_instance_id_by_floating_address
instance_id = snagiibfa(context, address)
if instance_id:
return self.compute_api.get(context, instance_id)
def disassociate_floating_ip(self, context, instance, address):
try:
self.network_api.disassociate_floating_ip(context, instance, address)
except exception.Forbidden:
raise webob.exc.HTTPForbidden()
except exception.CannotDisassociateAutoAssignedFloatingIP:
msg = _('Cannot disassociate auto assigned floating ip')
raise webob.exc.HTTPForbidden(explanation=msg)
class FloatingIPController(object):
"""The Floating IPs API controller for the OpenStack API."""
def __init__(self):
self.compute_api = compute.API()
self.network_api = network.API()
super(FloatingIPController, self).__init__()
@wsgi.serializers(xml=FloatingIPTemplate)
def show(self, req, id):
"""Return data about the given floating ip."""
context = req.environ['nova.context']
authorize(context)
try:
floating_ip = self.network_api.get_floating_ip(context, id)
except (exception.NotFound, exception.InvalidID):
msg = _("Floating ip not found for id %s") % id
raise webob.exc.HTTPNotFound(explanation=msg)
return _translate_floating_ip_view(floating_ip)
@wsgi.serializers(xml=FloatingIPsTemplate)
def index(self, req):
"""Return a list of floating ips allocated to a project."""
context = req.environ['nova.context']
authorize(context)
floating_ips = self.network_api.get_floating_ips_by_project(context)
return _translate_floating_ips_view(floating_ips)
@wsgi.serializers(xml=FloatingIPTemplate)
def create(self, req, body=None):
context = req.environ['nova.context']
authorize(context)
pool = None
if body and 'pool' in body:
pool = body['pool']
try:
address = self.network_api.allocate_floating_ip(context, pool)
ip = self.network_api.get_floating_ip_by_address(context, address)
except exception.NoMoreFloatingIps:
if pool:
msg = _("No more floating ips in pool %s.") % pool
else:
msg = _("No more floating ips available.")
raise webob.exc.HTTPNotFound(explanation=msg)
except exception.FloatingIpLimitExceeded:
if pool:
msg = _("IP allocation over quota in pool %s.") % pool
else:
msg = _("IP allocation over quota.")
raise webob.exc.HTTPForbidden(explanation=msg)
except exception.FloatingIpPoolNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
return _translate_floating_ip_view(ip)
def delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
# get the floating ip object
try:
floating_ip = self.network_api.get_floating_ip(context, id)
except (exception.NotFound, exception.InvalidID):
msg = _("Floating ip not found for id %s") % id
raise webob.exc.HTTPNotFound(explanation=msg)
address = floating_ip['address']
# get the associated instance object (if any)
instance = get_instance_by_floating_ip_addr(self, context, address)
try:
self.network_api.disassociate_and_release_floating_ip(
context, instance, floating_ip)
except exception.Forbidden:
raise webob.exc.HTTPForbidden()
except exception.CannotDisassociateAutoAssignedFloatingIP:
msg = _('Cannot disassociate auto assigned floating ip')
raise webob.exc.HTTPForbidden(explanation=msg)
return webob.Response(status_int=202)
class FloatingIPActionController(wsgi.Controller):
def __init__(self, ext_mgr=None, *args, **kwargs):
super(FloatingIPActionController, self).__init__(*args, **kwargs)
self.compute_api = compute.API()
self.network_api = network.API()
self.ext_mgr = ext_mgr
@wsgi.action('addFloatingIp')
def _add_floating_ip(self, req, id, body):
"""Associate floating_ip to an instance."""
context = req.environ['nova.context']
authorize(context)
try:
address = body['addFloatingIp']['address']
except TypeError:
msg = _("Missing parameter dict")
raise webob.exc.HTTPBadRequest(explanation=msg)
except KeyError:
msg = _("Address not specified")
raise webob.exc.HTTPBadRequest(explanation=msg)
instance = common.get_instance(self.compute_api, context, id)
cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
if not cached_nwinfo:
msg = _('No nw_info cache associated with instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
fixed_ips = cached_nwinfo.fixed_ips()
if not fixed_ips:
msg = _('No fixed ips associated to instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
fixed_address = None
if self.ext_mgr.is_loaded('os-extended-floating-ips'):
if 'fixed_address' in body['addFloatingIp']:
fixed_address = body['addFloatingIp']['fixed_address']
for fixed in fixed_ips:
if fixed['address'] == fixed_address:
break
else:
msg = _('Specified fixed address not assigned to instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
if not fixed_address:
fixed_address = fixed_ips[0]['address']
if len(fixed_ips) > 1:
LOG.warn(_LW('multiple fixed_ips exist, using the first: '
'%s'), fixed_address)
try:
self.network_api.associate_floating_ip(context, instance,
floating_address=address,
fixed_address=fixed_address)
except exception.FloatingIpAssociated:
msg = _('floating ip is already associated')
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NoFloatingIpInterface:
msg = _('l3driver call to add floating ip failed')
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.FloatingIpNotFoundForAddress:
msg = _('floating ip not found')
raise webob.exc.HTTPNotFound(explanation=msg)
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(explanation=e.format_message())
except Exception:
msg = _('Error. Unable to associate floating ip')
LOG.exception(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
return webob.Response(status_int=202)
@wsgi.action('removeFloatingIp')
def _remove_floating_ip(self, req, id, body):
"""Dissociate floating_ip from an instance."""
context = req.environ['nova.context']
authorize(context)
try:
address = body['removeFloatingIp']['address']
except TypeError:
msg = _("Missing parameter dict")
raise webob.exc.HTTPBadRequest(explanation=msg)
except KeyError:
msg = _("Address not specified")
raise webob.exc.HTTPBadRequest(explanation=msg)
# get the floating ip object
try:
floating_ip = self.network_api.get_floating_ip_by_address(context,
address)
except exception.FloatingIpNotFoundForAddress:
msg = _("floating ip not found")
raise webob.exc.HTTPNotFound(explanation=msg)
# get the associated instance object (if any)
instance = get_instance_by_floating_ip_addr(self, context, address)
# disassociate if associated
if (instance and
floating_ip.get('fixed_ip_id') and
(uuidutils.is_uuid_like(id) and
[instance['uuid'] == id] or
[instance['id'] == id])[0]):
try:
disassociate_floating_ip(self, context, instance, address)
except exception.FloatingIpNotAssociated:
msg = _('Floating ip is not associated')
raise webob.exc.HTTPBadRequest(explanation=msg)
return webob.Response(status_int=202)
else:
msg = _("Floating ip %(address)s is not associated with instance "
"%(id)s.") % {'address': address, 'id': id}
raise webob.exc.HTTPUnprocessableEntity(explanation=msg)
class Floating_ips(extensions.ExtensionDescriptor):
"""Floating IPs support."""
name = "FloatingIps"
alias = "os-floating-ips"
namespace = "http://docs.openstack.org/compute/ext/floating_ips/api/v1.1"
updated = "2011-06-16T00:00:00Z"
def get_resources(self):
resources = []
res = extensions.ResourceExtension('os-floating-ips',
FloatingIPController(),
member_actions={})
resources.append(res)
return resources
def get_controller_extensions(self):
controller = FloatingIPActionController(self.ext_mgr)
extension = extensions.ControllerExtension(self, 'servers', controller)
return [extension]
|
jumpstarter-io/nova
|
nova/api/openstack/compute/contrib/floating_ips.py
|
Python
|
apache-2.0
| 12,423 |
/**
*
*/
package com.bimaas.exception;
import org.json.JSONObject;
/**
* Builds the errors and return a {@link JSONObject} with the error.
* <p>
* <code>
* {"response":
* {"error|warning": "error details"}
* }
* </code>
* </p>
*
* @author isuru
*
*/
public class JSONErrorBuilder {
/**
* Build the error as a json object.
*
* @param e
* to be included.
* @return {@link JSONObject} to be return.
*/
public static JSONObject getErrorResponse(String e) {
JSONObject errorResponse = new JSONObject();
JSONObject error = new JSONObject();
error.put("error", e);
errorResponse.put("response", error);
return errorResponse;
}
/**
* Build the warning as a json object.
*
* @param e
* to be included.
* @return {@link JSONObject} to be return.
*/
public static JSONObject getWarningResponse(String e) {
JSONObject errorResponse = new JSONObject();
JSONObject error = new JSONObject();
error.put("warning", e);
errorResponse.put("response", error);
return errorResponse;
}
}
|
bbrangeo/OpenSourceBIMaaS
|
dev/foundation/src/main/java/com/bimaas/exception/JSONErrorBuilder.java
|
Java
|
apache-2.0
| 1,064 |
#/usr/bin/python
"""
Author: David Benson (dbenson@tssg.org)
Date: 02/09/2013
Description: This python module is responsible for storing information about all
systems within the eve universe.
"""
import system
import datetime
import evelink.api
class EveUniverse:
""" This class acts as a storage class for the all the space systems in Eve Online.
A very simple version control system is implemented using timestamps.
"""
def __init__(self):
# Constructor intialises empty array, the last updated timestamp and the connection to Eve APIs.
self.systems = {}
self.api = evelink.api.API()
self.current_timestamp = datetime.datetime.now()
def retrieve_systems(self):
# Method returns a list of all systems from eve api.
response = self.api.get('map/Sovereignty')
for item in response.iter('row'):
temp = system.System(item.attrib['solarSystemName'],
item.attrib['allianceID'], item.attrib['factionID'], item.attrib['corporationID'])
self.systems[item.attrib['solarSystemID']] = temp
self.current_timestamp = datetime.datetime.now()
def __repr__(self):
# Presents a string representation of the object.
result = "Last Updated: %s \n" % self.current_timestamp
result += self.systems.__str__()
return result
sys = EveUniverse()
sys.retrieve_systems()
print(sys.__repr__())
|
Funi1234/InternetSpaceships
|
python/main/eve_universe.py
|
Python
|
apache-2.0
| 1,437 |
package weixin.popular.bean.message.mass.sendall;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* 用于设定图文消息的接收者
* @author Moyq5
* @date 2016年9月17日
*/
public class Filter {
/**
* 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
*/
@JsonProperty("is_to_all")
private Boolean isToAll;
/**
* 群发到的标签的tag_id,参加用户管理中用户分组接口,若is_to_all值为true,可不填写tag_id
*/
@JsonProperty("tag_id")
private String tagId;
/**
* 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
* @return 是否向全部用户发送
*/
public Boolean getIsToAll() {
return isToAll;
}
/**
* 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
* @param isToAll 是否向全部用户发送
*/
public void setIsToAll(Boolean isToAll) {
this.isToAll = isToAll;
}
/**
* 群发到的标签的tag_id,参加用户管理中用户分组接口,若is_to_all值为true,可不填写tag_id
* @return 群发到的标签的tag_id
*/
public String getTagId() {
return tagId;
}
/**
* 群发到的标签的tag_id,参加用户管理中用户分组接口,若is_to_all值为true,可不填写tag_id
* @param tagId 群发到的标签的tag_id
*/
public void setTagId(String tagId) {
this.tagId = tagId;
}
}
|
moyq5/weixin-popular
|
src/main/java/weixin/popular/bean/message/mass/sendall/Filter.java
|
Java
|
apache-2.0
| 1,712 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.psi.search;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import javax.annotation.Nonnull;
public class EverythingGlobalScope extends GlobalSearchScope {
public EverythingGlobalScope(Project project) {
super(project);
}
public EverythingGlobalScope() {
}
@Nonnull
@Override
public String getDisplayName() {
return "All Places";
}
@Override
public int compare(@Nonnull final VirtualFile file1, @Nonnull final VirtualFile file2) {
return 0;
}
@Override
public boolean contains(@Nonnull final VirtualFile file) {
return true;
}
@Override
public boolean isSearchInLibraries() {
return true;
}
@Override
public boolean isSearchInModuleContent(@Nonnull final Module aModule) {
return true;
}
@Override
public boolean isSearchOutsideRootModel() {
return true;
}
@Nonnull
@Override
public GlobalSearchScope union(@Nonnull SearchScope scope) {
return this;
}
@Nonnull
@Override
public SearchScope intersectWith(@Nonnull SearchScope scope2) {
return scope2;
}
}
|
consulo/consulo
|
modules/base/core-api/src/main/java/com/intellij/psi/search/EverythingGlobalScope.java
|
Java
|
apache-2.0
| 1,792 |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LayoutModule } from '../layout/layout.module';
import { LandingPageComponent } from './landing-page.component';
describe('LandingPageComponent', () => {
let component: LandingPageComponent;
let fixture: ComponentFixture<LandingPageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LandingPageComponent],
imports: [LayoutModule.forRoot()]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LandingPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
|
manager-alert/manager-alert
|
src/app/landing-page/landing-page.component.spec.ts
|
TypeScript
|
apache-2.0
| 765 |
/*
* Copyright 2014-2021 Real Logic Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.agrona.agent;
import net.bytebuddy.asm.Advice;
import org.agrona.BitUtil;
import org.agrona.DirectBuffer;
/**
* Interceptor to be applied when verifying buffer alignment accesses.
*/
@SuppressWarnings("unused")
public class BufferAlignmentInterceptor
{
abstract static class Verifier
{
/**
* Interceptor for type alignment verifier.
*
* @param index into the buffer.
* @param buffer the buffer.
* @param alignment to be verified.
*/
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer, final int alignment)
{
final int alignmentOffset = (int)(buffer.addressOffset() + index) % alignment;
if (0 != alignmentOffset)
{
throw new BufferAlignmentException(
"Unaligned " + alignment + "-byte access (index=" + index + ", offset=" + alignmentOffset + ")");
}
}
}
/**
* Verifier for {@code long} types.
*/
public static final class LongVerifier extends Verifier
{
/**
* Verify alignment of the {@code long} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_LONG);
}
}
/**
* Verifier for {@code double} types.
*/
public static final class DoubleVerifier extends Verifier
{
/**
* Verify alignment of the {@code double} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_DOUBLE);
}
}
/**
* Verifier for {@code int} types.
*/
public static final class IntVerifier extends Verifier
{
/**
* Verify alignment of the {@code int} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_INT);
}
}
/**
* Verifier for {@code float} types.
*/
public static final class FloatVerifier extends Verifier
{
/**
* Verify alignment of the {@code float} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_FLOAT);
}
}
/**
* Verifier for {@code short} types.
*/
public static final class ShortVerifier extends Verifier
{
/**
* Verify alignment of the {@code short} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_SHORT);
}
}
/**
* Verifier for {@code char} types.
*/
public static final class CharVerifier extends Verifier
{
/**
* Verify alignment of the {@code char} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_CHAR);
}
}
}
|
real-logic/Agrona
|
agrona-agent/src/main/java/org/agrona/agent/BufferAlignmentInterceptor.java
|
Java
|
apache-2.0
| 4,703 |
package com.example.demo;
import java.util.Collection;
import java.util.stream.Stream;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@EnableDiscoveryClient
@SpringBootApplication
public class SimpleRestApiApplication {
@Bean
CommandLineRunner commandLineRunner(ReservationRepository reservationRepository) {
return strings -> {
Stream.of("Josh", "Peter", "Susi")
.forEach(n -> reservationRepository.save(new Reservation(n)));
};
}
public static void main(String[] args) {
SpringApplication.run(SimpleRestApiApplication.class, args);
}
}
@RepositoryRestResource
interface ReservationRepository extends JpaRepository<Reservation, Long>{
@RestResource(path="by-name")
Collection<Reservation> findByReservationName(@Param("rn") String rn);
}
@Entity
class Reservation{
@Id
@GeneratedValue
private Long id;
private String reservationName;
public Reservation() {
}
public Reservation(String n) {
this.reservationName= n;
}
public Long getId() {
return id;
}
public String getReservationName() {
return reservationName;
}
@Override
public String toString() {
return "Reservation{" +
"id= " + id +
", reservationName= '" + reservationName + "'";
}
}
@RefreshScope
@RestController
class MessageRestController {
@Value("${msg:Hello world - Config Server is not working..pelase check}")
private String msg;
@RequestMapping("/msg")
String getMsg() {
return this.msg;
}
}
|
manueldeveloper/springcloudconfigserver
|
SimpleRestAPI/src/main/java/com/example/demo/SimpleRestApiApplication.java
|
Java
|
apache-2.0
| 2,343 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 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.
*/
'use strict';
// MODULES //
var config = require( './config.js' );
// VARIABLES //
var valid;
var test;
// MAIN //
// Create our test cases:
valid = [];
test = {
'code': [
'/**',
'* Squares a number.',
'* ',
'* @param {number} x - input number',
'* @returns {number} x squared',
'*',
'* @example',
'* var y = square( 2.0 );',
'* // returns 4.0',
'*/',
'function square( x ) {',
' return x*x;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Returns a pseudo-random number on [0,1].',
'* ',
'* @returns {number} uniform random number',
'*',
'* @example',
'* var y = rand();',
'* // e.g., returns 0.5363925252089496',
'*/',
'function rand() {',
' return Math.random();',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Returns the number of minutes in a month.',
'*',
'* @param {(string|Date|integer)} [month] - month',
'* @param {integer} [year] - year',
'* @throws {TypeError} first argument must be either a string, integer, or `Date` object',
'* @throws {Error} must provide a recognized month',
'* @throws {RangeError} an integer month argument must be on the interval `[1,12]`',
'* @throws {TypeError} second argument must be an integer',
'* @returns {integer} minutes in a month',
'*',
'* @example',
'* var num = minutesInMonth();',
'* // returns <number>',
'*',
'* @example',
'* var num = minutesInMonth( 2 );',
'* // returns <number>',
'*',
'* @example',
'* var num = minutesInMonth( 2, 2016 );',
'* // returns 41760',
'*',
'* @example',
'* var num = minutesInMonth( 2, 2017 );',
'* // returns 40320',
'*/',
'function minutesInMonth( month, year ) {',
' var mins;',
' var mon;',
' var yr;',
' var d;',
' if ( arguments.length === 0 ) {',
' // Note: cannot cache as application may cross over into a new year:',
' d = new Date();',
' mon = d.getMonth() + 1; // zero-based',
' yr = d.getFullYear();',
' } else if ( arguments.length === 1 ) {',
' if ( isDateObject( month ) ) {',
' d = month;',
' mon = d.getMonth() + 1; // zero-based',
' yr = d.getFullYear();',
' } else if ( isString( month ) || isInteger( month ) ) {',
' // Note: cannot cache as application may cross over into a new year:',
' yr = ( new Date() ).getFullYear();',
' mon = month;',
' } else {',
' throw new TypeError( \'invalid argument. First argument must be either a string, integer, or `Date` object. Value: `\'+month+\'`.\' );',
' }',
' } else {',
' if ( !isString( month ) && !isInteger( month ) ) {',
' throw new TypeError( \'invalid argument. First argument must be either a string or integer. Value: `\'+month+\'`.\' );',
' }',
' if ( !isInteger( year ) ) {',
' throw new TypeError( \'invalid argument. Second argument must be an integer. Value: `\'+year+\'`.\' );',
' }',
' mon = month;',
' yr = year;',
' }',
' if ( isInteger( mon ) && (mon < 1 || mon > 12) ) {',
' throw new RangeError( \'invalid argument. An integer month value must be on the interval `[1,12]`. Value: `\'+mon+\'`.\' );',
' }',
' mon = lowercase( mon.toString() );',
' mins = MINUTES_IN_MONTH[ mon ];',
' if ( mins === void 0 ) {',
' throw new Error( \'invalid argument. Must provide a recognized month. Value: `\'+mon+\'`.\' );',
' }',
' // Check if February during a leap year...',
' if ( mins === 40320 && isLeapYear( yr ) ) {',
' mins += MINUTES_IN_DAY;',
' }',
' return mins;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Removes a UTF-8 byte order mark (BOM) from the beginning of a string.',
'*',
'* ## Notes',
'*',
'* - A UTF-8 byte order mark ([BOM][1]) is the byte sequence `0xEF,0xBB,0xBF`.',
'* - To convert a UTF-8 encoded `Buffer` to a `string`, the `Buffer` must be converted to \'[UTF-16][2]. The BOM thus gets converted to the single 16-bit code point `\'\ufeff\'` \'(UTF-16 BOM).',
'*',
'* [1]: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8',
'* [2]: http://es5.github.io/#x4.3.16',
'*',
'*',
'* @param {string} str - input string',
'* @throws {TypeError} must provide a string primitive',
'* @returns {string} string with BOM removed',
'*',
'* @example',
'* var str = removeUTF8BOM( \'\ufeffbeep\' );',
'* // returns \'beep\'',
'*/',
'function removeUTF8BOM( str ) {',
' if ( !isString( str ) ) {',
' throw new TypeError( \'invalid argument. Must provide a string primitive. Value: `\' + str + \'`.\' );',
' }',
' if ( str.charCodeAt( 0 ) === BOM ) {',
' return str.slice( 1 );',
' }',
' return str;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* @name arcsine',
'* @memberof random',
'* @readonly',
'* @type {Function}',
'* @see {@link module:@stdlib/random/base/arcsine}',
'*/',
'setReadOnly( random, \'arcsine\', require( \'@stdlib/random/base/arcsine\' ) );'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Beep boop.',
'*',
'* Some code...',
'*',
'* ```javascript',
'* var f = foo();',
'* ```',
'*',
'* Some LaTeX...',
'*',
'* ```tex',
'* \\frac{1}{2}',
'* ```',
'*',
'* ## Notes',
'*',
'* - First.',
'* - Second.',
'* - Third.',
'*',
'* ## References',
'*',
'* - Jane Doe. Science. 2017.',
'*',
'* | x | y |',
'* | 1 | 2 |',
'* | 2 | 1 |',
'*',
'*',
'* @param {string} str - input value',
'* @returns {string} output value',
'*',
'* @example',
'* var out = beep( "boop" );',
'* // returns "beepboop"',
'*/',
'function beep( str ) {',
'\treturn "beep" + str;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
// EXPORTS //
module.exports = valid;
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-markdown-remark/test/fixtures/valid.js
|
JavaScript
|
apache-2.0
| 6,669 |
#include <QSettings>
#include <QFileDialog>
#include "adduniquewindow.h"
#include "ui_adduniquewindow.h"
#include "functions.h"
#include "helpers.h"
#include "vendor/json.h"
#include "models/page.h"
#include "models/filename.h"
/**
* Constructor of the AddUniqueWindow class, generating its window.
* @param favorites List of favorites tags, needed for coloration
* @param parent The parent window
*/
AddUniqueWindow::AddUniqueWindow(QString selected, QMap<QString,Site*> sites, Profile *profile, QWidget *parent)
: QDialog(parent), ui(new Ui::AddUniqueWindow), m_sites(sites), m_profile(profile)
{
ui->setupUi(this);
ui->comboSites->addItems(m_sites.keys());
ui->comboSites->setCurrentIndex(m_sites.keys().indexOf(selected));
QSettings *settings = profile->getSettings();
ui->lineFolder->setText(settings->value("Save/path").toString());
ui->lineFilename->setText(settings->value("Save/filename").toString());
}
/**
* Ui events
*/
void AddUniqueWindow::on_buttonFolder_clicked()
{
QString folder = QFileDialog::getExistingDirectory(this, tr("Choose a save folder"), ui->lineFolder->text());
if (!folder.isEmpty())
{ ui->lineFolder->setText(folder); }
}
void AddUniqueWindow::on_lineFilename_textChanged(QString text)
{
QString message;
Filename fn(text);
fn.isValid(&message);
ui->labelFilename->setText(message);
}
/**
* Search for image in available websites.
*/
void AddUniqueWindow::add()
{ ok(false); }
void AddUniqueWindow::ok(bool close)
{
Site *site = m_sites[ui->comboSites->currentText()];
m_close = close;
bool useDirectLink = true;
if (
(site->value("Urls/Html/Post").contains("{id}") && ui->lineId->text().isEmpty()) ||
(site->value("Urls/Html/Post").contains("{md5}") && ui->lineMd5->text().isEmpty()) ||
!site->contains("Regex/ImageUrl")
)
{ useDirectLink = false; }
if (useDirectLink)
{
QString url = site->value("Urls/Html/Post");
url.replace("{id}", ui->lineId->text());
url.replace("{md5}", ui->lineMd5->text());
QMap<QString,QString> details = QMap<QString,QString>();
details.insert("page_url", url);
details.insert("id", ui->lineId->text());
details.insert("md5", ui->lineMd5->text());
details.insert("website", ui->comboSites->currentText());
details.insert("site", QString::number((qintptr)m_sites[ui->comboSites->currentText()]));
m_image = QSharedPointer<Image>(new Image(site, details, m_profile));
connect(m_image.data(), &Image::finishedLoadingTags, this, &AddUniqueWindow::addLoadedImage);
m_image->loadDetails();
}
else
{
m_page = new Page(m_profile, m_sites[ui->comboSites->currentText()], m_sites.values(), QStringList() << (ui->lineId->text().isEmpty() ? "md5:"+ui->lineMd5->text() : "id:"+ui->lineId->text()) << "status:any", 1, 1);
connect(m_page, SIGNAL(finishedLoading(Page*)), this, SLOT(replyFinished(Page*)));
m_page->load();
}
}
/**
* Signal triggered when the search is finished.
* @param r The QNetworkReply associated with the search
*/
void AddUniqueWindow::replyFinished(Page *p)
{
if (p->images().isEmpty())
{
p->deleteLater();
error(this, tr("No image found."));
return;
}
addImage(p->images().first());
p->deleteLater();
}
void AddUniqueWindow::addLoadedImage()
{
addImage(m_image);
}
void AddUniqueWindow::addImage(QSharedPointer<Image> img)
{
emit sendData(DownloadQueryImage(img, m_sites[ui->comboSites->currentText()], ui->lineFilename->text(), ui->lineFolder->text()));
if (m_close)
close();
}
|
YoukaiCat/imgbrd-grabber
|
gui/src/batch/adduniquewindow.cpp
|
C++
|
apache-2.0
| 3,454 |
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import * as tf from '../index';
import {ALL_ENVS, describeWithFlags} from '../jasmine_util';
import {expectArraysClose} from '../test_util';
describeWithFlags('sign', ALL_ENVS, () => {
it('basic', async () => {
const a = tf.tensor1d([1.5, 0, NaN, -1.4]);
const r = tf.sign(a);
expectArraysClose(await r.data(), [1, 0, 0, -1]);
});
it('does not propagate NaNs', async () => {
const a = tf.tensor1d([1.5, NaN, -1.4]);
const r = tf.sign(a);
expectArraysClose(await r.data(), [1, 0, -1]);
});
it('gradients: Scalar', async () => {
const a = tf.scalar(5.2);
const dy = tf.scalar(3);
const gradients = tf.grad(a => tf.sign(a))(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0]);
});
it('gradient with clones', async () => {
const a = tf.scalar(5.2);
const dy = tf.scalar(3);
const gradients = tf.grad(a => tf.sign(a.clone()).clone())(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0]);
});
it('gradients: Tensor1D', async () => {
const a = tf.tensor1d([-1.1, 2.6, 3, -5.9]);
const dy = tf.tensor1d([-1, 1, 1, -1]);
const gradients = tf.grad(a => tf.sign(a))(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0, 0, 0, 0]);
});
it('gradients: Tensor2D', async () => {
const a = tf.tensor2d([-3, 1, 2.2, 3], [2, 2]);
const dy = tf.tensor2d([1, 2, 3, 4], [2, 2]);
const gradients = tf.grad(a => tf.sign(a))(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0, 0, 0, 0]);
});
it('throws when passed a non-tensor', () => {
expect(() => tf.sign({} as tf.Tensor))
.toThrowError(/Argument 'x' passed to 'sign' must be a Tensor/);
});
it('accepts a tensor-like object', async () => {
const r = tf.sign([1.5, 0, NaN, -1.4]);
expectArraysClose(await r.data(), [1, 0, 0, -1]);
});
it('throws for string tensor', () => {
expect(() => tf.sign('q'))
.toThrowError(/Argument 'x' passed to 'sign' must be numeric/);
});
});
|
tensorflow/tfjs
|
tfjs-core/src/ops/sign_test.ts
|
TypeScript
|
apache-2.0
| 3,063 |
/*
* Copyright 2015-2016 OpenCB
*
* 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.opencb.opencga.storage.alignment.hbase;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.opencb.biodata.models.alignment.Alignment;
import org.opencb.biodata.models.alignment.stats.RegionCoverage;
import org.opencb.biodata.models.feature.Region;
import org.opencb.commons.containers.QueryResult;
import org.opencb.commons.containers.map.QueryOptions;
import org.opencb.opencga.core.auth.MonbaseCredentials;
import org.opencb.opencga.storage.alignment.AlignmentQueryBuilder;
import org.opencb.opencga.storage.alignment.AlignmentSummary;
import org.opencb.opencga.storage.alignment.proto.AlignmentProto;
import org.opencb.opencga.storage.alignment.proto.AlignmentProtoHelper;
import org.xerial.snappy.Snappy;
/**
* Created with IntelliJ IDEA.
* User: jcoll
* Date: 3/7/14
* Time: 10:12 AM
* To change this template use File | Settings | File Templates.
*/
public class AlignmentHBaseQueryBuilder implements AlignmentQueryBuilder {
HBaseManager manager;
String tableName, columnFamilyName = null;
public void connect(){
manager.connect();
}
// public AlignmentHBaseQueryBuilder(MonbaseCredentials credentials, String tableName) {
// manager = new HBaseManager(credentials);
// this.tableName = tableName;
// }
public AlignmentHBaseQueryBuilder(String tableName) {
}
public AlignmentHBaseQueryBuilder(Configuration config, String tableName) {
manager = new HBaseManager(config);
this.tableName = tableName;
}
@Override
public QueryResult getAllAlignmentsByRegion(Region region, QueryOptions options) {
boolean wasOpened = true;
if(!manager.isOpened()){
manager.connect();
wasOpened = false;
}
HTable table = manager.getTable(tableName);//manager.createTable(tableName, columnFamilyName);
if(table == null){
return null;
}
QueryResult<Alignment> queryResult = new QueryResult<>();
String sample = options.getString("sample", "HG00096");
String family = options.getString("family", "c");
int bucketSize = 256; //FIXME: HARDCODE!
//String startRow = region.getChromosome() + "_" + String.format("%07d", region.getStart() / bucketSize);
//String endRow = region.getChromosome() + "_" + String.format("%07d", region.getEnd() / bucketSize);
String startRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getStart(), bucketSize);
String endRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getEnd()+bucketSize, bucketSize);
System.out.println("Scaning from " + startRow + " to " + endRow);
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(endRow));
scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(sample));
scan.setMaxVersions(1);
// scan.setMaxResultSize()
ResultScanner resultScanner;
try {
resultScanner = table.getScanner(scan);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.err.println("[ERROR] -- Bad query");
return null;
}
Map<Integer, AlignmentSummary> summaryMap = new HashMap<>();
for(Result result : resultScanner){
for(Cell cell : result.listCells()){
//System.out.println("Qualifier : " + keyValue.getKeyString() + " : Value : "/* + Bytes.toString(keyValue.getValue())*/);
AlignmentProto.AlignmentBucket alignmentBucket = null;
try {
alignmentBucket = AlignmentProto.AlignmentBucket.parseFrom(Snappy.uncompress(CellUtil.cloneValue(cell)));
} catch (InvalidProtocolBufferException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
continue;
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
continue;
}
//System.out.println("Tenemos un bucket!");
AlignmentSummary summary;
if(!summaryMap.containsKey(alignmentBucket.getSummaryIndex())) {
summaryMap.put(alignmentBucket.getSummaryIndex(), getRegionSummary(region.getChromosome(), alignmentBucket.getSummaryIndex(), table));
}
summary = summaryMap.get(alignmentBucket.getSummaryIndex());
long pos = AlignmentHBase.getPositionFromRowkey(org.apache.hadoop.hbase.util.Bytes.toString(cell.getRowArray()), bucketSize);
List<Alignment> alignmentList = AlignmentProtoHelper.toAlignmentList(alignmentBucket, summary, region.getChromosome(), pos);
//System.out.println("Los tenemos!!");
for(Alignment alignment : alignmentList){
queryResult.addResult(alignment);
}
}
}
if(!wasOpened){
manager.disconnect();
}
return queryResult;
//return null;
}
private AlignmentSummary getRegionSummary(String chromosome, int index,HTable table){
// manager.connect();
// HTable table = manager.createTable(tableName, columnFamilyName);
Scan scan = new Scan(
Bytes.toBytes(AlignmentHBase.getSummaryRowkey(chromosome, index)) ,
Bytes.toBytes(AlignmentHBase.getSummaryRowkey(chromosome, index+1)));
ResultScanner resultScanner;
try {
resultScanner = table.getScanner(scan);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.err.println("[ERROR] -- Bad query");
return null;
}
AlignmentSummary summary = null;
for(Result result : resultScanner){
for(KeyValue keyValue : result.list()){
//System.out.println("Qualifier : " + keyValue.getKeyString() );
try {
summary = new AlignmentSummary( AlignmentProto.Summary.parseFrom(Snappy.uncompress(keyValue.getValue())), index);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
return summary;
}
@Override
public QueryResult getAllAlignmentsByGene(String gene, QueryOptions options) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public QueryResult getCoverageByRegion(Region region, QueryOptions options) {
QueryResult<RegionCoverage> queryResult = new QueryResult<>();
if (!manager.isOpened()) {
manager.connect();
}
String sample = options.getString("sample", "HG00096");
String family = options.getString("family", "c");
int bucketSize = 256; //FIXME: HARDCODE!
//String startRow = region.getChromosome() + "_" + String.format("%07d", region.getStart() / bucketSize);
//String endRow = region.getChromosome() + "_" + String.format("%07d", region.getEnd() / bucketSize);
String startRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getStart(), bucketSize);
String endRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getEnd() + bucketSize, bucketSize);
HTable table = manager.getTable(tableName);
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(endRow));
scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(sample));
scan.setMaxVersions(1);
ResultScanner scanner;
try {
scanner = table.getScanner(scan);
} catch (IOException ex) {
Logger.getLogger(AlignmentHBaseQueryBuilder.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
for (Result result : scanner) {
for (Cell cell : result.listCells()) {
AlignmentProto.Coverage parseFrom;
try {
parseFrom = AlignmentProto.Coverage.parseFrom(CellUtil.cloneValue(cell));
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(AlignmentHBaseQueryBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return queryResult;
}
@Override
public QueryResult getAlignmentsHistogramByRegion(Region region, boolean histogramLogarithm, int histogramMax) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public QueryResult getAlignmentRegionInfo(Region region, QueryOptions options) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getColumnFamilyName() {
return columnFamilyName;
}
public void setColumnFamilyName(String columnFamilyName) {
this.columnFamilyName = columnFamilyName;
}
}
|
javild/opencga
|
opencga-storage/src/main/java/org/opencb/opencga/storage/alignment/hbase/AlignmentHBaseQueryBuilder.java
|
Java
|
apache-2.0
| 10,790 |
"""Check that available RPM packages match the required versions."""
from openshift_checks import OpenShiftCheck
from openshift_checks.mixins import NotContainerizedMixin
class PackageVersion(NotContainerizedMixin, OpenShiftCheck):
"""Check that available RPM packages match the required versions."""
name = "package_version"
tags = ["preflight"]
# NOTE: versions outside those specified are mapped to least/greatest
openshift_to_ovs_version = {
(3, 4): "2.4",
(3, 5): ["2.6", "2.7"],
(3, 6): ["2.6", "2.7", "2.8", "2.9"],
(3, 7): ["2.6", "2.7", "2.8", "2.9"],
(3, 8): ["2.6", "2.7", "2.8", "2.9"],
(3, 9): ["2.6", "2.7", "2.8", "2.9"],
(3, 10): ["2.6", "2.7", "2.8", "2.9"],
}
openshift_to_docker_version = {
(3, 1): "1.8",
(3, 2): "1.10",
(3, 3): "1.10",
(3, 4): "1.12",
(3, 5): "1.12",
(3, 6): "1.12",
(3, 7): "1.12",
(3, 8): "1.12",
(3, 9): ["1.12", "1.13"],
}
def is_active(self):
"""Skip hosts that do not have package requirements."""
group_names = self.get_var("group_names", default=[])
master_or_node = 'oo_masters_to_config' in group_names or 'oo_nodes_to_config' in group_names
return super(PackageVersion, self).is_active() and master_or_node
def run(self):
rpm_prefix = self.get_var("openshift_service_type")
if self._templar is not None:
rpm_prefix = self._templar.template(rpm_prefix)
openshift_release = self.get_var("openshift_release", default='')
deployment_type = self.get_var("openshift_deployment_type")
check_multi_minor_release = deployment_type in ['openshift-enterprise']
args = {
"package_mgr": self.get_var("ansible_pkg_mgr"),
"package_list": [
{
"name": "openvswitch",
"version": self.get_required_ovs_version(),
"check_multi": False,
},
{
"name": "docker",
"version": self.get_required_docker_version(),
"check_multi": False,
},
{
"name": "{}".format(rpm_prefix),
"version": openshift_release,
"check_multi": check_multi_minor_release,
},
{
"name": "{}-master".format(rpm_prefix),
"version": openshift_release,
"check_multi": check_multi_minor_release,
},
{
"name": "{}-node".format(rpm_prefix),
"version": openshift_release,
"check_multi": check_multi_minor_release,
},
],
}
return self.execute_module_with_retries("aos_version", args)
def get_required_ovs_version(self):
"""Return the correct Open vSwitch version(s) for the current OpenShift version."""
return self.get_required_version("Open vSwitch", self.openshift_to_ovs_version)
def get_required_docker_version(self):
"""Return the correct Docker version(s) for the current OpenShift version."""
return self.get_required_version("Docker", self.openshift_to_docker_version)
|
wbrefvem/openshift-ansible
|
roles/openshift_health_checker/openshift_checks/package_version.py
|
Python
|
apache-2.0
| 3,386 |
/*******************************************************************************
* 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.am0e.utils;
public interface Handler<T> {
public void handle(T ctx) throws Exception;
}
|
am0e/commons
|
src/main/java/com/github/am0e/utils/Handler.java
|
Java
|
apache-2.0
| 1,071 |
from .layout_helpers import *
|
armstrong/armstrong.core.arm_layout
|
tests/templatetags/__init__.py
|
Python
|
apache-2.0
| 30 |
package wx.sunl.entry;
/**
* WeixinUserInfo(΢ÐÅÓû§µÄ»ù±¾ÐÅÏ¢)
* @author Youngman
*/
public class WeixinOauth2Token {
// ÍøÒ³ÊÚȨ½Ó¿Úµ÷ÓÃÆ¾Ö¤
private String accessToken;
// ƾ֤ÓÐЧʱ³¤
private int expiresIn;
// ÓÃÓÚË¢ÐÂÆ¾Ö¤
private String refreshToken;
// Óû§±êʶ
private String openId;
// Óû§ÊÚȨ×÷ÓÃÓò
private String scope;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
|
Youngman619/cwkz
|
src/wx/sunl/entry/WeixinOauth2Token.java
|
Java
|
apache-2.0
| 1,035 |