code
stringlengths
4
1.01M
language
stringclasses
2 values
<html> <body> <table width="100%" height="100%" border="1"> <tr height="18"> <td width="20">_</td><td>_</td><td width="8">_</td><td width="50%">_</td><td width="50%">_</td><td width="20">_</td> </tr> <tr> <td></td><td colspan="4" align="full">description</td> </tr> <tr height="8"></tr> <tr> <td></td><td colspan="4" align="full">error_lbl</td> </tr> <tr height="8"></tr> <tr> <td></td><td align="right">address_lbl</td><td></td><td align="full" colspan="2">address</td> </tr> <tr height="8"></tr> <tr> <td></td><td align="right">name_lbl</td><td></td><td align="full" colspan="2">name</td> </tr> <tr height="8"></tr> <tr> <td></td><td align="right">title_lbl</td><td></td><td align="full" colspan="2">title</td> </tr> <tr height="8"></tr> <tr> <td></td><td></td><td></td><td></td><td align="right">separate_vm</td> </tr> <tr height="100%"><td>_</td></tr> </table> </body> </html>
Java
-- CREATE DATABASE CREATE DATABASE agile_metrics WITH ENCODING='UTF8' OWNER=postgres CONNECTION LIMIT=-1; -- Table: "user" -- DROP TABLE "user"; CREATE TABLE "user" ( id bigserial NOT NULL, asana_id bigint, name character varying(200), email character varying(200), photo_url character varying(500), created_at timestamp with time zone NOT NULL DEFAULT now(), updated_at timestamp with time zone, deleted_at timestamp with time zone, username character varying(100), password character varying(100), CONSTRAINT pk_user_id PRIMARY KEY (id) ) WITH ( OIDS=FALSE ); ALTER TABLE "user" OWNER TO postgres; -- Table: token -- DROP TABLE token; CREATE TABLE token ( id bigserial NOT NULL, user_id bigint, created_at timestamp with time zone NOT NULL DEFAULT now(), updated_at timestamp with time zone, deleted_at timestamp with time zone, expiry timestamp with time zone, access_token character varying(500), refresh_token character varying(60), token_type character varying(50), CONSTRAINT pk_token_id PRIMARY KEY (id), CONSTRAINT fk_token_user_id FOREIGN KEY (user_id) REFERENCES "user" (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION ) WITH ( OIDS=FALSE ); ALTER TABLE token OWNER TO postgres; -- Index: fki_token_user_id -- DROP INDEX fki_token_user_id; CREATE INDEX fki_token_user_id ON token USING btree (user_id);
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <!-- Generated by javadoc (1.8.0_60) on Tue Mar 29 13:02:11 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>play.db.jpa (Play! API)</title> <meta name="date" content="2016-03-29"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="play.db.jpa (Play! API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../play/db/helper/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../play/deps/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?play/db/jpa/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;play.db.jpa</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/Blob.html" title="class in play.db.jpa">Blob</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/FileAttachment.html" title="class in play.db.jpa">FileAttachment</a></td> <td class="colLast">Deprecated</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/GenericModel.html" title="class in play.db.jpa">GenericModel</a></td> <td class="colLast"> <div class="block">A super class for JPA entities</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/GenericModel.JPAQuery.html" title="class in play.db.jpa">GenericModel.JPAQuery</a></td> <td class="colLast"> <div class="block">A JPAQuery</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/HibernateInterceptor.html" title="class in play.db.jpa">HibernateInterceptor</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPA.html" title="class in play.db.jpa">JPA</a></td> <td class="colLast"> <div class="block">JPA Support</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPA.JPAContext.html" title="class in play.db.jpa">JPA.JPAContext</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPABase.html" title="class in play.db.jpa">JPABase</a></td> <td class="colLast"> <div class="block">A super class for JPA entities</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPAEnhancer.html" title="class in play.db.jpa">JPAEnhancer</a></td> <td class="colLast"> <div class="block">Enhance JPABase entities classes</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPAModelLoader.html" title="class in play.db.jpa">JPAModelLoader</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPAPlugin.html" title="class in play.db.jpa">JPAPlugin</a></td> <td class="colLast"> <div class="block">JPA Plugin</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPASupport.html" title="class in play.db.jpa">JPASupport</a></td> <td class="colLast">Deprecated</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPASupport.JPAQuery.html" title="class in play.db.jpa">JPASupport.JPAQuery</a></td> <td class="colLast">Deprecated</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPQL.html" title="class in play.db.jpa">JPQL</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/Model.html" title="class in play.db.jpa">Model</a></td> <td class="colLast"> <div class="block">Base class for JPA model objects Automatically provide a @Id Long id field</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/MySQLDialect.html" title="class in play.db.jpa">MySQLDialect</a></td> <td class="colLast"> <div class="block">InnoDB, UTF-8 dialect for Mysql</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Exception Summary table, listing exceptions, and an explanation"> <caption><span>Exception Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Exception</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/JPABase.JPAQueryException.html" title="class in play.db.jpa">JPABase.JPAQueryException</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Annotation Types Summary table, listing annotation types, and an explanation"> <caption><span>Annotation Types Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Annotation Type</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../play/db/jpa/NoTransaction.html" title="annotation in play.db.jpa">NoTransaction</a></td> <td class="colLast"> <div class="block">Annotation to be used on methods telling JPA that it should not create a Transaction at all</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../play/db/jpa/Transactional.html" title="annotation in play.db.jpa">Transactional</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../play/db/helper/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../play/deps/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?play/db/jpa/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><a href="http://guillaume.bort.fr">Guillaume Bort</a> &amp; <a href="http://www.zenexity.fr">zenexity</a> - Distributed under <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2 licence</a>, without any warrantly</small></p> </body> </html>
Java
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "absl/container/flat_hash_map.h" #include "struct2tensor/kernels/parquet/parquet_reader.h" #include "struct2tensor/kernels/parquet/parquet_reader_util.h" #include "struct2tensor/kernels/vector_to_tensor.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/types.h" namespace struct2tensor { namespace parquet_dataset { class Dataset : public tensorflow::data::DatasetBase { public: explicit Dataset(tensorflow::OpKernelContext* ctx, const std::vector<std::string>& filenames, const std::vector<std::string>& value_paths, const tensorflow::DataTypeVector& value_dtypes, const std::vector<std::vector<int>>& segregated_path_indices, const tensorflow::int64 batch_size, const tensorflow::DataTypeVector& output_dtypes) : DatasetBase(tensorflow::data::DatasetContext(ctx)), filenames_(filenames), value_paths_(value_paths), value_dtypes_(value_dtypes), segregated_path_indices_(segregated_path_indices), batch_size_(batch_size), output_dtypes_(output_dtypes), output_shapes_([this]() { // The first output tensor is always the root size (number of messages // read) which is a scalar. Other output tensors are parent indices // so they are 1-D. std::vector<tensorflow::PartialTensorShape> shapes( output_dtypes_.size(), tensorflow::PartialTensorShape({-1})); shapes[0] = tensorflow::PartialTensorShape({}); return shapes; }()) {} std::unique_ptr<tensorflow::data::IteratorBase> MakeIteratorInternal( const std::string& prefix) const override { return absl::WrapUnique(new Iterator( {this, tensorflow::strings::StrCat(prefix, "::Parquet")}, filenames_, value_paths_, value_dtypes_, segregated_path_indices_, batch_size_)); } const tensorflow::DataTypeVector& output_dtypes() const override { return output_dtypes_; } const std::vector<tensorflow::PartialTensorShape>& output_shapes() const override { return output_shapes_; } std::string DebugString() const override { return "ParquetDatasetOp::Dataset"; } tensorflow::Status CheckExternalState() const { return tensorflow::Status::OK(); } protected: // TODO(andylou): Implement saving dataset state. tensorflow::Status AsGraphDefInternal( tensorflow::data::SerializationContext* ctx, DatasetGraphDefBuilder* b, tensorflow::Node** output) const override { return tensorflow::errors::Unimplemented( DebugString(), " does not support serialization."); } private: class Iterator : public tensorflow::data::DatasetIterator<Dataset> { public: explicit Iterator( const Params& params, const std::vector<std::string>& filenames, const std::vector<std::string>& value_paths, const tensorflow::DataTypeVector& value_dtypes, const std::vector<std::vector<int>>& segregated_path_indices, const tensorflow::int64 batch_size) : DatasetIterator<Dataset>(params), filenames_(filenames), value_paths_(value_paths), value_dtypes_(value_dtypes), segregated_path_indices_(segregated_path_indices), batch_size_(batch_size), current_file_index_(0) {} // For a deeper understanding of what tensors are returned in out_tensors, // see parquet_dataset_op.cc. tensorflow::Status GetNextInternal( tensorflow::data::IteratorContext* ctx, std::vector<tensorflow::Tensor>* out_tensors, bool* end_of_sequence) override { tensorflow::mutex_lock l(mu_); if (current_file_index_ >= filenames_.size()) { *end_of_sequence = true; return tensorflow::Status::OK(); } if (!parquet_reader_) { // Once a file is finished reading, this will create a ParquetReader // for the next file in file_names_. TF_RETURN_IF_ERROR( ValidateFileAndSchema(filenames_[current_file_index_])); TF_RETURN_IF_ERROR(ParquetReader::Create( filenames_[current_file_index_], value_paths_, value_dtypes_, batch_size_, &parquet_reader_)); } bool end_of_file = false; std::vector<ParquetReader::ParentIndicesAndValues> parent_indices_and_values; TF_RETURN_IF_ERROR(parquet_reader_->ReadMessages( ctx, &parent_indices_and_values, &end_of_file)); if (end_of_file) { ++current_file_index_; parquet_reader_.reset(); } // pushes the number of messages read as the first output tensor. tensorflow::Tensor root_tensor(ctx->allocator({}), tensorflow::DT_INT64, {}); if (parent_indices_and_values.size() != value_paths_.size()) { return tensorflow::errors::Internal(absl::StrCat( parent_indices_and_values.size(), " messages read, expected to read ", value_paths_.size())); } if (parent_indices_and_values[0].parent_indices.empty()) { return tensorflow::errors::Internal( absl::StrCat("0 messages read, expected to read ", batch_size_)); } root_tensor.flat<tensorflow::int64>()(0) = parent_indices_and_values[0].parent_indices[0].size(); out_tensors->push_back(std::move(root_tensor)); for (int column_index = 0; column_index < value_paths_.size(); ++column_index) { for (int path_index : segregated_path_indices_[column_index]) { tensorflow::Tensor res( ctx->allocator({}), tensorflow::DT_INT64, {static_cast<long long>(parent_indices_and_values[column_index] .parent_indices[path_index] .size())}); struct2tensor::VectorToTensor(parent_indices_and_values[column_index] .parent_indices[path_index], &res, /*produce_string_view=*/false); out_tensors->push_back(std::move(res)); } out_tensors->push_back( std::move(parent_indices_and_values[column_index].values)); } return tensorflow::Status::OK(); } protected: // TODO(b/139440495): Implement saving and restoring iterator state. tensorflow::Status SaveInternal( tensorflow::data::SerializationContext* ctx, tensorflow::data::IteratorStateWriter* writer) { return tensorflow::errors::Unimplemented( "Parquet Dataset Iterator does not support checkpointing."); } tensorflow::Status RestoreInternal( tensorflow::data::IteratorContext* ctx, tensorflow::data::IteratorStateReader* reader) { return tensorflow::errors::Unimplemented( "Parquet Dataset Iterator does not support checkpointing."); } private: // validates that the file exists and can be opened as a parquet file. // validates that the schema is the expected schema. tensorflow::Status ValidateFileAndSchema(const std::string& filename) { std::unique_ptr<parquet::ParquetFileReader> file_reader; tensorflow::Status s = OpenFileWithStatus(filename, &file_reader); absl::flat_hash_map<std::string, tensorflow::DataType> paths; std::shared_ptr<parquet::FileMetaData> file_metadata = file_reader->metadata(); for (int i = 0; i < file_metadata->num_columns(); ++i) { std::string path = file_metadata->schema()->Column(i)->path()->ToDotString(); switch (file_metadata->schema()->Column(i)->physical_type()) { case parquet::Type::INT32: paths[path] = tensorflow::DT_INT32; break; case parquet::Type::INT64: paths[path] = tensorflow::DT_INT64; break; case parquet::Type::FLOAT: paths[path] = tensorflow::DT_FLOAT; break; case parquet::Type::DOUBLE: paths[path] = tensorflow::DT_DOUBLE; break; case parquet::Type::BOOLEAN: paths[path] = tensorflow::DT_BOOL; break; case parquet::Type::BYTE_ARRAY: paths[path] = tensorflow::DT_STRING; break; default: return tensorflow::errors::Unimplemented(absl::StrCat( "This Parquet Data Type is unimplemented ", file_metadata->schema()->Column(i)->physical_type())); } } for (int i = 0; i < value_dtypes_.size(); ++i) { auto paths_iter = paths.find(value_paths_[i]); if (paths_iter == paths.end()) { return tensorflow::errors::InvalidArgument( absl::StrCat("path not found ", value_paths_[i])); } else if (paths_iter->second != value_dtypes_[i]) { return tensorflow::errors::InvalidArgument( absl::StrCat("This dtype is incorrect: ", value_dtypes_[i], ". dtype should be: ", paths_iter->second)); } } return s; } const std::vector<std::string>& filenames_; const std::vector<std::string>& value_paths_; const tensorflow::DataTypeVector& value_dtypes_; const std::vector<std::vector<int>>& segregated_path_indices_; const tensorflow::int64 batch_size_; int current_file_index_ ABSL_GUARDED_BY(mu_); std::unique_ptr<ParquetReader> parquet_reader_ ABSL_GUARDED_BY(mu_); tensorflow::mutex mu_; }; const std::vector<std::string> filenames_; const std::vector<std::string> value_paths_; const tensorflow::DataTypeVector value_dtypes_; // 2D vectore to tell us which parent_indices from the path we want. i.e. // [[0,1],[0]] means we want the 0th field and 1st field of the 0th path, and // the 0th field of the 1st path. const std::vector<std::vector<int>> segregated_path_indices_; const tensorflow::int64 batch_size_; const tensorflow::DataTypeVector output_dtypes_; const std::vector<tensorflow::PartialTensorShape> output_shapes_; }; class ParquetDatasetOp : public tensorflow::data::DatasetOpKernel { public: ParquetDatasetOp(tensorflow::OpKernelConstruction* ctx) : DatasetOpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("value_paths", &value_paths_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("value_dtypes", &value_dtypes_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("parent_index_paths", &parent_index_paths_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("path_index", &path_index_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_size", &batch_size_)); } void MakeDataset(tensorflow::OpKernelContext* ctx, tensorflow::data::DatasetBase** output) override { const tensorflow::Tensor* filenames_tensor; OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor)); std::vector<std::string> filenames; filenames.reserve(filenames_tensor->NumElements()); for (int i = 0; i < filenames_tensor->NumElements(); ++i) { filenames.push_back(filenames_tensor->flat<tensorflow::tstring>()(i)); } tensorflow::DataTypeVector output_dtypes = tensorflow::DataTypeVector(); int column_counter = 0; std::string prev = parent_index_paths_[0]; output_dtypes.push_back(tensorflow::DT_INT64); for (int i = 1; i < parent_index_paths_.size(); ++i) { std::string curr = parent_index_paths_[i]; output_dtypes.push_back(tensorflow::DT_INT64); if (curr != prev) { output_dtypes.push_back(value_dtypes_[column_counter]); ++column_counter; prev = curr; } } output_dtypes.push_back(tensorflow::DT_INT64); output_dtypes.push_back(value_dtypes_[column_counter]); // This validates that parent_index_paths is aligned with value_paths, // so segregated_path_indices can correctly be constructed. for (int i = 0, j = 0; i < parent_index_paths_.size(); ++i) { while (parent_index_paths_[i] != value_paths_[j]) { ++j; if (j >= value_paths_.size()) { ctx->CtxFailure(tensorflow::errors::InvalidArgument( "parent_index_paths is not aligned with value_paths")); return; } } } std::vector<std::vector<int>> segregated_path_indices(value_paths_.size()); // This is used to transform path_index to a 2d vector, splitting it up // by clustering the same paths. for example: [0, 1, 2, 0, 1, 0, 1, 2, 3] // becomes: [[0, 1, 2], [0, 1], [0, 1, 2, 3]] for (int i = 0, j = 0; i < parent_index_paths_.size(); ++i) { if (parent_index_paths_[i] == value_paths_[j]) { segregated_path_indices[j].push_back(path_index_[i] + 1); } if (i < parent_index_paths_.size() - 1 && parent_index_paths_[i + 1] != parent_index_paths_[i]) { ++j; } } *output = new Dataset(ctx, filenames, value_paths_, value_dtypes_, segregated_path_indices, batch_size_, output_dtypes); } private: std::vector<std::string> value_paths_; tensorflow::DataTypeVector value_dtypes_; // Paths of parent indices that we want. For example: // ["DocId", "Name.Language.Code", "Name.Language.Code", "Name.Language.Code"] std::vector<std::string> parent_index_paths_; std::vector<int> path_index_; int batch_size_; }; // Register the kernel implementation for ParquetDataset. REGISTER_KERNEL_BUILDER(Name("ParquetDataset").Device(tensorflow::DEVICE_CPU), ParquetDatasetOp); } // namespace parquet_dataset } // namespace struct2tensor
Java
/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef GDCMMD5_H #define GDCMMD5_H #include "gdcmTypes.h" namespace gdcm { //----------------------------------------------------------------------------- class MD5Internals; /** * \brief Class for MD5 * * \warning this class is able to pick from two implementations: * * 1. a lightweight md5 implementation (when GDCM_BUILD_TESTING is turned ON) * 2. the one from OpenSSL (when GDCM_USE_SYSTEM_OPENSSL is turned ON) * * In all other cases it will return an error */ class GDCM_EXPORT MD5 { public : MD5(); ~MD5(); static bool Compute(const char *buffer, unsigned long buf_len, char digest_str[33]); static bool ComputeFile(const char *filename, char digest_str[33]); private: MD5Internals *Internals; private: MD5(const MD5&); // Not implemented. void operator=(const MD5&); // Not implemented. }; } // end namespace gdcm //----------------------------------------------------------------------------- #endif //GDCMMD5_H
Java
$(function () { var controller = new ScrollMagic.Controller({ globalSceneOptions: { triggerHook: 'onLeave', reverse: true } }); // $('.homepage .panel').each(function () { // var element = $(this); // console.log(element); // new ScrollMagic.Scene({triggerElement: element}) // .setPin(element) // .setClassToggle(element,'active') // .addTo(controller) // }) // var actual_positions = [0]; // var mid_points = []; // var all_scenes = []; // $('.services .panel').each(function (index) { // if($(this).hasClass('main')) { // new ScrollMagic.Scene({triggerElement: '.services .main'}) // .setPin('.services .main') // .setClassToggle('.services .main','active') // .addTo(controller) // } // else { // var element_id = $(this).attr('id'); // var element_id_with_hash = '#' + $(this).attr('id'); // var scene = new ScrollMagic.Scene({triggerElement: element_id_with_hash}) // .setPin(element_id_with_hash) // .setClassToggle(element_id_with_hash,'show-bottom-nav') // .addTo(controller) // all_scenes.push({ // id: element_id, // scene: scene // }); // actual_positions.push(Math.ceil(scene.triggerPosition())); // if(actual_positions.length > 1) { // mid_points.push((actual_positions[index] + actual_positions [index-1]) / 2) // } // } // }) // $('a[href*=#]:not([href=#])').click(function () { // var id = $(this).attr('href').replace('#',''); // if($(this).parent().parent().parent().hasClass('bottom-nav')) { // var index = $('.bottom-nav ul li a').index($(this)); // }else { // var index = $('ul.wrap li a').index($(this)); // } // if(id == 'down') { // setTimeout(function () { // $('.bottom-nav').addClass('fixed') // },1100) // } // else { // var targetted_scene = all_scenes[index]; // if(targetted_scene.id == id) { // $('html,body').animate({scrollTop: targetted_scene.scene.scrollOffset()},1000); // return false; // } // } // }) // var add_and_remove_active_class = function (index) { // $('.bottom-nav').addClass('fixed') // $('.bottom-nav ul li').removeClass('active'); // $('.bottom-nav ul li:nth-child(' + index + ')').children('a').parent().last().addClass('active'); // } // $(window).scroll(function () { // if ($(".show-bottom-nav")[0]){ // $('.bottom-nav').addClass('fixed') // }else{ // $('.bottom-nav').removeClass('fixed') // } // for(var index=0; index<mid_points.length; index++) { // var next_index = index+1; // var last_index = mid_points.length-1 // /* check between mid point ranges and set active class to the respective nav item. */ // if($(window).scrollTop() > mid_points[index] && $(window).scrollTop() < mid_points[next_index]) { // add_and_remove_active_class(next_index); // break; // /* if nothing matches and reaches to last index then set active active to last nav item. */ // }else if ($(window).scrollTop() > mid_points[last_index]) { // add_and_remove_active_class(mid_points.length); // /* remove from all if its rolled back to the top*/ // }else { // $('.bottom-nav ul li').removeClass('active'); // } // } // }); }); //change navigation color on scroll /* var offset_top_news_section = $('.color-light').offset().top; var offset_top_contact_section = $('.pattern').offset().top; console.log(offset_top_contact_section, offset_top_news_section); $(window).scroll(function (event) { var scroll = $(window).scrollTop(); console.log(scroll); if(scroll < offset_top_contact_section && scroll >= offset_top_news_section) { $('.homepage nav').addClass('change-color'); } else { $('.homepage nav').removeClass('change-color'); } }); */
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.jmeter.protocol.http.sampler; import java.io.IOException; import java.net.Socket; import javax.net.ssl.SSLSocket; import org.apache.http.HttpHost; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.OperatedClientConnection; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.conn.DefaultClientConnection; import org.apache.http.impl.conn.DefaultClientConnectionOperator; import org.apache.jmeter.util.HostNameSetter; /** * Custom implementation of {@link DefaultClientConnectionOperator} to fix SNI Issue * @see "https://bz.apache.org/bugzilla/show_bug.cgi?id=57935" * @since 3.0 * TODO Remove it when full upgrade to 4.5.X is done and cleanup is made in the Socket Factory of JMeter that handles client certificates and Slow socket */ public class JMeterClientConnectionOperator extends DefaultClientConnectionOperator { /** * @param schemes * the scheme registry */ public JMeterClientConnectionOperator(final SchemeRegistry schemes) { super(schemes); } /** * @param schemes * the scheme registry * @param dnsResolver * the custom DNS lookup mechanism */ public JMeterClientConnectionOperator(final SchemeRegistry schemes, final DnsResolver dnsResolver) { super(schemes, dnsResolver); } @Override public OperatedClientConnection createConnection() { return new JMeterDefaultClientConnection(); } private static class JMeterDefaultClientConnection extends DefaultClientConnection { public JMeterDefaultClientConnection() { super(); } /* (non-Javadoc) * @see org.apache.http.impl.conn.DefaultClientConnection#opening(java.net.Socket, org.apache.http.HttpHost) */ @Override public void opening(Socket sock, HttpHost target) throws IOException { super.opening(sock, target); if(sock instanceof SSLSocket) { HostNameSetter.setServerNameIndication(target.getHostName(), (SSLSocket) sock); } } } }
Java
angular.module('aac.controllers.main', []) /** * Main layout controller * @param $scope */ .controller('MainCtrl', function($scope, $rootScope, $location, Data, Utils) { $scope.go = function(v) { $location.path(v); } $scope.activeView = function(view) { return view == $rootScope.currentView ? 'active' : ''; }; $scope.signOut = function() { window.document.location = "./logout"; }; Data.getProfile().then(function(data) { data.fullname = data.name + ' ' + data.surname; $rootScope.user = data; }).catch(function(err) { Utils.showError(err); }); }) .controller('HomeController', function($scope, $rootScope, $location) { }) .controller('AccountsController', function($scope, $rootScope, $location, Data, Utils) { Data.getAccounts().then(function(data) { Data.getProviders().then(function(providers) { providers.sort(function(a,b) { if (data.accounts[a] && !data.accounts[b]) return -1; if (data.accounts[b] && !data.accounts[a]) return 1; return a.localeCompare(b); }); $scope.providers = providers; var accounts = {}; for (var p in data.accounts) { var amap = {}; for (var k in data.accounts[p]) { if (k === 'it.smartcommunitylab.aac.surname') amap['surname'] = data.accounts[p][k]; else if (k === 'it.smartcommunitylab.aac.givenname') amap['givenname'] = data.accounts[p][k]; else if (k === 'it.smartcommunitylab.aac.username') amap['username'] = data.accounts[p][k]; else amap[k] = data.accounts[p][k]; } accounts[p] = amap; } $scope.accounts = accounts; }).catch(function(err) { Utils.showError(err); }); }).catch(function(err) { Utils.showError(err); }); $scope.confirmDeleteAccount = function() { $('#deleteConfirm').modal({keyboard: false}); } $scope.deleteAccount = function() { $('#deleteConfirm').modal('hide'); Data.deleteAccount().then(function() { window.location.href = './logout'; }).catch(function(err) { Utils.showError(err); }); } }) .controller('ConnectionsController', function($scope, $rootScope, $location, Data, Utils) { Data.getConnections().then(function(connections) { $scope.connections = connections; }).catch(function(err) { Utils.showError(err); }); $scope.confirmDeleteApp = function(app) { $scope.clientId = app.clientId; $('#deleteConfirm').modal({keyboard: false}); } $scope.deleteApp = function() { $('#deleteConfirm').modal('hide'); Data.removeConnection($scope.clientId).then(function(connections) { $scope.connections = connections; Utils.showSuccess(); }).catch(function(err) { Utils.showError(err); }); } }) .controller('ProfileController', function($scope, $rootScope, $location, Data, Utils) { $scope.profile = Object.assign($rootScope.user); Data.getAccounts().then(function(data) { if (!data.accounts.internal) { $scope.password_required = true; } }).catch(function(err) { Utils.showError(err); }); $scope.cancel = function() { window.history.back(); } $scope.save = function() { if (!$scope.profile.name || !$scope.profile.surname || !$scope.profile.username || $scope.profile.password && $scope.profile.password != $scope.profile.password2) { return; } Data.saveAccount($scope.profile).then(function(data) { data.fullname = data.name + ' ' + data.surname; $rootScope.user = data; $scope.profile = Object.assign($rootScope.user); $scope.password_required = false; Utils.showSuccess(); }).catch(function(err) { Utils.showError(err); }); } Utils.initUI(); }) ;
Java
# Callitris arenosa A. Cunn. ex R.T. Baker & H.G. Smith SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Generic values</title> <meta name="generator" content="DocBook XSL Stylesheets V1.77.1"> <link rel="home" href="index.html" title="GObject Reference Manual"> <link rel="up" href="rn01.html" title="API Reference"> <link rel="prev" href="gobject-Boxed-Types.html" title="Boxed Types"> <link rel="next" href="gobject-Standard-Parameter-and-Value-Types.html" title="Parameters and Values"> <meta name="generator" content="GTK-Doc V1.18 (XML mode)"> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="2"> <tr valign="middle"> <td><a accesskey="p" href="gobject-Boxed-Types.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td> <td><a accesskey="u" href="rn01.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td> <td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td> <th width="100%" align="center">GObject Reference Manual</th> <td><a accesskey="n" href="gobject-Standard-Parameter-and-Value-Types.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td> </tr> <tr><td colspan="5" class="shortcuts"> <a href="#gobject-Generic-values.synopsis" class="shortcut">Top</a>  |  <a href="#gobject-Generic-values.description" class="shortcut">Description</a> </td></tr> </table> <div class="refentry"> <a name="gobject-Generic-values"></a><div class="titlepage"></div> <div class="refnamediv"><table width="100%"><tr> <td valign="top"> <h2><span class="refentrytitle"><a name="gobject-Generic-values.top_of_page"></a>Generic values</span></h2> <p>Generic values — A polymorphic type that can hold values of any other type</p> </td> <td valign="top" align="right"></td> </tr></table></div> <div class="refsynopsisdiv"> <a name="gobject-Generic-values.synopsis"></a><h2>Synopsis</h2> <pre class="synopsis"> #include &lt;glib-object.h&gt; #define <a class="link" href="gobject-Generic-values.html#G-VALUE-INIT:CAPS" title="G_VALUE_INIT">G_VALUE_INIT</a> #define <a class="link" href="gobject-Generic-values.html#G-VALUE-HOLDS:CAPS" title="G_VALUE_HOLDS()">G_VALUE_HOLDS</a> (value, type) #define <a class="link" href="gobject-Generic-values.html#G-VALUE-TYPE:CAPS" title="G_VALUE_TYPE()">G_VALUE_TYPE</a> (value) #define <a class="link" href="gobject-Generic-values.html#G-VALUE-TYPE-NAME:CAPS" title="G_VALUE_TYPE_NAME()">G_VALUE_TYPE_NAME</a> (value) #define <a class="link" href="gobject-Generic-values.html#G-TYPE-IS-VALUE:CAPS" title="G_TYPE_IS_VALUE()">G_TYPE_IS_VALUE</a> (type) #define <a class="link" href="gobject-Generic-values.html#G-TYPE-IS-VALUE-ABSTRACT:CAPS" title="G_TYPE_IS_VALUE_ABSTRACT()">G_TYPE_IS_VALUE_ABSTRACT</a> (type) #define <a class="link" href="gobject-Generic-values.html#G-IS-VALUE:CAPS" title="G_IS_VALUE()">G_IS_VALUE</a> (value) <a class="link" href="gobject-Generic-values.html#GValue" title="GValue">GValue</a>; #define <a class="link" href="gobject-Generic-values.html#G-TYPE-VALUE:CAPS" title="G_TYPE_VALUE">G_TYPE_VALUE</a> #define <a class="link" href="gobject-Generic-values.html#G-TYPE-VALUE-ARRAY:CAPS" title="G_TYPE_VALUE_ARRAY">G_TYPE_VALUE_ARRAY</a> <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()">g_value_init</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> g_type</code></em>); <span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-copy" title="g_value_copy ()">g_value_copy</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>); <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * <a class="link" href="gobject-Generic-values.html#g-value-reset" title="g_value_reset ()">g_value_reset</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>); <span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-unset" title="g_value_unset ()">g_value_unset</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>); <span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-set-instance" title="g_value_set_instance ()">g_value_set_instance</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>, <em class="parameter"><code><a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="type">gpointer</span></a> instance</code></em>); <a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-fits-pointer" title="g_value_fits_pointer ()">g_value_fits_pointer</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>); <a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="returnvalue">gpointer</span></a> <a class="link" href="gobject-Generic-values.html#g-value-peek-pointer" title="g_value_peek_pointer ()">g_value_peek_pointer</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>); <a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-type-compatible" title="g_value_type_compatible ()">g_value_type_compatible</a> (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>); <a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-type-transformable" title="g_value_type_transformable ()">g_value_type_transformable</a> (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>); <a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-transform" title="g_value_transform ()">g_value_transform</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>); <span class="returnvalue">void</span> (<a class="link" href="gobject-Generic-values.html#GValueTransform" title="GValueTransform ()">*GValueTransform</a>) (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>); <span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-register-transform-func" title="g_value_register_transform_func ()">g_value_register_transform_func</a> (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValueTransform" title="GValueTransform ()"><span class="type">GValueTransform</span></a> transform_func</code></em>); <a href="./../glib/glib/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * <a class="link" href="gobject-Generic-values.html#g-strdup-value-contents" title="g_strdup_value_contents ()">g_strdup_value_contents</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>); </pre> </div> <div class="refsect1"> <a name="gobject-Generic-values.description"></a><h2>Description</h2> <p> The <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure is basically a variable container that consists of a type identifier and a specific value of that type. The type identifier within a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure always determines the type of the associated value. To create a undefined <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure, simply create a zero-filled <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure. To initialize the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>, use the <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a> function. A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> cannot be used until it is initialized. The basic type operations (such as freeing and copying) are determined by the <a class="link" href="gobject-Type-Information.html#GTypeValueTable" title="struct GTypeValueTable"><span class="type">GTypeValueTable</span></a> associated with the type ID stored in the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>. Other <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> operations (such as converting values between types) are provided by this interface. </p> <p> The code in the example program below demonstrates <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>'s features. </p> <p> </p> <div class="informalexample"> <table class="listing_frame" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td class="listing_lines" align="right"><pre>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54</pre></td> <td class="listing_code"><pre class="programlisting"><span class="preproc">#include</span><span class="normal"> </span><span class="string">&lt;glib-object.h&gt;</span> <span class="keyword">static</span><span class="normal"> </span><span class="type">void</span> <span class="function">int2string</span><span class="normal"> </span><span class="symbol">(</span><span class="keyword">const</span><span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">src_value</span><span class="symbol">,</span> <span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">dest_value</span><span class="symbol">)</span> <span class="cbracket">{</span> <span class="normal"> </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-int">g_value_get_int</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal">src_value</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">==</span><span class="normal"> </span><span class="number">42</span><span class="symbol">)</span> <span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-static-string">g_value_set_static_string</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal">dest_value</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"An important number"</span><span class="symbol">);</span> <span class="normal"> </span><span class="keyword">else</span> <span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-static-string">g_value_set_static_string</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal">dest_value</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"What's that?"</span><span class="symbol">);</span> <span class="cbracket">}</span> <span class="type">int</span> <span class="function">main</span><span class="normal"> </span><span class="symbol">(</span><span class="type">int</span><span class="normal"> argc</span><span class="symbol">,</span> <span class="normal"> </span><span class="type">char</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">argv</span><span class="symbol">[])</span> <span class="cbracket">{</span> <span class="normal"> </span><span class="comment">/* GValues must be initialized */</span> <span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> a </span><span class="symbol">=</span><span class="normal"> <a href="gobject-Generic-values.html#G-VALUE-INIT:CAPS">G_VALUE_INIT</a></span><span class="symbol">;</span> <span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> b </span><span class="symbol">=</span><span class="normal"> <a href="gobject-Generic-values.html#G-VALUE-INIT:CAPS">G_VALUE_INIT</a></span><span class="symbol">;</span> <span class="normal"> </span><span class="keyword">const</span><span class="normal"> </span><span class="usertype">gchar</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">message</span><span class="symbol">;</span> <span class="normal"> </span><span class="function"><a href="gobject-Type-Information.html#g-type-init">g_type_init</a></span><span class="normal"> </span><span class="symbol">();</span> <span class="normal"> </span><span class="comment">/* The GValue starts empty */</span> <span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-Testing.html#g-assert">g_assert</a></span><span class="normal"> </span><span class="symbol">(!</span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#G-VALUE-HOLDS-STRING:CAPS">G_VALUE_HOLDS_STRING</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">));</span> <span class="normal"> </span><span class="comment">/* Put a string in it */</span> <span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-init">g_value_init</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">);</span> <span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-Testing.html#g-assert">g_assert</a></span><span class="normal"> </span><span class="symbol">(</span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#G-VALUE-HOLDS-STRING:CAPS">G_VALUE_HOLDS_STRING</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">));</span> <span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-static-string">g_value_set_static_string</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"Hello, world!"</span><span class="symbol">);</span> <span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-String-Utility-Functions.html#g-printf">g_printf</a></span><span class="normal"> </span><span class="symbol">(</span><span class="string">"%s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-string">g_value_get_string</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">));</span> <span class="normal"> </span><span class="comment">/* Reset it to its pristine state */</span> <span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-unset">g_value_unset</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">);</span> <span class="normal"> </span><span class="comment">/* It can then be reused for another type */</span> <span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-init">g_value_init</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-INT:CAPS">G_TYPE_INT</a></span><span class="symbol">);</span> <span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-int">g_value_set_int</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="number">42</span><span class="symbol">);</span> <span class="normal"> </span><span class="comment">/* Attempt to transform it into a GValue of type STRING */</span> <span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-init">g_value_init</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">b</span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">);</span> <span class="normal"> </span><span class="comment">/* An INT is transformable to a STRING */</span> <span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-Testing.html#g-assert">g_assert</a></span><span class="normal"> </span><span class="symbol">(</span><span class="function"><a href="gobject-Generic-values.html#g-value-type-transformable">g_value_type_transformable</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal"><a href="gobject-Type-Information.html#G-TYPE-INT:CAPS">G_TYPE_INT</a></span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">));</span> <span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-transform">g_value_transform</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">&amp;</span><span class="normal">b</span><span class="symbol">);</span> <span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-String-Utility-Functions.html#g-printf">g_printf</a></span><span class="normal"> </span><span class="symbol">(</span><span class="string">"%s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-string">g_value_get_string</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">b</span><span class="symbol">));</span> <span class="normal"> </span><span class="comment">/* Attempt to transform it again using a custom transform function */</span> <span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-register-transform-func">g_value_register_transform_func</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal"><a href="gobject-Type-Information.html#G-TYPE-INT:CAPS">G_TYPE_INT</a></span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">,</span><span class="normal"> int2string</span><span class="symbol">);</span> <span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-transform">g_value_transform</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">&amp;</span><span class="normal">b</span><span class="symbol">);</span> <span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-String-Utility-Functions.html#g-printf">g_printf</a></span><span class="normal"> </span><span class="symbol">(</span><span class="string">"%s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-string">g_value_get_string</a></span><span class="normal"> </span><span class="symbol">(&amp;</span><span class="normal">b</span><span class="symbol">));</span> <span class="normal"> </span><span class="keyword">return</span><span class="normal"> </span><span class="number">0</span><span class="symbol">;</span> <span class="cbracket">}</span></pre></td> </tr> </tbody> </table> </div> <p> </p> </div> <div class="refsect1"> <a name="gobject-Generic-values.details"></a><h2>Details</h2> <div class="refsect2"> <a name="G-VALUE-INIT:CAPS"></a><h3>G_VALUE_INIT</h3> <pre class="programlisting">#define G_VALUE_INIT { 0, { { 0 } } } </pre> <p> A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> must be initialized before it can be used. This macro can be used as initializer instead of an explicit <code class="literal">{ 0 }</code> when declaring a variable, but it cannot be assigned to a variable. </p> <p> </p> <div class="informalexample"> <table class="listing_frame" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td class="listing_lines" align="right"><pre>1</pre></td> <td class="listing_code"><pre class="programlisting"><span class="usertype">GValue</span><span class="normal"> value </span><span class="symbol">=</span><span class="normal"> <a href="gobject-Generic-values.html#G-VALUE-INIT:CAPS">G_VALUE_INIT</a></span><span class="symbol">;</span></pre></td> </tr> </tbody> </table> </div> <p> </p> <p class="since">Since 2.30</p> </div> <hr> <div class="refsect2"> <a name="G-VALUE-HOLDS:CAPS"></a><h3>G_VALUE_HOLDS()</h3> <pre class="programlisting">#define G_VALUE_HOLDS(value,type) (G_TYPE_CHECK_VALUE_TYPE ((value), (type))) </pre> <p> Checks if <em class="parameter"><code>value</code></em> holds (or contains) a value of <em class="parameter"><code>type</code></em>. This macro will also check for <em class="parameter"><code>value</code></em> != <a href="./../glib/glib/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a> and issue a warning if the check fails. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>type</code></em> :</span></p></td> <td>A <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> value.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if <em class="parameter"><code>value</code></em> holds the <em class="parameter"><code>type</code></em>.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="G-VALUE-TYPE:CAPS"></a><h3>G_VALUE_TYPE()</h3> <pre class="programlisting">#define G_VALUE_TYPE(value) (((GValue*) (value))-&gt;g_type) </pre> <p> Get the type identifier of <em class="parameter"><code>value</code></em>. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>the <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a>.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="G-VALUE-TYPE-NAME:CAPS"></a><h3>G_VALUE_TYPE_NAME()</h3> <pre class="programlisting">#define G_VALUE_TYPE_NAME(value) (g_type_name (G_VALUE_TYPE (value))) </pre> <p> Gets the type name of <em class="parameter"><code>value</code></em>. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>the type name.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="G-TYPE-IS-VALUE:CAPS"></a><h3>G_TYPE_IS_VALUE()</h3> <pre class="programlisting">#define G_TYPE_IS_VALUE(type) (g_type_check_is_value_type (type)) </pre> <p> Checks whether the passed in type ID can be used for <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a>. That is, this macro checks whether this type provides an implementation of the <a class="link" href="gobject-Type-Information.html#GTypeValueTable" title="struct GTypeValueTable"><span class="type">GTypeValueTable</span></a> functions required for a type to create a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> of. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>type</code></em> :</span></p></td> <td>A <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> value.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>Whether <em class="parameter"><code>type</code></em> is suitable as a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> type.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="G-TYPE-IS-VALUE-ABSTRACT:CAPS"></a><h3>G_TYPE_IS_VALUE_ABSTRACT()</h3> <pre class="programlisting">#define G_TYPE_IS_VALUE_ABSTRACT(type) (g_type_test_flags ((type), G_TYPE_FLAG_VALUE_ABSTRACT)) </pre> <p> Checks if <em class="parameter"><code>type</code></em> is an abstract value type. An abstract value type introduces a value table, but can't be used for <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a> and is normally used as an abstract base type for derived value types. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>type</code></em> :</span></p></td> <td>A <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> value.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> on success.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="G-IS-VALUE:CAPS"></a><h3>G_IS_VALUE()</h3> <pre class="programlisting">#define G_IS_VALUE(value) (G_TYPE_CHECK_VALUE (value)) </pre> <p> Checks if <em class="parameter"><code>value</code></em> is a valid and initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> on success.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="GValue"></a><h3>GValue</h3> <pre class="programlisting">typedef struct { } GValue; </pre> <p> An opaque structure used to hold different types of values. The data within the structure has protected scope: it is accessible only to functions within a <a class="link" href="gobject-Type-Information.html#GTypeValueTable" title="struct GTypeValueTable"><span class="type">GTypeValueTable</span></a> structure, or implementations of the g_value_*() API. That is, code portions which implement new fundamental types. <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> users cannot make any assumptions about how data is stored within the 2 element <em class="parameter"><code>data</code></em> union, and the <em class="parameter"><code>g_type</code></em> member should only be accessed through the <a class="link" href="gobject-Generic-values.html#G-VALUE-TYPE:CAPS" title="G_VALUE_TYPE()"><code class="function">G_VALUE_TYPE()</code></a> macro. </p> </div> <hr> <div class="refsect2"> <a name="G-TYPE-VALUE:CAPS"></a><h3>G_TYPE_VALUE</h3> <pre class="programlisting">#define G_TYPE_VALUE (g_value_get_type ()) </pre> <p> The type ID of the "GValue" type which is a boxed type, used to pass around pointers to GValues. </p> </div> <hr> <div class="refsect2"> <a name="G-TYPE-VALUE-ARRAY:CAPS"></a><h3>G_TYPE_VALUE_ARRAY</h3> <pre class="programlisting">#define G_TYPE_VALUE_ARRAY (g_value_array_get_type ()) </pre> <div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"> <h3 class="title">Warning</h3> <p><code class="literal">G_TYPE_VALUE_ARRAY</code> has been deprecated since version 2.32 and should not be used in newly-written code. Use <a href="./../glib/glib/glib-Arrays.html#GArray"><span class="type">GArray</span></a> instead of <a class="link" href="gobject-Value-arrays.html#GValueArray" title="struct GValueArray"><span class="type">GValueArray</span></a></p> </div> <p> The type ID of the "GValueArray" type which is a boxed type, used to pass around pointers to GValueArrays. </p> </div> <hr> <div class="refsect2"> <a name="g-value-init"></a><h3>g_value_init ()</h3> <pre class="programlisting"><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * g_value_init (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> g_type</code></em>);</pre> <p> Initializes <em class="parameter"><code>value</code></em> with the default value of <em class="parameter"><code>type</code></em>. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>A zero-filled (uninitialized) <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>g_type</code></em> :</span></p></td> <td>Type the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> should hold values of.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure that has been passed in. <span class="annotation">[<acronym title="Don't free data after the code is done."><span class="acronym">transfer none</span></acronym>]</span> </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-copy"></a><h3>g_value_copy ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> g_value_copy (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);</pre> <p> Copies the value of <em class="parameter"><code>src_value</code></em> into <em class="parameter"><code>dest_value</code></em>. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>src_value</code></em> :</span></p></td> <td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>dest_value</code></em> :</span></p></td> <td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure of the same type as <em class="parameter"><code>src_value</code></em>.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-reset"></a><h3>g_value_reset ()</h3> <pre class="programlisting"><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * g_value_reset (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre> <p> Clears the current value in <em class="parameter"><code>value</code></em> and resets it to the default value (as if the value had just been initialized). </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure that has been passed in</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-unset"></a><h3>g_value_unset ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> g_value_unset (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre> <p> Clears the current value in <em class="parameter"><code>value</code></em> and "unsets" the type, this releases all resources associated with this GValue. An unset value is the same as an uninitialized (zero-filled) <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody><tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr></tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-set-instance"></a><h3>g_value_set_instance ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> g_value_set_instance (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>, <em class="parameter"><code><a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="type">gpointer</span></a> instance</code></em>);</pre> <p> Sets <em class="parameter"><code>value</code></em> from an instantiatable type via the value_table's <code class="function">collect_value()</code> function. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>instance</code></em> :</span></p></td> <td>the instance. <span class="annotation">[<acronym title="NULL is ok, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span> </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-fits-pointer"></a><h3>g_value_fits_pointer ()</h3> <pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_fits_pointer (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre> <p> Determines if <em class="parameter"><code>value</code></em> will fit inside the size of a pointer value. This is an internal function introduced mainly for C marshallers. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if <em class="parameter"><code>value</code></em> will fit inside a pointer value.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-peek-pointer"></a><h3>g_value_peek_pointer ()</h3> <pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="returnvalue">gpointer</span></a> g_value_peek_pointer (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>the value contents as pointer. This function asserts that <a class="link" href="gobject-Generic-values.html#g-value-fits-pointer" title="g_value_fits_pointer ()"><code class="function">g_value_fits_pointer()</code></a> returned <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> for the passed in value. This is an internal function introduced mainly for C marshallers. <span class="annotation">[<acronym title="Don't free data after the code is done."><span class="acronym">transfer none</span></acronym>]</span> </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-type-compatible"></a><h3>g_value_type_compatible ()</h3> <pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_type_compatible (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>);</pre> <p> Returns whether a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> of type <em class="parameter"><code>src_type</code></em> can be copied into a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> of type <em class="parameter"><code>dest_type</code></em>. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>src_type</code></em> :</span></p></td> <td>source type to be copied.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>dest_type</code></em> :</span></p></td> <td>destination type for copying.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if <a class="link" href="gobject-Generic-values.html#g-value-copy" title="g_value_copy ()"><code class="function">g_value_copy()</code></a> is possible with <em class="parameter"><code>src_type</code></em> and <em class="parameter"><code>dest_type</code></em>.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-type-transformable"></a><h3>g_value_type_transformable ()</h3> <pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_type_transformable (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>);</pre> <p> Check whether <a class="link" href="gobject-Generic-values.html#g-value-transform" title="g_value_transform ()"><code class="function">g_value_transform()</code></a> is able to transform values of type <em class="parameter"><code>src_type</code></em> into values of type <em class="parameter"><code>dest_type</code></em>. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>src_type</code></em> :</span></p></td> <td>Source type.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>dest_type</code></em> :</span></p></td> <td>Target type.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if the transformation is possible, <a href="./../glib/glib/glib-Standard-Macros.html#FALSE:CAPS"><code class="literal">FALSE</code></a> otherwise.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-transform"></a><h3>g_value_transform ()</h3> <pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_transform (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);</pre> <p> Tries to cast the contents of <em class="parameter"><code>src_value</code></em> into a type appropriate to store in <em class="parameter"><code>dest_value</code></em>, e.g. to transform a <a class="link" href="gobject-Type-Information.html#G-TYPE-INT:CAPS" title="G_TYPE_INT"><code class="literal">G_TYPE_INT</code></a> value into a <a class="link" href="gobject-Type-Information.html#G-TYPE-FLOAT:CAPS" title="G_TYPE_FLOAT"><code class="literal">G_TYPE_FLOAT</code></a> value. Performing transformations between value types might incur precision lossage. Especially transformations into strings might reveal seemingly arbitrary results and shouldn't be relied upon for production code (such as rcfile value or object property serialization). </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>src_value</code></em> :</span></p></td> <td>Source value.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>dest_value</code></em> :</span></p></td> <td>Target value.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>Whether a transformation rule was found and could be applied. Upon failing transformations, <em class="parameter"><code>dest_value</code></em> is left untouched.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="GValueTransform"></a><h3>GValueTransform ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> (*GValueTransform) (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);</pre> <p> The type of value transformation functions which can be registered with <a class="link" href="gobject-Generic-values.html#g-value-register-transform-func" title="g_value_register_transform_func ()"><code class="function">g_value_register_transform_func()</code></a>. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>src_value</code></em> :</span></p></td> <td>Source value.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>dest_value</code></em> :</span></p></td> <td>Target value.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-value-register-transform-func"></a><h3>g_value_register_transform_func ()</h3> <pre class="programlisting"><span class="returnvalue">void</span> g_value_register_transform_func (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>, <em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValueTransform" title="GValueTransform ()"><span class="type">GValueTransform</span></a> transform_func</code></em>);</pre> <p> Registers a value transformation function for use in <a class="link" href="gobject-Generic-values.html#g-value-transform" title="g_value_transform ()"><code class="function">g_value_transform()</code></a>. A previously registered transformation function for <em class="parameter"><code>src_type</code></em> and <em class="parameter"><code>dest_type</code></em> will be replaced. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>src_type</code></em> :</span></p></td> <td>Source type.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>dest_type</code></em> :</span></p></td> <td>Target type.</td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>transform_func</code></em> :</span></p></td> <td>a function which transforms values of type <em class="parameter"><code>src_type</code></em> into value of type <em class="parameter"><code>dest_type</code></em> </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2"> <a name="g-strdup-value-contents"></a><h3>g_strdup_value_contents ()</h3> <pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * g_strdup_value_contents (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre> <p> Return a newly allocated string, which describes the contents of a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>. The main purpose of this function is to describe <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> contents for debugging output, the way in which the contents are described may change between different GLib versions. </p> <div class="variablelist"><table border="0" class="variablelist"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td> <td> <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> which contents are to be described.</td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td>Newly allocated string.</td> </tr> </tbody> </table></div> </div> </div> <div class="refsect1"> <a name="gobject-Generic-values.see-also"></a><h2>See Also</h2> The fundamental types which all support <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> operations and thus can be used as a type initializer for <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a> are defined by a separate interface. See the <a class="link" href="gobject-Standard-Parameter-and-Value-Types.html" title="Parameters and Values">Standard Values API</a> for details. </div> </div> <div class="footer"> <hr> Generated by GTK-Doc V1.18</div> </body> </html>
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.rdd import java.io.{IOException, ObjectOutputStream} import scala.reflect.ClassTag import org.apache.spark._ import org.apache.spark.util.Utils private[spark] /** * Cartesian 笛卡尔积 */ class CartesianPartition( idx: Int, @transient rdd1: RDD[_], @transient rdd2: RDD[_], s1Index: Int, s2Index: Int ) extends Partition { var s1 = rdd1.partitions(s1Index) var s2 = rdd2.partitions(s2Index) override val index: Int = idx @throws(classOf[IOException]) private def writeObject(oos: ObjectOutputStream): Unit = Utils.tryOrIOException { // Update the reference to parent split at the time of task serialization s1 = rdd1.partitions(s1Index) s2 = rdd2.partitions(s2Index) oos.defaultWriteObject() } } private[spark] class CartesianRDD[T: ClassTag, U: ClassTag]( sc: SparkContext, var rdd1 : RDD[T], var rdd2 : RDD[U]) extends RDD[Pair[T, U]](sc, Nil) with Serializable { val numPartitionsInRdd2 = rdd2.partitions.length override def getPartitions: Array[Partition] = { // create the cross product split 创建交叉产品拆分 val array = new Array[Partition](rdd1.partitions.length * rdd2.partitions.length) for (s1 <- rdd1.partitions; s2 <- rdd2.partitions) { val idx = s1.index * numPartitionsInRdd2 + s2.index array(idx) = new CartesianPartition(idx, rdd1, rdd2, s1.index, s2.index) } array } override def getPreferredLocations(split: Partition): Seq[String] = { val currSplit = split.asInstanceOf[CartesianPartition] (rdd1.preferredLocations(currSplit.s1) ++ rdd2.preferredLocations(currSplit.s2)).distinct } override def compute(split: Partition, context: TaskContext): Iterator[(T, U)] = { val currSplit = split.asInstanceOf[CartesianPartition] for (x <- rdd1.iterator(currSplit.s1, context); y <- rdd2.iterator(currSplit.s2, context)) yield (x, y) } override def getDependencies: Seq[Dependency[_]] = List( new NarrowDependency(rdd1) { def getParents(id: Int): Seq[Int] = List(id / numPartitionsInRdd2) }, new NarrowDependency(rdd2) { def getParents(id: Int): Seq[Int] = List(id % numPartitionsInRdd2) } ) override def clearDependencies() { super.clearDependencies() rdd1 = null rdd2 = null } }
Java
#!/bin/env python import itertools import collections def read_table(filename): with open(filename) as fp: header = next(fp).split() rows = [line.split()[1:] for line in fp if line.strip()] columns = zip(*rows) data = dict(zip(header, columns)) return data table = read_table("../../data/colldata.txt") pots = sorted(table) alphabet = "+-?" for num in range(2, len(table) + 1): for group in itertools.combinations(pots, num): patterns = zip(*[table[p] for p in group]) counts = collections.Counter(patterns) for poss in itertools.product(alphabet, repeat=num): print ', '.join(group) + ':', print ''.join(poss), counts[poss]
Java
package com.jota.patterns.singleton; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.jota.patterns.singleton.singleton.User; public class MainActivity extends AppCompatActivity { @BindView(R.id.user1) TextView user1Text; @BindView(R.id.user2) TextView user2Text; @BindView(R.id.user3) TextView user3Text; private User user, user1, user2, user3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); user = User.getInstance(); user.setToken("token"); user.setSocialNetwork("Facebook"); user1 = User.getInstance(); user2 = User.getInstance(); user3 = User.getInstance(); } private void showUsers() { user1Text.setText(user1.getSocialNetwork() + " - " + user1.getToken()); user2Text.setText(user2.getSocialNetwork() + " - " + user2.getToken()); user3Text.setText(user3.getSocialNetwork() + " - " + user3.getToken()); } @OnClick(R.id.change_social_button) public void changeSocial() { user.setSocialNetwork("Twitter"); showUsers(); } @OnClick(R.id.change_token_button) public void changeToken() { user.setToken("Token token"); showUsers(); } }
Java
# This file is part of the MapProxy project. # Copyright (C) 2010 Omniscale <http://omniscale.de> # # 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. from __future__ import with_statement import operator import threading from mapproxy.grid import bbox_intersects, bbox_contains from mapproxy.util.py import cached_property from mapproxy.util.geom import ( require_geom_support, load_polygon_lines, transform_geometry, bbox_polygon, ) from mapproxy.srs import SRS import logging log_config = logging.getLogger('mapproxy.config.coverage') try: import shapely.geometry import shapely.prepared except ImportError: # missing Shapely is handled by require_geom_support pass def coverage(geom, srs): if isinstance(geom, (list, tuple)): return BBOXCoverage(geom, srs) else: return GeomCoverage(geom, srs) def load_limited_to(limited_to): require_geom_support() srs = SRS(limited_to['srs']) geom = limited_to['geometry'] if not hasattr(geom, 'type'): # not a Shapely geometry if isinstance(geom, (list, tuple)): geom = bbox_polygon(geom) else: polygons = load_polygon_lines(geom.split('\n')) if len(polygons) == 1: geom = polygons[0] else: geom = shapely.geometry.MultiPolygon(polygons) return GeomCoverage(geom, srs, clip=True) class MultiCoverage(object): clip = False """Aggregates multiple coverages""" def __init__(self, coverages): self.coverages = coverages self.bbox = self.extent.bbox @cached_property def extent(self): return reduce(operator.add, [c.extent for c in self.coverages]) def intersects(self, bbox, srs): return any(c.intersects(bbox, srs) for c in self.coverages) def contains(self, bbox, srs): return any(c.contains(bbox, srs) for c in self.coverages) def transform_to(self, srs): return MultiCoverage([c.transform_to(srs) for c in self.coverages]) def __eq__(self, other): if not isinstance(other, MultiCoverage): return NotImplemented if self.bbox != other.bbox: return False if len(self.coverages) != len(other.coverages): return False for a, b in zip(self.coverages, other.coverages): if a != b: return False return True def __ne__(self, other): if not isinstance(other, MultiCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '<MultiCoverage %r: %r>' % (self.extent.llbbox, self.coverages) class BBOXCoverage(object): clip = False def __init__(self, bbox, srs): self.bbox = bbox self.srs = srs self.geom = None @property def extent(self): from mapproxy.layer import MapExtent return MapExtent(self.bbox, self.srs) def _bbox_in_coverage_srs(self, bbox, srs): if srs != self.srs: bbox = srs.transform_bbox_to(self.srs, bbox) return bbox def intersects(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) return bbox_intersects(self.bbox, bbox) def intersection(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) intersection = ( max(self.bbox[0], bbox[0]), max(self.bbox[1], bbox[1]), min(self.bbox[2], bbox[2]), min(self.bbox[3], bbox[3]), ) if intersection[0] >= intersection[2] or intersection[1] >= intersection[3]: return None return BBOXCoverage(intersection, self.srs) def contains(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) return bbox_contains(self.bbox, bbox) def transform_to(self, srs): if srs == self.srs: return self bbox = self.srs.transform_bbox_to(srs, self.bbox) return BBOXCoverage(bbox, srs) def __eq__(self, other): if not isinstance(other, BBOXCoverage): return NotImplemented if self.srs != other.srs: return False if self.bbox != other.bbox: return False return True def __ne__(self, other): if not isinstance(other, BBOXCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '<BBOXCoverage %r/%r>' % (self.extent.llbbox, self.bbox) class GeomCoverage(object): def __init__(self, geom, srs, clip=False): self.geom = geom self.bbox = geom.bounds self.srs = srs self.clip = clip self._prep_lock = threading.Lock() self._prepared_geom = None self._prepared_counter = 0 self._prepared_max = 10000 @property def extent(self): from mapproxy.layer import MapExtent return MapExtent(self.bbox, self.srs) @property def prepared_geom(self): # GEOS internal data structure for prepared geometries grows over time, # recreate to limit memory consumption if not self._prepared_geom or self._prepared_counter > self._prepared_max: self._prepared_geom = shapely.prepared.prep(self.geom) self._prepared_counter = 0 self._prepared_counter += 1 return self._prepared_geom def _geom_in_coverage_srs(self, geom, srs): if isinstance(geom, shapely.geometry.base.BaseGeometry): if srs != self.srs: geom = transform_geometry(srs, self.srs, geom) elif len(geom) == 2: if srs != self.srs: geom = srs.transform_to(self.srs, geom) geom = shapely.geometry.Point(geom) else: if srs != self.srs: geom = srs.transform_bbox_to(self.srs, geom) geom = bbox_polygon(geom) return geom def transform_to(self, srs): if srs == self.srs: return self geom = transform_geometry(self.srs, srs, self.geom) return GeomCoverage(geom, srs) def intersects(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) with self._prep_lock: return self.prepared_geom.intersects(bbox) def intersection(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) return GeomCoverage(self.geom.intersection(bbox), self.srs) def contains(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) with self._prep_lock: return self.prepared_geom.contains(bbox) def __eq__(self, other): if not isinstance(other, GeomCoverage): return NotImplemented if self.srs != other.srs: return False if self.bbox != other.bbox: return False if not self.geom.equals(other.geom): return False return True def __ne__(self, other): if not isinstance(other, GeomCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '<GeomCoverage %r: %r>' % (self.extent.llbbox, self.geom)
Java
# Quamoclit multifida Raf. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in New Fl. 4:57. 1838 "<I>Quamoctita</I>" #### Original name null ### Remarks null
Java
package ru.maizy.ambient7.core.data /** * Copyright (c) Nikita Kovaliov, maizy.ru, 2016-2017 * See LICENSE.txt for details. */ import java.time.ZonedDateTime case class Co2AggregatedLevels( lowLevel: Int, mediumLevel: Int, highLevel: Int, unknownLevel: Int, from: ZonedDateTime, to: ZonedDateTime, agentId: Co2Agent ) { override def toString: String = s"Co2AggregatedLevels(low=$lowLevel, med=$mediumLevel, high=$highLevel, " + s"unknown=$unknownLevel, $from->$to, agent=${agentId.agentName}, tags=${agentId.tags})" def hasAnyResult: Boolean = lowLevel > 0 || mediumLevel > 0 || highLevel > 0 def combine(other: Co2AggregatedLevels): Co2AggregatedLevels = copy( lowLevel = lowLevel + other.lowLevel, mediumLevel = mediumLevel + other.mediumLevel, highLevel = highLevel + other.highLevel, unknownLevel = unknownLevel + other.unknownLevel, if (other.from.compareTo(from) < 0) other.from else from, if (other.to.compareTo(to) > 0) other.to else to ) }
Java
jQuery(function($) { //smooth scroll $('.navbar-nav > li.anchor').click(function(event) { //event.preventDefault(); var target = $(this).find('>a').prop('hash'); $('#navbar .active').removeClass('active'); $(this).addClass('active'); $('html, body').animate({ scrollTop: $(target).offset().top }, 500); }); //scrollspy $('[data-spy="scroll"]').each(function () { var $spy = $(this).scrollspy('refresh') }); $(function() { $(".navbar-btn").click(function() { $("#options").toggle(); $(".navbar-btn .glyphicon").toggleClass("glyphicon-plus") .toggleClass("glyphicon-minus"); }); }); });
Java
// Licensed under the Apache License, Version 2.0 // Details: https://raw.githubusercontent.com/square/quotaservice/master/LICENSE // Package memory implements token buckets in memory, inspired by the algorithms used in Guava's // RateLimiter library - https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/RateLimiter.java // Note that this implementation spins up a goroutine *per bucket* that's created. That can get // expensive, and is not recommended for production use, with a large number of static or dynamic // buckets. package memory import ( "context" "time" "github.com/square/quotaservice" "github.com/square/quotaservice/config" "github.com/square/quotaservice/logging" pbconfig "github.com/square/quotaservice/protos/config" ) type bucketFactory struct { cfg *pbconfig.ServiceConfig } func (bf *bucketFactory) Init(cfg *pbconfig.ServiceConfig) { bf.cfg = cfg } func (bf *bucketFactory) Client() interface{} { return nil } func (bf *bucketFactory) NewBucket(namespace, bucketName string, cfg *pbconfig.BucketConfig, dyn bool) quotaservice.Bucket { // fill rate is tokens-per-second. bucket := &tokenBucket{ dynamic: dyn, cfg: cfg, nanosBetweenTokens: 1e9 / cfg.FillRate, accumulatedTokens: cfg.Size, // Start full fullName: config.FullyQualifiedName(namespace, bucketName), waitTimer: make(chan *waitTimeReq), closer: make(chan struct{})} go bucket.waitTimeLoop() return bucket } func NewBucketFactory() quotaservice.BucketFactory { return &bucketFactory{} } // tokenBucket is a single-threaded implementation. A single goroutine updates the values of // tokensNextAvailable and accumulatedTokens. When requesting tokens, Take() puts a request on // the waitTimer channel, and listens on the response channel in the request for a result. The // goroutine is shut down when Destroy() is called on this bucket. In-flight requests will be // served, but new requests will not. type tokenBucket struct { dynamic bool cfg *pbconfig.BucketConfig nanosBetweenTokens int64 tokensNextAvailableNanos int64 accumulatedTokens int64 fullName string waitTimer chan *waitTimeReq closer chan struct{} quotaservice.DefaultBucket // Extension for default methods on interface } // waitTimeReq is a request that you put on the channel for the waitTimer goroutine to pick up and // process. type waitTimeReq struct { requested, maxWaitTimeNanos int64 response chan int64 } func (b *tokenBucket) Take(_ context.Context, numTokens int64, maxWaitTime time.Duration) (time.Duration, bool) { rsp := make(chan int64, 1) b.waitTimer <- &waitTimeReq{numTokens, maxWaitTime.Nanoseconds(), rsp} waitTimeNanos := <-rsp if waitTimeNanos < 0 { // Timed out return 0, false } return time.Duration(waitTimeNanos) * time.Nanosecond, true } // calcWaitTime is designed to run in a single event loop and is not thread-safe. func (b *tokenBucket) calcWaitTime(requested, maxWaitTimeNanos int64) (waitTimeNanos int64) { currentTimeNanos := time.Now().UnixNano() tna := b.tokensNextAvailableNanos ac := b.accumulatedTokens var freshTokens int64 if currentTimeNanos > tna { freshTokens = (currentTimeNanos - tna) / b.nanosBetweenTokens ac = min(b.cfg.Size, ac+freshTokens) tna = currentTimeNanos } waitTimeNanos = tna - currentTimeNanos accumulatedTokensUsed := min(ac, requested) tokensToWaitFor := requested - accumulatedTokensUsed futureWaitNanos := tokensToWaitFor * b.nanosBetweenTokens tna += futureWaitNanos ac -= accumulatedTokensUsed if (tna-currentTimeNanos > b.cfg.MaxDebtMillis*1e6) || (waitTimeNanos > 0 && waitTimeNanos > maxWaitTimeNanos) { waitTimeNanos = -1 } else { b.tokensNextAvailableNanos = tna b.accumulatedTokens = ac } return waitTimeNanos } func min(x, y int64) int64 { if x < y { return x } return y } // waitTimeLoop is the single event loop that claims tokens on a given bucket. func (b *tokenBucket) waitTimeLoop() { for { select { case req := <-b.waitTimer: req.response <- b.calcWaitTime(req.requested, req.maxWaitTimeNanos) case <-b.closer: logging.Printf("Garbage collecting bucket %v", b.fullName) // TODO(manik) properly notify goroutines who are currently trying to write to waitTimer return } } } func (b *tokenBucket) Config() *pbconfig.BucketConfig { return b.cfg } func (b *tokenBucket) Dynamic() bool { return b.dynamic } func (b *tokenBucket) Destroy() { // Signal the waitTimeLoop to exit close(b.closer) }
Java
<?php namespace Academe\Instructions; use Academe\Contracts\Mapper\Executable; abstract class BaseExecutable implements Executable { }
Java
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var STATIC_REG = /.*\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)$/; var VER_REG = /[\W][\d\w]+(?=\.\w+$)/; var _default = function _default(req, res, next) { var filePaths = req.url.split('/'); if (STATIC_REG.test(req.path) && filePaths[2] === 'prd') { filePaths.splice(2, 1); req.url = filePaths.join('/').replace(VER_REG, ''); } next(); }; exports["default"] = _default;
Java
System.register([], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function toSnakeCase(camelCase) { if (!camelCase) { throw new Error("Please provide camelCase."); } return camelCase.replace(/([A-Z])/g, "-$1").toLowerCase(); } exports_1("toSnakeCase", toSnakeCase); return { setters: [], execute: function () { } }; }); //# sourceMappingURL=to.snake.case.js.map
Java
package com.gotcreations.emojilibrary.controller; import android.animation.Animator; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import androidx.annotation.DrawableRes; import androidx.appcompat.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.gotcreations.emojilibrary.R; import com.gotcreations.emojilibrary.model.layout.EmojiCompatActivity; import com.gotcreations.emojilibrary.model.layout.EmojiEditText; import com.gotcreations.emojilibrary.model.layout.AppPanelEventListener; import com.gotcreations.emojilibrary.model.layout.TelegramPanelView; import com.gotcreations.emojilibrary.util.AbstractAnimatorListener; import static android.view.View.GONE; import static android.view.View.getDefaultSize; /** * Created by edgar on 18/02/2016. */ public class TelegramPanel extends AppPanel{ private static final String TAG = "TelegramPanel"; public static final int EMPTY_MESSAGE = 0; public static final int EMPTY_MESSAGE_EMOJI_KEYBOARD = 1; public static final int EMPTY_MESSAGE_KEYBOARD = 2; public static final int PREPARED_MESSAGE = 3; public static final int PREPARED_MESSAGE_EMOJI_KEYBOARD = 4; public static final int PREPARED_MESSAGE_KEYBOARD = 5; public static final int AUDIO = 6; private Toolbar mBottomPanel; private TextView audioTime; private TelegramPanelView panelView; private int state; // CONSTRUCTOR public TelegramPanel(EmojiCompatActivity activity, AppPanelEventListener listener) { super(activity); this.mActivity = activity; init(); this.mEmojiKeyboard = new EmojiKeyboard(this.mActivity, this.mInput); this.mListener = listener; } public TelegramPanel(EmojiCompatActivity activity) { this(activity, null); } // INITIALIZATION @Override protected void initBottomPanel() { this.audioTime = (TextView) this.mActivity.findViewById(R.id.audio_time); this.mBottomPanel = (Toolbar) this.mActivity.findViewById(R.id.panel); this.panelView = (TelegramPanelView) this.mActivity.findViewById(R.id.panel_container).getParent(); this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); this.mBottomPanel.inflateMenu(R.menu.telegram_menu); this.mBottomPanel.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (state == AUDIO) { fireOnMicOffClicked(); showAudioPanel(false); } else if (TelegramPanel.this.isEmojiKeyboardVisible) { TelegramPanel.this.closeCurtain(); if (TelegramPanel.this.mInput.isSoftKeyboardVisible()) { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); TelegramPanel.this.mInput.hideSoftKeyboard(); } else { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); TelegramPanel.this.mInput.showSoftKeyboard(); } } else { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); TelegramPanel.this.closeCurtain(); TelegramPanel.this.showEmojiKeyboard(0); } } }); this.mBottomPanel.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_attach) { fireOnAttachClicked(); } else if (item.getItemId() == R.id.action_mic) { switch (state) { case AUDIO: fireOnSendClicked(); showAudioPanel(false); break; default: if (TelegramPanel.this.mInput.getText().toString().equals("")) { showAudioPanel(true); } else { fireOnSendClicked(); } } } return Boolean.TRUE; } }); this.mCurtain = (LinearLayout) this.mActivity.findViewById(R.id.curtain); this.state = EMPTY_MESSAGE; } @Override protected void setInputConfig() { this.mInput = (EmojiEditText) this.mBottomPanel.findViewById(R.id.input); mInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); this.mInput.addOnSoftKeyboardListener(new EmojiEditText.OnSoftKeyboardListener() { @Override public void onSoftKeyboardDisplay() { if (!TelegramPanel.this.isEmojiKeyboardVisible) { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.schedule(new Runnable() { @Override public void run() { Handler mainHandler = new Handler(TelegramPanel.this.mActivity.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { TelegramPanel.this.openCurtain(); TelegramPanel.this.showEmojiKeyboard(0); } }; mainHandler.post(myRunnable); } }, 150, TimeUnit.MILLISECONDS); } } @Override public void onSoftKeyboardHidden() { if (TelegramPanel.this.isEmojiKeyboardVisible) { TelegramPanel.this.closeCurtain(); TelegramPanel.this.hideEmojiKeyboard(200); } } }); this.mInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { showSendOptions(true); } @Override public void afterTextChanged(Editable s) { } }); audioTime.setTextColor(panelView.getAudioTextColor()); mInput.setTextColor(panelView.getTextColor()); mInput.setHint(panelView.getHintText()); mInput.setHintTextColor(panelView.getTextColorHint()); setIcon(R.id.action_attach, panelView.getAttachIconColor(), R.drawable.ic_attachment); setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic); } private void setIcon(int itemId, int color, @DrawableRes int drawableId) { Drawable icon = mActivity.getResources().getDrawable(drawableId); icon.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); setIcon(itemId, icon); } private void setIcon(int itemId, Drawable icon) { Menu menu = this.mBottomPanel.getMenu(); MenuItem mi = menu.findItem(itemId); mi.setIcon(icon); } @Override public void showAudioPanel(final boolean show) { if (show) { state = AUDIO; hideEmojiKeyboard(0); this.mInput.hideSoftKeyboard(); this.mInput.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Hide mInput"); mInput.setVisibility(GONE); } }).start(); this.audioTime.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "show audioTime"); audioTime.setVisibility(View.VISIBLE); } }).start(); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } Drawable icCircle = mActivity.getResources().getDrawable(R.drawable.ic_circle); icCircle.setColorFilter(panelView.getAudioIconColor(), PorterDuff.Mode.SRC_ATOP); this.mBottomPanel.setNavigationIcon(icCircle); fireOnMicOnClicked(); } else { this.audioTime.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Hide audioInput"); audioTime.setVisibility(GONE); } }).start(); this.mInput.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Show mInput"); mInput.setVisibility(View.VISIBLE); } }).start(); showSendOptions(true); } } public void showSendOptions(boolean show) { final MenuItem micButton = TelegramPanel.this.mBottomPanel.getMenu().findItem(R.id.action_mic); if (isEmojiKeyboardVisible) { this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); } else { this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); } if (!this.mInput.getText().toString().equals("") && show) { if (state != PREPARED_MESSAGE && state != PREPARED_MESSAGE_EMOJI_KEYBOARD && state != PREPARED_MESSAGE_KEYBOARD) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } } state = PREPARED_MESSAGE; if (mInput.isSoftKeyboardVisible()) { state = PREPARED_MESSAGE_KEYBOARD; } else if (isEmojiKeyboardVisible) { state = PREPARED_MESSAGE_EMOJI_KEYBOARD; } } else { state = EMPTY_MESSAGE; if (mInput.isSoftKeyboardVisible()) { state = EMPTY_MESSAGE_KEYBOARD; } else if (isEmojiKeyboardVisible) { state = EMPTY_MESSAGE_EMOJI_KEYBOARD; } TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(1).scaleY(1).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } } } public int getState() { return state; } public boolean isInState(int state) { return this.state == state; } public boolean isInAudioState() { return isInState(AUDIO); } public boolean isInMessageState() { return !isInAudioState(); } @Override public void hideEmojiKeyboard(int delay) { super.hideEmojiKeyboard(delay); this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); } public void setAudioTime(CharSequence time) { this.audioTime.setText(time); } }
Java
/** * Copyright Pravega Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pravega.controller.server.eventProcessor.requesthandlers; import com.google.common.annotations.VisibleForTesting; import io.pravega.common.Timer; import io.pravega.common.concurrent.Futures; import io.pravega.common.tracing.TagLogger; import io.pravega.controller.eventProcessor.impl.SerializedRequestHandler; import io.pravega.controller.metrics.TransactionMetrics; import io.pravega.controller.server.ControllerService; import io.pravega.controller.store.stream.OperationContext; import io.pravega.controller.store.stream.StreamMetadataStore; import io.pravega.controller.store.stream.records.StreamSegmentRecord; import io.pravega.controller.task.Stream.StreamMetadataTasks; import io.pravega.shared.controller.event.AbortEvent; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import org.slf4j.LoggerFactory; /** * This actor processes commit txn events. * It does the following 2 operations in order. * 1. Send abort txn message to active segments of the stream. * 2. Change txn state from aborting to aborted. */ public class AbortRequestHandler extends SerializedRequestHandler<AbortEvent> { private static final TagLogger log = new TagLogger(LoggerFactory.getLogger(AbortRequestHandler.class)); private final StreamMetadataStore streamMetadataStore; private final StreamMetadataTasks streamMetadataTasks; private final ScheduledExecutorService executor; private final BlockingQueue<AbortEvent> processedEvents; @VisibleForTesting public AbortRequestHandler(final StreamMetadataStore streamMetadataStore, final StreamMetadataTasks streamMetadataTasks, final ScheduledExecutorService executor, final BlockingQueue<AbortEvent> queue) { super(executor); this.streamMetadataStore = streamMetadataStore; this.streamMetadataTasks = streamMetadataTasks; this.executor = executor; this.processedEvents = queue; } public AbortRequestHandler(final StreamMetadataStore streamMetadataStore, final StreamMetadataTasks streamMetadataTasks, final ScheduledExecutorService executor) { super(executor); this.streamMetadataStore = streamMetadataStore; this.streamMetadataTasks = streamMetadataTasks; this.executor = executor; this.processedEvents = null; } @Override public CompletableFuture<Void> processEvent(AbortEvent event) { String scope = event.getScope(); String stream = event.getStream(); int epoch = event.getEpoch(); UUID txId = event.getTxid(); long requestId = event.getRequestId(); if (requestId == 0L) { requestId = ControllerService.nextRequestId(); } Timer timer = new Timer(); OperationContext context = streamMetadataStore.createStreamContext(scope, stream, requestId); log.info(requestId, "Aborting transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); return Futures.toVoid(streamMetadataStore.getSegmentsInEpoch(event.getScope(), event.getStream(), epoch, context, executor) .thenApply(segments -> segments.stream().map(StreamSegmentRecord::segmentId) .collect(Collectors.toList())) .thenCompose(segments -> streamMetadataTasks.notifyTxnAbort(scope, stream, segments, txId, context.getRequestId())) .thenCompose(x -> streamMetadataStore.abortTransaction(scope, stream, txId, context, executor)) .whenComplete((result, error) -> { if (error != null) { log.warn(context.getRequestId(), "Failed aborting transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); TransactionMetrics.getInstance().abortTransactionFailed(scope, stream); } else { log.info(context.getRequestId(), "Successfully aborted transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); if (processedEvents != null) { processedEvents.offer(event); } TransactionMetrics.getInstance().abortTransaction(scope, stream, timer.getElapsed()); } })); } }
Java
# Halanthium purpureum (Moq.) Bunge SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Copyright (c) 2019 Infortrend Technology, 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. class InfortrendNASTestData(object): fake_share_id = ['5a0aa06e-1c57-4996-be46-b81e360e8866', # NFS 'aac4fe64-7a9c-472a-b156-9adbb50b4d29'] # CIFS fake_share_name = [fake_share_id[0].replace('-', ''), fake_share_id[1].replace('-', '')] fake_channel_ip = ['172.27.112.223', '172.27.113.209'] fake_service_status_data = ('(64175, 1234, 272, 0)\n\n' '{"cliCode": ' '[{"Return": "0x0000", "CLI": "Successful"}], ' '"returnCode": [], ' '"data": ' '[{"A": ' '{"NFS": ' '{"displayName": "NFS", ' '"state_time": "2017-05-04 14:19:53", ' '"enabled": true, ' '"cpu_rate": "0.0", ' '"mem_rate": "0.0", ' '"state": "exited", ' '"type": "share"}}}]}\n\n') fake_folder_status_data = ('(64175, 1234, 1017, 0)\n\n' '{"cliCode": ' '[{"Return": "0x0000", "CLI": "Successful"}], ' '"returnCode": [], ' '"data": ' '[{"utility": "1.00", ' '"used": "33886208", ' '"subshare": true, ' '"share": false, ' '"worm": "", ' '"free": "321931374592", ' '"fsType": "xfs", ' '"owner": "A", ' '"readOnly": false, ' '"modifyTime": "2017-04-27 16:16", ' '"directory": "/share-pool-01/LV-1", ' '"volumeId": "6541BAFB2E6C57B6", ' '"mounted": true, ' '"size": "321965260800"}, ' '{"utility": "1.00", ' '"used": "33779712", ' '"subshare": false, ' '"share": false, ' '"worm": "", ' '"free": "107287973888", ' '"fsType": "xfs", ' '"owner": "A", ' '"readOnly": false, ' '"modifyTime": "2017-04-27 15:45", ' '"directory": "/share-pool-02/LV-1", ' '"volumeId": "147A8FB67DA39914", ' '"mounted": true, ' '"size": "107321753600"}]}\n\n') fake_nfs_status_off = [{ 'A': { 'NFS': { 'displayName': 'NFS', 'state_time': '2017-05-04 14:19:53', 'enabled': False, 'cpu_rate': '0.0', 'mem_rate': '0.0', 'state': 'exited', 'type': 'share', } } }] fake_folder_status = [{ 'utility': '1.00', 'used': '33886208', 'subshare': True, 'share': False, 'worm': '', 'free': '321931374592', 'fsType': 'xfs', 'owner': 'A', 'readOnly': False, 'modifyTime': '2017-04-27 16:16', 'directory': '/share-pool-01/LV-1', 'volumeId': '6541BAFB2E6C57B6', 'mounted': True, 'size': '321965260800'}, { 'utility': '1.00', 'used': '33779712', 'subshare': False, 'share': False, 'worm': '', 'free': '107287973888', 'fsType': 'xfs', 'owner': 'A', 'readOnly': False, 'modifyTime': '2017-04-27 15:45', 'directory': '/share-pool-02/LV-1', 'volumeId': '147A8FB67DA39914', 'mounted': True, 'size': '107321753600', }] def fake_get_channel_status(self, ch1_status='UP'): return [{ 'datalink': 'mgmt0', 'status': 'UP', 'typeConfig': 'DHCP', 'IP': '172.27.112.125', 'MAC': '00:d0:23:00:15:a6', 'netmask': '255.255.240.0', 'type': 'dhcp', 'gateway': '172.27.127.254'}, { 'datalink': 'CH0', 'status': 'UP', 'typeConfig': 'DHCP', 'IP': self.fake_channel_ip[0], 'MAC': '00:d0:23:80:15:a6', 'netmask': '255.255.240.0', 'type': 'dhcp', 'gateway': '172.27.127.254'}, { 'datalink': 'CH1', 'status': ch1_status, 'typeConfig': 'DHCP', 'IP': self.fake_channel_ip[1], 'MAC': '00:d0:23:40:15:a6', 'netmask': '255.255.240.0', 'type': 'dhcp', 'gateway': '172.27.127.254'}, { 'datalink': 'CH2', 'status': 'DOWN', 'typeConfig': 'DHCP', 'IP': '', 'MAC': '00:d0:23:c0:15:a6', 'netmask': '', 'type': '', 'gateway': ''}, { 'datalink': 'CH3', 'status': 'DOWN', 'typeConfig': 'DHCP', 'IP': '', 'MAC': '00:d0:23:20:15:a6', 'netmask': '', 'type': '', 'gateway': '', }] fake_fquota_status = [{ 'quota': '21474836480', 'used': '0', 'name': 'test-folder', 'type': 'subfolder', 'id': '537178178'}, { 'quota': '32212254720', 'used': '0', 'name': fake_share_name[0], 'type': 'subfolder', 'id': '805306752'}, { 'quota': '53687091200', 'used': '21474836480', 'name': fake_share_name[1], 'type': 'subfolder', 'id': '69'}, { 'quota': '94091997184', 'used': '0', 'type': 'subfolder', 'id': '70', "name": 'test-folder-02' }] fake_fquota_status_with_no_settings = [] def fake_get_share_status_nfs(self, status=False): fake_share_status_nfs = [{ 'ftp': False, 'cifs': False, 'oss': False, 'sftp': False, 'nfs': status, 'directory': '/LV-1/share-pool-01/' + self.fake_share_name[0], 'exist': True, 'afp': False, 'webdav': False }] if status: fake_share_status_nfs[0]['nfs_detail'] = { 'hostList': [{ 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'ro', 'host': '*', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check', }] } return fake_share_status_nfs def fake_get_share_status_cifs(self, status=False): fake_share_status_cifs = [{ 'ftp': False, 'cifs': status, 'oss': False, 'sftp': False, 'nfs': False, 'directory': '/share-pool-01/LV-1/' + self.fake_share_name[1], 'exist': True, 'afp': False, 'webdav': False }] if status: fake_share_status_cifs[0]['cifs_detail'] = { 'available': True, 'encrypt': False, 'description': '', 'sharename': 'cifs-01', 'failover': '', 'AIO': True, 'priv': 'None', 'recycle_bin': False, 'ABE': True, } return fake_share_status_cifs fake_subfolder_data = [{ 'size': '6', 'index': '34', 'description': '', 'encryption': '', 'isEnd': False, 'share': False, 'volumeId': '6541BAFB2E6C57B6', 'quota': '', 'modifyTime': '2017-04-06 11:35', 'owner': 'A', 'path': '/share-pool-01/LV-1/UserHome', 'subshare': True, 'type': 'subfolder', 'empty': False, 'name': 'UserHome'}, { 'size': '6', 'index': '39', 'description': '', 'encryption': '', 'isEnd': False, 'share': False, 'volumeId': '6541BAFB2E6C57B6', 'quota': '21474836480', 'modifyTime': '2017-04-27 15:44', 'owner': 'A', 'path': '/share-pool-01/LV-1/test-folder', 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': 'test-folder'}, { 'size': '6', 'index': '45', 'description': '', 'encryption': '', 'isEnd': False, 'share': True, 'volumeId': '6541BAFB2E6C57B6', 'quota': '32212254720', 'modifyTime': '2017-04-27 16:15', 'owner': 'A', 'path': '/share-pool-01/LV-1/' + fake_share_name[0], 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': fake_share_name[0]}, { 'size': '6', 'index': '512', 'description': '', 'encryption': '', 'isEnd': True, 'share': True, 'volumeId': '6541BAFB2E6C57B6', 'quota': '53687091200', 'modifyTime': '2017-04-27 16:16', 'owner': 'A', 'path': '/share-pool-01/LV-1/' + fake_share_name[1], 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': fake_share_name[1]}, { 'size': '6', 'index': '777', 'description': '', 'encryption': '', 'isEnd': False, 'share': False, 'volumeId': '6541BAFB2E6C57B6', 'quota': '94091997184', 'modifyTime': '2017-04-28 15:44', 'owner': 'A', 'path': '/share-pool-01/LV-1/test-folder-02', 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': 'test-folder-02' }] fake_cifs_user_list = [{ 'Superuser': 'No', 'Group': 'users', 'Description': '', 'Quota': 'none', 'PWD Expiry Date': '2291-01-19', 'Home Directory': '/share-pool-01/LV-1/UserHome/user01', 'UID': '100001', 'Type': 'Local', 'Name': 'user01'}, { 'Superuser': 'No', 'Group': 'users', 'Description': '', 'Quota': 'none', 'PWD Expiry Date': '2017-08-07', 'Home Directory': '/share-pool-01/LV-1/UserHome/user02', 'UID': '100002', 'Type': 'Local', 'Name': 'user02' }] fake_share_status_nfs_with_rules = [{ 'ftp': False, 'cifs': False, 'oss': False, 'sftp': False, 'nfs': True, 'directory': '/share-pool-01/LV-1/' + fake_share_name[0], 'exist': True, 'nfs_detail': { 'hostList': [{ 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'ro', 'host': '*', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check'}, { 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'rw', 'host': '172.27.1.1', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check'}, { 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'rw', 'host': '172.27.1.2', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check'}] }, 'afp': False, 'webdav': False, }] fake_share_status_cifs_with_rules = [ { 'permission': { 'Read': True, 'Write': True, 'Execute': True}, 'type': 'user', 'id': '100001', 'name': 'user01' }, { 'permission': { 'Read': True, 'Write': False, 'Execute': True}, 'type': 'user', 'id': '100002', 'name': 'user02' }, { 'permission': { 'Read': True, 'Write': False, 'Execute': True}, 'type': 'group@', 'id': '100', 'name': 'users' }, { 'permission': { 'Read': True, 'Write': False, 'Execute': True}, 'type': 'other@', 'id': '', 'name': '' } ]
Java
import { createStore, applyMiddleware, compose } from 'redux' import logger from 'redux-logger' import thunkMiddleware from 'redux-thunk' import rootReducer from './reducers' const configureStore = () => { const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; return createStore(rootReducer, /* preloadedState, */ composeEnhancers( applyMiddleware(thunkMiddleware) // applyMiddleware(logger) )); } export default configureStore
Java
(function outer(modules, cache, entries){ /** * Global */ var global = (function(){ return this; })(); /** * Require `name`. * * @param {String} name * @param {Boolean} jumped * @api public */ function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); } /** * Call module `id` and cache it. * * @param {Number} id * @param {Function} require * @return {Function} * @api private */ function call(id, require){ var m = cache[id] = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep ? dep : req); }, m, m.exports, outer, modules, cache, entries); // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; } /** * Require all entries exposing them on global if needed. */ for (var id in entries) { if (entries[id]) { global[entries[id]] = require(id); } else { require(id); } } /** * Duo flag. */ require.duo = true; /** * Expose cache. */ require.cache = cache; /** * Expose modules */ require.modules = modules; /** * Return newest require. */ return require; })({ 1: [function(require, module, exports) { /** @jsx React.DOM */ React.renderComponent( React.DOM.h1(null, "Hello, world!"), document.getElementById('example') ); }, {}]}, {}, {"1":""})
Java
/** * Copyright 2011-2021 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.serde; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.math.BigDecimal; import java.sql.Timestamp; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.serde2.io.HiveCharWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable; import org.apache.hadoop.hive.serde2.io.TimestampWritable; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveCharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector; import org.apache.hadoop.io.Text; import org.junit.Test; import com.asakusafw.runtime.value.Date; import com.asakusafw.runtime.value.DateOption; import com.asakusafw.runtime.value.DateTime; import com.asakusafw.runtime.value.DateTimeOption; import com.asakusafw.runtime.value.DecimalOption; import com.asakusafw.runtime.value.StringOption; /** * Test for {@link ValueSerdeFactory}. */ public class ValueSerdeFactoryTest { /** * constants. */ @Test public void constants() { for (ValueSerdeFactory serde : ValueSerdeFactory.values()) { serde.getDriver(serde.getInspector()); } } /** * char. */ @Test public void getChar() { ValueSerde serde = ValueSerdeFactory.getChar(10); HiveCharObjectInspector inspector = (HiveCharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveChar value = new HiveChar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveCharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * varchar. */ @Test public void getVarchar() { ValueSerde serde = ValueSerdeFactory.getVarchar(10); HiveVarcharObjectInspector inspector = (HiveVarcharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveVarchar value = new HiveVarchar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); // HiveVarchar cannot compare by equals assertThat(inspector.getPrimitiveJavaObject(option).compareTo(value), is(0)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveVarcharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * qualified decimal. */ @Test public void getDecimal() { ValueSerde serde = ValueSerdeFactory.getDecimal(10, 2); HiveDecimalObjectInspector inspector = (HiveDecimalObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45")); HiveDecimal value = HiveDecimal.create(new BigDecimal("123.45")); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveDecimalWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * decimal by string. */ @Test public void decimal_by_string() { ValueSerde serde = StringValueSerdeFactory.DECIMAL; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45")); String value = "123.45"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by string. */ @Test public void date_by_string() { ValueSerde serde = StringValueSerdeFactory.DATE; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); String value = "2014-07-01"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(2014, 7, 1, 12, 5, 59)); String value = "2014-07-01 12:05:59"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string_w_zeros() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(1, 1, 1, 0, 0, 0)); String value = "0001-01-01 00:00:00"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by timestamp. */ @SuppressWarnings("deprecation") @Test public void date_by_timestamp() { ValueSerde serde = TimestampValueSerdeFactory.DATE; TimestampObjectInspector inspector = (TimestampObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); Timestamp value = new Timestamp(2014 - 1900, 7 - 1, 1, 0, 0, 0, 0); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new TimestampWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } }
Java
/* * 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. */ declare module '*.less'; declare function la(textToLocalize: string): string;
Java
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Embeds an instagram photo. The data-shortcode attribute can be * easily copied from a normal instagram URL. Example: <code> <amp-instagram * data-shortcode="fBwFP" data-captioned data-default-framing alt="Fastest page * in the west." width="320" height="392" layout="responsive"> </amp-instagram> * </code> * * For responsive embedding the width and height can be left unchanged from the * example above and should produce the correct aspect ratio. amp-instagram will * attempt to resize on load based on the height reported by the embedded frame. * If captions are specified (data-captioned) then a resize will be requested * every time due to the fact that it's not possible to know the height of the * caption in advance. * * If captions are included it is stringly reccomended that an overflow element * is also included. See description of overflow in amp-iframe. * * If data-default-framing is present will apply the default instagram frame * style without changing the layout/size. */ import {CSS} from '../../../build/amp-instagram-0.1.css'; import {getData, listen} from '../../../src/event-helper'; import {isLayoutSizeDefined} from '../../../src/layout'; import {isObject} from '../../../src/types'; import {removeElement} from '../../../src/dom'; import {setStyles} from '../../../src/style'; import {startsWith} from '../../../src/string'; import {tryParseJson} from '../../../src/json'; import {user} from '../../../src/log'; class AmpInstagram extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?Element} */ this.iframe_ = null; /** @private {?string} */ this.shortcode_ = ''; /** @private {?Function} */ this.unlistenMessage_ = null; /** @private {string} */ this.captioned_ = ''; /** * @private {?Promise} * @visibleForTesting */ this.iframePromise_ = null; } /** * @param {boolean=} opt_onLayout * @override */ preconnectCallback(opt_onLayout) { // See // https://instagram.com/developer/embedding/?hl=en this.preconnect.url('https://www.instagram.com', opt_onLayout); // Host instagram used for image serving. While the host name is // funky this appears to be stable in the post-domain sharding era. this.preconnect.url('https://instagram.fsnc1-1.fna.fbcdn.net', opt_onLayout); } /** @override */ renderOutsideViewport() { return false; } /** @override */ buildCallback() { this.shortcode_ = user().assert( (this.element.getAttribute('data-shortcode') || this.element.getAttribute('shortcode')), 'The data-shortcode attribute is required for <amp-instagram> %s', this.element); this.captioned_ = this.element.hasAttribute('data-captioned') ? 'captioned/' : ''; } /** @override */ createPlaceholderCallback() { const placeholder = this.win.document.createElement('div'); placeholder.setAttribute('placeholder', ''); const image = this.win.document.createElement('amp-img'); image.setAttribute('noprerender', ''); // This will redirect to the image URL. By experimentation this is // always the same URL that is actually used inside of the embed. image.setAttribute('src', 'https://www.instagram.com/p/' + encodeURIComponent(this.shortcode_) + '/media/?size=l'); image.setAttribute('layout', 'fill'); image.setAttribute('referrerpolicy', 'origin'); this.propagateAttributes(['alt'], image); /* * Add instagram default styling */ if (this.element.hasAttribute('data-default-framing')) { this.element.classList.add('amp-instagram-default-framing'); } // This makes the non-iframe image appear in the exact same spot // where it will be inside of the iframe. setStyles(image, { 'top': '0 px', 'bottom': '0 px', 'left': '0 px', 'right': '0 px', }); placeholder.appendChild(image); return placeholder; } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ layoutCallback() { const iframe = this.element.ownerDocument.createElement('iframe'); this.iframe_ = iframe; this.unlistenMessage_ = listen( this.win, 'message', this.handleInstagramMessages_.bind(this) ); iframe.setAttribute('scrolling', 'no'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowtransparency', 'true'); //Add title to the iframe for better accessibility. iframe.setAttribute('title', 'Instagram: ' + this.element.getAttribute('alt')); iframe.src = 'https://www.instagram.com/p/' + encodeURIComponent(this.shortcode_) + '/embed/' + this.captioned_ + '?cr=1&v=7'; this.applyFillContent(iframe); this.element.appendChild(iframe); setStyles(iframe, { 'opacity': 0, }); return this.iframePromise_ = this.loadPromise(iframe).then(() => { this.getVsync().mutate(() => { setStyles(iframe, { 'opacity': 1, }); }); }); } /** * @param {!Event} event * @private */ handleInstagramMessages_(event) { if (event.origin != 'https://www.instagram.com' || event.source != this.iframe_.contentWindow) { return; } const eventData = getData(event); if (!eventData || !(isObject(eventData) || startsWith(/** @type {string} */ (eventData), '{'))) { return; // Doesn't look like JSON. } const data = isObject(eventData) ? eventData : tryParseJson(eventData); if (data === undefined) { return; // We only process valid JSON. } if (data['type'] == 'MEASURE' && data['details']) { const height = data['details']['height']; this.getVsync().measure(() => { if (this.iframe_ && this.iframe_./*OK*/offsetHeight !== height) { this./*OK*/changeHeight(height); } }); } } /** @override */ unlayoutOnPause() { return true; } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; this.iframePromise_ = null; } if (this.unlistenMessage_) { this.unlistenMessage_(); } return true; // Call layoutCallback again. } } AMP.extension('amp-instagram', '0.1', AMP => { AMP.registerElement('amp-instagram', AmpInstagram, CSS); });
Java
import arez.Arez; import arez.ArezContext; import arez.Component; import arez.Disposable; import arez.ObservableValue; import arez.SafeProcedure; import arez.component.DisposeNotifier; import arez.component.Identifiable; import arez.component.internal.ComponentKernel; import java.text.ParseException; import javax.annotation.Generated; import javax.annotation.Nonnull; import org.realityforge.braincheck.Guards; @Generated("arez.processor.ArezProcessor") final class Arez_ObservableWithSpecificExceptionModel extends ObservableWithSpecificExceptionModel implements Disposable, Identifiable<Integer>, DisposeNotifier { private static volatile int $$arezi$$_nextId; private final ComponentKernel $$arezi$$_kernel; @Nonnull private final ObservableValue<Long> $$arez$$_time; Arez_ObservableWithSpecificExceptionModel() { super(); final ArezContext $$arezv$$_context = Arez.context(); final int $$arezv$$_id = ++$$arezi$$_nextId; final String $$arezv$$_name = Arez.areNamesEnabled() ? "ObservableWithSpecificExceptionModel." + $$arezv$$_id : null; final Component $$arezv$$_component = Arez.areNativeComponentsEnabled() ? $$arezv$$_context.component( "ObservableWithSpecificExceptionModel", $$arezv$$_id, $$arezv$$_name, this::$$arezi$$_nativeComponentPreDispose ) : null; this.$$arezi$$_kernel = new ComponentKernel( Arez.areZonesEnabled() ? $$arezv$$_context : null, Arez.areNamesEnabled() ? $$arezv$$_name : null, $$arezv$$_id, Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, null, Arez.areNativeComponentsEnabled() ? null : this::$$arezi$$_dispose, null, true, false, false ); this.$$arez$$_time = $$arezv$$_context.observable( Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, Arez.areNamesEnabled() ? $$arezv$$_name + ".time" : null, Arez.arePropertyIntrospectorsEnabled() ? () -> super.getTime() : null, Arez.arePropertyIntrospectorsEnabled() ? v -> super.setTime( v ) : null ); this.$$arezi$$_kernel.componentConstructed(); this.$$arezi$$_kernel.componentReady(); } private int $$arezi$$_id() { return this.$$arezi$$_kernel.getId(); } @Override @Nonnull public Integer getArezId() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'getArezId' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'getArezId' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return $$arezi$$_id(); } private void $$arezi$$_nativeComponentPreDispose() { this.$$arezi$$_kernel.notifyOnDisposeListeners(); } @Override public void addOnDisposeListener(@Nonnull final Object key, @Nonnull final SafeProcedure action) { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'addOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } this.$$arezi$$_kernel.addOnDisposeListener( key, action ); } @Override public void removeOnDisposeListener(@Nonnull final Object key) { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'removeOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'removeOnDisposeListener' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } this.$$arezi$$_kernel.removeOnDisposeListener( key ); } @Override public boolean isDisposed() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'isDisposed' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'isDisposed' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return this.$$arezi$$_kernel.isDisposed(); } @Override public void dispose() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'dispose' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'dispose' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } this.$$arezi$$_kernel.dispose(); } private void $$arezi$$_dispose() { this.$$arez$$_time.dispose(); } @Override public long getTime() throws ParseException { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'getTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" ); } this.$$arez$$_time.reportObserved(); return super.getTime(); } @Override public void setTime(final long time) throws ParseException { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'setTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" ); } this.$$arez$$_time.preReportChanged(); final long $$arezv$$_currentValue = super.getTime(); if ( time != $$arezv$$_currentValue ) { super.setTime( time ); this.$$arez$$_time.reportChanged(); } } @Override public String toString() { if ( Arez.areNamesEnabled() ) { return "ArezComponent[" + this.$$arezi$$_kernel.getName() + "]"; } else { return super.toString(); } } }
Java
namespace RoslynPad.Roslyn.Snippets { public sealed class SnippetInfo { public string Shortcut { get; } public string Title { get; } public string Description { get; } public SnippetInfo(string shortcut, string title, string description) { Shortcut = shortcut; Title = title; Description = description; } } }
Java
/** * Licensing arrangement (from website FAQ): * * The software is completely free for any purpose, unless notes at the * head of the program text indicates otherwise (which is rare). In any * case, the notes about licensing are never more restrictive than the * BSD License. * */ package com.novartis.pcs.ontology.service.mapper; /* Porter stemmer in Java. The original paper is in Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, no. 3, pp 130-137, See also http://www.tartarus.org/~martin/PorterStemmer/index.html Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below. Tthe words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1] is then out outside the bounds of b. Similarly, Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below. 'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and b[j] is then outside the bounds of b. Release 3. [ This version is derived from Release 3, modified by Brian Goetz to optimize for fewer object creations. ] */ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * * Stemmer, implementing the Porter Stemming Algorithm * * The Stemmer class transforms a word into its root form. The input * word can be provided a character at time (by calling add()), or at once * by calling one of the various stem(something) methods. */ class PorterStemmer { private char[] b; private int i, /* offset into b */ j, k, k0; private boolean dirty = false; private static final int INC = 50; /* unit of size whereby b is increased */ private static final int EXTRA = 1; public PorterStemmer() { b = new char[INC]; i = 0; } /** * reset() resets the stemmer so it can stem another word. If you invoke * the stemmer by calling add(char) and then stem(), you must call reset() * before starting another word. */ public void reset() { i = 0; dirty = false; } /** * Add a character to the word being stemmed. When you are finished * adding characters, you can call stem(void) to process the word. */ public void add(char ch) { if (b.length <= i + EXTRA) { char[] new_b = new char[b.length+INC]; System.arraycopy(b, 0, new_b, 0, b.length); b = new_b; } b[i++] = ch; } /** * After a word has been stemmed, it can be retrieved by toString(), * or a reference to the internal buffer can be retrieved by getResultBuffer * and getResultLength (which is generally more efficient.) */ @Override public String toString() { return new String(b,0,i); } /** * Returns the length of the word resulting from the stemming process. */ public int getResultLength() { return i; } /** * Returns a reference to a character buffer containing the results of * the stemming process. You also need to consult getResultLength() * to determine the length of the result. */ public char[] getResultBuffer() { return b; } /* cons(i) is true <=> b[i] is a consonant. */ private final boolean cons(int i) { switch (b[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': return false; case 'y': return (i==k0) ? true : !cons(i-1); default: return true; } } /* m() measures the number of consonant sequences between k0 and j. if c is a consonant sequence and v a vowel sequence, and <..> indicates arbitrary presence, <c><v> gives 0 <c>vc<v> gives 1 <c>vcvc<v> gives 2 <c>vcvcvc<v> gives 3 .... */ private final int m() { int n = 0; int i = k0; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; while(true) { while(true) { if (i > j) return n; if (cons(i)) break; i++; } i++; n++; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; } } /* vowelinstem() is true <=> k0,...j contains a vowel */ private final boolean vowelinstem() { int i; for (i = k0; i <= j; i++) if (! cons(i)) return true; return false; } /* doublec(j) is true <=> j,(j-1) contain a double consonant. */ private final boolean doublec(int j) { if (j < k0+1) return false; if (b[j] != b[j-1]) return false; return cons(j); } /* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant and also if the second c is not w,x or y. this is used when trying to restore an e at the end of a short word. e.g. cav(e), lov(e), hop(e), crim(e), but snow, box, tray. */ private final boolean cvc(int i) { if (i < k0+2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; else { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; } private final boolean ends(String s) { int l = s.length(); int o = k-l+1; if (o < k0) return false; for (int i = 0; i < l; i++) if (b[o+i] != s.charAt(i)) return false; j = k-l; return true; } /* setto(s) sets (j+1),...k to the characters in the string s, readjusting k. */ void setto(String s) { int l = s.length(); int o = j+1; for (int i = 0; i < l; i++) b[o+i] = s.charAt(i); k = j+l; dirty = true; } /* r(s) is used further down. */ void r(String s) { if (m() > 0) setto(s); } /* step1() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree disabled -> disable matting -> mat mating -> mate meeting -> meet milling -> mill messing -> mess meetings -> meet */ private final void step1() { if (b[k] == 's') { if (ends("sses")) k -= 2; else if (ends("ies")) setto("i"); else if (b[k-1] != 's') k--; } if (ends("eed")) { if (m() > 0) k--; } else if ((ends("ed") || ends("ing")) && vowelinstem()) { k = j; if (ends("at")) setto("ate"); else if (ends("bl")) setto("ble"); else if (ends("iz")) setto("ize"); else if (doublec(k)) { int ch = b[k--]; if (ch == 'l' || ch == 's' || ch == 'z') k++; } else if (m() == 1 && cvc(k)) setto("e"); } } /* step2() turns terminal y to i when there is another vowel in the stem. */ private final void step2() { if (ends("y") && vowelinstem()) { b[k] = 'i'; dirty = true; } } /* step3() maps double suffices to single ones. so -ization ( = -ize plus -ation) maps to -ize etc. note that the string before the suffix must give m() > 0. */ private final void step3() { if (k == k0) return; /* For Bug 1 */ switch (b[k-1]) { case 'a': if (ends("ational")) { r("ate"); break; } if (ends("tional")) { r("tion"); break; } break; case 'c': if (ends("enci")) { r("ence"); break; } if (ends("anci")) { r("ance"); break; } break; case 'e': if (ends("izer")) { r("ize"); break; } break; case 'l': if (ends("bli")) { r("ble"); break; } if (ends("alli")) { r("al"); break; } if (ends("entli")) { r("ent"); break; } if (ends("eli")) { r("e"); break; } if (ends("ousli")) { r("ous"); break; } break; case 'o': if (ends("ization")) { r("ize"); break; } if (ends("ation")) { r("ate"); break; } if (ends("ator")) { r("ate"); break; } break; case 's': if (ends("alism")) { r("al"); break; } if (ends("iveness")) { r("ive"); break; } if (ends("fulness")) { r("ful"); break; } if (ends("ousness")) { r("ous"); break; } break; case 't': if (ends("aliti")) { r("al"); break; } if (ends("iviti")) { r("ive"); break; } if (ends("biliti")) { r("ble"); break; } break; case 'g': if (ends("logi")) { r("log"); break; } } } /* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */ private final void step4() { switch (b[k]) { case 'e': if (ends("icate")) { r("ic"); break; } if (ends("ative")) { r(""); break; } if (ends("alize")) { r("al"); break; } break; case 'i': if (ends("iciti")) { r("ic"); break; } break; case 'l': if (ends("ical")) { r("ic"); break; } if (ends("ful")) { r(""); break; } break; case 's': if (ends("ness")) { r(""); break; } break; } } /* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */ private final void step5() { if (k == k0) return; /* for Bug 1 */ switch (b[k-1]) { case 'a': if (ends("al")) break; return; case 'c': if (ends("ance")) break; if (ends("ence")) break; return; case 'e': if (ends("er")) break; return; case 'i': if (ends("ic")) break; return; case 'l': if (ends("able")) break; if (ends("ible")) break; return; case 'n': if (ends("ant")) break; if (ends("ement")) break; if (ends("ment")) break; /* element etc. not stripped before the m */ if (ends("ent")) break; return; case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break; /* j >= 0 fixes Bug 2 */ if (ends("ou")) break; return; /* takes care of -ous */ case 's': if (ends("ism")) break; return; case 't': if (ends("ate")) break; if (ends("iti")) break; return; case 'u': if (ends("ous")) break; return; case 'v': if (ends("ive")) break; return; case 'z': if (ends("ize")) break; return; default: return; } if (m() > 1) k = j; } /* step6() removes a final -e if m() > 1. */ private final void step6() { j = k; if (b[k] == 'e') { int a = m(); if (a > 1 || a == 1 && !cvc(k-1)) k--; } if (b[k] == 'l' && doublec(k) && m() > 1) k--; } /** * Stem a word provided as a String. Returns the result as a String. */ public String stem(String s) { if (stem(s.toCharArray(), s.length())) return toString(); else return s; } /** Stem a word contained in a char[]. Returns true if the stemming process * resulted in a word different from the input. You can retrieve the * result with getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] word) { return stem(word, word.length); } /** Stem a word contained in a portion of a char[] array. Returns * true if the stemming process resulted in a word different from * the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] wordBuffer, int offset, int wordLen) { reset(); if (b.length < wordLen) { char[] new_b = new char[wordLen + EXTRA]; b = new_b; } System.arraycopy(wordBuffer, offset, b, 0, wordLen); i = wordLen; return stem(0); } /** Stem a word contained in a leading portion of a char[] array. * Returns true if the stemming process resulted in a word different * from the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] word, int wordLen) { return stem(word, 0, wordLen); } /** Stem the word placed into the Stemmer buffer through calls to add(). * Returns true if the stemming process resulted in a word different * from the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem() { return stem(0); } public boolean stem(int i0) { k = i - 1; k0 = i0; if (k > k0+1) { step1(); step2(); step3(); step4(); step5(); step6(); } // Also, a word is considered dirty if we lopped off letters // Thanks to Ifigenia Vairelles for pointing this out. if (i != k+1) dirty = true; i = k+1; return dirty; } /** Test program for demonstrating the Stemmer. It reads a file and * stems each word, writing the result to standard out. * Usage: Stemmer file-name */ public static void main(String[] args) { PorterStemmer s = new PorterStemmer(); for (int i = 0; i < args.length; i++) { try { InputStream in = new FileInputStream(args[i]); byte[] buffer = new byte[1024]; int bufferLen, offset, ch; bufferLen = in.read(buffer); offset = 0; s.reset(); while(true) { if (offset < bufferLen) ch = buffer[offset++]; else { bufferLen = in.read(buffer); offset = 0; if (bufferLen < 0) ch = -1; else ch = buffer[offset++]; } if (Character.isLetter((char) ch)) { s.add(Character.toLowerCase((char) ch)); } else { s.stem(); System.out.print(s.toString()); s.reset(); if (ch < 0) break; else { System.out.print((char) ch); } } } in.close(); } catch (IOException e) { System.out.println("error reading " + args[i]); } } } }
Java
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. # # Generated code. DO NOT EDIT! # # Snippet for GetTagKey # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-resourcemanager # [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] from google.cloud import resourcemanager_v3 async def sample_get_tag_key(): # Create a client client = resourcemanager_v3.TagKeysAsyncClient() # Initialize request argument(s) request = resourcemanager_v3.GetTagKeyRequest( name="name_value", ) # Make the request response = await client.get_tag_key(request=request) # Handle the response print(response) # [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]
Java
<?php /** * @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com) */ namespace Magento\Sales\Model\Grid; class CollectionUpdater implements \Magento\Framework\View\Layout\Argument\UpdaterInterface { /** * @var \Magento\Framework\Registry */ protected $registryManager; /** * @param \Magento\Framework\Registry $registryManager */ public function __construct(\Magento\Framework\Registry $registryManager) { $this->registryManager = $registryManager; } /** * Update grid collection according to chosen order * * @param \Magento\Sales\Model\Resource\Transaction\Grid\Collection $argument * @return \Magento\Sales\Model\Resource\Transaction\Grid\Collection */ public function update($argument) { $order = $this->registryManager->registry('current_order'); if ($order) { $argument->setOrderFilter($order->getId()); } $argument->addOrderInformation(['increment_id']); return $argument; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Mon Nov 06 11:57:26 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup (BOM: * : All 2017.11.0 API)</title> <meta name="date" content="2017-11-06"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup (BOM: * : All 2017.11.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.11.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/BroadcastGroup.html" target="_top">Frames</a></li> <li><a href="BroadcastGroup.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup" class="title">Uses of Class<br>org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq">org.wildfly.swarm.config.messaging.activemq</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq.server">org.wildfly.swarm.config.messaging.activemq.server</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></code></td> <td class="colLast"><span class="typeNameLabel">Server.ServerResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.ServerResources.html#broadcastGroup-java.lang.String-">broadcastGroup</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;key)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> that return types with arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">Server.ServerResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.ServerResources.html#broadcastGroups--">broadcastGroups</a></span>()</code> <div class="block">Get the list of BroadcastGroup resources</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html" title="type parameter in Server">T</a></code></td> <td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html#broadcastGroup-org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup-">broadcastGroup</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>&nbsp;value)</code> <div class="block">Add the BroadcastGroup object to the list of subresources</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Method parameters in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> with type arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html" title="type parameter in Server">T</a></code></td> <td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html#broadcastGroups-java.util.List-">broadcastGroups</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a>&lt;<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>&gt;&nbsp;value)</code> <div class="block">Add all BroadcastGroup objects to this subresource</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq.server"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> with type parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>&lt;T&gt;&gt;</span></code> <div class="block">A broadcast group is the means by which a server broadcasts connectors over the network.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroupConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroupConsumer</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>&lt;T&gt;&gt;</span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroupSupplier.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroupSupplier</a>&lt;T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>&gt;</span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></code></td> <td class="colLast"><span class="typeNameLabel">BroadcastGroupSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroupSupplier.html#get--">get</a></span>()</code> <div class="block">Constructed instance of BroadcastGroup resource</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.11.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/BroadcastGroup.html" target="_top">Frames</a></li> <li><a href="BroadcastGroup.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
Java
// 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 resolve import ( "context" "fmt" "github.com/google/gapid/core/data/id" "github.com/google/gapid/core/log" "github.com/google/gapid/gapis/api" "github.com/google/gapid/gapis/api/sync" "github.com/google/gapid/gapis/capture" "github.com/google/gapid/gapis/database" "github.com/google/gapid/gapis/resolve/initialcmds" "github.com/google/gapid/gapis/service/path" ) // ResolvedResources contains all of the resolved resources for a // particular point in the trace. type ResolvedResources struct { resourceMap api.ResourceMap resources map[id.ID]api.Resource resourceData map[id.ID]interface{} } // Resolve builds a ResolvedResources object for all of the resources // at the path r.After func (r *AllResourceDataResolvable) Resolve(ctx context.Context) (interface{}, error) { ctx = SetupContext(ctx, r.After.Capture, r.Config) resources, err := buildResources(ctx, r.After) if err != nil { return nil, err } return resources, nil } func buildResources(ctx context.Context, p *path.Command) (*ResolvedResources, error) { cmdIdx := p.Indices[0] capture, err := capture.Resolve(ctx) if err != nil { return nil, err } allCmds, err := Cmds(ctx, p.Capture) if err != nil { return nil, err } s, err := SyncData(ctx, p.Capture) if err != nil { return nil, err } cmds, err := sync.MutationCmdsFor(ctx, p.Capture, s, allCmds, api.CmdID(cmdIdx), p.Indices[1:], false) if err != nil { return nil, err } initialCmds, ranges, err := initialcmds.InitialCommands(ctx, p.Capture) if err != nil { return nil, err } state := capture.NewUninitializedState(ctx).ReserveMemory(ranges) var currentCmdIndex uint64 var currentCmdResourceCount int idMap := api.ResourceMap{} resources := make(map[id.ID]api.Resource) state.OnResourceCreated = func(r api.Resource) { currentCmdResourceCount++ i := genResourceID(currentCmdIndex, currentCmdResourceCount) idMap[r] = i resources[i] = r } api.ForeachCmd(ctx, initialCmds, func(ctx context.Context, id api.CmdID, cmd api.Cmd) error { if err := cmd.Mutate(ctx, id, state, nil, nil); err != nil { log.W(ctx, "Get resources at %v: Initial cmd [%v]%v - %v", p.Indices, id, cmd, err) } return nil }) err = api.ForeachCmd(ctx, cmds, func(ctx context.Context, id api.CmdID, cmd api.Cmd) error { currentCmdResourceCount = 0 currentCmdIndex = uint64(id) cmd.Mutate(ctx, id, state, nil, nil) return nil }) if err != nil { return nil, err } resourceData := make(map[id.ID]interface{}) for k, v := range resources { res, err := v.ResourceData(ctx, state) if err != nil { resourceData[k] = err } else { resourceData[k] = res } } return &ResolvedResources{idMap, resources, resourceData}, nil } // ResourceData resolves the data of the specified resource at the specified // point in the capture. func ResourceData(ctx context.Context, p *path.ResourceData, r *path.ResolveConfig) (interface{}, error) { obj, err := database.Build(ctx, &ResourceDataResolvable{Path: p, Config: r}) if err != nil { return nil, err } return obj, nil } // Resolve implements the database.Resolver interface. func (r *ResourceDataResolvable) Resolve(ctx context.Context) (interface{}, error) { resources, err := database.Build(ctx, &AllResourceDataResolvable{After: r.Path.After, Config: r.Config}) if err != nil { return nil, err } res, ok := resources.(*ResolvedResources) if !ok { return nil, fmt.Errorf("Cannot resolve resources at command: %v", r.Path.After) } id := r.Path.ID.ID() if val, ok := res.resourceData[id]; ok { if err, isErr := val.(error); isErr { return nil, err } return val, nil } return nil, fmt.Errorf("Cannot find resource with id: %v", id) }
Java
<style type="text/css"> .placeholder { display: none; } </style> <div class="contentRight"> <div class="sanpham" style=" height: 100%; margin-top: 0"> <div class="row" style="margin: 5px"> <div class="page-header"> <h2><?php echo lang('form_checkout'); ?></h2> </div> <?php if (validation_errors()): ?> <div class="alert alert-error"> <a class="close" data-dismiss="alert">×</a> <?php echo validation_errors(); ?> </div> <?php endif; ?> <script type="text/javascript"> $(document).ready(function () { //if we support placeholder text, remove all the labels if (!supports_placeholder()) { $('.placeholder').show(); } <?php // Restore previous selection, if we are on a validation page reload $zone_id = set_value('zone_id'); echo "\$('#zone_id').val($zone_id);\n"; ?> }); function supports_placeholder() { return 'placeholder' in document.createElement('input'); } </script> <script type="text/javascript"> $(document).ready(function () { $('#country_id').change(function () { populate_zone_menu(); }); }); // context is ship or bill function populate_zone_menu(value) { $.post('<?php echo site_url('locations/get_zone_menu');?>', {id: $('#country_id').val()}, function (data) { $('#zone_id').html(data); }); } </script> <?php /* Only show this javascript if the user is logged in */ ?> <?php if ($this->Customer_model->is_logged_in(false, false)) : ?> <script type="text/javascript"> <?php $add_list = array(); foreach($customer_addresses as $row) { // build a new array $add_list[$row['id']] = $row['field_data']; } $add_list = json_encode($add_list); echo "eval(addresses=$add_list);"; ?> function populate_address(address_id) { if (address_id == '') { return; } // - populate the fields $.each(addresses[address_id], function (key, value) { $('.address[name=' + key + ']').val(value); // repopulate the zone menu and set the right value if we change the country if (key == 'zone_id') { zone_id = value; } }); // repopulate the zone list, set the right value, then copy all to billing $.post('<?php echo site_url('locations/get_zone_menu');?>', {id: $('#country_id').val()}, function (data) { $('#zone_id').html(data); $('#zone_id').val(zone_id); }); } </script> <?php endif; ?> <?php $countries = $this->Location_model->get_countries_menu(); if (!empty($customer[$address_form_prefix . '_address']['country_id'])) { $zone_menu = $this->Location_model->get_zones_menu($customer[$address_form_prefix . '_address']['country_id']); } else { $zone_menu = array('' => '') + $this->Location_model->get_zones_menu(array_shift(array_keys($countries))); } //form elements $company = array('placeholder' => lang('address_company'), 'class' => 'address span8', 'name' => 'company', 'value' => set_value('company', @$customer[$address_form_prefix . '_address']['company'])); $address1 = array('placeholder' => lang('address1'), 'class' => 'address span8', 'name' => 'address1', 'value' => set_value('address1', @$customer[$address_form_prefix . '_address']['address1'])); $address2 = array('placeholder' => lang('address2'), 'class' => 'address span8', 'name' => 'address2', 'value' => set_value('address2', @$customer[$address_form_prefix . '_address']['address2'])); $first = array('placeholder' => lang('address_firstname'), 'class' => 'address span4', 'name' => 'firstname', 'value' => set_value('firstname', @$customer[$address_form_prefix . '_address']['firstname'])); $last = array('placeholder' => lang('address_lastname'), 'class' => 'address span4', 'name' => 'lastname', 'value' => set_value('lastname', @$customer[$address_form_prefix . '_address']['lastname'])); $email = array('placeholder' => lang('address_email'), 'class' => 'address span4', 'name' => 'email', 'value' => set_value('email', @$customer[$address_form_prefix . '_address']['email'])); $phone = array('placeholder' => lang('address_phone'), 'class' => 'address span4', 'name' => 'phone', 'value' => set_value('phone', @$customer[$address_form_prefix . '_address']['phone'])); $city = array('placeholder' => lang('address_city'), 'class' => 'address span3', 'name' => 'city', 'value' => set_value('city', @$customer[$address_form_prefix . '_address']['city'])); $zip = array('placeholder' => lang('address_zip'), 'maxlength' => '10', 'class' => 'address span2', 'name' => 'zip', 'value' => set_value('zip', @$customer[$address_form_prefix . '_address']['zip'])); ?> <?php //post to the correct place. echo ($address_form_prefix == 'bill') ? form_open('checkout/step_1', 'style = "padding-left: 60px;"') : form_open('checkout/shipping_address', 'style = "padding-left: 60px;"');?> <div class="row"> <?php // Address form ?> <div class="span8"> <div class="row"> <div class="span4"> <h2 style="margin:0px;"> <?php echo ($address_form_prefix == 'bill') ? lang('address') : lang('shipping_address'); ?> </h2> </div> <div class="span4"> <?php if ($this->Customer_model->is_logged_in(false, false)) : ?> <button class="btn btn-inverse pull-right" onclick="$('#address_manager').modal().modal('show');" type="button"><i class="icon-envelope icon-white"></i> <?php echo lang('choose_address'); ?> </button> <?php endif; ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address_company'); ?></label> <?php echo form_input($company); ?> </div> </div> <div class="row"> <div class="span4"> <label class="placeholder"><?php echo lang('address_firstname'); ?><b class="r"> *</b></label> <?php echo form_input($first); ?> </div> <div class="span4"> <label class="placeholder"><?php echo lang('address_lastname'); ?><b class="r"> *</b></label> <?php echo form_input($last); ?> </div> </div> <div class="row"> <div class="span4"> <label class="placeholder"><?php echo lang('address_email'); ?><b class="r"> *</b></label> <?php echo form_input($email); ?> </div> <div class="span4"> <label class="placeholder"><?php echo lang('address_phone'); ?><b class="r"> *</b></label> <?php echo form_input($phone); ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address_country'); ?><b class="r"> *</b></label> <?php echo form_dropdown('country_id', $countries, @$customer[$address_form_prefix . '_address']['country_id'], 'id="country_id" class="address span8"'); ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address1'); ?><b class="r"> *</b></label> <?php echo form_input($address1); ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address2'); ?></label> <?php echo form_input($address2); ?> </div> </div> <div class="row"> <div class="span3"> <label class="placeholder"><?php echo lang('address_city'); ?><b class="r"> *</b></label> <?php echo form_input($city); ?> </div> <div class="span3"> <label class="placeholder"><?php echo lang('address_state'); ?><b class="r"> *</b></label> <?php echo form_dropdown('zone_id', $zone_menu, @$customer[$address_form_prefix . '_address']['zone_id'], 'id="zone_id" class="address span3" ');?> </div> <div class="span2"> <label class="placeholder"><?php echo lang('address_zip'); ?><b class="r"> *</b></label> <?php echo form_input($zip); ?> </div> </div> <?php if ($address_form_prefix == 'bill') : ?> <div class="row"> <div class="span3"> <label class="checkbox inline" for="use_shipping"> <?php echo form_checkbox(array('name' => 'use_shipping', 'value' => 'yes', 'id' => 'use_shipping', 'checked' => $use_shipping)) ?> <?php echo lang('ship_to_address') ?> </label> </div> </div> <?php endif ?> <div class="row"> <div class="span8"> <?php if ($address_form_prefix == 'ship') : ?> <input class="btn btn-block btn-large btn-secondary" type="button" value="<?php echo lang('form_previous'); ?>" onclick="window.location='<?php echo base_url('checkout/step_1') ?>'"/> <?php endif; ?> <input class="btn btn-block btn-large btn-primary" type="submit" value="<?php echo lang('form_continue'); ?>"/> </div> </div> </div> </div> </form> </div> </div> </div> <?php if ($this->Customer_model->is_logged_in(false, false)) : ?> <div class="modal hide" id="address_manager"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h3><?php echo lang('your_addresses'); ?></h3> </div> <div class="modal-body"> <p> <table class="table table-striped"> <?php $c = 1; foreach ($customer_addresses as $a):?> <tr> <td> <?php $b = $a['field_data']; echo nl2br(format_address($b)); ?> </td> <td style="width:100px;"><input type="button" class="btn btn-primary choose_address pull-right" onclick="populate_address(<?php echo $a['id']; ?>);" data-dismiss="modal" value="<?php echo lang('form_choose'); ?>"/></td> </tr> <?php endforeach; ?> </table> </p> </div> <div class="modal-footer"> <a href="#" class="btn" data-dismiss="modal">Close</a> </div> </div> <?php endif; ?>
Java
/* * Copyright 2014-2021 Sayi * * 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.deepoove.poi.xwpf; import java.util.List; import org.apache.poi.xwpf.usermodel.IRunBody; import org.apache.poi.xwpf.usermodel.XWPFFieldRun; import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.xmlbeans.XmlObject; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField; public class ParagraphContext implements RunBodyContext { private XWPFParagraphWrapper paragraphWrapper; public ParagraphContext(XWPFParagraphWrapper paragraphWrapper) { this.paragraphWrapper = paragraphWrapper; } @Override public IRunBody getTarget() { return paragraphWrapper.getParagraph(); } @Override public List<XWPFRun> getRuns() { return paragraphWrapper.getParagraph().getRuns(); } @Override public void setAndUpdateRun(XWPFRun xwpfRun, XWPFRun sourceRun, int insertPostionCursor) { paragraphWrapper.setAndUpdateRun(xwpfRun, sourceRun, insertPostionCursor); } @Override public XWPFRun insertNewRun(XWPFRun xwpfRun, int insertPostionCursor) { if (xwpfRun instanceof XWPFHyperlinkRun) { return paragraphWrapper.insertNewHyperLinkRun(insertPostionCursor, ""); } else if (xwpfRun instanceof XWPFFieldRun) { return paragraphWrapper.insertNewField(insertPostionCursor); } else { return paragraphWrapper.insertNewRun(insertPostionCursor); } } @Override public XWPFRun createRun(XWPFRun xwpfRun, IRunBody p) { if (xwpfRun instanceof XWPFHyperlinkRun) { return new XWPFHyperlinkRun((CTHyperlink) ((XWPFHyperlinkRun) xwpfRun).getCTHyperlink().copy(), (CTR) ((XWPFHyperlinkRun) xwpfRun).getCTR().copy(), p); } else if (xwpfRun instanceof XWPFFieldRun) { return new XWPFFieldRun((CTSimpleField) ((XWPFFieldRun) xwpfRun).getCTField().copy(), (CTR) ((XWPFFieldRun) xwpfRun).getCTR().copy(), p); } else { return new XWPFRun((CTR) xwpfRun.getCTR().copy(), p); } } @Override public XWPFRun createRun(XmlObject object, IRunBody p) { if (object instanceof CTHyperlink) { return new XWPFHyperlinkRun((CTHyperlink) object, ((CTHyperlink) object).getRArray(0), p); } else if (object instanceof CTSimpleField) { return new XWPFFieldRun((CTSimpleField) object, ((CTSimpleField) object).getRArray(0), p); } else { return new XWPFRun((CTR) object, p); } } @Override public void removeRun(int pos) { paragraphWrapper.removeRun(pos); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Mon Jan 15 08:36:52 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.undertow.Server.ServerResources (BOM: * : All 2018.1.0 API)</title> <meta name="date" content="2018-01-15"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.config.undertow.Server.ServerResources (BOM: * : All 2018.1.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2018.1.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/undertow/class-use/Server.ServerResources.html" target="_top">Frames</a></li> <li><a href="Server.ServerResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.undertow.Server.ServerResources" class="title">Uses of Class<br>org.wildfly.swarm.config.undertow.Server.ServerResources</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.undertow">org.wildfly.swarm.config.undertow</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.undertow"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a> in <a href="../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a> that return <a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a></code></td> <td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.html#subresources--">subresources</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2018.1.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/undertow/class-use/Server.ServerResources.html" target="_top">Frames</a></li> <li><a href="Server.ServerResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.portable; import org.apache.ignite.internal.portable.streams.*; import org.apache.ignite.internal.util.*; import org.apache.ignite.internal.util.typedef.internal.*; import sun.misc.*; import static org.apache.ignite.IgniteSystemProperties.*; /** * Thread-local memory allocator. */ public class PortableThreadLocalMemoryAllocator implements PortableMemoryAllocator { /** Memory allocator instance. */ public static final PortableThreadLocalMemoryAllocator THREAD_LOCAL_ALLOC = new PortableThreadLocalMemoryAllocator(); /** Holders. */ private static final ThreadLocal<ByteArrayHolder> holders = new ThreadLocal<>(); /** Unsafe instance. */ protected static final Unsafe UNSAFE = GridUnsafe.unsafe(); /** Array offset: byte. */ protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class); /** * Ensures singleton. */ private PortableThreadLocalMemoryAllocator() { // No-op. } /** {@inheritDoc} */ @Override public byte[] allocate(int size) { ByteArrayHolder holder = holders.get(); if (holder == null) holders.set(holder = new ByteArrayHolder()); if (holder.acquired) return new byte[size]; holder.acquired = true; if (holder.data == null || size > holder.data.length) holder.data = new byte[size]; return holder.data; } /** {@inheritDoc} */ @Override public byte[] reallocate(byte[] data, int size) { ByteArrayHolder holder = holders.get(); assert holder != null; byte[] newData = new byte[size]; if (holder.data == data) holder.data = newData; UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length); return newData; } /** {@inheritDoc} */ @Override public void release(byte[] data, int maxMsgSize) { ByteArrayHolder holder = holders.get(); assert holder != null; if (holder.data != data) return; holder.maxMsgSize = maxMsgSize; holder.acquired = false; holder.shrink(); } /** {@inheritDoc} */ @Override public long allocateDirect(int size) { return 0; } /** {@inheritDoc} */ @Override public long reallocateDirect(long addr, int size) { return 0; } /** {@inheritDoc} */ @Override public void releaseDirect(long addr) { // No-op } /** * Checks whether a thread-local array is acquired or not. * The function is used by Unit tests. * * @return {@code true} if acquired {@code false} otherwise. */ public boolean isThreadLocalArrayAcquired() { ByteArrayHolder holder = holders.get(); return holder != null && holder.acquired; } /** * Thread-local byte array holder. */ private static class ByteArrayHolder { /** */ private static final Long CHECK_FREQ = Long.getLong(IGNITE_MARSHAL_BUFFERS_RECHECK, 10000); /** Data array */ private byte[] data; /** Max message size detected between checks. */ private int maxMsgSize; /** Last time array size is checked. */ private long lastCheck = U.currentTimeMillis(); /** Whether the holder is acquired or not. */ private boolean acquired; /** * Shrinks array size if needed. */ private void shrink() { long now = U.currentTimeMillis(); if (now - lastCheck >= CHECK_FREQ) { int halfSize = data.length >> 1; if (maxMsgSize < halfSize) data = new byte[halfSize]; lastCheck = now; } } } }
Java
package BinaryTreeLevelOrderTraversal; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class BinaryTreeLevelOrderTraversalSolutionTest { private BinaryTreeLevelOrderTraversalSolution solution = new BinaryTreeLevelOrderTraversalSolution(); @Test public void nullInput() { List<List<Integer>> result = solution.levelOrder(null); assertThat(result).isEmpty(); } @Test public void singleNodeInput() { TreeNode root = new TreeNode(1); List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(1); assertThat(result.get(0)).containsExactly(1); } @Test public void twoNodesInput() { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(2); assertThat(result.get(0)).containsExactly(1); assertThat(result.get(1)).containsExactly(2); } @Test public void threeNodesInput() { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(2); assertThat(result.get(0)).containsExactly(1); assertThat(result.get(1)).containsExactly(2, 3); } @Test public void fiveNodesInput() { TreeNode root = new TreeNode(3); root.left = new TreeNode(9); TreeNode rightTree = new TreeNode(20); rightTree.left = new TreeNode(15); rightTree.right = new TreeNode(7); root.right = rightTree; List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(3); assertThat(result.get(0)).containsExactly(3); assertThat(result.get(1)).containsExactly(9, 20); assertThat(result.get(2)).containsExactly(15, 7); } }
Java
package cn.aezo.spring.base.annotation.combineannotation; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by smalle on 2017/6/11. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration @ComponentScan public @interface WiselyConfiguration { String[] value() default {}; }
Java
.ff0{font-family:sans-serif;visibility:hidden;} @font-face{font-family:ff1;src:url(f1.woff)format("woff");}.ff1{font-family:ff1;line-height:1.534180;font-style:normal;font-weight:normal;visibility:visible;} @font-face{font-family:ff2;src:url(f2.woff)format("woff");}.ff2{font-family:ff2;line-height:1.456055;font-style:normal;font-weight:normal;visibility:visible;} @font-face{font-family:ff3;src:url(f3.woff)format("woff");}.ff3{font-family:ff3;line-height:1.695312;font-style:normal;font-weight:normal;visibility:visible;} @font-face{font-family:ff4;src:url(f4.woff)format("woff");}.ff4{font-family:ff4;line-height:0.910645;font-style:normal;font-weight:normal;visibility:visible;} .m0{transform:matrix(0.250000,0.000000,0.000000,0.250000,0,0);-ms-transform:matrix(0.250000,0.000000,0.000000,0.250000,0,0);-webkit-transform:matrix(0.250000,0.000000,0.000000,0.250000,0,0);} .m1{transform:none;-ms-transform:none;-webkit-transform:none;} .v0{vertical-align:0.000000px;} .ls2{letter-spacing:-0.096000px;} .ls0{letter-spacing:0.000000px;} .ls1{letter-spacing:0.096000px;} .sc_{text-shadow:none;} .sc0{text-shadow:-0.015em 0 transparent,0 0.015em transparent,0.015em 0 transparent,0 -0.015em transparent;} @media screen and (-webkit-min-device-pixel-ratio:0){ .sc_{-webkit-text-stroke:0px transparent;} .sc0{-webkit-text-stroke:0.015em transparent;text-shadow:none;} } .ws0{word-spacing:0.000000px;} ._0{margin-left:-1.008000px;} ._1{width:1.016000px;} .fc1{color:rgb(255,0,0);} .fc0{color:rgb(0,0,0);} .fs0{font-size:48.000000px;} .fs1{font-size:56.000000px;} .y26{bottom:16.000000px;} .y52{bottom:79.584000px;} .y25{bottom:88.464000px;} .y4e{bottom:90.144000px;} .y51{bottom:95.544000px;} .y24{bottom:104.420000px;} .y4d{bottom:105.980000px;} .y4f{bottom:108.500000px;} .y50{bottom:108.620000px;} .y23{bottom:120.260000px;} .y4c{bottom:121.820000px;} .y22{bottom:136.100000px;} .y4b{bottom:137.660000px;} .y21{bottom:151.940000px;} .y4a{bottom:153.620000px;} .y20{bottom:167.900000px;} .y49{bottom:169.460000px;} .y1f{bottom:183.740000px;} .y48{bottom:185.300000px;} .y1e{bottom:199.580000px;} .y47{bottom:201.140000px;} .y1d{bottom:215.450000px;} .y46{bottom:217.130000px;} .y1c{bottom:231.410000px;} .y45{bottom:232.970000px;} .y1b{bottom:247.250000px;} .y44{bottom:248.810000px;} .y1a{bottom:263.090000px;} .y43{bottom:264.650000px;} .y19{bottom:278.930000px;} .y42{bottom:280.610000px;} .y18{bottom:294.770000px;} .y41{bottom:296.450000px;} .y17{bottom:310.730000px;} .y40{bottom:312.290000px;} .y16{bottom:326.570000px;} .y3f{bottom:328.130000px;} .y15{bottom:342.410000px;} .y3e{bottom:344.090000px;} .y14{bottom:358.250000px;} .y3d{bottom:359.930000px;} .y13{bottom:374.230000px;} .y3c{bottom:375.790000px;} .y12{bottom:390.070000px;} .y3b{bottom:391.630000px;} .y11{bottom:405.910000px;} .y3a{bottom:407.470000px;} .y10{bottom:421.750000px;} .y39{bottom:423.430000px;} .yf{bottom:437.710000px;} .y38{bottom:439.270000px;} .ye{bottom:453.550000px;} .y37{bottom:455.110000px;} .yd{bottom:469.150000px;} .y36{bottom:470.950000px;} .yc{bottom:484.990000px;} .y35{bottom:486.910000px;} .yb{bottom:500.950000px;} .y34{bottom:502.750000px;} .ya{bottom:516.790000px;} .y33{bottom:518.590000px;} .y9{bottom:532.630000px;} .y32{bottom:534.430000px;} .y8{bottom:548.500000px;} .y31{bottom:550.420000px;} .y7{bottom:564.460000px;} .y30{bottom:566.260000px;} .y6{bottom:580.300000px;} .y2f{bottom:582.100000px;} .y5{bottom:596.140000px;} .y2e{bottom:597.940000px;} .y4{bottom:611.980000px;} .y2d{bottom:613.900000px;} .y3{bottom:627.940000px;} .y2c{bottom:629.740000px;} .y2{bottom:643.780000px;} .y2b{bottom:645.580000px;} .y0{bottom:656.500000px;} .y1{bottom:656.980000px;} .y2a{bottom:661.420000px;} .y29{bottom:677.380000px;} .y28{bottom:693.220000px;} .y27{bottom:709.080000px;} .h3{height:53.250000px;} .h2{height:54.960938px;} .h1{height:63.500000px;} .h4{height:69.015625px;} .h5{height:183.500000px;} .h0{height:792.000000px;} .w1{width:208.000000px;} .w2{width:468.000000px;} .w0{width:612.000000px;} .x0{left:72.000000px;} .x4{left:186.980000px;} .x6{left:253.000000px;} .x5{left:277.010000px;} .x1{left:279.890000px;} .x2{left:286.010000px;} .x3{left:306.050000px;} .x7{left:539.980000px;} @media print{ .v0{vertical-align:0.000000pt;} .ls2{letter-spacing:-0.128000pt;} .ls0{letter-spacing:0.000000pt;} .ls1{letter-spacing:0.128000pt;} .ws0{word-spacing:0.000000pt;} ._0{margin-left:-1.344000pt;} ._1{width:1.354667pt;} .fs0{font-size:64.000000pt;} .fs1{font-size:74.666667pt;} .y26{bottom:21.333333pt;} .y52{bottom:106.112000pt;} .y25{bottom:117.952000pt;} .y4e{bottom:120.192000pt;} .y51{bottom:127.392000pt;} .y24{bottom:139.226667pt;} .y4d{bottom:141.306667pt;} .y4f{bottom:144.666667pt;} .y50{bottom:144.826667pt;} .y23{bottom:160.346667pt;} .y4c{bottom:162.426667pt;} .y22{bottom:181.466667pt;} .y4b{bottom:183.546667pt;} .y21{bottom:202.586667pt;} .y4a{bottom:204.826667pt;} .y20{bottom:223.866667pt;} .y49{bottom:225.946667pt;} .y1f{bottom:244.986667pt;} .y48{bottom:247.066667pt;} .y1e{bottom:266.106667pt;} .y47{bottom:268.186667pt;} .y1d{bottom:287.266667pt;} .y46{bottom:289.506667pt;} .y1c{bottom:308.546667pt;} .y45{bottom:310.626667pt;} .y1b{bottom:329.666667pt;} .y44{bottom:331.746667pt;} .y1a{bottom:350.786667pt;} .y43{bottom:352.866667pt;} .y19{bottom:371.906667pt;} .y42{bottom:374.146667pt;} .y18{bottom:393.026667pt;} .y41{bottom:395.266667pt;} .y17{bottom:414.306667pt;} .y40{bottom:416.386667pt;} .y16{bottom:435.426667pt;} .y3f{bottom:437.506667pt;} .y15{bottom:456.546667pt;} .y3e{bottom:458.786667pt;} .y14{bottom:477.666667pt;} .y3d{bottom:479.906667pt;} .y13{bottom:498.973333pt;} .y3c{bottom:501.053333pt;} .y12{bottom:520.093333pt;} .y3b{bottom:522.173333pt;} .y11{bottom:541.213333pt;} .y3a{bottom:543.293333pt;} .y10{bottom:562.333333pt;} .y39{bottom:564.573333pt;} .yf{bottom:583.613333pt;} .y38{bottom:585.693333pt;} .ye{bottom:604.733333pt;} .y37{bottom:606.813333pt;} .yd{bottom:625.533333pt;} .y36{bottom:627.933333pt;} .yc{bottom:646.653333pt;} .y35{bottom:649.213333pt;} .yb{bottom:667.933333pt;} .y34{bottom:670.333333pt;} .ya{bottom:689.053333pt;} .y33{bottom:691.453333pt;} .y9{bottom:710.173333pt;} .y32{bottom:712.573333pt;} .y8{bottom:731.333333pt;} .y31{bottom:733.893333pt;} .y7{bottom:752.613333pt;} .y30{bottom:755.013333pt;} .y6{bottom:773.733333pt;} .y2f{bottom:776.133333pt;} .y5{bottom:794.853333pt;} .y2e{bottom:797.253333pt;} .y4{bottom:815.973333pt;} .y2d{bottom:818.533333pt;} .y3{bottom:837.253333pt;} .y2c{bottom:839.653333pt;} .y2{bottom:858.373333pt;} .y2b{bottom:860.773333pt;} .y0{bottom:875.333333pt;} .y1{bottom:875.973333pt;} .y2a{bottom:881.893333pt;} .y29{bottom:903.173333pt;} .y28{bottom:924.293333pt;} .y27{bottom:945.440000pt;} .h3{height:71.000000pt;} .h2{height:73.281250pt;} .h1{height:84.666667pt;} .h4{height:92.020833pt;} .h5{height:244.666667pt;} .h0{height:1056.000000pt;} .w1{width:277.333333pt;} .w2{width:624.000000pt;} .w0{width:816.000000pt;} .x0{left:96.000000pt;} .x4{left:249.306667pt;} .x6{left:337.333333pt;} .x5{left:369.346667pt;} .x1{left:373.186667pt;} .x2{left:381.346667pt;} .x3{left:408.066667pt;} .x7{left:719.973333pt;} }
Java
var addressBar = element(by.css("#addressBar")), url = 'http://www.example.com/base/ratingList.html#!/path?a=b#h'; it("should show fake browser info on load", function(){ expect(addressBar.getAttribute('value')).toBe(url); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/path'); expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}'); expect(element(by.binding('$location.hash()')).getText()).toBe('h'); }); it("should change $location accordingly", function(){ var navigation = element.all(by.css("#navigation a")); navigation.get(0).click(); expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/first?a=b"); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/first'); expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}'); expect(element(by.binding('$location.hash()')).getText()).toBe(''); navigation.get(1).click(); expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/sec/ond?flag#hash"); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/sec/ond'); expect(element(by.binding('$location.search()')).getText()).toBe('{"flag":true}'); expect(element(by.binding('$location.hash()')).getText()).toBe('hash'); });
Java
/* * Copyright 2006-2011 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kew.xml.export; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.kew.export.KewExportDataSet; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.group.GroupService; import org.kuali.rice.kim.api.identity.IdentityService; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.test.BaselineTestCase; import java.util.List; import static org.junit.Assert.assertTrue; /** * This is a description of what this class does - jjhanso don't forget to fill this in. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ @BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE) public class GroupXmlExporterTest extends XmlExporterTestCase { /** * This overridden method ... * * @see org.kuali.rice.kew.xml.export.XmlExporterTestCase#assertExport() */ @Override protected void assertExport() throws Exception { IdentityService identityService = KimApiServiceLocator.getIdentityService(); GroupService groupService = KimApiServiceLocator.getGroupService(); List<? extends Group> oldGroups = groupService.getGroupsByPrincipalId( identityService.getPrincipalByPrincipalName("ewestfal").getPrincipalId()); KewExportDataSet dataSet = new KewExportDataSet(); dataSet.getGroups().addAll(oldGroups); byte[] xmlBytes = CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet()); assertTrue("XML should be non empty.", xmlBytes != null && xmlBytes.length > 0); StringBuffer output = new StringBuffer(); for (int i=0; i < xmlBytes.length; i++){ output.append((char)xmlBytes[i]); } System.out.print(output.toString()); // now clear the tables //ClearDatabaseLifecycle clearLifeCycle = new ClearDatabaseLifecycle(); //clearLifeCycle.getTablesToClear().add("EN_RULE_BASE_VAL_T"); //clearLifeCycle.getTablesToClear().add("EN_RULE_ATTRIB_T"); //clearLifeCycle.getTablesToClear().add("EN_RULE_TMPL_T"); //clearLifeCycle.getTablesToClear().add("EN_DOC_TYP_T"); //clearLifeCycle.start(); //new ClearCacheLifecycle().stop(); //KimImplServiceLocator.getGroupService(). // import the exported xml //loadXmlStream(new BufferedInputStream(new ByteArrayInputStream(xmlBytes))); /* List newRules = KEWServiceLocator.getRuleService().fetchAllRules(true); assertEquals("Should have same number of old and new Rules.", oldRules.size(), newRules.size()); for (Iterator iterator = oldRules.iterator(); iterator.hasNext();) { RuleBaseValues oldRule = (RuleBaseValues) iterator.next(); boolean foundRule = false; for (Iterator iterator2 = newRules.iterator(); iterator2.hasNext();) { RuleBaseValues newRule = (RuleBaseValues) iterator2.next(); if (oldRule.getDescription().equals(newRule.getDescription())) { assertRuleExport(oldRule, newRule); foundRule = true; } } assertTrue("Could not locate the new rule for description " + oldRule.getDescription(), foundRule); } */ } }
Java
# AUTOGENERATED FILE FROM balenalib/imx8m-var-dart-ubuntu:xenial-run ENV NODE_VERSION 15.14.0 ENV YARN_VERSION 1.22.4 RUN buildDeps='curl libatomic1' \ && set -x \ && for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends \ && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \ && echo "6d5e0074fe4a45d444bc581aa1fd7ce7081b8491b0f785414a6e5cc30c42854a node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu xenial \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
Java
/** * Copyright 2015 Smart Society Services B.V. * * 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 */ package com.alliander.osgp.core.infra.jms.protocol.in; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jms.ConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; import org.springframework.beans.factory.InitializingBean; import org.springframework.jms.core.JmsTemplate; import com.alliander.osgp.core.infra.jms.JmsTemplateSettings; import com.alliander.osgp.domain.core.entities.ProtocolInfo; public class ProtocolResponseMessageJmsTemplateFactory implements InitializingBean { private final ConnectionFactory connectionFactory; private final JmsTemplateSettings jmsTemplateSettings; private Map<String, JmsTemplate> jmsTemplateMap = new HashMap<>(); public ProtocolResponseMessageJmsTemplateFactory(final ConnectionFactory connectionFactory, final JmsTemplateSettings jmsTemplateSettings, final List<ProtocolInfo> protocolInfos) { this.connectionFactory = connectionFactory; this.jmsTemplateSettings = jmsTemplateSettings; for (final ProtocolInfo protocolInfo : protocolInfos) { this.jmsTemplateMap.put(protocolInfo.getKey(), this.createJmsTemplate(protocolInfo)); } } public JmsTemplate getJmsTemplate(final String key) { return this.jmsTemplateMap.get(key); } @Override public void afterPropertiesSet() { for (final JmsTemplate jmsTemplate : this.jmsTemplateMap.values()) { jmsTemplate.afterPropertiesSet(); } } private JmsTemplate createJmsTemplate(final ProtocolInfo protocolInfo) { final JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setDefaultDestination(new ActiveMQQueue(protocolInfo.getOutgoingProtocolResponsesQueue())); // Enable the use of deliveryMode, priority, and timeToLive jmsTemplate.setExplicitQosEnabled(this.jmsTemplateSettings.isExplicitQosEnabled()); jmsTemplate.setTimeToLive(this.jmsTemplateSettings.getTimeToLive()); jmsTemplate.setDeliveryPersistent(this.jmsTemplateSettings.isDeliveryPersistent()); jmsTemplate.setConnectionFactory(this.connectionFactory); return jmsTemplate; } }
Java
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>About</title> <style> a:link { color: #1976d2; text-decoration: none; } </style> </head> <body> <ul> <li><code>Delete icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li> <li><code>Add alarm icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li> <li><code>Alarm icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li> <li><code>Forward icon</code> by <a href="https://www.iconfinder.com/DesignRevision">Design Revision</a>, free for commercial use.</li> <li><code>Time icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li> <li><code>Alarm off icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li> </ul> </body> </html>
Java
package com.codedpoetry.maven.dockerplugin.templates; import java.io.StringWriter; import java.util.Map; public interface TemplateRenderer { StringWriter renderTemplate(String templateUrl, Map context); }
Java
package st.domain.quitanda.client.model.contract; /** * Created by Daniel Costa at 8/27/16. * Using user computer xdata */ public interface TypePayment { public int getDataBaseId(); }
Java
package example.repo; import example.model.Customer1794; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1794Repository extends CrudRepository<Customer1794, Long> { List<Customer1794> findByLastName(String lastName); }
Java
"use strict"; define(["lib/three.min"], function() { var Reality = function(sourceCanvas){ // Create a default camera and scene. var camera = new THREE.Camera(); var scene = new THREE.Scene(); // Create a plane geometry to hold the sourceCanvas texture var geometry = new THREE.PlaneGeometry(2, 2, 0); // Create a material textured with the contents of sourceCanvas. var texture = new THREE.Texture(sourceCanvas); var material = new THREE.MeshBasicMaterial({ map: texture, depthTest: false, depthWrite: false }); // Build a mesh and add it to the scene. var mesh = new THREE.Mesh( geometry, material ); scene.add(mesh); // We need to notify ThreeJS when the texture has changed. function update() { texture.needsUpdate = true; } return { camera: camera, scene: scene, update: update, } } var Scene = function() { var scene = new THREE.Scene(); var camera = new THREE.Camera(); function add(object) { scene.add(object); } function remove(object) { scene.remove(object); } function setProjectionMatrix(matrix) { camera.projectionMatrix.setFromArray( matrix ); } return { scene:scene, camera:camera, add:add, remove:remove, setProjectionMatrix:setProjectionMatrix, } } var create = function(dimensions, sourceCanvas) { // Create a canvas which will be used for WebGL var glCanvas = document.createElement('canvas'); // Initialize the renderer and attach it to the canvas var renderer = new THREE.WebGLRenderer({canvas:glCanvas}); renderer.setSize(dimensions.width, dimensions.height); renderer.autoClear = false; // Create a reality scene var reality = new Reality(sourceCanvas); var virtual = new Scene(); var light = new THREE.SpotLight(0xffffff); light.position.set(0, 0, 9000); light.lookAt( new THREE.Vector3(0,0,0) ); virtual.scene.add(light); function render() { // Render the reality scene renderer.render(reality.scene, reality.camera); // Render the augmented components on top of the reality scene. renderer.render(virtual.scene, virtual.camera); } function update() { // Notify the reality scene to update it's texture reality.update(); } function setCameraMatrix( matrix ) { virtual.setProjectionMatrix( matrix ); } function add( object ) { virtual.add( object.model ); } function remove( object ) { virtual.remove( object.model ); } return { add: add, remove: remove, update: update, render: render, glCanvas: glCanvas, setCameraMatrix: setCameraMatrix, } } return { create: create, } });
Java
# Agrimonia viscidula Bunge SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Python utilities required by Keras.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import binascii import codecs import marshal import os import re import sys import time import types as python_types import numpy as np import six from tensorflow.python.util import nest from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_inspect from tensorflow.python.util.tf_export import keras_export _GLOBAL_CUSTOM_OBJECTS = {} @keras_export('keras.utils.CustomObjectScope') class CustomObjectScope(object): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. Example: Consider a custom object `MyObject` (e.g. a class): ```python with CustomObjectScope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` """ def __init__(self, *args): self.custom_objects = args self.backup = None def __enter__(self): self.backup = _GLOBAL_CUSTOM_OBJECTS.copy() for objects in self.custom_objects: _GLOBAL_CUSTOM_OBJECTS.update(objects) return self def __exit__(self, *args, **kwargs): _GLOBAL_CUSTOM_OBJECTS.clear() _GLOBAL_CUSTOM_OBJECTS.update(self.backup) @keras_export('keras.utils.custom_object_scope') def custom_object_scope(*args): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Convenience wrapper for `CustomObjectScope`. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. Example: Consider a custom object `MyObject` ```python with custom_object_scope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` Arguments: *args: Variable length list of dictionaries of name, class pairs to add to custom objects. Returns: Object of type `CustomObjectScope`. """ return CustomObjectScope(*args) @keras_export('keras.utils.get_custom_objects') def get_custom_objects(): """Retrieves a live reference to the global dictionary of custom objects. Updating and clearing custom objects using `custom_object_scope` is preferred, but `get_custom_objects` can be used to directly access `_GLOBAL_CUSTOM_OBJECTS`. Example: ```python get_custom_objects().clear() get_custom_objects()['MyObject'] = MyObject ``` Returns: Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`). """ return _GLOBAL_CUSTOM_OBJECTS def serialize_keras_class_and_config(cls_name, cls_config): """Returns the serialization of the class with the given config.""" return {'class_name': cls_name, 'config': cls_config} @keras_export('keras.utils.serialize_keras_object') def serialize_keras_object(instance): _, instance = tf_decorator.unwrap(instance) if instance is None: return None if hasattr(instance, 'get_config'): return serialize_keras_class_and_config(instance.__class__.__name__, instance.get_config()) if hasattr(instance, '__name__'): return instance.__name__ raise ValueError('Cannot serialize', instance) def class_and_config_for_serialized_keras_object( config, module_objects=None, custom_objects=None, printable_module_name='object'): """Returns the class name and config for a serialized keras object.""" if (not isinstance(config, dict) or 'class_name' not in config or 'config' not in config): raise ValueError('Improper config format: ' + str(config)) class_name = config['class_name'] if custom_objects and class_name in custom_objects: cls = custom_objects[class_name] elif class_name in _GLOBAL_CUSTOM_OBJECTS: cls = _GLOBAL_CUSTOM_OBJECTS[class_name] else: module_objects = module_objects or {} cls = module_objects.get(class_name) if cls is None: raise ValueError('Unknown ' + printable_module_name + ': ' + class_name) return (cls, config['config']) @keras_export('keras.utils.deserialize_keras_object') def deserialize_keras_object(identifier, module_objects=None, custom_objects=None, printable_module_name='object'): if identifier is None: return None if isinstance(identifier, dict): # In this case we are dealing with a Keras config dictionary. config = identifier (cls, cls_config) = class_and_config_for_serialized_keras_object( config, module_objects, custom_objects, printable_module_name) if hasattr(cls, 'from_config'): arg_spec = tf_inspect.getfullargspec(cls.from_config) custom_objects = custom_objects or {} if 'custom_objects' in arg_spec.args: return cls.from_config( cls_config, custom_objects=dict( list(_GLOBAL_CUSTOM_OBJECTS.items()) + list(custom_objects.items()))) with CustomObjectScope(custom_objects): return cls.from_config(cls_config) else: # Then `cls` may be a function returning a class. # in this case by convention `config` holds # the kwargs of the function. custom_objects = custom_objects or {} with CustomObjectScope(custom_objects): return cls(**cls_config) elif isinstance(identifier, six.string_types): object_name = identifier if custom_objects and object_name in custom_objects: obj = custom_objects.get(object_name) elif object_name in _GLOBAL_CUSTOM_OBJECTS: obj = _GLOBAL_CUSTOM_OBJECTS[object_name] else: obj = module_objects.get(object_name) if obj is None: raise ValueError('Unknown ' + printable_module_name + ':' + object_name) # Classes passed by name are instantiated with no args, functions are # returned as-is. if tf_inspect.isclass(obj): return obj() return obj else: raise ValueError('Could not interpret serialized ' + printable_module_name + ': ' + identifier) def func_dump(func): """Serializes a user defined function. Arguments: func: the function to serialize. Returns: A tuple `(code, defaults, closure)`. """ if os.name == 'nt': raw_code = marshal.dumps(func.__code__).replace(b'\\', b'/') code = codecs.encode(raw_code, 'base64').decode('ascii') else: raw_code = marshal.dumps(func.__code__) code = codecs.encode(raw_code, 'base64').decode('ascii') defaults = func.__defaults__ if func.__closure__: closure = tuple(c.cell_contents for c in func.__closure__) else: closure = None return code, defaults, closure def func_load(code, defaults=None, closure=None, globs=None): """Deserializes a user defined function. Arguments: code: bytecode of the function. defaults: defaults of the function. closure: closure of the function. globs: dictionary of global objects. Returns: A function object. """ if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code if isinstance(defaults, list): defaults = tuple(defaults) def ensure_value_to_cell(value): """Ensures that a value is converted to a python cell object. Arguments: value: Any value that needs to be casted to the cell type Returns: A value wrapped as a cell object (see function "func_load") """ def dummy_fn(): # pylint: disable=pointless-statement value # just access it so it gets captured in .__closure__ cell_value = dummy_fn.__closure__[0] if not isinstance(value, type(cell_value)): return cell_value return value if closure is not None: closure = tuple(ensure_value_to_cell(_) for _ in closure) try: raw_code = codecs.decode(code.encode('ascii'), 'base64') except (UnicodeEncodeError, binascii.Error): raw_code = code.encode('raw_unicode_escape') code = marshal.loads(raw_code) if globs is None: globs = globals() return python_types.FunctionType( code, globs, name=code.co_name, argdefs=defaults, closure=closure) def has_arg(fn, name, accept_all=False): """Checks if a callable accepts a given keyword argument. Arguments: fn: Callable to inspect. name: Check if `fn` can be called with `name` as a keyword argument. accept_all: What to return if there is no parameter called `name` but the function accepts a `**kwargs` argument. Returns: bool, whether `fn` accepts a `name` keyword argument. """ arg_spec = tf_inspect.getfullargspec(fn) if accept_all and arg_spec.varkw is not None: return True return name in arg_spec.args @keras_export('keras.utils.Progbar') class Progbar(object): """Displays a progress bar. Arguments: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose) stateful_metrics: Iterable of string names of metrics that should *not* be averaged over time. Metrics in this list will be displayed as-is. All others will be averaged by the progbar before display. interval: Minimum visual progress update interval (in seconds). unit_name: Display name for step counts (usually "step" or "sample"). """ def __init__(self, target, width=30, verbose=1, interval=0.05, stateful_metrics=None, unit_name='step'): self.target = target self.width = width self.verbose = verbose self.interval = interval self.unit_name = unit_name if stateful_metrics: self.stateful_metrics = set(stateful_metrics) else: self.stateful_metrics = set() self._dynamic_display = ((hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()) or 'ipykernel' in sys.modules or 'posix' in sys.modules) self._total_width = 0 self._seen_so_far = 0 # We use a dict + list to avoid garbage collection # issues found in OrderedDict self._values = {} self._values_order = [] self._start = time.time() self._last_update = 0 def update(self, current, values=None): """Updates the progress bar. Arguments: current: Index of current step. values: List of tuples: `(name, value_for_last_step)`. If `name` is in `stateful_metrics`, `value_for_last_step` will be displayed as-is. Else, an average of the metric over time will be displayed. """ values = values or [] for k, v in values: if k not in self._values_order: self._values_order.append(k) if k not in self.stateful_metrics: if k not in self._values: self._values[k] = [v * (current - self._seen_so_far), current - self._seen_so_far] else: self._values[k][0] += v * (current - self._seen_so_far) self._values[k][1] += (current - self._seen_so_far) else: # Stateful metrics output a numeric value. This representation # means "take an average from a single value" but keeps the # numeric formatting. self._values[k] = [v, 1] self._seen_so_far = current now = time.time() info = ' - %.0fs' % (now - self._start) if self.verbose == 1: if (now - self._last_update < self.interval and self.target is not None and current < self.target): return prev_total_width = self._total_width if self._dynamic_display: sys.stdout.write('\b' * prev_total_width) sys.stdout.write('\r') else: sys.stdout.write('\n') if self.target is not None: numdigits = int(np.log10(self.target)) + 1 bar = ('%' + str(numdigits) + 'd/%d [') % (current, self.target) prog = float(current) / self.target prog_width = int(self.width * prog) if prog_width > 0: bar += ('=' * (prog_width - 1)) if current < self.target: bar += '>' else: bar += '=' bar += ('.' * (self.width - prog_width)) bar += ']' else: bar = '%7d/Unknown' % current self._total_width = len(bar) sys.stdout.write(bar) if current: time_per_unit = (now - self._start) / current else: time_per_unit = 0 if self.target is not None and current < self.target: eta = time_per_unit * (self.target - current) if eta > 3600: eta_format = '%d:%02d:%02d' % (eta // 3600, (eta % 3600) // 60, eta % 60) elif eta > 60: eta_format = '%d:%02d' % (eta // 60, eta % 60) else: eta_format = '%ds' % eta info = ' - ETA: %s' % eta_format else: if time_per_unit >= 1 or time_per_unit == 0: info += ' %.0fs/%s' % (time_per_unit, self.unit_name) elif time_per_unit >= 1e-3: info += ' %.0fms/%s' % (time_per_unit * 1e3, self.unit_name) else: info += ' %.0fus/%s' % (time_per_unit * 1e6, self.unit_name) for k in self._values_order: info += ' - %s:' % k if isinstance(self._values[k], list): avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) if abs(avg) > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg else: info += ' %s' % self._values[k] self._total_width += len(info) if prev_total_width > self._total_width: info += (' ' * (prev_total_width - self._total_width)) if self.target is not None and current >= self.target: info += '\n' sys.stdout.write(info) sys.stdout.flush() elif self.verbose == 2: if self.target is not None and current >= self.target: numdigits = int(np.log10(self.target)) + 1 count = ('%' + str(numdigits) + 'd/%d') % (current, self.target) info = count + info for k in self._values_order: info += ' - %s:' % k avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) if avg > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg info += '\n' sys.stdout.write(info) sys.stdout.flush() self._last_update = now def add(self, n, values=None): self.update(self._seen_so_far + n, values) def make_batches(size, batch_size): """Returns a list of batch indices (tuples of indices). Arguments: size: Integer, total size of the data to slice into batches. batch_size: Integer, batch size. Returns: A list of tuples of array indices. """ num_batches = int(np.ceil(size / float(batch_size))) return [(i * batch_size, min(size, (i + 1) * batch_size)) for i in range(0, num_batches)] def slice_arrays(arrays, start=None, stop=None): """Slice an array or list of arrays. This takes an array-like, or a list of array-likes, and outputs: - arrays[start:stop] if `arrays` is an array-like - [x[start:stop] for x in arrays] if `arrays` is a list Can also work on list/array of indices: `slice_arrays(x, indices)` Arguments: arrays: Single array or list of arrays. start: can be an integer index (start index) or a list/array of indices stop: integer (stop index); should be None if `start` was a list. Returns: A slice of the array(s). Raises: ValueError: If the value of start is a list and stop is not None. """ if arrays is None: return [None] if isinstance(start, list) and stop is not None: raise ValueError('The stop argument has to be None if the value of start ' 'is a list.') elif isinstance(arrays, list): if hasattr(start, '__len__'): # hdf5 datasets only support list objects as indices if hasattr(start, 'shape'): start = start.tolist() return [None if x is None else x[start] for x in arrays] return [ None if x is None else None if not hasattr(x, '__getitem__') else x[start:stop] for x in arrays ] else: if hasattr(start, '__len__'): if hasattr(start, 'shape'): start = start.tolist() return arrays[start] if hasattr(start, '__getitem__'): return arrays[start:stop] return [None] def to_list(x): """Normalizes a list/tensor into a list. If a tensor is passed, we return a list of size 1 containing the tensor. Arguments: x: target object to be normalized. Returns: A list. """ if isinstance(x, list): return x return [x] def object_list_uid(object_list): """Creates a single string from object ids.""" object_list = nest.flatten(object_list) return ', '.join([str(abs(id(x))) for x in object_list]) def to_snake_case(name): intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name) insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower() # If the class is private the name starts with "_" which is not secure # for creating scopes. We prefix the name with "private" in this case. if insecure[0] != '_': return insecure return 'private' + insecure def is_all_none(structure): iterable = nest.flatten(structure) # We cannot use Python's `any` because the iterable may return Tensors. for element in iterable: if element is not None: return False return True def check_for_unexpected_keys(name, input_dict, expected_values): unknown = set(input_dict.keys()).difference(expected_values) if unknown: raise ValueError('Unknown entries in {} dictionary: {}. Only expected ' 'following keys: {}'.format(name, list(unknown), expected_values)) def validate_kwargs(kwargs, allowed_kwargs, error_message='Keyword argument not understood:'): """Checks that all keyword arguments are in the set of allowed keys.""" for kwarg in kwargs: if kwarg not in allowed_kwargs: raise TypeError(error_message, kwarg)
Java
const $ = require('jquery'); const { BagItProfile } = require('../../bagit/bagit_profile'); const { Job } = require('../../core/job'); const { JobRunController } = require('./job_run_controller'); const { PackageOperation } = require('../../core/package_operation'); const path = require('path'); const { StorageService } = require('../../core/storage_service'); const { TestUtil } = require('../../core/test_util'); const { UITestUtil } = require('../common/ui_test_util'); const { UploadOperation } = require('../../core/upload_operation'); const { Util } = require('../../core/util'); beforeEach(() => { TestUtil.deleteJsonFile('Job'); TestUtil.deleteJsonFile('StorageService'); }); afterAll(() => { TestUtil.deleteJsonFile('Job'); TestUtil.deleteJsonFile('StorageService'); }); function getStorageService(name, proto, host) { let ss = new StorageService({ name: name, protocol: proto, host: host }); ss.save(); return ss; } function getUploadOp(name, proto, host) { let ss = getStorageService(name, proto, host); let op = new UploadOperation(); op.sourceFiles = ['/dev/null']; op.storageServiceId = ss.id; return op; } function getJob() { var job = new Job(); job.packageOp = new PackageOperation('TestBag', '/dev/null'); job.packageOp.packageFormat = 'BagIt'; job.packageOp._trimLeadingPaths = false; job.packageOp.sourceFiles = [ __dirname, path.join(__dirname, '..', 'forms') ]; job.dirCount = 2; job.fileCount = 12; job.byteCount = 237174; job.uploadOps = [ getUploadOp('target1', 's3', 'target1.com'), getUploadOp('target2', 's3', 'target2.com') ]; job.bagItProfile = BagItProfile.load(path.join(__dirname, '..', '..', 'test', 'profiles', 'multi_manifest.json')); job.save(); return job; } function getController() { let job = getJob(); let params = new URLSearchParams({ id: job.id }); return new JobRunController(params); } test('constructor', () => { let controller = getController(); expect(controller.model).toEqual(Job); expect(controller.job).not.toBeNull(); }); test('show', () => { let controller = getController(); let response = controller.show() expect(response.container).toMatch(controller.job.packageOp.packageName); expect(response.container).toMatch(controller.job.packageOp.outputPath); expect(response.container).toMatch(controller.job.bagItProfile.name); expect(response.container).toMatch(controller.job.bagItProfile.description); expect(response.container).toMatch('2 Directories'); expect(response.container).toMatch('12 Files'); expect(response.container).toMatch('231.62 KB'); expect(response.container).toMatch(controller.job.packageOp.sourceFiles[0]); expect(response.container).toMatch(controller.job.packageOp.sourceFiles[1]); });
Java
package io.github.dantesun.petclinic.data.velocity; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.parsing.XNode; import org.apache.ibatis.scripting.LanguageDriver; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.Alias; import org.mybatis.scripting.velocity.Driver; /** * Created by dsun on 15/2/22. */ @Alias("velocity") public class VelocityDriver implements LanguageDriver { private Driver driverImpl = new Driver(); @Override public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { return driverImpl.createParameterHandler(mappedStatement, parameterObject, boundSql); } @Override public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) { return createSqlSource(configuration, script.getNode().getTextContent(), parameterType); } @Override public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) { if (parameterType == null) { parameterType = Object.class; } return new VelocitySqlSource(configuration, script, parameterType); } }
Java
# Pseudonocardia halophobica (Akimov et al., 1989) McVeigh et al., 1994 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
package core.utils; import java.util.ArrayList; import java.util.List; public class Page<T> { public static final int PAGE_SIZE = 10; protected List<T> listObjects = new ArrayList<>(); protected int currentPage; protected int pageSize = PAGE_SIZE; /** * Constructor. * @param list contains the ArrayList to copy * @param page correspond to the currentPage */ public Page(List<T> list, int page) { for (int i = 0; i < list.size(); i++) { this.listObjects.add(list.get(i)); } this.currentPage = page; } /** * Constructor. * @param list contains the ArrayList to copy * @param page correspond to the currentPage * @param pageSize the page size */ public Page(List<T> list, int page, int pageSize) { for (int i = 0; i < list.size(); i++) { this.listObjects.add(list.get(i)); } this.currentPage = page; this.pageSize = pageSize; } /** * Get the ArrayList containing a T page. * @return the ArrayList containing a T page */ public List<T> getListPage() { return listObjects; } /** * Get the next page. * @return next page */ public int getNextPage() { return currentPage + 1; } /** * Get previous page. * @return previous page if currentPage > 0 else 0 */ public int getPreviousPage() { if (currentPage > 0) { return currentPage - 1; } else { return 0; } } /** * Get the current page. * @return the current page */ public int getCurrentPage() { return currentPage; } /** * Get the page size. * @return the page size */ public int getPageSize() { return pageSize; } /** * Test if the ArrayList<T> is empty. * @return True if Empty, else false */ public boolean isEmpty() { return listObjects.isEmpty(); } /** * Returns a string representation of the object. * @return a string representation of the object. */ @Override public String toString() { return this.getClass() + " [listObjects = " + listObjects + "]"; } /** * Equals Methode. * @param o other object * @return true if equals, else false */ @Override public boolean equals(Object o) { Page<T> page = (Page<T>) o; if (page.getPageSize() != this.pageSize || page.getCurrentPage() != this.currentPage) { return false; } boolean equals = true; int i = 0; while (i < this.pageSize && equals) { equals = page.getListPage().get(i).equals(this.listObjects.get(i)); i++; } return equals; } /** * Hash Code. * @return hash code */ @Override public int hashCode() { int result = listObjects != null ? listObjects.hashCode() : 0; result = 31 * result + currentPage; result = 31 * result + pageSize; return result; } /** * Add a Object in the ArrayList. * @param t the object */ public void add(T t) { listObjects.add(t); } }
Java
<?php /** * DO NOT EDIT THIS FILE! * * This file was automatically generated from external sources. * * Any manual change here will be lost the next time the SDK * is updated. You've been warned! */ namespace DTS\eBaySDK\Test\PostOrder\Types; use DTS\eBaySDK\PostOrder\Types\ReturnShippingCostDetailType; class ReturnShippingCostDetailTypeTest extends \PHPUnit_Framework_TestCase { private $obj; protected function setUp() { $this->obj = new ReturnShippingCostDetailType(); } public function testCanBeCreated() { $this->assertInstanceOf('\DTS\eBaySDK\PostOrder\Types\ReturnShippingCostDetailType', $this->obj); } public function testExtendsBaseType() { $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj); } }
Java
/** * @license Apache-2.0 * * Copyright (c) 2020 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 isPositiveInteger = require( '@stdlib/math/base/assert/is-positive-integer' ); var constantFunction = require( '@stdlib/utils/constant-function' ); var isfinite = require( '@stdlib/math/base/assert/is-finite' ); var round = require( '@stdlib/math/base/special/round' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var exp = require( '@stdlib/math/base/special/exp' ); var LN2 = require( '@stdlib/constants/float64/ln-two' ); var weights = require( './weights.js' ); // MAIN // /** * Returns a function for evaluating the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic with `n` observations. * * @param {PositiveInteger} n - number of observations * @returns {Function} CDF * * @example * var cdf = factory( 8 ); * var y = cdf( 3.9 ); * // returns ~0.027 * * y = cdf( 17.0 ); * // returns ~0.473 */ function factory( n ) { var mlim; var pui; if ( !isPositiveInteger( n ) || !isfinite( n ) ) { return constantFunction( NaN ); } pui = exp( -n * LN2 ); mlim = n * ( n + 1 ) / 2; return cdf; /** * Evaluates the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic. * * @private * @param {number} x - input value * @returns {Probability} evaluated CDF * * @example * var y = cdf( 2 ); * // returns <number> */ function cdf( x ) { var i; var p; if ( isnan( x ) ) { return NaN; } if ( x < 0.0 ) { return 0.0; } x = round( x ); if ( x >= mlim ) { return 1.0; } p = 0; for ( i = 0; i <= x; i++ ) { p += weights( i, n ) * pui; } return p; } } // EXPORTS // module.exports = factory;
Java
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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, OnInit} from '@angular/core'; import {SnackbarService} from "../../../services/snackbar.service"; import {ActivatedRoute, Router} from "@angular/router"; import {AppConfig} from "../../../../config/app.config"; import {DomainService} from "../../../services/domain.service"; import {AuthService} from "../../../services/auth.service"; @Component({ selector: 'app-scim', templateUrl: './scim.component.html', styleUrls: ['./scim.component.scss'] }) export class ScimComponent implements OnInit { domainId: string; domain: any = {}; formChanged = false; editMode: boolean; constructor(private domainService: DomainService, private snackbarService: SnackbarService, private authService: AuthService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.domain = this.route.snapshot.data['domain']; this.domainId = this.domain.id; this.editMode = this.authService.hasPermissions(['domain_scim_update']); } save() { this.domainService.patchScimSettings(this.domainId, this.domain).subscribe(data => { this.domain = data; this.formChanged = false; this.snackbarService.open('SCIM configuration updated'); }); } enableSCIM(event) { this.domain.scim = { 'enabled': (event.checked) }; this.formChanged = true; } isSCIMEnabled() { return this.domain.scim && this.domain.scim.enabled; } }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Software Testing</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="cookies.js"></script> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/small-business.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> <img src="http://techspot.ccsf.edu/images/yuba.png" width="170" height="90" alt=""> </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li> <a href="cookies.html">Log In</a> </li> <li> <a href="page1.html">Home</a> </li> <li> <a href="opp.html">Opportunity</a> </li> <li> <a href="ld.html">L&D</a> </li> <li> <a href="topics.html">Topics</a> </li> </ul> <span class="eggs"><script>readCookie('myCookie')</script></span> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <!-- Heading Row --> <div class="row"> <div class="col-md-8"> <img class="img-responsive img-rounded" src="http://www.clevertech.biz/img/service-header/software-testing.jpg" alt=""> </div> <!-- /.col-md-8 --> <div class="col-md-4"> <h1>In The News</h1> <p style="color: black"> <strong>US prisoners released early by software bug</strong> </p> <p style="color: black">The bug miscalculated the sentence reductions prisoners in Washington state had received for good behaviour.It was introduced in 2002 as part of an update that followed a court ruling about applying good behaviour credits.State officials said that many early-release prisoners would have to return to jail to finish their sentences.</p> <a class="btn btn-primary btn-lg" href="http://www.bbc.com/news/technology-35167191">Read more</a> </div> <!-- /.col-md-4 --> </div> <!-- /.row --> <hr> <!-- Call to Action Well --> <div class="row"> <div class="col-lg-12"> <div class="well text-center"> <a href="https://www.facebook.com/YearUpBayArea/" target="_blank"><img src="http://www.niftybuttons.com/scribble/facebook.png" border="0" margin="1px"></a><a href="https://www.linkedin.com/company/year-up" target="_blank"><img src="http://www.niftybuttons.com/scribble/linkedin.png" border="0" margin="1px"></a><a href="https://www.youtube.com/user/SFYearUp" target="_blank"><img src="http://www.niftybuttons.com/scribble/youtube.png" border="0" margin="1px"> <a href="https://twitter.com/yearupbayarea?lang=en" target="_blank"><img src="http://www.niftybuttons.com/scribble/twitter.png" border="0" margin="1px"></a> </a> </div> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <!-- Content Row --> <div class="row"> <div class="col-md-4"> <h2>Overview</h2> <p style="color: black">One of the very first things you will cover in QA are the different kinds of bus there are. There are a total of 5 you will need to remember. Software Development Life Cycle (SDLC), being the different stages a product goes threw before its releas date. How to properly log any bugs you find within a spec. Following the different methods testers use, which are constantly changing. One of the industry standards used today is Agile Testing. One other thing you will cover is White and Black Box Testing. In addition you will also cover White Box Dynamic and Static Testing; Black Box Dynamic and Static Testing. You will learn about Test-to-fail and Test-to-pass. One of the last of few things you will learn in QA is VCS (Version Control Systems), which can be very helpful while testing or creating a product. </p> <a class="btn btn-default" href="http://softwaretestingfundamentals.com/software-testing-methods/">More Info</a> </div> <!-- /.col-md-4 --> <div class="col-md-4"> <h2>Software Tools</h2> <p style="color:black">If you're intrested in learning a bit more about QA but don't know where to start, ther will be a link to a very insightful book at the end of this page. It is what we used in our QA class and it will give you an overview of QA and software testing. One out of two of the major things you will need to know is logging a specification bug. A basic templet should have your name, the date, the products name, the version number, and 3 pieces of information. Such as the type of bug you found, a potential bug, why you think it's a bug, and your suggested solution to fixing this bug. In addition you will have to know the 5 bugs that exist to actually identify them. The second thing will be Equivelence Partitioning. Equivalence partitioning (also called Equivalence Class Partitioning or ECP) is a software testing technique that divides the input data of a software unit into partitions of equivalent data from which test cases can be derived. In principle, test cases are designed to cover each partition at least once. </p> <a href="myfile.pdf"><img src="https://p.gr-assets.com/max_square/fill/books/1348774033/1543131.jpg" width="400" height="387"></a> </div> <!-- /.col-md-4 --> <!-- /.col-md-4 --> </div> <!-- /.row --> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <center> <p style="color:black">Copyright &copy; YUBA 2016&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="page1.html">Home&nbsp;&nbsp;</a> <a href="opp.html">Opportunities&nbsp;&nbsp;</a> <a href="ld.html">L+D&nbsp;&nbsp;</a> <a href="topics.html">Topics&nbsp;&nbsp;</a> <a href="http://www.yearup.org/future-students/?location=bay-area/">Apply Today</a> </p> </center> </div> </div> </footer> </div> <!-- /.container --> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> </body> </html>
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.ml.preprocessing.imputer; import org.apache.ignite.ml.math.functions.IgniteBiFunction; /** * Preprocessing function that makes imputing. * * @param <K> Type of a key in {@code upstream} data. * @param <V> Type of a value in {@code upstream} data. */ public class ImputerPreprocessor<K, V> implements IgniteBiFunction<K, V, double[]> { /** */ private static final long serialVersionUID = 6887800576392623469L; /** Filling values. */ private final double[] imputingValues; /** Base preprocessor. */ private final IgniteBiFunction<K, V, double[]> basePreprocessor; /** * Constructs a new instance of imputing preprocessor. * * @param basePreprocessor Base preprocessor. */ public ImputerPreprocessor(double[] imputingValues, IgniteBiFunction<K, V, double[]> basePreprocessor) { this.imputingValues = imputingValues; this.basePreprocessor = basePreprocessor; } /** * Applies this preprocessor. * * @param k Key. * @param v Value. * @return Preprocessed row. */ @Override public double[] apply(K k, V v) { double[] res = basePreprocessor.apply(k, v); assert res.length == imputingValues.length; for (int i = 0; i < res.length; i++) { if (Double.valueOf(res[i]).equals(Double.NaN)) res[i] = imputingValues[i]; } return res; } }
Java
/* © 2017 Altavant Technologies Inc. Web: http://www.altavant.com */ namespace Altavant.Fusion.Graphics { using System; using Fusion.Utils; public enum MatrixOrder : byte { Append, Prepend } public class Matrix { private float _m11; private float _m12; private float _m21; private float _m22; private float _offsetX; private float _offsetY; private float[] _values; public Matrix() : this(1F, 0F, 0F, 1F, 0F, 0F) { } public Matrix(float m11, float m12, float m21, float m22, float offsetX, float offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } public Matrix(Android.Graphics.Matrix matrix) { float[] values = new float[9]; matrix.GetValues(values); _m11 = values[Android.Graphics.Matrix.MscaleX]; _m21 = values[Android.Graphics.Matrix.MskewX]; _offsetX = values[Android.Graphics.Matrix.MtransX]; _m12 = values[Android.Graphics.Matrix.MskewY]; _m22 = values[Android.Graphics.Matrix.MscaleY]; _offsetY = values[Android.Graphics.Matrix.MtransY]; } public float M11 { get { return _m11; } set { _m11 = value; } } public float M12 { get { return _m12; } set { _m12 = value; } } public float M21 { get { return _m21; } set { _m21 = value; } } public float M22 { get { return _m22; } set { _m22 = value; } } public float OffsetX { get { return _offsetX; } set { _offsetX = value; } } public float OffsetY { get { return _offsetY; } set { _offsetY = value; } } public static Matrix Identity { get { return new Matrix(1F, 0F, 0F, 1F, 0F, 0F); } } public bool IsIdentity { get { if ((_m11 == 1F) && (_m12 == 0F) && (_m21 == 0F) && (_m22 == 1F) && (_offsetX == 0F) && (_offsetY == 0F)) return true; return false; } } public void SetValues(float m11, float m12, float m21, float m22, float offsetX, float offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } public void Reset() { _m11 = 1F; _m12 = 0F; _m21 = 0F; _m22 = 1F; _offsetX = 0F; _offsetY = 0F; } public void Multiply(Matrix matrix) { Multiply(matrix, MatrixOrder.Prepend); } public void Multiply(Matrix matrix, MatrixOrder order) { if (matrix == null) throw new ArgumentNullException(nameof(matrix)); float a11, a12, a21, a22, aX, aY; float b11, b12, b21, b22, bX, bY; if (order == MatrixOrder.Append) { a11 = _m11; a12 = _m12; a21 = _m21; a22 = _m22; aX = _offsetX; aY = _offsetY; b11 = matrix.M11; b12 = matrix.M12; b21 = matrix.M21; b22 = matrix.M22; bX = matrix.OffsetX; bY = matrix.OffsetY; } else { a11 = matrix.M11; a12 = matrix.M12; a21 = matrix.M21; a22 = matrix.M22; aX = matrix.OffsetX; aY = matrix.OffsetY; b11 = _m11; b12 = _m12; b21 = _m21; b22 = _m22; bX = _offsetX; bY = _offsetY; } _m11 = a11 * b11 + a12 * b21; _m12 = a11 * b12 + a12 * b22; _m21 = a21 * b11 + a22 * b21; _m22 = a21 * b12 + a22 * b22; _offsetX = aX * b11 + aY * b21 + bX; _offsetY = aX * b12 + aY * b22 + bY; } public void Translate(float offsetX, float offsetY) { Translate(offsetX, offsetY, MatrixOrder.Prepend); } public void Translate(float offsetX, float offsetY, MatrixOrder order) { Matrix matrix = Translation(offsetX, offsetY); Multiply(matrix, order); } public void Rotate(float angle) { Rotate(angle, MatrixOrder.Prepend); } public void Rotate(float angle, MatrixOrder order) { Matrix matrix = Rotation(angle); Multiply(matrix, order); } public void RotateAt(float angle, Point center) { RotateAt(angle, center.X, center.Y, MatrixOrder.Prepend); } public void RotateAt(float angle, float centerX, float centerY) { RotateAt(angle, centerX, centerY, MatrixOrder.Prepend); } public void RotateAt(float angle, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); RotateAt(angle, center.X, center.Y, order); } public void RotateAt(float angle, float centerX, float centerY, MatrixOrder order) { Matrix matrix = RotationAt(angle, centerX, centerY); Multiply(matrix, order); } public void Scale(float scaleX, float scaleY) { Scale(scaleX, scaleY, MatrixOrder.Prepend); } public void Scale(float scaleX, float scaleY, MatrixOrder order) { Matrix matrix = Scaling(scaleX, scaleY); Multiply(matrix, order); } public void ScaleAt(float scaleX, float scaleY, Point center) { ScaleAt(scaleX, scaleY, center.X, center.Y, MatrixOrder.Prepend); } public void ScaleAt(float scaleX, float scaleY, float centerX, float centerY) { ScaleAt(scaleX, scaleY, centerX, centerY, MatrixOrder.Prepend); } public void ScaleAt(float scaleX, float scaleY, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); ScaleAt(scaleX, scaleY, center.X, center.Y, order); } public void ScaleAt(float scaleX, float scaleY, float centerX, float centerY, MatrixOrder order) { Matrix matrix = ScalingAt(scaleX, scaleY, centerX, centerY); Multiply(matrix, order); } public void Shear(float shearX, float shearY) { Shear(shearX, shearY, MatrixOrder.Prepend); } public void Shear(float shearX, float shearY, MatrixOrder order) { Matrix matrix = Shearing(shearX, shearY); Multiply(matrix, order); } public void ShearAt(float shearX, float shearY, Point center) { ShearAt(shearX, shearY, center.X, center.Y, MatrixOrder.Prepend); } public void ShearAt(float shearX, float shearY, float centerX, float centerY) { ShearAt(shearX, shearY, centerX, centerY, MatrixOrder.Prepend); } public void ShearAt(float shearX, float shearY, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); ShearAt(shearX, shearY, center.X, center.Y, order); } public void ShearAt(float shearX, float shearY, float centerX, float centerY, MatrixOrder order) { Matrix matrix = ShearingAt(shearX, shearY, centerX, centerY); Multiply(matrix, order); } public void Skew(float skewX, float skewY) { Skew(skewX, skewY, MatrixOrder.Prepend); } public void Skew(float skewX, float skewY, MatrixOrder order) { Matrix matrix = Skewing(skewX, skewY); Multiply(matrix, order); } public void SkewAt(float skewX, float skewY, Point center) { SkewAt(skewX, skewY, center.X, center.Y, MatrixOrder.Prepend); } public void SkewAt(float skewX, float skewY, float centerX, float centerY) { SkewAt(skewX, skewY, centerX, centerY, MatrixOrder.Prepend); } public void SkewAt(float skewX, float skewY, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); SkewAt(skewX, skewY, center.X, center.Y, order); } public void SkewAt(float skewX, float skewY, float centerX, float centerY, MatrixOrder order) { Matrix matrix = SkewingAt(skewX, skewY, centerX, centerY); Multiply(matrix, order); } public Point TransformPoint(Point pt) { return TransformPoint(pt.X, pt.Y); } public Point TransformPoint(float x, float y) { float x1 = x * _m11 + y * _m21 + _offsetX; float y1 = x * _m12 + y * _m22 + _offsetY; return new Point(x1, y1); } public Matrix Clone() { return new Matrix(_m11, _m12, _m21, _m22, _offsetX, _offsetY); } public override int GetHashCode() { return _m11.GetHashCode() ^ _m12.GetHashCode() ^ _m21.GetHashCode() ^ _m22.GetHashCode() ^ _offsetX.GetHashCode() ^ _offsetY.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) return false; if (obj == this) return true; if (obj is Matrix) { Matrix matrix = (Matrix)obj; if ((_m11 == matrix.M11) && (_m12 == matrix.M12) && (_m21 == matrix.M21) && (_m22 == matrix.M22) && (_offsetX == matrix.OffsetX) && (_offsetY == matrix.OffsetY)) return true; } return false; } public override string ToString() { CharBuffer cb = new CharBuffer(); cb.Add(Converter.ToString(_m11, 3)); cb.Add(", "); cb.Add(Converter.ToString(_m12, 3)); cb.Add(", "); cb.Add(Converter.ToString(_m21, 3)); cb.Add(", "); cb.Add(Converter.ToString(_m22, 3)); cb.Add(", "); cb.Add(Converter.ToString(_offsetX, 3)); cb.Add(", "); cb.Add(Converter.ToString(_offsetY, 3)); return cb.ToString(); } public static Matrix Parse(string s) { if (string.IsNullOrEmpty(s)) throw new ArgumentException(nameof(s)); string[] vals = Utils.Split(s); float m11 = Convert.ToSingle(vals[0], Converter.NumberFormatInfo); float m12 = Convert.ToSingle(vals[1], Converter.NumberFormatInfo); float m21 = Convert.ToSingle(vals[2], Converter.NumberFormatInfo); float m22 = Convert.ToSingle(vals[3], Converter.NumberFormatInfo); float offsetX = Convert.ToSingle(vals[4], Converter.NumberFormatInfo); float offsetY = Convert.ToSingle(vals[5], Converter.NumberFormatInfo); return new Matrix(m11, m12, m21, m22, offsetX, offsetY); } public static Matrix Translation(Point offset) { return new Matrix(1F, 0F, 0F, 1F, offset.X, offset.Y); } public static Matrix Translation(float offsetX, float offsetY) { return new Matrix(1F, 0F, 0F, 1F, offsetX, offsetY); } public static Matrix Rotation(float angle) { double radianAngle = angle * Math.PI / 180F; float cosAngle = (float)Math.Cos(radianAngle); float sinAngle = (float)Math.Sin(radianAngle); return new Matrix(cosAngle, sinAngle, -sinAngle, cosAngle, 0F, 0F); } public static Matrix RotationAt(float angle, Point center) { return RotationAt(angle, center.X, center.Y); } public static Matrix RotationAt(float angle, float centerX, float centerY) { double radianAngle = angle * Math.PI / 180F; float cosAngle = (float)Math.Cos(radianAngle); float sinAngle = (float)Math.Sin(radianAngle); Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(cosAngle, sinAngle, -sinAngle, cosAngle, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public static Matrix Scaling(float scale) { return Scaling(scale, scale); } public static Matrix Scaling(float scaleX, float scaleY) { return new Matrix(scaleX, 0F, 0F, scaleY, 0F, 0F); } public static Matrix ScalingAt(float scale, Point center) { return ScalingAt(scale, scale, center.X, center.Y); } public static Matrix ScalingAt(float scaleX, float scaleY, Point center) { return ScalingAt(scaleX, scaleY, center.X, center.Y); } public static Matrix ScalingAt(float scale, float centerX, float centerY) { return ScalingAt(scale, scale, centerX, centerY); } public static Matrix ScalingAt(float scaleX, float scaleY, float centerX, float centerY) { Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(scaleX, 0F, 0F, scaleY, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public static Matrix Shearing(float shearX, float shearY) { return new Matrix(1F, shearY, shearX, 1F, 0F, 0F); } public static Matrix ShearingAt(float shearX, float shearY, Point center) { return ShearingAt(shearX, shearY, center.X, center.Y); } public static Matrix ShearingAt(float shearX, float shearY, float centerX, float centerY) { Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(1F, shearY, shearX, 1F, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public static Matrix Skewing(float skewX, float skewY) { double angleAlpha = skewX * Math.PI / 180F; double angleBeta = skewY * Math.PI / 180F; float tanAlpha = (float)Math.Tan(angleAlpha); float tanBeta = (float)Math.Tan(angleBeta); return new Matrix(1F, tanBeta, tanAlpha, 1F, 0F, 0F); } public static Matrix SkewingAt(float skewX, float skewY, Point center) { return SkewingAt(skewX, skewY, center.X, center.Y); } public static Matrix SkewingAt(float skewX, float skewY, float centerX, float centerY) { double angleAlpha = skewX * Math.PI / 180F; double angleBeta = skewY * Math.PI / 180F; float tanAlpha = (float)Math.Tan(angleAlpha); float tanBeta = (float)Math.Tan(angleBeta); Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(1F, tanBeta, tanAlpha, 1F, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public Android.Graphics.Matrix ToNative() { Android.Graphics.Matrix m = new Android.Graphics.Matrix(); ToNative(m); return m; } public void ToNative(Android.Graphics.Matrix m) { if (_values == null) _values = new float[9]; _values[Android.Graphics.Matrix.MscaleX] = _m11; _values[Android.Graphics.Matrix.MskewX] = _m21; _values[Android.Graphics.Matrix.MtransX] = _offsetX; _values[Android.Graphics.Matrix.MskewY] = _m12; _values[Android.Graphics.Matrix.MscaleY] = _m22; _values[Android.Graphics.Matrix.MtransY] = _offsetY; _values[Android.Graphics.Matrix.Mpersp2] = 1F; m.SetValues(_values); } } }
Java
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.core; import junit.framework.TestCase; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(com.hazelcast.util.RandomBlockJUnit4ClassRunner.class) public class IMapAsyncTest { private final String key = "key"; private final String value1 = "value1"; private final String value2 = "value2"; @BeforeClass @AfterClass public static void init() throws Exception { Hazelcast.shutdownAll(); } @Test public void testGetAsync() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:getAsync"); map.put(key, value1); Future<String> f1 = map.getAsync(key); TestCase.assertEquals(value1, f1.get()); } @Test public void testPutAsync() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:putAsync"); Future<String> f1 = map.putAsync(key, value1); String f1Val = f1.get(); TestCase.assertNull(f1Val); Future<String> f2 = map.putAsync(key, value2); String f2Val = f2.get(); TestCase.assertEquals(value1, f2Val); } @Test public void testRemoveAsync() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:removeAsync"); // populate map map.put(key, value1); Future<String> f1 = map.removeAsync(key); TestCase.assertEquals(value1, f1.get()); } @Test public void testRemoveAsyncWithImmediateTimeout() throws Exception { final IMap<String, String> map = Hazelcast.getMap("map:test:removeAsync:timeout"); // populate map map.put(key, value1); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { public void run() { map.lock(key); latch.countDown(); } }).start(); assertTrue(latch.await(20, TimeUnit.SECONDS)); Future<String> f1 = map.removeAsync(key); try { assertEquals(value1, f1.get(0L, TimeUnit.SECONDS)); } catch (TimeoutException e) { // expected return; } TestCase.fail("Failed to throw TimeoutException with zero timeout"); } @Test public void testRemoveAsyncWithNonExistantKey() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:removeAsync:nonexistant"); Future<String> f1 = map.removeAsync(key); TestCase.assertNull(f1.get()); } }
Java
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.index.query; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; /** * */ public class SpanFirstQueryBuilder extends BaseQueryBuilder implements SpanQueryBuilder, BoostableQueryBuilder<SpanFirstQueryBuilder> { public static final String NAME = "span_first"; private final SpanQueryBuilder matchBuilder; private final int end; private float boost = -1; public SpanFirstQueryBuilder(SpanQueryBuilder matchBuilder, int end) { this.matchBuilder = matchBuilder; this.end = end; } public SpanFirstQueryBuilder boost(float boost) { this.boost = boost; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); builder.field("match"); matchBuilder.toXContent(builder, params); builder.field("end", end); if (boost != -1) { builder.field("boost", boost); } builder.endObject(); } }
Java
[assembly: Xamarin.Forms.Platform.WPF.ExportRenderer(typeof(Xamarin.Forms.Entry), typeof(Xamarin.Forms.Platform.WPF.Controls.EntryRenderer))] namespace Xamarin.Forms.Platform.WPF.Controls { using System.Windows; using System.Windows.Controls; public partial class EntryRenderer : Xamarin.Forms.Platform.WPF.Rendereres.ViewRenderer { bool ignoreTextChange; public new Entry Model { get { return (Entry)base.Model; } set { base.Model = value; } } public EntryRenderer() { InitializeComponent(); } protected override void LoadModel(View model) { ((Entry)model).TextChanged += EntryModel_TextChanged; base.LoadModel(model); } protected override void UnloadModel(View model) { ((Entry)model).TextChanged -= EntryModel_TextChanged; base.UnloadModel(model); } void EntryModel_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e) { if (ignoreTextChange) return; ignoreTextChange = true; TextBox.Text = e.NewTextValue; PasswordBox.Password = e.NewTextValue; ignoreTextChange = false; } void TextBox_TextChanged(object sender, TextChangedEventArgs e) { if (ignoreTextChange) return; ignoreTextChange = true; Model.Text = TextBox.Text; PasswordBox.Password = TextBox.Text; ignoreTextChange = false; } void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) { if (ignoreTextChange) return; ignoreTextChange = true; Model.Text = PasswordBox.Password; TextBox.Text = PasswordBox.Password; ignoreTextChange = false; } private void Entry_LostFocus(object sender, RoutedEventArgs e) { if (Model != null) Model.SendCompleted(); } private void Entry_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (Model != null && e.Key == System.Windows.Input.Key.Return) { Model.SendCompleted(); e.Handled = true; } } protected override bool Handle_BackgroundColorProperty(BindableProperty property) { // Background color is set directly to the TextBox/PasswordBox with bindings. return true; } } }
Java
/*§ =========================================================================== MoonDeploy =========================================================================== Copyright (C) 2015-2016 Gianluca Costa =========================================================================== 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 test /* It is not trivial to perform automated tests for MoonDeploy. Currently, testing is based on its actual execution for existing programs such as GraphsJ, Chronos IDE and KnapScal. */
Java
# Asterinites colombiensis Doub. & D. Pons ex Kalgutkar & Janson. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in AASP Contributions Series (Dallas) 39: 32 + pl. 30, fig. 9 (2000) #### Original name Asterinites colombiensis Doub. & D. Pons ex Kalgutkar & Janson. ### Remarks null
Java
page_title: Dockerfile Reference page_description: Dockerfiles use a simple DSL which allows you to automate the steps you would normally manually take to create an image. page_keywords: builder, docker, Dockerfile, automation, image creation # Dockerfile Reference **Docker can act as a builder** and read instructions from a text *Dockerfile* to automate the steps you would otherwise take manually to create an image. Executing `docker build` will run your steps and commit them along the way, giving you a final image. ## Usage To [*build*](../commandline/cli/#cli-build) an image from a source repository, create a description file called Dockerfile at the root of your repository. This file will describe the steps to assemble the image. Then call `docker build` with the path of your source repository as the argument (for example, `.`): $ sudo docker build . The path to the source repository defines where to find the *context* of the build. The build is run by the Docker daemon, not by the CLI, so the whole context must be transferred to the daemon. The Docker CLI reports "Sending build context to Docker daemon" when the context is sent to the daemon. You can specify a repository and tag at which to save the new image if the build succeeds: $ sudo docker build -t shykes/myapp . The Docker daemon will run your steps one-by-one, committing the result to a new image if necessary, before finally outputting the ID of your new image. The Docker daemon will automatically clean up the context you sent. Note that each instruction is run independently, and causes a new image to be created - so `RUN cd /tmp` will not have any effect on the next instructions. Whenever possible, Docker will re-use the intermediate images, accelerating `docker build` significantly (indicated by `Using cache`): $ docker build -t SvenDowideit/ambassador . Uploading context 10.24 kB Uploading context Step 1 : FROM docker-ut ---> cbba202fe96b Step 2 : MAINTAINER SvenDowideit@home.org.au ---> Using cache ---> 51182097be13 Step 3 : CMD env | grep _TCP= | sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \&/' | sh && top ---> Using cache ---> 1a5ffc17324d Successfully built 1a5ffc17324d When you're done with your build, you're ready to look into [*Pushing a repository to its registry*]( /userguide/dockerrepos/#image-push). ## Format Here is the format of the Dockerfile: # Comment INSTRUCTION arguments The Instruction is not case-sensitive, however convention is for them to be UPPERCASE in order to distinguish them from arguments more easily. Docker evaluates the instructions in a Dockerfile in order. **The first instruction must be \`FROM\`** in order to specify the [*Base Image*](/terms/image/#base-image-def) from which you are building. Docker will treat lines that *begin* with `#` as a comment. A `#` marker anywhere else in the line will be treated as an argument. This allows statements like: # Comment RUN echo 'we are running some # of cool things' Here is the set of instructions you can use in a Dockerfile for building images. ## .dockerignore If a file named `.dockerignore` exists in the source repository, then it is interpreted as a newline-separated list of exclusion patterns. Exclusion patterns match files or directories relative to the source repository that will be excluded from the context. Globbing is done using Go's [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. The following example shows the use of the `.dockerignore` file to exclude the `.git` directory from the context. Its effect can be seen in the changed size of the uploaded context. $ docker build . Uploading context 18.829 MB Uploading context Step 0 : FROM busybox ---> 769b9341d937 Step 1 : CMD echo Hello World ---> Using cache ---> 99cc1ad10469 Successfully built 99cc1ad10469 $ echo ".git" > .dockerignore $ docker build . Uploading context 6.76 MB Uploading context Step 0 : FROM busybox ---> 769b9341d937 Step 1 : CMD echo Hello World ---> Using cache ---> 99cc1ad10469 Successfully built 99cc1ad10469 ## FROM FROM <image> Or FROM <image>:<tag> The `FROM` instruction sets the [*Base Image*](/terms/image/#base-image-def) for subsequent instructions. As such, a valid Dockerfile must have `FROM` as its first instruction. The image can be any valid image – it is especially easy to start by **pulling an image** from the [*Public Repositories*]( /userguide/dockerrepos/#using-public-repositories). `FROM` must be the first non-comment instruction in the Dockerfile. `FROM` can appear multiple times within a single Dockerfile in order to create multiple images. Simply make a note of the last image id output by the commit before each new `FROM` command. If no `tag` is given to the `FROM` instruction, `latest` is assumed. If the used tag does not exist, an error will be returned. ## MAINTAINER MAINTAINER <name> The `MAINTAINER` instruction allows you to set the *Author* field of the generated images. ## RUN RUN has 2 forms: - `RUN <command>` (the command is run in a shell - `/bin/sh -c`) - `RUN ["executable", "param1", "param2"]` (*exec* form) The `RUN` instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile. Layering `RUN` instructions and generating commits conforms to the core concepts of Docker where commits are cheap and containers can be created from any point in an image's history, much like source control. The *exec* form makes it possible to avoid shell string munging, and to `RUN` commands using a base image that does not contain `/bin/sh`. The cache for `RUN` instructions isn't invalidated automatically during the next build. The cache for an instruction like `RUN apt-get dist-upgrade -y` will be reused during the next build. The cache for `RUN` instructions can be invalidated by using the `--no-cache` flag, for example `docker build --no-cache`. The cache for `RUN` instructions can be invalidated by `ADD` instructions. See [below](#add) for details. ### Known Issues (RUN) - [Issue 783](https://github.com/dotcloud/docker/issues/783) is about file permissions problems that can occur when using the AUFS file system. You might notice it during an attempt to `rm` a file, for example. The issue describes a workaround. - [Issue 2424](https://github.com/dotcloud/docker/issues/2424) Locale will not be set automatically. ## CMD CMD has three forms: - `CMD ["executable","param1","param2"]` (like an *exec*, this is the preferred form) - `CMD ["param1","param2"]` (as *default parameters to ENTRYPOINT*) - `CMD command param1 param2` (as a *shell*) There can only be one CMD in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. **The main purpose of a CMD is to provide defaults for an executing container.** These defaults can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT as well. When used in the shell or exec formats, the `CMD` instruction sets the command to be executed when running the image. If you use the *shell* form of the CMD, then the `<command>` will execute in `/bin/sh -c`: FROM ubuntu CMD echo "This is a test." | wc - If you want to **run your** `<command>` **without a shell** then you must express the command as a JSON array and give the full path to the executable. **This array form is the preferred format of CMD.** Any additional parameters must be individually expressed as strings in the array: FROM ubuntu CMD ["/usr/bin/wc","--help"] If you would like your container to run the same executable every time, then you should consider using `ENTRYPOINT` in combination with `CMD`. See [*ENTRYPOINT*](#entrypoint). If the user specifies arguments to `docker run` then they will override the default specified in CMD. > **Note**: > don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits > the result; `CMD` does not execute anything at build time, but specifies > the intended command for the image. ## EXPOSE EXPOSE <port> [<port>...] The `EXPOSE` instructions informs Docker that the container will listen on the specified network ports at runtime. Docker uses this information to interconnect containers using links (see the [Docker User Guide](/userguide/dockerlinks)). ## ENV ENV <key> <value> The `ENV` instruction sets the environment variable `<key>` to the value `<value>`. This value will be passed to all future `RUN` instructions. This is functionally equivalent to prefixing the command with `<key>=<value>` The environment variables set using `ENV` will persist when a container is run from the resulting image. You can view the values using `docker inspect`, and change them using `docker run --env <key>=<value>`. > **Note**: > One example where this can cause unexpected consequences, is setting > `ENV DEBIAN_FRONTEND noninteractive`. Which will persist when the container > is run interactively; for example: `docker run -t -i image bash` ## ADD ADD <src> <dest> The `ADD` instruction will copy new files from `<src>` and add them to the container's filesystem at path `<dest>`. `<src>` must be the path to a file or directory relative to the source directory being built (also called the *context* of the build) or a remote file URL. `<dest>` is the absolute path to which the source will be copied inside the destination container. All new files and directories are created with a uid and gid of 0. In the case where `<src>` is a remote file URL, the destination will have permissions 600. > **Note**: > If you build by passing a Dockerfile through STDIN (`docker build - < somefile`), > there is no build context, so the Dockerfile can only contain a URL > based ADD statement. > You can also pass a compressed archive through STDIN: > (`docker build - < archive.tar.gz`), the `Dockerfile` at the root of > the archive and the rest of the archive will get used at the context > of the build. > > **Note**: > If your URL files are protected using authentication, you will need to > use `RUN wget` , `RUN curl` > or use another tool from within the container as ADD does not support > authentication. > **Note**: > The first encountered `ADD` instruction will invalidate the cache for all > following instructions from the Dockerfile if the contents of `<src>` have > changed. This includes invalidating the cache for `RUN` instructions. The copy obeys the following rules: - The `<src>` path must be inside the *context* of the build; you cannot `ADD ../something /something`, because the first step of a `docker build` is to send the context directory (and subdirectories) to the docker daemon. - If `<src>` is a URL and `<dest>` does not end with a trailing slash, then a file is downloaded from the URL and copied to `<dest>`. - If `<src>` is a URL and `<dest>` does end with a trailing slash, then the filename is inferred from the URL and the file is downloaded to `<dest>/<filename>`. For instance, `ADD http://example.com/foobar /` would create the file `/foobar`. The URL must have a nontrivial path so that an appropriate filename can be discovered in this case (`http://example.com` will not work). - If `<src>` is a directory, the entire directory is copied, including filesystem metadata. - If `<src>` is a *local* tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from *remote* URLs are **not** decompressed. When a directory is copied or unpacked, it has the same behavior as `tar -x`: the result is the union of: 1. whatever existed at the destination path and 2. the contents of the source tree, with conflicts resolved in favor of "2." on a file-by-file basis. - If `<src>` is any other kind of file, it is copied individually along with its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it will be considered a directory and the contents of `<src>` will be written at `<dest>/base(<src>)`. - If `<dest>` does not end with a trailing slash, it will be considered a regular file and the contents of `<src>` will be written at `<dest>`. - If `<dest>` doesn't exist, it is created along with all missing directories in its path. ## COPY COPY <src> <dest> The `COPY` instruction will copy new files from `<src>` and add them to the container's filesystem at path `<dest>`. `<src>` must be the path to a file or directory relative to the source directory being built (also called the *context* of the build). `<dest>` is the absolute path to which the source will be copied inside the destination container. All new files and directories are created with a uid and gid of 0. > **Note**: > If you build using STDIN (`docker build - < somefile`), there is no > build context, so `COPY` can't be used. The copy obeys the following rules: - The `<src>` path must be inside the *context* of the build; you cannot `COPY ../something /something`, because the first step of a `docker build` is to send the context directory (and subdirectories) to the docker daemon. - If `<src>` is a directory, the entire directory is copied, including filesystem metadata. - If `<src>` is any other kind of file, it is copied individually along with its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it will be considered a directory and the contents of `<src>` will be written at `<dest>/base(<src>)`. - If `<dest>` does not end with a trailing slash, it will be considered a regular file and the contents of `<src>` will be written at `<dest>`. - If `<dest>` doesn't exist, it is created along with all missing directories in its path. ## ENTRYPOINT ENTRYPOINT has two forms: - `ENTRYPOINT ["executable", "param1", "param2"]` (like an *exec*, preferred form) - `ENTRYPOINT command param1 param2` (as a *shell*) There can only be one `ENTRYPOINT` in a Dockerfile. If you have more than one `ENTRYPOINT`, then only the last one in the Dockerfile will have an effect. An `ENTRYPOINT` helps you to configure a container that you can run as an executable. That is, when you specify an `ENTRYPOINT`, then the whole container runs as if it was just that executable. The `ENTRYPOINT` instruction adds an entry command that will **not** be overwritten when arguments are passed to `docker run`, unlike the behavior of `CMD`. This allows arguments to be passed to the entrypoint. i.e. `docker run <image> -d` will pass the "-d" argument to the ENTRYPOINT. You can specify parameters either in the ENTRYPOINT JSON array (as in "like an exec" above), or by using a CMD statement. Parameters in the ENTRYPOINT will not be overridden by the `docker run` arguments, but parameters specified via CMD will be overridden by `docker run` arguments. Like a `CMD`, you can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`: FROM ubuntu ENTRYPOINT wc -l - For example, that Dockerfile's image will *always* take STDIN as input ("-") and print the number of lines ("-l"). If you wanted to make this optional but default, you could use a CMD: FROM ubuntu CMD ["-l", "-"] ENTRYPOINT ["/usr/bin/wc"] ## VOLUME VOLUME ["/data"] The `VOLUME` instruction will create a mount point with the specified name and mark it as holding externally mounted volumes from native host or other containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain string, `VOLUME /var/log`. For more information/examples and mounting instructions via the Docker client, refer to [*Share Directories via Volumes*]( /userguide/dockervolumes/#volume-def) documentation. ## USER USER daemon The `USER` instruction sets the username or UID to use when running the image and for any following `RUN` directives. ## WORKDIR WORKDIR /path/to/workdir The `WORKDIR` instruction sets the working directory for the `RUN`, `CMD` and `ENTRYPOINT` Dockerfile commands that follow it. It can be used multiple times in the one Dockerfile. If a relative path is provided, it will be relative to the path of the previous `WORKDIR` instruction. For example: WORKDIR /a WORKDIR b WORKDIR c RUN pwd The output of the final `pwd` command in this Dockerfile would be `/a/b/c`. ## ONBUILD ONBUILD [INSTRUCTION] The `ONBUILD` instruction adds to the image a "trigger" instruction to be executed at a later time, when the image is used as the base for another build. The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the *FROM* instruction in the downstream Dockerfile. Any build instruction can be registered as a trigger. This is useful if you are building an image which will be used as a base to build other images, for example an application build environment or a daemon which may be customized with user-specific configuration. For example, if your image is a reusable python application builder, it will require application source code to be added in a particular directory, and it might require a build script to be called *after* that. You can't just call *ADD* and *RUN* now, because you don't yet have access to the application source code, and it will be different for each application build. You could simply provide application developers with a boilerplate Dockerfile to copy-paste into their application, but that is inefficient, error-prone and difficult to update because it mixes with application-specific code. The solution is to use *ONBUILD* to register in advance instructions to run later, during the next build stage. Here's how it works: 1. When it encounters an *ONBUILD* instruction, the builder adds a trigger to the metadata of the image being built. The instruction does not otherwise affect the current build. 2. At the end of the build, a list of all triggers is stored in the image manifest, under the key *OnBuild*. They can be inspected with *docker inspect*. 3. Later the image may be used as a base for a new build, using the *FROM* instruction. As part of processing the *FROM* instruction, the downstream builder looks for *ONBUILD* triggers, and executes them in the same order they were registered. If any of the triggers fail, the *FROM* instruction is aborted which in turn causes the build to fail. If all triggers succeed, the FROM instruction completes and the build continues as usual. 4. Triggers are cleared from the final image after being executed. In other words they are not inherited by "grand-children" builds. For example you might add something like this: [...] ONBUILD ADD . /app/src ONBUILD RUN /usr/local/bin/python-build --dir /app/src [...] > **Warning**: Chaining ONBUILD instructions using ONBUILD ONBUILD isn't allowed. > **Warning**: ONBUILD may not trigger FROM or MAINTAINER instructions. ## Dockerfile Examples # Nginx # # VERSION 0.0.1 FROM ubuntu MAINTAINER Victor Vieux <victor@docker.com> # make sure the package repository is up to date RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list RUN apt-get update RUN apt-get install -y inotify-tools nginx apache2 openssh-server # Firefox over VNC # # VERSION 0.3 FROM ubuntu # make sure the package repository is up to date RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list RUN apt-get update # Install vnc, xvfb in order to create a 'fake' display and firefox RUN apt-get install -y x11vnc xvfb firefox RUN mkdir /.vnc # Setup a password RUN x11vnc -storepasswd 1234 ~/.vnc/passwd # Autostart firefox (might not be the best way, but it does the trick) RUN bash -c 'echo "firefox" >> /.bashrc' EXPOSE 5900 CMD ["x11vnc", "-forever", "-usepw", "-create"] # Multiple images example # # VERSION 0.1 FROM ubuntu RUN echo foo > bar # Will output something like ===> 907ad6c2736f FROM ubuntu RUN echo moo > oink # Will output something like ===> 695d7793cbe4 # You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with # /oink.
Java
/** * @license * Copyright The Closure Library Authors. * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Displays and edits the value of a cookie. * Intended only for debugging. */ goog.provide('goog.ui.CookieEditor'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events.EventType'); goog.require('goog.net.Cookies'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.requireType('goog.events.Event'); /** * Displays and edits the value of a cookie. * @final * @unrestricted */ goog.ui.CookieEditor = class extends goog.ui.Component { /** * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. */ constructor(opt_domHelper) { 'use strict'; super(opt_domHelper); } /** * Sets the cookie which this component will edit. * @param {string} cookieKey Cookie key. */ selectCookie(cookieKey) { 'use strict'; goog.asserts.assert(goog.net.Cookies.getInstance().isValidName(cookieKey)); this.cookieKey_ = cookieKey; if (this.textAreaElem_) { this.textAreaElem_.value = goog.net.Cookies.getInstance().get(cookieKey) || ''; } } /** @override */ canDecorate() { 'use strict'; return false; } /** @override */ createDom() { 'use strict'; // Debug-only, so we don't need i18n. this.clearButtonElem_ = goog.dom.createDom( goog.dom.TagName.BUTTON, /* attributes */ null, 'Clear'); this.updateButtonElem_ = goog.dom.createDom( goog.dom.TagName.BUTTON, /* attributes */ null, 'Update'); var value = this.cookieKey_ && goog.net.Cookies.getInstance().get(this.cookieKey_); this.textAreaElem_ = goog.dom.createDom( goog.dom.TagName.TEXTAREA, /* attibutes */ null, value || ''); this.valueWarningElem_ = goog.dom.createDom( goog.dom.TagName.SPAN, /* attibutes */ {'style': 'display:none;color:red'}, 'Invalid cookie value.'); this.setElementInternal(goog.dom.createDom( goog.dom.TagName.DIV, /* attibutes */ null, this.valueWarningElem_, goog.dom.createDom(goog.dom.TagName.BR), this.textAreaElem_, goog.dom.createDom(goog.dom.TagName.BR), this.clearButtonElem_, this.updateButtonElem_)); } /** @override */ enterDocument() { 'use strict'; super.enterDocument(); this.getHandler().listen( this.clearButtonElem_, goog.events.EventType.CLICK, this.handleClear_); this.getHandler().listen( this.updateButtonElem_, goog.events.EventType.CLICK, this.handleUpdate_); } /** * Handles user clicking clear button. * @param {!goog.events.Event} e The click event. * @private */ handleClear_(e) { 'use strict'; if (this.cookieKey_) { goog.net.Cookies.getInstance().remove(this.cookieKey_); } this.textAreaElem_.value = ''; } /** * Handles user clicking update button. * @param {!goog.events.Event} e The click event. * @private */ handleUpdate_(e) { 'use strict'; if (this.cookieKey_) { var value = this.textAreaElem_.value; if (value) { // Strip line breaks. value = goog.string.stripNewlines(value); } if (goog.net.Cookies.getInstance().isValidValue(value)) { goog.net.Cookies.getInstance().set(this.cookieKey_, value); goog.style.setElementShown(this.valueWarningElem_, false); } else { goog.style.setElementShown(this.valueWarningElem_, true); } } } /** @override */ disposeInternal() { 'use strict'; this.clearButtonElem_ = null; this.cookieKey_ = null; this.textAreaElem_ = null; this.updateButtonElem_ = null; this.valueWarningElem_ = null; } }; /** * Cookie key. * @type {?string} * @private */ goog.ui.CookieEditor.prototype.cookieKey_; /** * Text area. * @type {HTMLTextAreaElement} * @private */ goog.ui.CookieEditor.prototype.textAreaElem_; /** * Clear button. * @type {HTMLButtonElement} * @private */ goog.ui.CookieEditor.prototype.clearButtonElem_; /** * Invalid value warning text. * @type {HTMLSpanElement} * @private */ goog.ui.CookieEditor.prototype.valueWarningElem_; /** * Update button. * @type {HTMLButtonElement} * @private */ goog.ui.CookieEditor.prototype.updateButtonElem_; // TODO(user): add combobox for user to select different cookies
Java
/* * Forge SDK * * The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. * * OpenAPI spec version: 0.1.0 * Contact: forge.help@autodesk.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Autodesk.Forge.Model { /// <summary> /// RelRefMeta /// </summary> [DataContract] public partial class RelRefMeta : IEquatable<RelRefMeta> { /// <summary> /// Gets or Sets RefType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum RefTypeEnum { /// <summary> /// Enum Derived for "derived" /// </summary> [EnumMember(Value = "derived")] Derived, /// <summary> /// Enum Dependencies for "dependencies" /// </summary> [EnumMember(Value = "dependencies")] Dependencies, /// <summary> /// Enum Auxiliary for "auxiliary" /// </summary> [EnumMember(Value = "auxiliary")] Auxiliary, /// <summary> /// Enum Xrefs for "xrefs" /// </summary> [EnumMember(Value = "xrefs")] Xrefs } /// <summary> /// describes the direction of the reference relative to the resource the refs are queried for /// </summary> /// <value>describes the direction of the reference relative to the resource the refs are queried for</value> [JsonConverter(typeof(StringEnumConverter))] public enum DirectionEnum { /// <summary> /// Enum From for "from" /// </summary> [EnumMember(Value = "from")] From, /// <summary> /// Enum To for "to" /// </summary> [EnumMember(Value = "to")] To } /// <summary> /// Gets or Sets FromType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum FromTypeEnum { /// <summary> /// Enum Folders for "folders" /// </summary> [EnumMember(Value = "folders")] Folders, /// <summary> /// Enum Items for "items" /// </summary> [EnumMember(Value = "items")] Items, /// <summary> /// Enum Versions for "versions" /// </summary> [EnumMember(Value = "versions")] Versions } /// <summary> /// Gets or Sets ToType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ToTypeEnum { /// <summary> /// Enum Folders for "folders" /// </summary> [EnumMember(Value = "folders")] Folders, /// <summary> /// Enum Items for "items" /// </summary> [EnumMember(Value = "items")] Items, /// <summary> /// Enum Versions for "versions" /// </summary> [EnumMember(Value = "versions")] Versions } /// <summary> /// Gets or Sets RefType /// </summary> [DataMember(Name="refType", EmitDefaultValue=false)] public RefTypeEnum? RefType { get; set; } /// <summary> /// describes the direction of the reference relative to the resource the refs are queried for /// </summary> /// <value>describes the direction of the reference relative to the resource the refs are queried for</value> [DataMember(Name="direction", EmitDefaultValue=false)] public DirectionEnum? Direction { get; set; } /// <summary> /// Gets or Sets FromType /// </summary> [DataMember(Name="fromType", EmitDefaultValue=false)] public FromTypeEnum? FromType { get; set; } /// <summary> /// Gets or Sets ToType /// </summary> [DataMember(Name="toType", EmitDefaultValue=false)] public ToTypeEnum? ToType { get; set; } /// <summary> /// Initializes a new instance of the <see cref="RelRefMeta" /> class. /// </summary> [JsonConstructorAttribute] protected RelRefMeta() { } /// <summary> /// Initializes a new instance of the <see cref="RelRefMeta" /> class. /// </summary> /// <param name="RefType">RefType (required).</param> /// <param name="Direction">describes the direction of the reference relative to the resource the refs are queried for (required).</param> /// <param name="FromId">FromId (required).</param> /// <param name="FromType">FromType (required).</param> /// <param name="ToId">ToId (required).</param> /// <param name="ToType">ToType (required).</param> /// <param name="Extension">Extension (required).</param> public RelRefMeta(RefTypeEnum? RefType = null, DirectionEnum? Direction = null, string FromId = null, FromTypeEnum? FromType = null, string ToId = null, ToTypeEnum? ToType = null, BaseAttributesExtensionObject Extension = null) { // to ensure "RefType" is required (not null) if (RefType == null) { throw new InvalidDataException("RefType is a required property for RelRefMeta and cannot be null"); } else { this.RefType = RefType; } // to ensure "Direction" is required (not null) if (Direction == null) { throw new InvalidDataException("Direction is a required property for RelRefMeta and cannot be null"); } else { this.Direction = Direction; } // to ensure "FromId" is required (not null) if (FromId == null) { throw new InvalidDataException("FromId is a required property for RelRefMeta and cannot be null"); } else { this.FromId = FromId; } // to ensure "FromType" is required (not null) if (FromType == null) { throw new InvalidDataException("FromType is a required property for RelRefMeta and cannot be null"); } else { this.FromType = FromType; } // to ensure "ToId" is required (not null) if (ToId == null) { throw new InvalidDataException("ToId is a required property for RelRefMeta and cannot be null"); } else { this.ToId = ToId; } // to ensure "ToType" is required (not null) if (ToType == null) { throw new InvalidDataException("ToType is a required property for RelRefMeta and cannot be null"); } else { this.ToType = ToType; } // to ensure "Extension" is required (not null) if (Extension == null) { throw new InvalidDataException("Extension is a required property for RelRefMeta and cannot be null"); } else { this.Extension = Extension; } } /// <summary> /// Gets or Sets FromId /// </summary> [DataMember(Name="fromId", EmitDefaultValue=false)] public string FromId { get; set; } /// <summary> /// Gets or Sets ToId /// </summary> [DataMember(Name="toId", EmitDefaultValue=false)] public string ToId { get; set; } /// <summary> /// Gets or Sets Extension /// </summary> [DataMember(Name="extension", EmitDefaultValue=false)] public BaseAttributesExtensionObject Extension { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RelRefMeta {\n"); sb.Append(" RefType: ").Append(RefType).Append("\n"); sb.Append(" Direction: ").Append(Direction).Append("\n"); sb.Append(" FromId: ").Append(FromId).Append("\n"); sb.Append(" FromType: ").Append(FromType).Append("\n"); sb.Append(" ToId: ").Append(ToId).Append("\n"); sb.Append(" ToType: ").Append(ToType).Append("\n"); sb.Append(" Extension: ").Append(Extension).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RelRefMeta); } /// <summary> /// Returns true if RelRefMeta instances are equal /// </summary> /// <param name="other">Instance of RelRefMeta to be compared</param> /// <returns>Boolean</returns> public bool Equals(RelRefMeta other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.RefType == other.RefType || this.RefType != null && this.RefType.Equals(other.RefType) ) && ( this.Direction == other.Direction || this.Direction != null && this.Direction.Equals(other.Direction) ) && ( this.FromId == other.FromId || this.FromId != null && this.FromId.Equals(other.FromId) ) && ( this.FromType == other.FromType || this.FromType != null && this.FromType.Equals(other.FromType) ) && ( this.ToId == other.ToId || this.ToId != null && this.ToId.Equals(other.ToId) ) && ( this.ToType == other.ToType || this.ToType != null && this.ToType.Equals(other.ToType) ) && ( this.Extension == other.Extension || this.Extension != null && this.Extension.Equals(other.Extension) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.RefType != null) hash = hash * 59 + this.RefType.GetHashCode(); if (this.Direction != null) hash = hash * 59 + this.Direction.GetHashCode(); if (this.FromId != null) hash = hash * 59 + this.FromId.GetHashCode(); if (this.FromType != null) hash = hash * 59 + this.FromType.GetHashCode(); if (this.ToId != null) hash = hash * 59 + this.ToId.GetHashCode(); if (this.ToType != null) hash = hash * 59 + this.ToType.GetHashCode(); if (this.Extension != null) hash = hash * 59 + this.Extension.GetHashCode(); return hash; } } } }
Java
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 db contains functions related to database. * db.go includes conneting to db, query and insertion. * dbschema.go contains definitions of struct for db tables. Currently it only contains Module struct. */ package db import ( "database/sql" "fmt" "os" "strconv" "github.com/golang/glog" // Go postgres driver for Go's database/sql package _ "github.com/lib/pq" ) // These are SQL stataments used in this package. // Query statements can be appended based on its query parameters. const ( // $4 and $5 should be assigned with the same value (the JSON data of module). insertModule = `INSERT INTO modules (orgName, name, version, data) VALUES($1, $2, $3, $4) on conflict (orgName, name, version) do update set data=$5` selectModules = `select * from modules` // We want to ensure that user has to provide all three inputs, // instead of deleting too many modules by mistake with some fields missing. deleteModule = `delete from modules where orgName = $1 and name = $2 and version = $3` selectFeatureBundles = `select * from featureBundles` // $4 and $5 should be assigned with the same value (the JSON data of feature-bundle). insertFeatureBundle = `INSERT INTO featureBundles (orgName, name, version, data) VALUES($1, $2, $3, $4) on conflict (orgName, name, version) do update set data=$5` deleteFeatureBundle = `delete from featurebundles where orgName = $1 and name = $2 and version = $3` ) // db is the global variable of connection to database. // It would be assigned value when *ConnectDB* function is called. // // We choose to use this global variable due to that *gqlgen* automatically generates many server side codes. // Resolver functions generated by *gqlgen* are handler functions for graphQL queries and are methods of *resolver* struct. // If we define a struct with field of db connection instead of using the global variable // and change *Query* functions to methods of that struct, // we need to initialize db connection while initializing *resolver* object in server codes // such that *resolver* functions can call these *Query* functions. // However, initialization function of *resolver* struct is automatically generated and overwritten every time. // Thus, we cannot initialize a db connection inside the *resolver* objects. // // Another option is to establish a new db connection for each *Query* function and close it after query finishes. // However, that would be too expensive to connect to db every time server receives a new query. var db *sql.DB // ConnectDB establishes connection to database, *db* variable is assigned when opening database. // This should only be called once before any other database function is called. // // Users need set environment variables for connection, including // * DB_HOST: host address of target db instances, by default: localhost. // * DB_PORT: port number of postgres db, by default: 5432. // * DB_USERNAME: username of database, error would be returned if not set. // * DB_PWD: password of target database, error would be returned if not set. // * DB_NAME: name of database for connection, error would be returned if not set. // * DB_SOCKER_DIR: directory of Unix socket in Cloud Run which serves as Cloud SQL // Auth proxy to connect to postgres database. // If service is deployed on Cloud Run, just use the default value. // By default, it is set to `/cloudsql`. func ConnectDB() error { // read db config from env // port number of target database port := 5432 if portStr, ok := os.LookupEnv("DB_PORT"); !ok { glog.Infof("DB_PORT not set, setting port to %d", port) } else { var err error if port, err = strconv.Atoi(portStr); err != nil { return fmt.Errorf("DB_PORT in incorrect format: %v", err) } } // username of target database user, ok := os.LookupEnv("DB_USERNAME") if !ok { return fmt.Errorf("DB_USERNAME not set") } // password of target database password, ok := os.LookupEnv("DB_PWD") if !ok { return fmt.Errorf("DB_PWD not set") } // name of target database dbname, ok := os.LookupEnv("DB_NAME") if !ok { return fmt.Errorf("DB_NAME not set") } // (Cloud Run only) Directory of Unix socket socketDir, ok := os.LookupEnv("DB_SOCKET_DIR") if !ok { socketDir = "/cloudsql" } var psqlconn string // connection string used to connect to traget database // host address of target database host, ok := os.LookupEnv("DB_HOST") switch { case !ok: glog.Infoln("DB_HOST not set, setting host to localhost") host = "localhost" fallthrough case host == "localhost": // This connection string is used if service is not deployed on Cloud Run, // instead connection is made from localhost via Cloud SQL proxy. psqlconn = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname) default: psqlconn = fmt.Sprintf("host=%s/%s port=%d user=%s password=%s dbname=%s", socketDir, host, port, user, password, dbname) } // open database var err error db, err = sql.Open("postgres", psqlconn) if err != nil { return fmt.Errorf("open database failed: %v", err) } // see if connection is established successfully if err := db.Ping(); err != nil { return fmt.Errorf("ping database failed: %v", err) } return nil } // Close function closes db connection func Close() error { return db.Close() } // InsertModule inserts module into database given values of four field of MODULE schema. // Or if there is existing module with existing key (orgName, name, version), update data field. // Error is returned when insertion failed. func InsertModule(orgName string, name string, version string, data string) error { if _, err := db.Exec(insertModule, orgName, name, version, data, data); err != nil { return fmt.Errorf("insert/update module into db failed: %v", err) } return nil } // ReadModulesByRow scans from queried modules from rows one by one, rows are closed inside. // Return slice of db Module struct each field of which corresponds to one column in db. // Error is returned when scan rows failed. func ReadModulesByRow(rows *sql.Rows) ([]Module, error) { var modules []Module defer rows.Close() for rows.Next() { var module Module if err := rows.Scan(&module.OrgName, &module.Name, &module.Version, &module.Data); err != nil { return nil, fmt.Errorf("scan db rows failure, %v", err) } modules = append(modules, module) } return modules, nil } // FormatQueryStr is used to generate query statement string based on query parameters. // * parmNames is a list of names of all non-nil query parameters. // * baseQuery is query statement without any query parameters. func FormatQueryStr(parmNames []string, baseQuery string) string { queryStmt := baseQuery for i := 0; i < len(parmNames); i++ { if i == 0 { queryStmt += " where" } else { queryStmt += " and" } queryStmt += fmt.Sprintf(" %s=$%d", parmNames[i], i+1) } return queryStmt } // QueryModulesByOrgName queries modules of organization with *orgName* from database. // If orgName is null then directly query all modules. // Return slice of db Module struct each field of which corresponds to one column in db. // Error is returned when query or reading data failed. func QueryModulesByOrgName(orgName *string) ([]Module, error) { var parms []interface{} // parms is used to store value of non-nil query parameters parmNames := []string{} // parmNames is used to store name of non-nil query parameters if orgName != nil { parms = append(parms, *orgName) parmNames = append(parmNames, "orgName") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectModules) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryModulesByOrgName failed: %v", err) } defer rows.Close() return ReadModulesByRow(rows) } // QueryModulesByKey queries modules by its key (name, version), it is possible that parameters are null. // If both parameters are null, this equals query for all modules. // Return slice of db Module struct each field of which corresponds to one column in db. // Error is returned when query or reading data failed. func QueryModulesByKey(name *string, version *string) ([]Module, error) { var parms []interface{} // parms is used to store value of non-nil query parameters parmNames := []string{} // parmNames is used to store name of non-nil query parameters if name != nil { parms = append(parms, *name) parmNames = append(parmNames, "name") } if version != nil { parms = append(parms, *version) parmNames = append(parmNames, "version") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectModules) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryModulesByOrgName failed: %v", err) } defer rows.Close() return ReadModulesByRow(rows) } // DeleteModule takes three string, orgName, name, version, // whose combination is key of one Module in DB's Module table. // If deletion fails, an non-nil error is returned. // If the number of rows affected by this deletion is not 1, an error is also returned. func DeleteModule(orgName string, name string, version string) error { result, err := db.Exec(deleteModule, orgName, name, version) if err != nil { return fmt.Errorf("DeleteModule failed: %v", err) } num, err := result.RowsAffected() if err != nil { return fmt.Errorf("DeleteModule, access rows affected in result failed: %v", err) } // delete should only affect one row if num != 1 { return fmt.Errorf("DeleteModule: affected row is not one, it affects %d rows", num) } return nil } // ReadFeatureBundlesByRow scans from queried FeatureBundles from rows one by one, rows are closed inside. // Return slice of db FeatureBundle struct each field of which corresponds to one column in db. // Error is returned when scan rows failed. func ReadFeatureBundlesByRow(rows *sql.Rows) ([]FeatureBundle, error) { var featureBundles []FeatureBundle defer rows.Close() for rows.Next() { var featureBundle FeatureBundle if err := rows.Scan(&featureBundle.OrgName, &featureBundle.Name, &featureBundle.Version, &featureBundle.Data); err != nil { return nil, fmt.Errorf("ReadFeatureBundlesByRow: scan db rows failure, %v", err) } featureBundles = append(featureBundles, featureBundle) } return featureBundles, nil } // QueryFeatureBundlesByOrgName queries feature-bundles of organization with *orgName* from database. // If orgName is null then directly query all feature-bundles. // Return slice of db FeatureBundle struct each field of which corresponds to one column in db. // Error is returned when query or reading data failed. func QueryFeatureBundlesByOrgName(orgName *string) ([]FeatureBundle, error) { var parms []interface{} // parms is used to store value of non-nil query parameters parmNames := []string{} // parmNames is used to store name of non-nil query parameters if orgName != nil { parms = append(parms, *orgName) parmNames = append(parmNames, "orgName") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectFeatureBundles) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryFeatureBundlesByOrgName failed: %v", err) } return ReadFeatureBundlesByRow(rows) } // InsertFeatureBundle inserts FeatureBundle into database given values of four field of FeatureBundle schema. // Or if there is existing FeatureBundle with existing key (orgName, name, version), update data field. // Error is returned when insertion failed. func InsertFeatureBundle(orgName string, name string, version string, data string) error { if _, err := db.Exec(insertFeatureBundle, orgName, name, version, data, data); err != nil { return fmt.Errorf("insert/update FeatureBundle into db failed: %v", err) } return nil } // DeleteFeatureBundle takes three pointer of string, orgName, name, version, // whose combination is key of one FeatureBundle in DB's FeatureBundle table. // If deletion fails, an non-nil error is returned. // If the number of rows affected by this deletion is not 1, an error is also returned. func DeleteFeatureBundle(orgName string, name string, version string) error { result, err := db.Exec(deleteFeatureBundle, orgName, name, version) if err != nil { return fmt.Errorf("DeleteFeatureBundle failed: %v", err) } num, err := result.RowsAffected() if err != nil { return fmt.Errorf("DeleteFeatureBundle, access rows affected in result failed: %v", err) } // delete should only affect one row if num != 1 { return fmt.Errorf("DeleteFeatureBundle: affected row is not one, it affects %d rows", num) } return nil } // QueryFeatureBundlesByKey queries feature-bundles by its key (name, version), it is possible that // If both parameters are null, this equals query for all feature-bundles. // Return slice of db FeatureBundle struct each field of which corresponds to one column in // Error is returned when query or reading data failed. func QueryFeatureBundlesByKey(name *string, version *string) ([]FeatureBundle, error) { var parms []interface{} // parms is used to store value of non-nil query paramete parmNames := []string{} // parmNames is used to store name of non-nil query param if name != nil { parms = append(parms, *name) parmNames = append(parmNames, "name") } if version != nil { parms = append(parms, *version) parmNames = append(parmNames, "version") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectFeatureBundles) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryFeatureBundlesByKey failed: %v", err) } return ReadFeatureBundlesByRow(rows) }
Java
#!/usr/bin/env perl use warnings; use strict; use POSIX; # convert a set of numbers to a distribution my $bin = shift @ARGV; my $col = shift @ARGV; $bin or die "usage: $0 <bin size> <column number (0 based)> <table (on STDIN)>\n"; my $delim = "\t"; my $n=0; my $sum=0; my $min=1000000000; my $max = -999999999; my %dist; while (<>) { chomp; my @x = split /$delim/, $_; my $val = $x[$col]; is_numeric($val) or next; $sum += $val; $min = $val if ($val < $min); $max = $val if ($val > $max); my $obin = int($val/$bin); $dist{$obin}++; $n++; } my $nover2=$n/2; my $half_ass = $sum/2; my $mean = int(1000*$sum/$n+0.5)/1000; my $sum2=0; my $minbin = $bin*floor($min/$bin); my %cumdist; while (my($obin,$tally) = each %dist) { $sum2 += $tally*($obin*$bin-$mean)**2 } my $stdev = int(1000*sqrt($sum2/$n)+0.5)/1000; my $N50_sum=0; my $N50=0; my ($mode_height,$mode_bin)=(0,0); my $median_bin=0; my $iter=0; my $previ; my @bins = sort {$a <=> $b} keys %dist; for my $i (@bins) { $iter++; if ($N50_sum < $half_ass) { $N50 = $minbin+$i*$bin + floor($bin/2); $N50_sum += $dist{$i}*$N50; } $cumdist{$i} = $dist{$i}; if ($iter>1) { $cumdist{$i} += $cumdist{$previ}; } if ($cumdist{$i} < $nover2) { $median_bin = $i; } if($dist{$i} > $mode_height) { $mode_height = $dist{$i}; $mode_bin = $i; } $previ=$i; } my $mode = $mode_bin*$bin; my $median = $median_bin*$bin; #print "# ", join ("\t",qw(N mean stdev median mode min max N50(bin))),"\n"; #print "# ", join ("\t",($n,$mean,$stdev,$median, $mode,$min,$max,$N50)),"\n"; print qq{# N\t$n # mean\t$mean # stdev\t$stdev # median\t$median # mode\t$mode # min\t$min # max\t$max # N50\t$N50 }; print "\n#", join ("\t",qw(bin raw_dist norm_dist cumulative_dist)),"\n"; for my $i (@bins) { print join ("\t",$i*$bin,$dist{$i},int(1000*$dist{$i}/$n)/1000,int(1000*$cumdist{$i}/$n)/1000),"\n"; } sub getnum { my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') || ($unparsed != 0) || $!) { return undef; } else { return $num; } } sub is_numeric { defined getnum($_[0]) }
Java
/* Copyright 2014 Cloudbase Solutions Srl Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Tcp.h" #include "Ethernet.h" #include "Ipv4.h" #include "Ipv6.h" #include "Frame.h" #include "PacketInfo.h" #include "OvsNetBuffer.h" #include "Checksum.h" OVS_TCP_HEADER* GetTcpHeader(VOID* pPacketBuffer) { OVS_ETHERNET_HEADER* pEthHeader = (OVS_ETHERNET_HEADER*)pPacketBuffer; OVS_TCP_HEADER* pTcpHeader = NULL; if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_QTAG)) { pEthHeader = (OVS_ETHERNET_HEADER*)((BYTE*)pEthHeader + OVS_ETHERNET_VLAN_LEN); } if (pEthHeader->type != RtlUshortByteSwap(OVS_ETHERTYPE_IPV4) && pEthHeader->type != RtlUshortByteSwap(OVS_ETHERTYPE_IPV6)) { return NULL; } if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_IPV4)) { const OVS_IPV4_HEADER* pIpv4Header = ReadIpv4Header(pEthHeader); if (pIpv4Header->Protocol != OVS_IPPROTO_TCP) { return NULL; } pTcpHeader = (OVS_TCP_HEADER*)AdvanceIpv4Header(pIpv4Header); return pTcpHeader; } if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_IPV6)) { OVS_IPV6_HEADER* pIpv6Header = ReadIpv6Header(pEthHeader); BYTE nextHeader = pIpv6Header->nextHeader; VOID* advancedBuffer = AdvanceIpv6Header(pIpv6Header); BYTE headerLength = 0; while (IsIpv6Extension(nextHeader)) { nextHeader = *((BYTE*)advancedBuffer); headerLength = *(sizeof(nextHeader) + (BYTE*)advancedBuffer); advancedBuffer = ((BYTE*)advancedBuffer) + headerLength + 8; } if (nextHeader != OVS_IPV6_EXTH_TCP) { return NULL; } pTcpHeader = (OVS_TCP_HEADER*)advancedBuffer; return pTcpHeader; } return NULL; } BOOLEAN ONB_SetTcp(OVS_NET_BUFFER* pOvsNb, const OVS_PI_TCP* pTcpPI) { OVS_TCP_HEADER *pTcpHeader = NULL; OVS_IPV4_HEADER* pIpv4Header = NULL; VOID* buffer = NULL; UINT16 csumRecomp = 0; UINT16 offset = 0, reserved = 0, flags = 0; buffer = ONB_GetData(pOvsNb); pIpv4Header = GetIpv4Header(buffer); pTcpHeader = GetTcpHeader(buffer); if (pTcpPI->source != pTcpHeader->sourcePort) { DEBUGP_FRAMES(LOG_INFO, "src port (BE): 0x%x -> 0x%x\n", pTcpHeader->sourcePort, pTcpPI->source); DEBUGP_FRAMES(LOG_INFO, "dst port (BE): 0x%x\n", pTcpHeader->destinationPort); csumRecomp = (WORD)RecomputeChecksum((BYTE*)&pTcpHeader->sourcePort, (BYTE*)&pTcpPI->source, 2, pTcpHeader->checksum); csumRecomp = RtlUshortByteSwap(csumRecomp); pTcpHeader->checksum = csumRecomp; pTcpHeader->sourcePort = pTcpPI->source; } if (pTcpPI->destination != pTcpHeader->destinationPort) { DEBUGP_FRAMES(LOG_INFO, "src port (BE): 0x%x\n", pTcpHeader->sourcePort); DEBUGP_FRAMES(LOG_INFO, "dst port (BE): 0x%x -> 0x%x\n", pTcpHeader->destinationPort, pTcpPI->destination); csumRecomp = (WORD)RecomputeChecksum((BYTE*)&pTcpHeader->destinationPort, (BYTE*)&pTcpPI->destination, 2, pTcpHeader->checksum); csumRecomp = RtlUshortByteSwap(csumRecomp); pTcpHeader->checksum = csumRecomp; pTcpHeader->destinationPort = pTcpPI->destination; } offset = GetTcpDataOffset(pTcpHeader->flagsAndOffset); reserved = GetTcpReserved(pTcpHeader->flagsAndOffset); flags = GetTcpFlags(pTcpHeader->flagsAndOffset); DEBUGP_FRAMES(LOG_INFO, "seq number: 0x%x; ack number: 0x%x; offset: 0x%x; reserved: 0x%x; flags: 0x%x\n", pTcpHeader->sequenceNo, pTcpHeader->acknowledgeNo, offset, reserved, flags); return TRUE; } _Use_decl_annotations_ void DbgPrintTcpHeader(const VOID* buffer) { OVS_TCP_HEADER* pTcpHeader = (OVS_TCP_HEADER*)buffer; UNREFERENCED_PARAMETER(pTcpHeader); DEBUGP_FRAMES(LOG_INFO, "tcp: src port = %d; dest port = %d\n", RtlUshortByteSwap(pTcpHeader->sourcePort), RtlUshortByteSwap(pTcpHeader->destinationPort)); } BOOLEAN VerifyTcpHeader(BYTE* buffer, ULONG* pLength) { OVS_TCP_HEADER* pTcpHeader = (OVS_TCP_HEADER*)buffer; //TODO: verify. ATM nothing is done UNREFERENCED_PARAMETER(buffer); UNREFERENCED_PARAMETER(pLength); UNREFERENCED_PARAMETER(pTcpHeader); return TRUE; }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Wed Sep 03 20:01:19 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>AuthenticationProtos.WhoAmIRequestOrBuilder (HBase 0.98.6-hadoop2 API)</title> <meta name="date" content="2014-09-03"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AuthenticationProtos.WhoAmIRequestOrBuilder (HBase 0.98.6-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AuthenticationProtos.WhoAmIRequestOrBuilder.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">Frames</a></li> <li><a href="AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.hadoop.hbase.protobuf.generated</div> <h2 title="Interface AuthenticationProtos.WhoAmIRequestOrBuilder" class="title">Interface AuthenticationProtos.WhoAmIRequestOrBuilder</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Superinterfaces:</dt> <dd>com.google.protobuf.MessageLiteOrBuilder, com.google.protobuf.MessageOrBuilder</dd> </dl> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AuthenticationProtos.WhoAmIRequest</a>, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AuthenticationProtos.WhoAmIRequest.Builder</a></dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AuthenticationProtos</a></dd> </dl> <hr> <br> <pre>public static interface <span class="strong">AuthenticationProtos.WhoAmIRequestOrBuilder</span> extends com.google.protobuf.MessageOrBuilder</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageOrBuilder"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.google.protobuf.MessageOrBuilder</h3> <code>findInitializationErrors, getAllFields, getDefaultInstanceForType, getDescriptorForType, getField, getInitializationErrorString, getRepeatedField, getRepeatedFieldCount, getUnknownFields, hasField</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageLiteOrBuilder"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.google.protobuf.MessageLiteOrBuilder</h3> <code>isInitialized</code></li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AuthenticationProtos.WhoAmIRequestOrBuilder.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">Frames</a></li> <li><a href="AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
Java
// LUCENENET specific - excluding this class in favor of DirectoryNotFoundException, // although that means we need to catch DirectoryNotFoundException everywhere that // FileNotFoundException is being caught (because it is a superclass) to be sure we have the same behavior. //using System; //using System.IO; //namespace YAF.Lucene.Net.Store //{ // /* // * 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. // */ // /// <summary> // /// This exception is thrown when you try to list a // /// non-existent directory. // /// </summary> // // LUCENENET: It is no longer good practice to use binary serialization. // // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 //#if FEATURE_SERIALIZABLE_EXCEPTIONS // [Serializable] //#endif // public class NoSuchDirectoryException : FileNotFoundException // { // public NoSuchDirectoryException(string message) // : base(message) // { // } // } //}
Java
# Caperonia hystrix Pax & K.Hoffm. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.kie.workbench.common.screens.library.client.screens.assets; import elemental2.dom.HTMLElement; import org.guvnor.common.services.project.model.WorkspaceProject; import org.jboss.errai.ui.client.local.spi.TranslationService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.screens.library.api.LibraryService; import org.kie.workbench.common.screens.library.client.util.LibraryPlaces; import org.kie.workbench.common.services.shared.project.KieModule; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.uberfire.ext.widgets.common.client.common.BusyIndicatorView; import org.uberfire.mocks.CallerMock; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class AssetsScreenTest { private AssetsScreen assetsScreen; @Mock private AssetsScreen.View view; @Mock private LibraryPlaces libraryPlaces; @Mock private EmptyAssetsScreen emptyAssetsScreen; @Mock private PopulatedAssetsScreen populatedAssetsScreen; @Mock private InvalidProjectScreen invalidProjectScreen; @Mock private TranslationService ts; @Mock private BusyIndicatorView busyIndicatorView; @Mock private LibraryService libraryService; private WorkspaceProject workspaceProject; @Before public void setUp() { workspaceProject = mock(WorkspaceProject.class); doReturn(mock(KieModule.class)).when(workspaceProject).getMainModule(); when(libraryPlaces.getActiveWorkspaceContext()).thenReturn(workspaceProject); EmptyAssetsView emptyView = mock(EmptyAssetsView.class); PopulatedAssetsView populatedView = mock(PopulatedAssetsView.class); InvalidProjectView invalidProjectView = mock(InvalidProjectView.class); HTMLElement emptyElement = mock(HTMLElement.class); HTMLElement populatedElement = mock(HTMLElement.class); HTMLElement invalidProjectElement = mock(HTMLElement.class); when(emptyAssetsScreen.getView()).thenReturn(emptyView); when(emptyView.getElement()).thenReturn(emptyElement); when(populatedAssetsScreen.getView()).thenReturn(populatedView); when(populatedView.getElement()).thenReturn(populatedElement); when(invalidProjectScreen.getView()).thenReturn(invalidProjectView); when(invalidProjectView.getElement()).thenReturn(invalidProjectElement); this.assetsScreen = new AssetsScreen(view, libraryPlaces, emptyAssetsScreen, populatedAssetsScreen, invalidProjectScreen, ts, busyIndicatorView, new CallerMock<>(libraryService)); } @Test public void testShowEmptyScreenAssets() { when(libraryService.hasAssets(any(WorkspaceProject.class))).thenReturn(false); this.assetsScreen.init(); verify(emptyAssetsScreen, times(1)).getView(); verify(populatedAssetsScreen, never()).getView(); verify(view).setContent(emptyAssetsScreen.getView().getElement()); } @Test public void testShowPopulatedScreenAssets() { when(libraryService.hasAssets(any(WorkspaceProject.class))).thenReturn(true); this.assetsScreen.init(); verify(emptyAssetsScreen, never()).getView(); verify(populatedAssetsScreen, times(1)).getView(); verify(view).setContent(populatedAssetsScreen.getView().getElement()); } @Test public void testSetContentNotCalledWhenAlreadyDisplayed() throws Exception { try { testShowEmptyScreenAssets(); } catch (AssertionError ae) { throw new AssertionError("Precondition failed. Could not set empty asset screen.", ae); } HTMLElement emptyElement = emptyAssetsScreen.getView().getElement(); emptyElement.parentNode = mock(HTMLElement.class); reset(view); assetsScreen.init(); verify(view, never()).setContent(any()); } @Test public void testInvalidProject() throws Exception { reset(workspaceProject); doReturn(null).when(workspaceProject).getMainModule(); assetsScreen.init(); verify(view).setContent(invalidProjectScreen.getView().getElement()); verify(libraryService, never()).hasAssets(any(WorkspaceProject.class)); } }
Java
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { public partial class ExtractMethodTests : ExtractMethodBase { [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod2() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 10; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod3() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|int i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; NewMethod(i); } private static void NewMethod(int i) { int i2 = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod4() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 += i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; i2 = NewMethod(i); } private static int NewMethod(int i, int i2) { i2 += i; return i2; } }"; // compoundaction not supported yet. await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod5() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; NewMethod(i); } private static void NewMethod(int i) { int i2 = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod6() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; [|field = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; NewMethod(i); } private void NewMethod(int i) { field = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod7() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string[] a = null; NewMethod(a); } private void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod8() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string[] a = null; NewMethod(a); } private static void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod9() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; string s; [|i = 10; s = args[0] + i.ToString();|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(args); } private static void NewMethod(string[] args) { int i; string s; i = 10; s = args[0] + i.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod10() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10; string s; s = args[0] + i.ToString();|] Console.WriteLine(s); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string s = NewMethod(args); Console.WriteLine(s); } private static string NewMethod(string[] args) { int i = 10; string s; s = args[0] + i.ToString(); return s; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] i = 10; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; NewMethod(); i = 10; } private static void NewMethod() { int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11_1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod12() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|i = i + 1;|] Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { i = i + 1; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ControlVariableInForeachStatement() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { [|Console.WriteLine(s);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { NewMethod(s); } } private static void NewMethod(string s) { Console.WriteLine(s); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod14() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for(var i = 1; i < 10; i++) { [|Console.WriteLine(i);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for (var i = 1; i < 10; i++) { NewMethod(i); } } private static void NewMethod(int i) { Console.WriteLine(i); } }"; // var in for loop doesn't get bound yet await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod15() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int s = 10, i = 1; int b = s + i;|] System.Console.WriteLine(s); System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int s, i; NewMethod(out s, out i); System.Console.WriteLine(s); System.Console.WriteLine(i); } private static void NewMethod(out int s, out int i) { s = 10; i = 1; int b = s + i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod16() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 1;|] System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = NewMethod(); System.Console.WriteLine(i); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod17() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1; Test(out t1); t = t1;|] System.Console.WriteLine(t1.ToString()); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { Test(out t1); t = t1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod18() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1 = GetValue(out t);|] System.Console.WriteLine(t1.ToString()); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { t1 = GetValue(out t); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod19() { var code = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { NewMethod(); } private static void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod20() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { NewMethod(); } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542677")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod21() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { [|int i = 1;|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { NewMethod(); } } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod22() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; NewMethod(i); i = 6; Console.WriteLine(i); } private static void NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod23() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) [|Console.WriteLine(args[0].ToString());|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) NewMethod(args); } private static void NewMethod(string[] args) { Console.WriteLine(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod24() { var code = @"using System; class Program { static void Main(string[] args) { int y = [|int.Parse(args[0].ToString())|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int y = GetY(args); } private static int GetY(string[] args) { return int.Parse(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod25() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (([|new int[] { 1, 2, 3 }|]).Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ((NewMethod()).Any()) { return; } } private static int[] NewMethod() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod26() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ([|(new int[] { 1, 2, 3 })|].Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (NewMethod().Any()) { return; } } private static int[] NewMethod() { return (new int[] { 1, 2, 3 }); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod27() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; NewMethod(i); i = 6; Console.WriteLine(i); } private static void NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod28() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { [|return 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { return NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod29() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; [|if (i < 0) { return 1; } else { return 0; }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; return NewMethod(i); } private static int NewMethod(int i) { if (i < 0) { return 1; } else { return 0; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod30() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { [|i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod31() { var code = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); [|builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn"");|] return builder.ToString(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); NewMethod(builder); return builder.ToString(); } private static void NewMethod(StringBuilder builder) { builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod32() { var code = @"using System; class Program { void Test() { int v = 0; Console.Write([|v|]); } }"; var expected = @"using System; class Program { void Test() { int v = 0; Console.Write(GetV(v)); } private static int GetV(int v) { return v; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(3792, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod33() { var code = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write([|v++|]); } } }"; var expected = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write(NewMethod(ref v)); } } private static int NewMethod(ref int v) { return v++; } }"; // this bug has two issues. one is "v" being not in the dataFlowIn and ReadInside collection (hence no method parameter) // and the other is binding not working for "v++" (hence object as return type) await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod34() { var code = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = [|x + y|]; } } "; var expected = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = GetZ(x, y); } private static int GetZ(int x, int y) { return x + y; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538239")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod35() { var code = @"using System; class Program { static void Main(string[] args) { int[] r = [|new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int[] r = GetR(); } private static int[] GetR() { return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod36() { var code = @"using System; class Program { static void Main(ref int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(ref int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod37() { var code = @"using System; class Program { static void Main(out int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(out int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod38() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); [|unassigned = unassigned + 10;|] // read // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); NewMethod(unassigned); // read // int newVar = unassigned; // write // unassigned = 0; } private static void NewMethod(int unassigned) { unassigned = unassigned + 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod39() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract [|// unassigned = ReturnVal(0); unassigned = unassigned + 10; // read|] // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract NewMethod(unassigned); // int newVar = unassigned; // write // unassigned = 0; } private static void NewMethod(int unassigned) { // unassigned = ReturnVal(0); unassigned = unassigned + 10; // read } }"; // current bottom-up re-writer makes re-attaching trivia half belongs to previous token // and half belongs to next token very hard. // for now, it won't be able to re-associate trivia belongs to next token. await TestExtractMethodAsync(code, expected); } [WorkItem(538303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538303")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod40() { var code = @"class Program { static void Main(string[] args) { [|int x;|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(868414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868414")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithLeadingTrivia() { // ensure that the extraction doesn't result in trivia moving up a line: // // a //b // NewMethod(); await TestExtractMethodAsync( @"class C { void M() { // a // b [|System.Console.WriteLine();|] } }", @"class C { void M() { // a // b NewMethod(); } private static void NewMethod() { System.Console.WriteLine(); } }"); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause() { var code = @"class Program { static void Main(string[] args) { var z = from [|T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause_1() { var code = @"class Program { static void Main(string[] args) { var z = from [|W.T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(538314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538314")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod41() { var code = @"class Program { static void Main(string[] args) { int x = 10; [|int y; if (x == 10) y = 5;|] Console.WriteLine(y); } }"; var expected = @"class Program { static void Main(string[] args) { int x = 10; int y = NewMethod(x); Console.WriteLine(y); } private static int NewMethod(int x) { int y; if (x == 10) y = 5; return y; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod42() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod43() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538328")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod44() { var code = @"using System; class Program { static void Main(string[] args) { int a; //modified in [|a = 1;|] /*data flow out*/ Console.Write(a); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a; //modified in a = NewMethod(); /*data flow out*/ Console.Write(a); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod45() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/[|;|]/**/ } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/ NewMethod();/**/ } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod46() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|Goo(ref x);|] Console.WriteLine(x); } static void Goo(ref int x) { x = x + 1; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; x = NewMethod(x); Console.WriteLine(x); } private static int NewMethod(int x) { Goo(ref x); return x; } static void Goo(ref int x) { x = x + 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538399")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod47() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (true) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (true) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538401")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod48() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = [|{ 1, 2, 3 }|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = GetX(); } private static int[] GetX() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538405")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod49() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = GetX1(); } private static int GetX1() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNormalProperty() { var code = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = [|Class.Names|]; } }"; var expected = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = GetStr(); } private static string GetStr() { return Class.Names; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodAutoProperty() { var code = @" class Class { public string Name { get; set; } static void Main() { string str = new Class().[|Name|]; } }"; // given span is not an expression // selection validator should take care of this case var expected = @" class Class { public string Name { get; set; } static void Main() { string str = GetStr(); } private static string GetStr() { return new Class().Name; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538402")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3994() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = GetX(); } private static byte GetX() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538404")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3996() { var code = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = [|Goo()|]; } } }"; var expected = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = GetX(); } private static B GetX() { return Goo(); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InsertionPoint() { var code = @"class Test { void Method(string i) { int y2 = [|1|]; } void Method(int i) { } }"; var expected = @"class Test { void Method(string i) { int y2 = GetY2(); } private static int GetY2() { return 1; } void Method(int i) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757() { var code = @"class GenericMethod { void Method<T>(T t) { T a; [|a = t;|] } }"; var expected = @"class GenericMethod { void Method<T>(T t) { NewMethod(t); } private static void NewMethod<T>(T t) { T a = t; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_2() { var code = @"class GenericMethod<T1> { void Method<T>(T t) { T a; T1 b; [|a = t; b = default(T1);|] } }"; var expected = @"class GenericMethod<T1> { void Method<T>(T t) { NewMethod(t); } private static void NewMethod<T>(T t) { T a; T1 b; a = t; b = default(T1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_3() { var code = @"class GenericMethod { void Method<T, T1>(T t) { T1 a1; T a; [|a = t; a1 = default(T);|] } }"; var expected = @"class GenericMethod { void Method<T, T1>(T t) { NewMethod<T, T1>(t); } private static void NewMethod<T, T1>(T t) { T1 a1; T a; a = t; a1 = default(T); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758() { var code = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758_2() { var code = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4761() { var code = @"using System; class A { void Method() { System.Func<int, int> a = x => [|x * x|]; } }"; var expected = @"using System; class A { void Method() { System.Func<int, int> a = x => NewMethod(x); } private static int NewMethod(int x) { return x * x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779() { var code = @"using System; class Program { static void Main() { string s = ""; Func<string> f = [|s|].ToString; } } "; var expected = @"using System; class Program { static void Main() { string s = ""; Func<string> f = GetS(s).ToString; } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779_2() { var code = @"using System; class Program { static void Main() { string s = ""; var f = [|s|].ToString(); } } "; var expected = @"using System; class Program { static void Main() { string s = ""; var f = GetS(s).ToString(); } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)[|s.ToString|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)GetToString(s); } private static Func<string> GetToString(string s) { return s.ToString; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780_2() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (string)[|s.ToString()|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (string)NewMethod(s); } private static string NewMethod(string s) { return s.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = [|default(T)|]; } } }"; var expected = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = GetT<T>(); } private static T GetT<T>() { return default(T); } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782_2() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo() { D.B x = [|new D.B()|]; } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(4791, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4791() { var code = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => [|a|]; } }"; var expected = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => GetA(a); } private static int GetA(int a) { return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539019")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4809() { var code = @"class Program { public Program() { [|int x = 2;|] } }"; var expected = @"class Program { public Program() { NewMethod(); } private static void NewMethod() { int x = 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4813() { var code = @"using System; class Program { public Program() { object o = [|new Program()|]; } }"; var expected = @"using System; class Program { public Program() { object o = GetO(); } private static Program GetO() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538425")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4031() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else [|while (z) { }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else NewMethod(z); } private static void NewMethod(bool z) { while (z) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(527499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527499")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3992() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (false) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (false) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4823() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } }"; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538985")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4762() { var code = @"class Program { static void Main(string[] args) { //comments [|int x = 2;|] } } "; var expected = @"class Program { static void Main(string[] args) { //comments NewMethod(); } private static void NewMethod() { int x = 2; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538966")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4744() { var code = @"class Program { static void Main(string[] args) { [|int x = 2; //comments|] } } "; var expected = @"class Program { static void Main(string[] args) { NewMethod(); } private static void NewMethod() { int x = 2; //comments } } "; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoNo() { var code = @"using System; class Program { void Test1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test1() { int i; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoYes() { var code = @"using System; class Program { void Test2() { int i = 0; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test2() { int i = 0; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesNo() { var code = @"using System; class Program { void Test3() { int i; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test3() { int i; while (i > 10) ; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesYes() { var code = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test4_1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_1() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test4_2() { int i = 10; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_2() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoNo() { var code = @"using System; class Program { void Test5() { [| int i; |] } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoYes() { var code = @"using System; class Program { void Test6() { [| int i; |] i = 1; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoNo() { var code = @"using System; class Program { void Test7() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test7() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoYes() { var code = @"using System; class Program { void Test8() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] i = 2; } }"; var expected = @"using System; class Program { void Test8() { int i; NewMethod(); i = 2; } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoNo() { var code = @"using System; class Program { void Test9() { [| int i; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test9() { NewMethod(); } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoYes() { var code = @"using System; class Program { void Test10() { [| int i; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test10() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoNo() { var code = @"using System; class Program { void Test11() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test11() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoYes() { var code = @"using System; class Program { void Test12() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test12() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoNo() { var code = @"using System; class Program { void Test13() { int i; [| i = 10; |] } }"; var expected = @"using System; class Program { void Test13() { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoYes() { var code = @"using System; class Program { void Test14() { int i; [| i = 10; |] i = 1; } }"; var expected = @"using System; class Program { void Test14() { int i; NewMethod(); i = 1; } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesNo() { var code = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); [| i = 10; |] } }"; var expected = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesYes() { var code = @"using System; class Program { void Test16() { int i; [| i = 10; |] i = 10; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test16() { int i; NewMethod(); i = 10; Console.WriteLine(i); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test16_1() { int i; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_1() { NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test16_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_2() { int i = 10; NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoNo() { var code = @"using System; class Program { void Test17() { [| int i = 10; |] } }"; var expected = @"using System; class Program { void Test17() { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoYes() { var code = @"using System; class Program { void Test18() { [| int i = 10; |] i = 10; } }"; var expected = @"using System; class Program { void Test18() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoNo() { var code = @"using System; class Program { void Test19() { [| int i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test19() { NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoYes() { var code = @"using System; class Program { void Test20() { [| int i = 10; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test20() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesNo() { var code = @"using System; class Program { void Test21() { int i; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test21() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesYes() { var code = @"using System; class Program { void Test22() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test22_1() { int i; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_1() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test22_2() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_2() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesNo() { var code = @"using System; class Program { void Test23() { [| int i; |] Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesYes() { var code = @"using System; class Program { void Test24() { [| int i; |] Console.WriteLine(i); i = 10; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesNo() { var code = @"using System; class Program { void Test25() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test25() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesYes() { var code = @"using System; class Program { void Test26() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test26() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesNo() { var code = @"using System; class Program { void Test27() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test27() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesYes() { var code = @"using System; class Program { void Test28() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test28() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesNo() { var code = @"using System; class Program { void Test29() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test29() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesYes() { var code = @"using System; class Program { void Test30() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test30() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesNo() { var code = @"using System; class Program { void Test31() { int i; [| i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test31() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesYes() { var code = @"using System; class Program { void Test32() { int i; [| i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test32() { int i; i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test32_1() { int i; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_1() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test32_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_2() { int i = 10; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesNo() { var code = @"using System; class Program { void Test33() { [| int i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test33() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesYes() { var code = @"using System; class Program { void Test34() { [| int i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test34() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesNo() { var code = @"using System; class Program { void Test35() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test35() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesYes() { var code = @"using System; class Program { void Test36() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test36() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoNo() { var code = @"using System; class Program { void Test37() { int i; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test37() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoYes() { var code = @"using System; class Program { void Test38() { int i = 10; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test38() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesNo() { var code = @"using System; class Program { void Test39() { int i; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test39() { int i; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesYes() { var code = @"using System; class Program { void Test40() { int i = 10; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test40() { int i = 10; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test41() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test41() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test42() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test42() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test45() { int i; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test45() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test46() { int i = 10; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test46() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test49() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test49() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test50() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test50() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test51() { int i; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test51() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test52() { int i = 10; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test52() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty1() { var code = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return [|C2.Area|]; } } } "; var expected = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return GetArea(); } } private static int GetArea() { return C2.Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty2() { var code = @"class C3 { public static int Area { get { [|int i = 10; return i;|] } } } "; var expected = @"class C3 { public static int Area { get { return NewMethod(); } } private static int NewMethod() { return 10; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty3() { var code = @"class C3 { public static int Area { set { [|int i = value;|] } } } "; var expected = @"class C3 { public static int Area { set { NewMethod(value); } } private static void NewMethod(int value) { int i = value; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodProperty() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } } "; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] x = 4; Console.Write(x + y); } }"; var expected = @"class C { void M() { int x; int y = NewMethod(); x = 4; Console.Write(x + y); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineNotBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { int x, y = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539214")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodForSplitOutStatementWithComments() { var code = @"class C { void M() { //start [|int x, y; x = 5; y = 10;|] //end Console.Write(x + y); } }"; var expected = @"class C { void M() { //start int x, y; NewMethod(out x, out y); //end Console.Write(x + y); } private static void NewMethod(out int x, out int y) { x = 5; y = 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539225")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5098() { var code = @"class Program { static void Main(string[] args) { [|return;|] Console.Write(4); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5107() { var code = @"class Program { static void Main(string[] args) { int i = 10; [|int j = j + i;|] Console.Write(i); Console.Write(j); } }"; var expected = @"class Program { static void Main(string[] args) { int i = 10; int j = NewMethod(i); Console.Write(i); Console.Write(j); } private static int NewMethod(int i) { return j + i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539500")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable1() { var code = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { [|temp = arg = arg2;|] }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } }"; var expected = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { arg = NewMethod(arg2); }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } private static int NewMethod(int arg2) { int arg, temp; temp = arg = arg2; return arg; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539488")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable2() { var code = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } [|i = 3;|] query(); } }"; var expected = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } NewMethod(); query(); } private static void NewMethod() { int i = 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_1() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { int y = x; x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { int y = x; x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_2() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { [|int y = x; x = 10;|] }; int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { x = NewMethod(x); }; int p = 2; testDel(ref p); Console.WriteLine(p); } private static int NewMethod(int x) { int y = x; x = 10; return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_3() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = delegate (ref int x) { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return delegate (ref int x) { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539859")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable3() { var code = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { [|Console.WriteLine(args.Length + x2 + x);|] }; F2(x); }; F(args.Length); } }"; var expected = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { NewMethod(args, x, x2); }; F2(x); }; F(args.Length); } private static void NewMethod(string[] args, int x, int x2) { Console.WriteLine(args.Length + x2 + x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539882")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5982() { var code = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine([|list.Capacity|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine(GetCapacity(list)); } private static int GetCapacity(List<int> list) { return list.Capacity; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6041() { var code = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; [|d(new ArgumentException());|] } }"; var expected = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; NewMethod(d); } private static void NewMethod(Del<Exception, ArgumentException> d) { d(new ArgumentException()); } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: false); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod50() { var code = @"class C { void Method() { while (true) { [|int i = 1; while (false) { int j = 1;|] } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod51() { var code = @"class C { void Method() { while (true) { switch(1) { case 1: [|int i = 10; break; case 2: int i2 = 20;|] break; } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { switch (1) { case 1: int i = 10; break; case 2: int i2 = 20; break; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod52() { var code = @"class C { void Method() { [|int i = 1; while (false) { int j = 1;|] } } }"; var expected = @"class C { void Method() { NewMethod(); } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539963")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod53() { var code = @"class Class { void Main() { Enum e = Enum.[|Field|]; } } enum Enum { }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539964")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod54() { var code = @"class Class { void Main([|string|][] args) { } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220() { var code = @"class C { void Main() { [| float f = 1.2f; |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220_1() { var code = @"class C { void Main() { [| float f = 1.2f; // test |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; // test } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540071")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6219() { var code = @"class C { void Main() { float @float = 1.2f; [|@float = 1.44F;|] } }"; var expected = @"class C { void Main() { float @float = 1.2f; NewMethod(); } private static void NewMethod() { float @float = 1.44F; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230() { var code = @"class C { void M() { int v =[| /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { int v = GetV(); System.Console.WriteLine(); } private static int GetV() { return /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230_1() { var code = @"class C { void M() { int v [|= /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { int v = /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540052")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6197() { var code = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = [|NewMethod|]; d.Invoke(2); } private static int NewMethod(int x) { return x * 2; } }"; var expected = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = GetD(); d.Invoke(2); } private static Func<int, int> GetD() { return NewMethod; } private static int NewMethod(int x) { return x * 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(6277, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6277() { var code = @"using System; class Program { static void Main(string[] args) { [|int x; x = 1;|] return; int y = x; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int x = NewMethod(); return; int y = x; } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression() { var code = @"using System; class Program { void Test() { [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); return; Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_1() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_2() { var code = @"using System; class Program { void Test() { [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_3() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; } Console.WriteLine();|] } }"; var expected = @"using System; class Program { void Test(bool b) { NewMethod(b); } private static void NewMethod(bool b) { if (b) { return; } Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_1() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; }|] Console.WriteLine(); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_2() { var code = @"using System; class Program { int Test(bool b) { [|if (b) { return 1; } Console.WriteLine();|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_3() { var code = @"using System; class Program { void Test() { [|bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); };|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_4() { var code = @"using System; class Program { void Test() { [|Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); };|] Console.WriteLine(1); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); Console.WriteLine(1); } private static void NewMethod() { Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_5() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; } Console.WriteLine(1);|] }; } }"; var expected = @"using System; class Program { void Test() { Action d = () => { NewMethod(); }; } private static void NewMethod() { int i = 1; if (i > 10) { return; } Console.WriteLine(1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_6() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; }|] Console.WriteLine(1); }; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540170")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6333() { var code = @"using System; class Program { void Test() { Program p; [|p = new Program()|]; } }"; var expected = @"using System; class Program { void Test() { Program p; p = NewMethod(); } private static Program NewMethod() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540216")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6393() { var code = @"using System; class Program { object Test<T>() { T abcd; [|abcd = new T()|]; return abcd; } }"; var expected = @"using System; class Program { object Test<T>() { T abcd; abcd = NewMethod<T>(); return abcd; } private static T NewMethod<T>() { return new T(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine();|] /*End*/ } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); /*End*/ } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_1() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/|] } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_2() { var code = @"class Test { void method() { if (true) [|{ for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ }|] } }"; var expected = @"class Test { void method() { if (true) NewMethod(); } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540333")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6560() { var code = @"using System; class Program { static void Main(string[] args) { string S = [|null|]; int Y = S.Length; } }"; var expected = @"using System; class Program { static void Main(string[] args) { string S = GetS(); int Y = S.Length; } private static string GetS() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562() { var code = @"using System; class Program { int y = [|10|]; }"; var expected = @"using System; class Program { int y = GetY(); private static int GetY() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_1() { var code = @"using System; class Program { const int i = [|10|]; }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_2() { var code = @"using System; class Program { Func<string> f = [|() => ""test""|]; }"; var expected = @"using System; class Program { Func<string> f = GetF(); private static Func<string> GetF() { return () => ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_3() { var code = @"using System; class Program { Func<string> f = () => [|""test""|]; }"; var expected = @"using System; class Program { Func<string> f = () => NewMethod(); private static string NewMethod() { return ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540361")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6598() { var code = @"using System; using System.Collections.Generic; using System.Linq; class { static void Main(string[] args) { [|Program|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540372")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6613() { var code = @"#define A using System; class Program { static void Main(string[] args) { #if A [|Console.Write(5);|] #endif } }"; var expected = @"#define A using System; class Program { static void Main(string[] args) { #if A NewMethod(); #endif } private static void NewMethod() { Console.Write(5); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540396")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InvalidSelection_MethodBody() { var code = @"using System; class Program { static void Main(string[] args) { void Method5(bool b1, bool b2) [|{ if (b1) { if (b2) return; Console.WriteLine(); } Console.WriteLine(); }|] } } "; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541586")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task StructThis() { var code = @"struct S { void Goo() { [|this = new S();|] } }"; var expected = @"struct S { void Goo() { NewMethod(); } private void NewMethod() { this = new S(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541627")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontUseConvertedTypeForImplicitNumericConversion() { var code = @"class T { void Goo() { int x1 = 5; long x2 = [|x1|]; } }"; var expected = @"class T { void Goo() { int x1 = 5; long x2 = GetX2(x1); } private static int GetX2(int x1) { return x1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541668")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BreakInSelection() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string x1 = ""Hello""; switch (x1) { case null: int i1 = 10; break; default: switch (x1) { default: switch (x1) { [|default: int j1 = 99; i1 = 45; x1 = ""t""; string j2 = i1.ToString() + j1.ToString() + x1; break; } break; } break;|] } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541671, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541671")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnreachableCodeWithReturnStatement() { var code = @"class Program { static void Main(string[] args) { return; [|int i1 = 45; i1 = i1 + 10;|] return; } }"; var expected = @"class Program { static void Main(string[] args) { return; NewMethod(); return; } private static void NewMethod() { int i1 = 45; i1 = i1 + 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable1() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { [|a.F(x)|]; return x * v; }; d(3); } } namespace Ros { partial class A { public void F(int s) { } } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { NewMethod(x, a); return x * v; }; d(3); } private static void NewMethod(int x, Ros.A a) { a.F(x); } } namespace Ros { partial class A { public void F(int s) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable2() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { [|p = null;|]; return x * v; }; d(3); } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { p = NewMethod(); ; return x * v; }; d(3); } private static Program NewMethod() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541889")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontCrashOnRangeVariableSymbol() { var code = @"class Test { public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = [|from|] n in numbers where n < 5 select n; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractRangeVariable() { var code = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select [|s|]; } }"; var expected = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select GetS(s); } private static string GetS(string s) { return s; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542155")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GenericWithErrorType() { var code = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<[|Integer|]> x = null; x.IsEmpty(); } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; var expected = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<Integer> x = NewMethod(); x.IsEmpty(); } private static Goo<Integer> NewMethod() { return null; } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542105")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NamedArgument() { var code = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = this[[|y|]: 1]; } }"; var expected = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = GetY(); } private int GetY() { return this[y: 1]; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542213")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task QueryExpressionVariable() { var code = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where ([|a == b|]) select a; } }"; var expected = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where (NewMethod(a, b)) select a; } private static bool NewMethod(int a, int b) { return a == b; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542465")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task IsExpression() { var code = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = new Class1() is [|Class1|]; } static void Main() { } }"; var expected = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = GetB(); } private static bool GetB() { return new Class1() is Class1; } static void Main() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542526")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GlobalNamespaceInReturnType() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ Console.WriteLine(i);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < [|10|]; i++) ; } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < NewMethod(); i++) ; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") [|{ Console.Write(c);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") NewMethod(c); } private static void NewMethod(char c) { Console.Write(c); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in [|""123""|]) { Console.Write(c); } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in NewMethod()) { Console.Write(c); } } private static string NewMethod() { return ""123""; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnElseClause() { var code = @"using System; class Program { static void Main(string[] args) { if ([|true|]) { } else { } } }"; var expected = @"using System; class Program { static void Main(string[] args) { if (NewMethod()) { } else { } } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn"")[|;|] if (true) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: NewMethod(); if (true) goto repeat; } private static void NewMethod() { Console.WriteLine(""Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if ([|true|]) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if (NewMethod()) goto repeat; } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": Console.WriteLine(""one"")[|;|] break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": NewMethod(); break; default: Console.WriteLine(""other""); break; } } private static void NewMethod() { Console.WriteLine(""one""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch ([|args[0]|]) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (NewMethod(args)) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } private static string NewMethod(string[] args) { return args[0]; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do [|{ Console.WriteLine(""I don't like"");|] } while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do NewMethod(); while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } private static void NewMethod() { Console.WriteLine(""I don't like""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while ([|DateTime.Now.DayOfWeek == DayOfWeek.Monday|]); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while (NewMethod()); } private static bool NewMethod() { return DateTime.Now.DayOfWeek == DayOfWeek.Monday; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnWhile() { var code = @"using System; class Program { static void Main(string[] args) { while (true) [|{ ;|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { while (true) NewMethod(); } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnStruct() { var code = @"using System; struct Goo { static Action a = () => { Console.WriteLine(); [|}|]; }"; var expected = @"using System; struct Goo { static Action a = GetA(); private static Action GetA() { return () => { Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodIncludeGlobal() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; static void Main(string[] args) { } }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } static void Main(string[] args) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelection() { var code = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ System.Console.WriteLine(i);|] } } }"; var expected = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { System.Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename1() { var code = @"class Program { static void Main() { [|var i = 42;|] var j = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename2() { var code = @"class Program { static void Main() { NewMethod1(); [|var j = 42;|] } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); NewMethod3(); } private static void NewMethod3() { var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542632")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInInteractive1() { var code = @"int i; [|i = 2|]; i = 3;"; var expected = @"int i; i = NewMethod(); int NewMethod() { return 2; } i = 3;"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(542670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542670")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint1() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint2() { var code = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : IComparable<T> where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint3() { var code = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : class where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint4() { var code = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = [|x.Count|]; } } "; var expected = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : struct where S : IList<I2<IEnumerable<T>, T>> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraintBestEffort() { var code = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = [|s.ToString()|]; } } "; var expected = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = GetT(s); } private static string GetT<S>(S s) where S : string { return s.ToString(); } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(542672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542672")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ConstructedTypes() { var code = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine([|x.Count|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine(GetCount(x)); } private static int GetCount<T>(List<T> x) { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542792")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeInDefault() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = default([|K|]); Item = new T(); NextNode = null; Console.WriteLine(Key); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = NewMethod(); Item = new T(); NextNode = null; Console.WriteLine(Key); } private static K NewMethod() { return default(K); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542708")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Script_ArgumentException() { var code = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = [|delegateType|].GetMethod(""Invoke""); }"; var expected = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = GetDelegateType(delegateType).GetMethod(""Invoke""); } Type GetDelegateType(Type delegateType) { return delegateType; }"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(529008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529008")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ReadOutSideIsUnReachable() { var code = @"class Test { public static void Main() { string str = string.Empty; object obj; [|lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; }|] System.Console.Write(obj); } }"; var expected = @"class Test { public static void Main() { string str = string.Empty; object obj; NewMethod(str, out obj); return; System.Console.Write(obj); } private static void NewMethod(string str, out object obj) { lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; } } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] public async Task AnonymousTypePropertyName() { var code = @"class C { void M() { var x = new { [|String|] = true }; } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { var x = new { String = true }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(543662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentOfBaseConstrInit() { var code = @"class O { public O(int t) : base([|t|]) { } }"; var expected = @"class O { public O(int t) : base(GetT(t)) { } private static int GetT(int t) { return t; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnsafeType() { var code = @" unsafe class O { unsafe public O(int t) { [|t = 1;|] } }"; var expected = @" unsafe class O { unsafe public O(int t) { NewMethod(); } private static void NewMethod() { int t = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544144")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task CastExpressionWithImplicitUserDefinedConversion() { var code = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = [|(int)c|]; } }"; var expected = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = GetY1(c); } private static int GetY1(C c) { return (int)c; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544387")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task FixedPointerVariable() { var code = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = [|*p1|]; } } }"; var expected = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = GetA1(p1); } } private static unsafe int GetA1(int* p1) { return *p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544444")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PointerDeclarationStatement() { var code = @" class Program { unsafe static void Main() { int* p1 = null; [|int* p2 = p1;|] } }"; var expected = @" class Program { unsafe static void Main() { int* p1 = null; NewMethod(p1); } private static unsafe void NewMethod(int* p1) { int* p2 = p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544446")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PrecededByCastExpr() { var code = @" class Program { static void Main() { int i1 = (int)[|5L|]; } }"; var expected = @" class Program { static void Main() { int i1 = (int)NewMethod(); } private static long NewMethod() { return 5L; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; NewMethod(a); } private static void NewMethod(string a) { a = null; } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: true); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst2() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; a = NewMethod(a); } private static string NewMethod(string a) { a = null; return a; } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: false); } [WorkItem(544675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544675")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task HiddenPosition() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } #line default #line hidden }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(530609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530609")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NoCrashInteractive() { var code = @"[|if (true) { }|]"; var expected = @"NewMethod(); void NewMethod() { if (true) { } }"; await TestExtractMethodAsync(code, expected, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); } [WorkItem(530322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530322")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodShouldNotBreakFormatting() { var code = @"class C { void M(int i, int j, int k) { M(0, [|1|], 2); } }"; var expected = @"class C { void M(int i, int j, int k) { M(0, NewMethod(), 2); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractLiteralExpression() { var code = @"class Program { static void Main() { var c = new C { X = { Y = { [|1|] } } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = new C { X = { Y = { NewMethod() } } }; } private static int NewMethod() { return 1; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer() { var code = @"class Program { static void Main() { var c = new C { X = { Y = [|{ 1 }|] } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = GetC(); } private static C GetC() { return new C { X = { Y = { 1 } } }; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(854662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer2() { var code = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { [|a + 2|], 0 } } }.A.Count; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { NewMethod(a), 0 } } }.A.Count; } private static int NewMethod(int a) { return a + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530267")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestCoClassImplicitConversion() { var code = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { [|new I()|]; // Extract Method } }"; var expected = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { NewMethod(); // Extract Method } private static I NewMethod() { return new I(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x|].Ex(); }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { GetX(x).Ex(); }, y))); // Prints 1 } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution1() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex()|]; }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution2() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex();|] }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(731924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/731924")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestTreatEnumSpecial() { var code = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; [|Console.WriteLine(a);|] } }"; var expected = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; NewMethod(a); } private static void NewMethod(A a) { Console.WriteLine(a); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(756222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756222")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestReturnStatementInAsyncMethod() { var code = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); [|return 3;|] } }"; var expected = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); return NewMethod(); } private static int NewMethod() { return 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(574576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574576")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithRefOrOutParameters() { var code = @"using System.Threading.Tasks; class C { public async void Goo() { [|var q = 1; var p = 2; await Task.Yield();|] var r = q; var s = p; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(1025272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1025272")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; var expected = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; int i = await NewMethod(ref cancellationToken); cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } private static async Task<int> NewMethod(ref CancellationToken cancellationToken) { return await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken); } }"; await ExpectExtractMethodToFailAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType1() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken = CancellationToken.None; return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code, allowMovingDeclaration: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOff() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; await ExpectExtractMethodToFailAsync(code, dontPutOutOrRefOnStruct: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOn() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; var expected = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; int i = await NewMethod(s); return i; } private async Task<int> NewMethod(S s) { return await Task.Run(() => { var i2 = s.I; return Test(); }); } } }"; await TestExtractMethodAsync(code, expected, dontPutOutOrRefOnStruct: true); } [Theory] [InlineData("add", "remove")] [InlineData("remove", "add")] [WorkItem(17474, "https://github.com/dotnet/roslyn/issues/17474")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractMethodEventAccessorUnresolvedName(string testedAccessor, string untestedAccessor) { // This code intentionally omits a 'using System;' var code = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ [|throw new NotImplementedException();|] }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} }} }}"; var expected = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ NewMethod(); }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} private static void NewMethod() {{ throw new NotImplementedException(); }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThrough() { var code = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref [|x|])); } }"; var expected = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref $x$)); public static ref int NewMethod(ref int x) { return ref x; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThroughDuplicateVariable() { var code = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref [|guid|], out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } } }"; var expected = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref NewMethod(ref guid), out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } public static ref Guid NewMethod(ref Guid guid) { return ref guid; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument1() { var service = new CSharpExtractMethodService(); Assert.NotNull(await Record.ExceptionAsync(async () => { var tree = await service.ExtractMethodAsync(null, default(TextSpan), null, CancellationToken.None); })); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument2() { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", LanguageNames.CSharp).GetProject(projectId); var document = project.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("Document", SourceText.From("")); var service = new CSharpExtractMethodService() as IExtractMethodService; await service.ExtractMethodAsync(document, default(TextSpan)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void ExtractMethodCommandDisabledInSubmission() { var exportProvider = MinimalTestExportProvider.CreateExportProvider( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveDocumentSupportsFeatureService))); using (var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> typeof(string).$$Name </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, exportProvider: exportProvider)) { // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new ExtractMethodCommandHandler( workspace.GetService<ITextBufferUndoManagerProvider>(), workspace.GetService<IEditorOperationsFactoryService>(), workspace.GetService<IInlineRenameService>(), workspace.GetService<Host.IWaitIndicator>()); var delegatedToNext = false; Func<CommandState> nextHandler = () => { delegatedToNext = true; return CommandState.Unavailable; }; var state = handler.GetCommandState(new Commands.ExtractMethodCommandArgs(textView, textView.TextBuffer), nextHandler); Assert.True(delegatedToNext); Assert.False(state.IsAvailable); } } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|int localValue = arg;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); int LocalCapture() => arg; } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction2() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|int localValue = arg;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; NewMethod(arg); } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction3() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); int LocalCapture() => arg; } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction4() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|arg = arg + 3;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; NewMethod(arg); } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction5() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction1(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ [|arg = arg + 3;|] {usageSyntax} int LocalCapture() => arg; }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ arg = NewMethod(arg); {usageSyntax} int LocalCapture() => arg; }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction2(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } /// <summary> /// This test verifies that Extract Method works properly when the region to extract references a local /// function, the local function uses an unassigned but wholly local variable. /// </summary> [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunctionWithUnassignedLocal(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodDoesNotFlowToLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } } }
Java
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能导致不正确的行为,如果 // 重新生成代码,则所做更改将丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace News { public partial class NewsEdit { /// <summary> /// tbTitle 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbTitle; /// <summary> /// ddlSort 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlSort; /// <summary> /// CKEditorControl1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::CKEditor.NET.CKEditorControl CKEditorControl1; /// <summary> /// btnSave 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnSave; /// <summary> /// btnBack 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnBack; } }
Java
//- Copyright 2013 the Neutrino authors (see AUTHORS). //- Licensed under the Apache License, Version 2.0 (see LICENSE). #ifndef _RUNTIME_INL #define _RUNTIME_INL #include "runtime.h" // Expands to the body of a safe_ function that works by calling a delegate and // if it fails garbage collecting and trying again once. #define RETRY_ONCE_IMPL(RUNTIME, DELEGATE) do { \ __GENERIC_RETRY_DEF__(P_FLAVOR, RUNTIME, value, DELEGATE, P_RETURN); \ return value; \ } while (false) #endif // _RUNTIME_INL
Java
# Strobilanthes perplexa J.R.I.Wood SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
/* * Copyright 2010 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.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Notes; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.provider.ScheduleDatabase.VendorsSearchColumns; import com.google.android.apps.iosched.util.NotesExporter; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.MatrixCursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import android.provider.OpenableColumns; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.bespokesystems.android.apps.wicsa2011.de.service.SyncService; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link SyncService}, and queried by various {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = "ScheduleProvider"; private static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_VENDORS = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_SEARCH = 402; private static final int SESSIONS_AT = 403; private static final int SESSIONS_ID = 404; private static final int SESSIONS_ID_SPEAKERS = 405; private static final int SESSIONS_ID_TRACKS = 406; private static final int SESSIONS_ID_NOTES = 407; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int VENDORS = 600; private static final int VENDORS_STARRED = 601; private static final int VENDORS_SEARCH = 603; private static final int VENDORS_ID = 604; private static final int NOTES = 700; private static final int NOTES_EXPORT = 701; private static final int NOTES_ID = 702; private static final int SEARCH_SUGGEST = 800; private static final String MIME_XML = "text/xml"; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "sessions/*/notes", SESSIONS_ID_NOTES); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "vendors", VENDORS); matcher.addURI(authority, "vendors/starred", VENDORS_STARRED); matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH); matcher.addURI(authority, "vendors/*", VENDORS_ID); matcher.addURI(authority, "notes", NOTES); matcher.addURI(authority, "notes/export", NOTES_EXPORT); matcher.addURI(authority, "notes/*", NOTES_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { final Context context = getContext(); mOpenHelper = new ScheduleDatabase(context); return true; } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_VENDORS: return Vendors.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SESSIONS_ID_NOTES: return Notes.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case VENDORS: return Vendors.CONTENT_TYPE; case VENDORS_STARRED: return Vendors.CONTENT_TYPE; case VENDORS_SEARCH: return Vendors.CONTENT_TYPE; case VENDORS_ID: return Vendors.CONTENT_ITEM_TYPE; case NOTES: return Notes.CONTENT_TYPE; case NOTES_EXPORT: return MIME_XML; case NOTES_ID: return Notes.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (LOGV) Log.v(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case NOTES_EXPORT: { // Provide query values for file attachments final String[] columns = { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }; final MatrixCursor cursor = new MatrixCursor(columns, 1); cursor.addRow(new String[] { "notes.xml", null }); return cursor; } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { if (LOGV) Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SESSIONS_ID_NOTES: { final String sessionId = Sessions.getSessionId(uri); values.put(Notes.SESSION_ID, sessionId); final long noteId = db.insertOrThrow(Tables.NOTES, null, values); return ContentUris.withAppendedId(Notes.CONTENT_URI, noteId); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case VENDORS: { db.insertOrThrow(Tables.VENDORS, null, values); return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID)); } case NOTES: { final long noteId = db.insertOrThrow(Tables.NOTES, null, values); return ContentUris.withAppendedId(Notes.CONTENT_URI, noteId); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); return SearchSuggest.CONTENT_URI; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); return builder.where(selection, selectionArgs).update(db, values); } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "delete(uri=" + uri + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); return builder.where(selection, selectionArgs).delete(db); } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case NOTES: { return builder.table(Tables.NOTES); } case NOTES_ID: { final String noteId = uri.getPathSegments().get(1); return builder.table(Tables.NOTES) .where(Notes._ID + "=?", noteId); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_VENDORS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Qualified.VENDORS_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.STARRED + "=1"); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_NOTES: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.NOTES) .where(Notes.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS); } case VENDORS_STARRED: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.STARRED + "=1"); } case VENDORS_SEARCH: { final String query = Vendors.getSearchQuery(uri); return builder.table(Tables.VENDORS_SEARCH_JOIN_VENDORS_TRACKS) .map(Vendors.SEARCH_SNIPPET, Subquery.VENDORS_SNIPPET) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.VENDOR_ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(VendorsSearchColumns.BODY + " MATCH ?", query); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case NOTES: { return builder.table(Tables.NOTES); } case NOTES_ID: { final long noteId = Notes.getNoteId(uri); return builder.table(Tables.NOTES) .where(Notes._ID + "=?", Long.toString(noteId)); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { case NOTES_EXPORT: { try { final File notesFile = NotesExporter.writeExportedNotes(getContext()); return ParcelFileDescriptor .open(notesFile, ParcelFileDescriptor.MODE_READ_ONLY); } catch (IOException e) { throw new FileNotFoundException("Unable to export notes: " + e.toString()); } } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_CONTAINS_STARRED = "(SELECT MAX(" + Qualified.SESSIONS_STARRED + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM " + Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; String VENDORS_SNIPPET = "snippet(" + Tables.VENDORS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID; String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID; @SuppressWarnings("hiding") String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.STARRED; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
Java
# dtstructs [![Build Status](https://travis-ci.org/mbe24/dtstructs.svg?branch=master)](https://travis-ci.org/mbe24/dtstructs) [![License Info](http://img.shields.io/badge/license-Apache%20License%20v2.0-orange.svg)](https://raw.githubusercontent.com/mbe24/jcurry/master/LICENSE) =========== C++ Data Structures -------------------
Java
/* * Copyright 2010-2016 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.inspector.model; import com.amazonaws.AmazonServiceException; /** * */ public class NoSuchEntityException extends AmazonServiceException { private static final long serialVersionUID = 1L; /** * Constructs a new NoSuchEntityException with the specified error message. * * @param message * Describes the error encountered. */ public NoSuchEntityException(String message) { super(message); } }
Java
/* * 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.dataexchange.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dataexchange-2017-07-25/DeleteEventAction" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteEventActionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The unique identifier for the event action. * </p> */ private String eventActionId; /** * <p> * The unique identifier for the event action. * </p> * * @param eventActionId * The unique identifier for the event action. */ public void setEventActionId(String eventActionId) { this.eventActionId = eventActionId; } /** * <p> * The unique identifier for the event action. * </p> * * @return The unique identifier for the event action. */ public String getEventActionId() { return this.eventActionId; } /** * <p> * The unique identifier for the event action. * </p> * * @param eventActionId * The unique identifier for the event action. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteEventActionRequest withEventActionId(String eventActionId) { setEventActionId(eventActionId); 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 (getEventActionId() != null) sb.append("EventActionId: ").append(getEventActionId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteEventActionRequest == false) return false; DeleteEventActionRequest other = (DeleteEventActionRequest) obj; if (other.getEventActionId() == null ^ this.getEventActionId() == null) return false; if (other.getEventActionId() != null && other.getEventActionId().equals(this.getEventActionId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEventActionId() == null) ? 0 : getEventActionId().hashCode()); return hashCode; } @Override public DeleteEventActionRequest clone() { return (DeleteEventActionRequest) super.clone(); } }
Java
# Daedalea microzona Lév., 1846 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Annls Sci. Nat. , Bot. , sér. 3 5: 142 (1846) #### Original name Daedalea microzona Lév., 1846 ### Remarks null
Java
/******************************************************************************* * Copyright 2017 Xoriant 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. ******************************************************************************/ /* * Doctor Appointment * Appointment * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.model.Payload; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for DefaultApi */ @Ignore public class DefaultApiTest { private final DefaultApi api = new DefaultApi(); /** * Post new Doctor info * * endpoint for posting a newly created Doctor entity to the server * * @throws ApiException * if the Api call fails */ @Test public void createDoctorTest() throws ApiException { Payload payload = null; api.createDoctor(payload); // TODO: test validations } }
Java
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace com.huawei.ebg.esdk.ucsdk.client.control { public partial class DialCall : Button { public DialCall() { InitializeComponent(); } # region 自定义字段 private string _ucAccount; [Description("被叫UC帐号")] public string UCAccount { get { return _ucAccount; } set { _ucAccount = value; } } private string _calledNumber; [Description("被叫号码")] public string CalledNumber { get { return _calledNumber; } set { _calledNumber = value; } } # endregion protected override void OnClick(EventArgs e) { base.OnClick(e); try { CtrlBusiness.DirectCall(_ucAccount, _calledNumber); } catch (Exception ex) { //throw ex; } } } }
Java
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.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 org.thymeleaf.dialect.dialectwrapping; import org.thymeleaf.context.ITemplateContext; import org.thymeleaf.model.IModel; import org.thymeleaf.processor.element.AbstractElementModelProcessor; import org.thymeleaf.processor.element.IElementModelStructureHandler; import org.thymeleaf.templatemode.TemplateMode; public class ElementModelProcessor extends AbstractElementModelProcessor { public ElementModelProcessor(final String dialectPrefix) { super(TemplateMode.HTML, dialectPrefix, "div", true, null, false, 100); } @Override protected void doProcess(final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) { } }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Accela.WindowsStoreSDK")] [assembly: AssemblyDescription("Accela SDK for Windows & Windows Phone")] [assembly: AssemblyCompany("Accela Inc.")] [assembly: AssemblyProduct("AccelaSDK")] [assembly: AssemblyCopyright("Copyright © 2013, Accela Inc.")] [assembly: AssemblyVersion("3.0.1.3")] [assembly: AssemblyFileVersion("3.0.1.3")] [assembly: ComVisible(false)]
Java
--- layout: default title: CAS - SMS Messaging category: Notifications --- # SMS Messaging CAS presents the ability to notify users on select actions via SMS messaging. Example actions include notification of risky authentication attempts or password reset links/tokens. SMS providers supported by CAS are listed below. Note that an active/professional subscription may be required for certain providers. ## Custom Send text messages using your own custom implementation. ```java @Bean public SmsSender smsSender() { ... } ``` ## Groovy Send text messages using an external Groovy script. ```groovy import java.util.* def run(Object[] args) { def from = args[0] def to = args[1] def message = args[2] def logger = args[3] logger.debug("Sending message ${message} to ${to} from ${from}") true } ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#groovy). ## REST Send text messages using a RESTful API. This is a `POST` with the following parameters: | Field | Description |---------------------|--------------------------------------------------- | `clientIpAddress` | The client IP address. | `serverIpAddress` | The server IP address. | `from` | The from address of the text message. | `to` | The target recipient of the text message. The request body contains the actual message. A status code of `200` is expected from the endpoint. To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#rest-2). ## Twilio To learn more, [visit this site](https://www.twilio.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-twilio</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#twilio). ## TextMagic To learn more, [visit this site](https://www.textmagic.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-textmagic</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#textmagic). ## Clickatell To learn more, [visit this site](http://www.clickatell.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-clickatell</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#clickatell). ## Amazon SNS To learn more, [visit this site](https://docs.aws.amazon.com/sns). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-aws-sns</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#amazon-sns). ## Nexmo To learn more, [visit this site](https://dashboard.nexmo.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-nexmo</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#nexmo).
Java
/** * @license Apache-2.0 * * Copyright (c) 2020 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 Float32Array = require( '@stdlib/array/float32' ); var addon = require( './smin.native.js' ); // MAIN // /** * Computes the minimum value of a single-precision floating-point strided array. * * @param {PositiveInteger} N - number of indexed elements * @param {Float32Array} x - input array * @param {integer} stride - stride length * @param {NonNegativeInteger} offset - starting index * @returns {number} minimum value * * @example * var Float32Array = require( '@stdlib/array/float32' ); * var floor = require( '@stdlib/math/base/special/floor' ); * * var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] ); * var N = floor( x.length / 2 ); * * var v = smin( N, x, 2, 1 ); * // returns -2.0 */ function smin( N, x, stride, offset ) { var view; if ( stride < 0 ) { offset += (N-1) * stride; } view = new Float32Array( x.buffer, x.byteOffset+(x.BYTES_PER_ELEMENT*offset), x.length-offset ); // eslint-disable-line max-len return addon( N, view, stride ); } // EXPORTS // module.exports = smin;
Java
/* * 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.lightsail.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lightsail.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DetachStaticIpResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DetachStaticIpResultJsonUnmarshaller implements Unmarshaller<DetachStaticIpResult, JsonUnmarshallerContext> { public DetachStaticIpResult unmarshall(JsonUnmarshallerContext context) throws Exception { DetachStaticIpResult detachStaticIpResult = new DetachStaticIpResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return detachStaticIpResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("operations", targetDepth)) { context.nextToken(); detachStaticIpResult.setOperations(new ListUnmarshaller<Operation>(OperationJsonUnmarshaller.getInstance()).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return detachStaticIpResult; } private static DetachStaticIpResultJsonUnmarshaller instance; public static DetachStaticIpResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DetachStaticIpResultJsonUnmarshaller(); return instance; } }
Java
package io.teknek.nibiru.transport.rpc; import io.teknek.nibiru.transport.BaseResponse; public class BlockingRpcResponse<T> implements BaseResponse { private String exception; private T rpcResult; public BlockingRpcResponse(){ } public String getException() { return exception; } public void setException(String exception) { this.exception = exception; } public T getRpcResult() { return rpcResult; } public void setRpcResult(T rpcResult) { this.rpcResult = rpcResult; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Thu Oct 15 19:26:58 UTC 2015 --> <title>DescribeScheduledActionsResult (AWS SDK for Java - 1.10.27)</title> <meta name="date" content="2015-10-15"> <link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DescribeScheduledActionsResult (AWS SDK for Java - 1.10.27)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <!-- Scripts for Syntax Highlighter START--> <script id="syntaxhighlight_script_core" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shCore.js"> </script> <script id="syntaxhighlight_script_java" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shBrushJava.js"> </script> <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/> <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/> <!-- Scripts for Syntax Highlighter END--> <div> <!-- BEGIN-SECTION --> <div id="divsearch" style="float:left;"> <span id="lblsearch" for="searchQuery"> <label>Search</label> </span> <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java"> <div id="nav-searchfield-outer" class="nav-sprite"> <div class="nav-searchfield-inner nav-sprite"> <div id="nav-searchfield-width"> <input id="nav-searchfield" name="searchQuery"> </div> </div> </div> <div id="nav-search-button" class="nav-sprite"> <input alt="" id="nav-search-button-inner" type="image"> </div> <input name="searchPath" type="hidden" value="documentation-guide" /> <input name="this_doc_product" type="hidden" value="AWS SDK for Java" /> <input name="this_doc_guide" type="hidden" value="API Reference" /> <input name="doc_locale" type="hidden" value="en_us" /> </form> </div> <!-- END-SECTION --> <!-- BEGIN-FEEDBACK-SECTION --> <div id="feedback-section"> <h3>Did this page help you?</h3> <div id="feedback-link-sectioin"> <a id="feedback_yes" target="_blank" style="display:inline;">Yes</a>&nbsp;&nbsp; <a id="feedback_no" target="_blank" style="display:inline;">No</a>&nbsp;&nbsp; <a id="go_cti" target="_blank" style="display:inline;">Tell us about it...</a> </div> </div> <script type="text/javascript"> window.onload = function(){ /* Dynamically add feedback links */ var javadoc_root_name = "/javadoc/"; var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id="; var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id="; var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name="; if(file_path != "overview-frame.html") { var file_name = file_path.replace(/[/.]/g, '_'); document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name); document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name); document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name); } else { // hide the search box and the feeback links in overview-frame page, // show "AWS SDK for Java" instead. document.getElementById("feedback-section").outerHTML = "AWS SDK for Java"; document.getElementById("divsearch").outerHTML = ""; } }; </script> <!-- END-FEEDBACK-SECTION --> </div> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeTagsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" target="_top">Frames</a></li> <li><a href="DescribeScheduledActionsResult.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.amazonaws.services.autoscaling.model</div> <h2 title="Class DescribeScheduledActionsResult" class="title">Class DescribeScheduledActionsResult</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.amazonaws.services.autoscaling.model.DescribeScheduledActionsResult</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Cloneable</dd> </dl> <hr> <br> <pre>public class <span class="strong">DescribeScheduledActionsResult</span> extends java.lang.Object implements java.io.Serializable, java.lang.Cloneable</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../serialized-form.html#com.amazonaws.services.autoscaling.model.DescribeScheduledActionsResult">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#DescribeScheduledActionsResult()">DescribeScheduledActionsResult</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#clone()">clone</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object&nbsp;obj)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#getNextToken()">getNextToken</a></strong>()</code> <div class="block">The token to use when requesting the next set of items.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#getScheduledUpdateGroupActions()">getScheduledUpdateGroupActions</a></strong>()</code> <div class="block">The scheduled actions.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#hashCode()">hashCode</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#setNextToken(java.lang.String)">setNextToken</a></strong>(java.lang.String&nbsp;nextToken)</code> <div class="block">The token to use when requesting the next set of items.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#setScheduledUpdateGroupActions(java.util.Collection)">setScheduledUpdateGroupActions</a></strong>(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</code> <div class="block">The scheduled actions.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#toString()">toString</a></strong>()</code> <div class="block">Returns a string representation of this object; useful for testing and debugging.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withNextToken(java.lang.String)">withNextToken</a></strong>(java.lang.String&nbsp;nextToken)</code> <div class="block">The token to use when requesting the next set of items.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withScheduledUpdateGroupActions(java.util.Collection)">withScheduledUpdateGroupActions</a></strong>(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</code> <div class="block">The scheduled actions.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withScheduledUpdateGroupActions(com.amazonaws.services.autoscaling.model.ScheduledUpdateGroupAction...)">withScheduledUpdateGroupActions</a></strong>(<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>...&nbsp;scheduledUpdateGroupActions)</code> <div class="block">The scheduled actions.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DescribeScheduledActionsResult()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DescribeScheduledActionsResult</h4> <pre>public&nbsp;DescribeScheduledActionsResult()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getScheduledUpdateGroupActions()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getScheduledUpdateGroupActions</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;getScheduledUpdateGroupActions()</pre> <div class="block">The scheduled actions.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The scheduled actions.</dd></dl> </li> </ul> <a name="setScheduledUpdateGroupActions(java.util.Collection)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setScheduledUpdateGroupActions</h4> <pre>public&nbsp;void&nbsp;setScheduledUpdateGroupActions(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</pre> <div class="block">The scheduled actions.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>scheduledUpdateGroupActions</code> - The scheduled actions.</dd></dl> </li> </ul> <a name="withScheduledUpdateGroupActions(com.amazonaws.services.autoscaling.model.ScheduledUpdateGroupAction...)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withScheduledUpdateGroupActions</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;withScheduledUpdateGroupActions(<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>...&nbsp;scheduledUpdateGroupActions)</pre> <div class="block">The scheduled actions. <p> <b>NOTE:</b> This method appends the values to the existing list (if any). Use <a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#setScheduledUpdateGroupActions(java.util.Collection)"><code>setScheduledUpdateGroupActions(java.util.Collection)</code></a> or <a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withScheduledUpdateGroupActions(java.util.Collection)"><code>withScheduledUpdateGroupActions(java.util.Collection)</code></a> if you want to override the existing values. <p> Returns a reference to this object so that method calls can be chained together.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>scheduledUpdateGroupActions</code> - The scheduled actions.</dd> <dt><span class="strong">Returns:</span></dt><dd>A reference to this updated object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="withScheduledUpdateGroupActions(java.util.Collection)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withScheduledUpdateGroupActions</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;withScheduledUpdateGroupActions(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</pre> <div class="block">The scheduled actions. <p> Returns a reference to this object so that method calls can be chained together.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>scheduledUpdateGroupActions</code> - The scheduled actions.</dd> <dt><span class="strong">Returns:</span></dt><dd>A reference to this updated object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="getNextToken()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getNextToken</h4> <pre>public&nbsp;java.lang.String&nbsp;getNextToken()</pre> <div class="block">The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. <p> <b>Constraints:</b><br/> <b>Pattern: </b>[&#92;u0020-&#92;uD7FF&#92;uE000-&#92;uFFFD&#92;uD800&#92;uDC00-&#92;uDBFF&#92;uDFFF\r\n\t]*<br/></div> <dl><dt><span class="strong">Returns:</span></dt><dd>The token to use when requesting the next set of items. If there are no additional items to return, the string is empty.</dd></dl> </li> </ul> <a name="setNextToken(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setNextToken</h4> <pre>public&nbsp;void&nbsp;setNextToken(java.lang.String&nbsp;nextToken)</pre> <div class="block">The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. <p> <b>Constraints:</b><br/> <b>Pattern: </b>[&#92;u0020-&#92;uD7FF&#92;uE000-&#92;uFFFD&#92;uD800&#92;uDC00-&#92;uDBFF&#92;uDFFF\r\n\t]*<br/></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>nextToken</code> - The token to use when requesting the next set of items. If there are no additional items to return, the string is empty.</dd></dl> </li> </ul> <a name="withNextToken(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withNextToken</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;withNextToken(java.lang.String&nbsp;nextToken)</pre> <div class="block">The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. <p> Returns a reference to this object so that method calls can be chained together. <p> <b>Constraints:</b><br/> <b>Pattern: </b>[&#92;u0020-&#92;uD7FF&#92;uE000-&#92;uFFFD&#92;uD800&#92;uDC00-&#92;uDBFF&#92;uDFFF\r\n\t]*<br/></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>nextToken</code> - The token to use when requesting the next set of items. If there are no additional items to return, the string is empty.</dd> <dt><span class="strong">Returns:</span></dt><dd>A reference to this updated object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block">Returns a string representation of this object; useful for testing and debugging.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> <dt><span class="strong">Returns:</span></dt><dd>A string representation of this object.</dd><dt><span class="strong">See Also:</span></dt><dd><code>Object.toString()</code></dd></dl> </li> </ul> <a name="hashCode()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="equals(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;obj)</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="clone()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>clone</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;clone()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>clone</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <div> <!-- Script for Syntax Highlighter START --> <script type="text/javascript"> SyntaxHighlighter.all() </script> <!-- Script for Syntax Highlighter END --> </div> <script src="http://a0.awsstatic.com/chrome/js/1.0.46/jquery.1.9.js" type="text/javascript"></script> <script>jQuery.noConflict();</script> <script> jQuery(function ($) { $("div.header").prepend('<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->'); }); </script> <!-- BEGIN-URCHIN-TRACKER --> <script src="http://l0.awsstatic.com/js/urchin.js" type="text/javascript"></script> <script type="text/javascript">urchinTracker();</script> <!-- END-URCHIN-TRACKER --> <!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved. More info available at http://www.omniture.com --> <script language="JavaScript" type="text/javascript" src="https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js (view-source:https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js)" /> <script language="JavaScript" type="text/javascript"> <!-- // Documentation Service Name s.prop66='AWS SDK for Java'; s.eVar66='D=c66'; // Documentation Guide Name s.prop65='API Reference'; s.eVar65='D=c65'; var s_code=s.t();if(s_code)document.write(s_code) //--> </script> <script language="JavaScript" type="text/javascript"> <!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-') //--> </script> <noscript> <img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" /> </noscript> <!--/DO NOT REMOVE/--> <!-- End SiteCatalyst code version: H.25.2. --> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeTagsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" target="_top">Frames</a></li> <li><a href="DescribeScheduledActionsResult.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> Copyright &#169; 2013 Amazon Web Services, Inc. All Rights Reserved. </small></p> </body> </html>
Java
/* Copyright 2021 The Kubeflow 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 main import ( "encoding/json" "fmt" "os" "strings" "github.com/go-openapi/spec" "github.com/kubeflow/katib/pkg/apis/v1beta1" "k8s.io/klog" "k8s.io/kube-openapi/pkg/common" ) // Generate OpenAPI spec definitions for Katib Resource func main() { if len(os.Args) <= 2 { klog.Fatal("Supply Swagger version and Katib Version") } version := os.Args[1] if !strings.HasPrefix(version, "v") { version = "v" + version } refCallback := func(name string) spec.Ref { return spec.MustCreateRef("#/definitions/" + common.EscapeJsonPointer(swaggify(name))) } katibVersion := os.Args[2] oAPIDefs := make(map[string]common.OpenAPIDefinition) if katibVersion == "v1beta1" { oAPIDefs = v1beta1.GetOpenAPIDefinitions(refCallback) } else { klog.Fatalf("Katib version %v is not supported", katibVersion) } defs := spec.Definitions{} for defName, val := range oAPIDefs { defs[swaggify(defName)] = val.Schema } swagger := spec.Swagger{ SwaggerProps: spec.SwaggerProps{ Swagger: "2.0", Definitions: defs, Paths: &spec.Paths{Paths: map[string]spec.PathItem{}}, Info: &spec.Info{ InfoProps: spec.InfoProps{ Title: "Katib", Description: "Swagger description for Katib", Version: version, }, }, }, } jsonBytes, err := json.MarshalIndent(swagger, "", " ") if err != nil { klog.Fatal(err.Error()) } fmt.Println(string(jsonBytes)) } func swaggify(name string) string { name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/common/", "", -1) name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/experiments/", "", -1) name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/suggestions", "", -1) name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/trials", "", -1) name = strings.Replace(name, "k8s.io/api/core/", "", -1) name = strings.Replace(name, "k8s.io/apimachinery/pkg/apis/meta/", "", -1) name = strings.Replace(name, "/", ".", -1) return name }
Java
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type)
Java