code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# Semecarpus euodiifolius Kochummen SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Anacardiaceae/Semecarpus/Semecarpus euodiifolius/README.md
Markdown
apache-2.0
183
# Raciborskanthos minax (Rchb.f.) Szlach. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Cleisostoma/Cleisostoma minax/ Syn. Raciborskanthos minax/README.md
Markdown
apache-2.0
196
# Miltonia bismarckii (Dodson & D.E.Benn.) P.F.Hunt SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Miltoniopsis/Miltoniopsis bismarckii/ Syn. Miltonia bismarckii/README.md
Markdown
apache-2.0
206
# Termitomyces subumkowaanii Mossebo SPECIES #### Status SYNONYM #### According to Index Fungorum #### Published in null #### Original name Termitomyces subumkowaanii Mossebo ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Lyophyllaceae/Termitomyces/Termitomyces subumkowaan/ Syn. Termitomyces subumkowaanii/README.md
Markdown
apache-2.0
196
# Polyblastia cinerea (A. Massal.) Jatta SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Amphoridium cinereum A. Massal. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Eurotiomycetes/Verrucariales/Verrucariaceae/Polyblastia/Polyblastia cinerea/README.md
Markdown
apache-2.0
223
# Trachelomonas elliptica (Playfair) Deflandre SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Protozoa/Euglenozoa/Euglenida/Euglenales/Euglenaceae/Trachelomonas/Trachelomonas elliptica/README.md
Markdown
apache-2.0
202
# Pilosella flammea (Lindeb.) Norrl. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/incertae sedis/Pilosella fuscoatra/ Syn. Pilosella flammea/README.md
Markdown
apache-2.0
191
# Trametes meyenii (Klotzsch) Lloyd, 1918 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Mycol. Writ. 5(no. 67): 14 (1918) #### Original name Polyporus meyenii Klotzsch, 1843 ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Trametes/Trametes meyenii/README.md
Markdown
apache-2.0
254
/* Copyright 2012 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. Author: Landry DEFO KUATE (defolandry@yahoo.fr) */ function onError(e) { console.log(e); } // Support du système de fichier ---------------------------------------------------------- var fs = null; var FOLDERNAME = 'test'; function writeFile(blob) { if (!fs) { return; } fs.root.getDirectory(FOLDERNAME, {create: true}, function(dirEntry) { dirEntry.getFile(blob.name, {create: true, exclusive: false}, function(fileEntry) { // Créer un objet FileWriter pour notre FileEntry, et écrire le blob fileEntry.createWriter(function(fileWriter) { fileWriter.onerror = onError; fileWriter.onwriteend = function(e) { console.log('Write completed.'); }; fileWriter.write(blob); }, onError); }, onError); }, onError); } // ----------------------------------------------------------------------------- var gContactApp = angular.module('gContactApp', []); gContactApp.factory('gcontacts', function() { var gcontacts = {items: []}; var dnd = new DnDFileController('body', function(files) { var chosenEntry = null; var $scope = angular.element(this).scope(); for (var i = 0; i < files.items.length; i++) { var item = files.items[i]; if (item.kind == 'file' && item.type.match('text/*') && item.webkitGetAsEntry()) { chosenEntry = item.webkitGetAsEntry(); break; } }; Util.readAsText(chosenEntry, function(result) { var data = angular.fromJson(result); $scope.fetchContacts(data); }); }); return gcontacts; }); //Controller principal de l'application function ContactsController($scope, $http, gcontacts) { $scope.contacts = []; $scope.fetchContacts = function(resp) { var docs = []; var totalEntries = resp.items.length; resp.items.forEach(function(entry, i) { var doc = { title: entry.title, firstname: entry.firstname, lastname: entry.lastname, email: entry.email, tel: entry.tel, updatedDate: Util.formatDate(entry.modifiedDate), updatedDateFull: entry.modifiedDate, icon: entry.iconLink, alternateLink: entry.alternateLink, size: entry.fileSize ? '( ' + entry.fileSize + ' bytes)' : null }; // 'http://gstatic.google.com/doc_icon_128.png' -> 'doc_icon_128.png' doc.iconFilename = doc.icon.substring(doc.icon.lastIndexOf('/') + 1); // Si le fichier existe, il retourne un FileEntry pour l'URL du système de fichier // Sinon, nous allons avoir un callback d'erreur qui nous permettra de recupérer le fichier // et le stocker dans le système de fichier var fsURL = fs.root.toURL() + FOLDERNAME + '/' + doc.iconFilename; window.webkitResolveLocalFileSystemURL(fsURL, function(entry) { console.log('Recuperation du fichier du systeme de fichier'); doc.icon = entry.toURL(); $scope.contacts.push(doc); // On souhaite effectuer le tri seulement si on a toutes les données if (totalEntries - 1 == i) { $scope.contacts.sort(Util.sortByDate); $scope.$apply(function($scope) {}); // Informer angular que nous avons effectué les changements } }, function(e) { $http.get(doc.icon, {responseType: 'blob'}).success(function(blob) { console.log('Fetched icon via XHR'); blob.name = doc.iconFilename; // Ajouter la photo dans le blob writeFile(blob); // L'écriture est asynchrone, mais c'est OK doc.icon = window.URL.createObjectURL(blob); $scope.contacts.push(doc); if (totalEntries - 1 == i) { $scope.contacts.sort(Util.sortByDate); } }); }); }); }; $scope.clearContacts = function() { $scope.contacts = []; // Vider les anciens résultats }; } ContactsController.$inject = ['$scope', '$http', 'gcontacts']; // Pour la minification du code source. //Initialisation et attachement des Listeners document.addEventListener('DOMContentLoaded', function(e) { var closeButton = document.querySelector('#close-button'); closeButton.addEventListener('click', function(e) { window.close(); }); // SUPPORT FILESYSTEM -------------------------------------------------------- window.webkitRequestFileSystem(TEMPORARY, 1024 * 1024, function(localFs) { fs = localFs; }, onError); // --------------------------------------------------------------------------- });
defus/gContacts
js/app.js
JavaScript
apache-2.0
5,069
module.exports = function(req, res, log, next) { res.json({keyWithParamPOST: 'value'}); };
contactlab/saray
test/data/call4?param1=value1.POST.js
JavaScript
apache-2.0
92
package cn.elvea.platform.commons.user; import java.io.Serializable; /** * User * * @author elvea * @since 0.0.1 */ public interface User extends Serializable { /** * ID */ Long getId(); /** * 用户名 */ String getUsername(); }
elveahuang/platform
platform-commons/platform-commons-core/src/main/java/cn/elvea/platform/commons/user/User.java
Java
apache-2.0
276
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/iotanalytics/model/GetDatasetContentRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::IoTAnalytics::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws::Http; GetDatasetContentRequest::GetDatasetContentRequest() : m_datasetNameHasBeenSet(false), m_versionIdHasBeenSet(false) { } Aws::String GetDatasetContentRequest::SerializePayload() const { return {}; } void GetDatasetContentRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_versionIdHasBeenSet) { ss << m_versionId; uri.AddQueryStringParameter("versionId", ss.str()); ss.str(""); } }
cedral/aws-sdk-cpp
aws-cpp-sdk-iotanalytics/source/model/GetDatasetContentRequest.cpp
C++
apache-2.0
1,384
package com.dt.scala.implicits import java.io.File import scala.io.Source /** * @author Wang Jialin * Date 2015/7/20 * Contact Information: * WeChat: 18610086859 * QQ: 1740415547 * Email: 18610086859@126.com * Tel: 18610086859 */ object Context_Helper{ implicit class FileEnhancer(file : File){ def read = Source.fromFile(file.getPath).mkString } implicit class Op(x:Int){ def addSAP(second: Int) = x + second } } object Implicits_Class { def main(args: Array[String]){ import Context_Helper._ println(1.addSAP(2)) println(new File("E:\\WangJialin.txt").read) } }
slieer/scala-tutorials
src/main/scala/com/dt/scala/implicits/Implicits_Class.scala
Scala
apache-2.0
675
package io.github.i49.cascade.tests; /** * Namespaces used in the test cases. */ public final class Namespaces { public static final String XHTML = "http://www.w3.org/1999/xhtml"; public static final String SVG = "http://www.w3.org/2000/svg"; public static final String XLINK = "http://www.w3.org/1999/xlink"; public static final String NONEXISTENT = "http://www.example.org/nonexistent"; private Namespaces() { } }
i49/cascade
cascade/src/test/java/io/github/i49/cascade/tests/Namespaces.java
Java
apache-2.0
471
package com.github.sormuras.stash; import java.nio.ByteBuffer; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; public interface Stashlet { String BUFFER = "this.buffer"; String CLOCK = "this.clock"; String DELEGATE = "this.delegate"; Class<?> forClass(); TypeMirror forTypeMirror(Elements elements, Types types); String getGetStatement(); String getPutStatement(String name); /** * Returns an informative string representation of this type. The string is * of a form suitable for representing this type in source code. Any names * embedded in the result are qualified. * * @return source code representation of this type. */ String getSourceSnippet(); Object runtimeGet(ByteBuffer source); void runtimePut(ByteBuffer target, Object object); }
sormuras/treasure
stashonly/src/com/github/sormuras/stash/Stashlet.java
Java
apache-2.0
847
/* * Copyright 2017 Mirko Sertic * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.mirkosertic.bytecoder.core; public class BytecodeInstructionALOAD extends BytecodeInstruction { private final int variableIndex; public BytecodeInstructionALOAD(BytecodeOpcodeAddress aOpcodeIndex, int aIndex) { super(aOpcodeIndex); variableIndex = aIndex; } public int getVariableIndex() { return variableIndex; } }
mirkosertic/Bytecoder
core/src/main/java/de/mirkosertic/bytecoder/core/BytecodeInstructionALOAD.java
Java
apache-2.0
973
// // Copyright 2011 Jeff Verkoeyen // // 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 <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIPreprocessorMacros.h" /* for NI_WEAK */ @protocol NICollectionViewModelDelegate; #pragma mark Sectioned Array Objects // Classes used when creating NICollectionViewModels. @class NICollectionViewModelFooter; // Provides the information for a footer. /** * A non-mutable collection view model that complies to the UICollectionViewDataSource protocol. * * This model allows you to easily create a data source for a UICollectionView without having to * implement the UICollectionViewDataSource methods in your controller. * * This base class is non-mutable, much like an NSArray. You must initialize this model with * the contents when you create it. * * This model simply manages the data relationship with your collection view. It is up to you to * implement the collection view's layout object. * * @ingroup CollectionViewModels */ @interface NICollectionViewModel : NSObject <UICollectionViewDataSource> #pragma mark Creating Collection View Models // Designated initializer. - (id)initWithDelegate:(id<NICollectionViewModelDelegate>)delegate; - (id)initWithListArray:(NSArray *)listArray delegate:(id<NICollectionViewModelDelegate>)delegate; // Each NSString in the array starts a new section. Any other object is a new row (with exception of certain model-specific objects). - (id)initWithSectionedArray:(NSArray *)sectionedArray delegate:(id<NICollectionViewModelDelegate>)delegate; #pragma mark Accessing Objects - (id)objectAtIndexPath:(NSIndexPath *)indexPath; #pragma mark Creating Collection View Cells @property (nonatomic, NI_WEAK) id<NICollectionViewModelDelegate> delegate; @end /** * A protocol for NICollectionViewModel to fetch rows to be displayed for the collection view. * * @ingroup CollectionViewModels */ @protocol NICollectionViewModelDelegate <NSObject> @required /** * Fetches a collection view cell at a given index path with a given object. * * The implementation of this method will generally use object to customize the cell. */ - (UICollectionViewCell *)collectionViewModel:(NICollectionViewModel *)collectionViewModel cellForCollectionView:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object; @optional /** * Fetches a supplementary collection view element at a given indexPath. * * The value of the kind property and indexPath are implementation-dependent * based on the type of UICollectionViewLayout being used. */ - (UICollectionReusableView *)collectionViewModel:(NICollectionViewModel *)collectionViewModel collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath; @end /** * An object used in sectioned arrays to denote a section footer title. * * Meant to be used in a sectioned array for NICollectionViewModel. * * <h3>Example</h3> * * @code * [NICollectionViewModelFooter footerWithTitle:@"Footer"] * @endcode */ @interface NICollectionViewModelFooter : NSObject + (id)footerWithTitle:(NSString *)title; - (id)initWithTitle:(NSString *)title; @property (nonatomic, copy) NSString* title; @end /** @name Creating Collection View Models */ /** * Initializes a newly allocated static model with the given delegate and empty contents. * * This method can be used to create an empty model. * * @fn NICollectionViewModel::initWithDelegate: */ /** * Initializes a newly allocated static model with the contents of a list array. * * A list array is a one-dimensional array that defines a flat list of rows. There will be * no sectioning of contents in any way. * * <h3>Example</h3> * * @code * NSArray* contents = * [NSArray arrayWithObjects: * [NSDictionary dictionaryWithObject:@"Row 1" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 2" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 3" forKey:@"title"], * nil]; * [[NICollectionViewModel alloc] initWithListArray:contents delegate:self]; * @endcode * * @fn NICollectionViewModel::initWithListArray:delegate: */ /** * Initializes a newly allocated static model with the contents of a sectioned array. * * A sectioned array is a one-dimensional array that defines a list of sections and each * section's contents. Each NSString begins a new section and any other object defines a * row for the current section. * * <h3>Example</h3> * * @code * NSArray* contents = * [NSArray arrayWithObjects: * @"Section 1", * [NSDictionary dictionaryWithObject:@"Row 1" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 2" forKey:@"title"], * @"Section 2", * // This section is empty. * @"Section 3", * [NSDictionary dictionaryWithObject:@"Row 3" forKey:@"title"], * [NICollectionViewModelFooter footerWithTitle:@"Footer"], * nil]; * [[NICollectionViewModel alloc] initWithSectionedArray:contents delegate:self]; * @endcode * * @fn NICollectionViewModel::initWithSectionedArray:delegate: */ /** @name Accessing Objects */ /** * Returns the object at the given index path. * * If no object exists at the given index path (an invalid index path, for example) then nil * will be returned. * * @fn NICollectionViewModel::objectAtIndexPath: */ /** @name Creating Collection View Cells */ /** * A delegate used to fetch collection view cells for the data source. * * @fn NICollectionViewModel::delegate */
0xced/nimbus
src/collections/src/NICollectionViewModel.h
C
apache-2.0
6,258
#!/bin/sh -- mkdir -p build/debug cd build/debug cmake -DCMAKE_BUILD_TYPE=Debug ../.. make clean && make
amzn/ion-c
build-debug.sh
Shell
apache-2.0
106
/* * Copyright 2020 Nikita Shakarun * * 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 javax.microedition.amms.control.audio3d; public interface MacroscopicControl extends OrientationControl { public void setSize(int x, int y, int z); public int[] getSize(); }
nikita36078/J2ME-Loader
app/src/main/java/javax/microedition/amms/control/audio3d/MacroscopicControl.java
Java
apache-2.0
786
#!/bin/bash source common.sh echo "Precompiling templates" python -c \ "from dpxdt.server import app; \ app.jinja_env.compile_templates( './deployment/appengine/templates_compiled.zip')" echo "Starting deployment" appcfg.py update ./deployment/appengine
mabushadi/dpxdt
appengine_deploy.sh
Shell
apache-2.0
274
# - Find lzma # Find the native lzma includes and library # # lzma_INCLUDE_DIR - where to find lzma.h, etc. # lzma_LIBRARIES - List of libraries when using lzma. # lzma_FOUND - True if lzma found. set(lzma_NAMES lzma) find_library(lzma_LIBRARY NAMES ${lzma_NAMES} ) if (lzma_LIBRARY) set(lzma_FOUND TRUE) set( lzma_LIBRARIES ${lzma_LIBRARY}) else () set(lzma_FOUND FALSE) set( lzma_LIBRARIES ) endif () if (lzma_FOUND) message(STATUS "Found lzma: ${lzma_LIBRARY}") message(STATUS "Found lzma: ${lzma_LIBRARIES}") else () message(STATUS "Not Found lzma") if (lzma_FIND_REQUIRED) message(STATUS "Looked for lzma libraries named ${lzma_NAMES}.") message(FATAL_ERROR "Could NOT find lzma library") endif () endif () mark_as_advanced( lzma_LIBRARIES )
letconex/MMT
src/decoder-phrasebased/src/native/cmake_modules/Findlzma.cmake
CMake
apache-2.0
823
<!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_71) on Wed May 25 10:45:49 IRDT 2016 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class additional.Datacenter</title> <meta name="date" content="2016-05-25"> <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="Uses of Class additional.Datacenter"; } //--> </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><a href="../../additional/Datacenter.html" title="class in additional">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-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?additional/class-use/Datacenter.html" target="_top">Frames</a></li> <li><a href="Datacenter.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> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class additional.Datacenter" class="title">Uses of Class<br>additional.Datacenter</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</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="#additional">additional</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="additional"> <!-- --> </a> <h3>Uses of <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a> in <a href="../../additional/package-summary.html">additional</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../additional/package-summary.html">additional</a> that return <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</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="../../additional/Datacenter.html" title="class in additional">Datacenter</a></code></td> <td class="colLast"><span class="strong">Link.</span><code><strong><a href="../../additional/Link.html#getDatacenter_1()">getDatacenter_1</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a></code></td> <td class="colLast"><span class="strong">Link.</span><code><strong><a href="../../additional/Link.html#getDatacenter_2()">getDatacenter_2</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a></code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#getPrimaryNeighbor(additional.Datacenter)">getPrimaryNeighbor</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;datacenter)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a></code></td> <td class="colLast"><span class="strong">DataitemInfo.</span><code><strong><a href="../../additional/DataitemInfo.html#removeDatacentersList(int)">removeDatacentersList</a></strong>(int&nbsp;d)</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../additional/package-summary.html">additional</a> that return types with arguments of type <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</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>java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#bfs(java.util.List,%20additional.Datacenter)">bfs</a></strong>(java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;inDs, <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;source)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#getDatacenters()">getDatacenters</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.Map&lt;java.lang.Integer,<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;</code></td> <td class="colLast"><span class="strong">DataitemInfo.</span><code><strong><a href="../../additional/DataitemInfo.html#getDatacenters()">getDatacenters</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;</code></td> <td class="colLast"><span class="strong">Datacenter.</span><code><strong><a href="../../additional/Datacenter.html#getNeighbours()">getNeighbours</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.util.List&lt;java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&gt;</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#zoning(additional.Datacenter,%20additional.Datacenter,%20java.util.List)">zoning</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;d1, <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;d2, java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;ds)</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../additional/package-summary.html">additional</a> with parameters of type <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</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>void</code></td> <td class="colLast"><span class="strong">DataitemInfo.</span><code><strong><a href="../../additional/DataitemInfo.html#addToDatacentersList(additional.Datacenter)">addToDatacentersList</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;d)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">Datacenter.</span><code><strong><a href="../../additional/Datacenter.html#addToNeighbourDatacenterList(additional.Datacenter)">addToNeighbourDatacenterList</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;datacenter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#bfs(java.util.List,%20additional.Datacenter)">bfs</a></strong>(java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;inDs, <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;source)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a></code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#getPrimaryNeighbor(additional.Datacenter)">getPrimaryNeighbor</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;datacenter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><span class="strong">Datacenter.Router.</span><code><strong><a href="../../additional/Datacenter.Router.html#route(additional.Datacenter)">route</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;distination)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">Link.</span><code><strong><a href="../../additional/Link.html#setDatacenter_1(additional.Datacenter)">setDatacenter_1</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;datacenter_1)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">Link.</span><code><strong><a href="../../additional/Link.html#setDatacenter_2(additional.Datacenter)">setDatacenter_2</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;datacenter_2)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.util.List&lt;java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&gt;</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#zoning(additional.Datacenter,%20additional.Datacenter,%20java.util.List)">zoning</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;d1, <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;d2, java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;ds)</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Method parameters in <a href="../../additional/package-summary.html">additional</a> with type arguments of type <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</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>java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#bfs(java.util.List,%20additional.Datacenter)">bfs</a></strong>(java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;inDs, <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;source)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int[][]</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#getAdjacencyMatrix(java.util.List)">getAdjacencyMatrix</a></strong>(java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;datacenters)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">Datacenter.</span><code><strong><a href="../../additional/Datacenter.html#setNeighbours(java.util.List)">setNeighbours</a></strong>(java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;linked)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.util.List&lt;java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&gt;</code></td> <td class="colLast"><span class="strong">DatacentersTopology.</span><code><strong><a href="../../additional/DatacentersTopology.html#zoning(additional.Datacenter,%20additional.Datacenter,%20java.util.List)">zoning</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;d1, <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;d2, java.util.List&lt;<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&gt;&nbsp;ds)</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../additional/package-summary.html">additional</a> with parameters of type <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../additional/Link.html#Link(additional.Datacenter,%20additional.Datacenter)">Link</a></strong>(<a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;datacenter_1, <a href="../../additional/Datacenter.html" title="class in additional">Datacenter</a>&nbsp;datacenter_2)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= 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><a href="../../additional/Datacenter.html" title="class in additional">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-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?additional/class-use/Datacenter.html" target="_top">Frames</a></li> <li><a href="Datacenter.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> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
haghighi-ahmad/gmc-hdfssim
dist/javadoc/additional/class-use/Datacenter.html
HTML
apache-2.0
17,900
# Oxytropis immersa var. jinaliensis Ali VARIETY #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Oxytropis/Oxytropis immersa/Oxytropis immersa jinaliensis/README.md
Markdown
apache-2.0
196
// Copyright 2012-2013 Samplecount S.L. // // 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 "Methcla/Audio/Synth.hpp" #include <boost/type_traits/alignment_of.hpp> #include <algorithm> using namespace Methcla::Audio; using namespace Methcla::Memory; static const Alignment kBufferAlignment = kSIMDAlignment; Synth::Synth(Environment& env, NodeId nodeId, const SynthDef& synthDef, Methcla_PortCount numControlInputs, Methcla_PortCount numControlOutputs, Methcla_PortCount numAudioInputs, Methcla_PortCount numAudioOutputs, Methcla_Synth* synth, AudioInputConnection* audioInputConnections, AudioOutputConnection* audioOutputConnections, sample_t* controlBuffers, sample_t* audioBuffers) : Node(env, nodeId) , m_synthDef(synthDef) , m_numControlInputs(numControlInputs) , m_numControlOutputs(numControlOutputs) , m_numAudioInputs(numAudioInputs) , m_numAudioOutputs(numAudioOutputs) , m_sampleOffset(0.) , m_synth(synth) , m_audioInputConnections(audioInputConnections) , m_audioOutputConnections(audioOutputConnections) , m_controlBuffers(controlBuffers) , m_audioBuffers(audioBuffers) { // Initialize flags memset(&m_flags, 0, sizeof(m_flags)); m_flags.state = kStateInactive; // Align audio buffers m_audioBuffers = kBufferAlignment.align(audioBuffers); // Validate alignment assert( Alignment::isAligned(boost::alignment_of<AudioInputConnection>::value, (uintptr_t)m_audioInputConnections)); assert( Alignment::isAligned(boost::alignment_of<AudioOutputConnection>::value, (uintptr_t)m_audioOutputConnections)); assert(Alignment::isAligned(boost::alignment_of<sample_t>::value, (uintptr_t)m_controlBuffers)); assert(kBufferAlignment.isAligned(m_audioBuffers)); } Synth::~Synth() { Methcla_World world(env()); m_synthDef.destroy(&world, m_synth); } Synth* Synth::construct(Environment& env, NodeId nodeId, const SynthDef& synthDef, OSCPP::Server::ArgStream controls, OSCPP::Server::ArgStream options) { // Get synth options const Methcla_SynthOptions* synthOptions = synthDef.configure(options); Methcla_PortCount numControlInputs = 0; Methcla_PortCount numControlOutputs = 0; Methcla_PortCount numAudioInputs = 0; Methcla_PortCount numAudioOutputs = 0; // Get port counts. Methcla_PortDescriptor port; for (size_t i = 0; synthDef.portDescriptor(synthOptions, i, &port); i++) { switch (port.type) { case kMethcla_AudioPort: switch (port.direction) { case kMethcla_Input: numAudioInputs++; break; case kMethcla_Output: numAudioOutputs++; break; } break; case kMethcla_ControlPort: switch (port.direction) { case kMethcla_Input: numControlInputs++; break; case kMethcla_Output: numControlOutputs++; break; } } } // const size_t numControlInputs = synthDef.numControlInputs(); // const size_t numControlOutputs = synthDef.numControlOutputs(); // const size_t numAudioInputs = synthDef.numAudioInputs(); // const size_t numAudioOutputs = synthDef.numAudioOutputs(); const size_t blockSize = env.blockSize(); const size_t synthAllocSize = sizeof(Synth) + synthDef.instanceSize(); const size_t audioInputOffset = synthAllocSize; const size_t audioInputAllocSize = numAudioInputs * sizeof(AudioInputConnection); const size_t audioOutputOffset = audioInputOffset + audioInputAllocSize; const size_t audioOutputAllocSize = numAudioOutputs * sizeof(AudioOutputConnection); const size_t controlBufferOffset = audioOutputOffset + audioOutputAllocSize; const size_t controlBufferAllocSize = (numControlInputs + numControlOutputs) * sizeof(sample_t); const size_t audioBufferOffset = controlBufferOffset + controlBufferAllocSize; const size_t audioBufferAllocSize = (numAudioInputs + numAudioOutputs) * blockSize * sizeof(sample_t); const size_t allocSize = audioBufferOffset + audioBufferAllocSize + kBufferAlignment /* alignment margin */; char* mem = env.rtMem().allocOf<char>(allocSize); // Instantiate synth Synth* synth = new (mem) Synth(env, nodeId, synthDef, numControlInputs, numControlOutputs, numAudioInputs, numAudioOutputs, reinterpret_cast<Methcla_Synth*>(mem + sizeof(Synth)), reinterpret_cast<AudioInputConnection*>(mem + audioInputOffset), reinterpret_cast<AudioOutputConnection*>(mem + audioOutputOffset), reinterpret_cast<sample_t*>(mem + controlBufferOffset), reinterpret_cast<sample_t*>(mem + audioBufferOffset)); // Construct synth synth->construct(synthOptions); // Connect ports synth->connectPorts(synthOptions, controls); return synth; } Synth* Synth::fromSynth(Methcla_Synth* synth) { // NOTE: This needs to be adapted if Synth memory layout is changed! return reinterpret_cast<Synth*>(static_cast<char*>(synth) - sizeof(Synth)); } void Synth::construct(const Methcla_SynthOptions* synthOptions) { Methcla_World world(env()); m_synthDef.construct(&world, synthOptions, m_synth); } void Synth::connectPorts(const Methcla_SynthOptions* synthOptions, OSCPP::Server::ArgStream controls) { Methcla_PortDescriptor port; Methcla_PortCount controlInputIndex = 0; Methcla_PortCount controlOutputIndex = 0; Methcla_PortCount audioInputIndex = 0; Methcla_PortCount audioOutputIndex = 0; for (size_t i = 0; m_synthDef.portDescriptor(synthOptions, i, &port); i++) { switch (port.type) { case kMethcla_ControlPort: switch (port.direction) { case kMethcla_Input: { // Initialize with control value m_controlBuffers[controlInputIndex] = controls.next<float>(); sample_t* buffer = &m_controlBuffers[controlInputIndex]; m_synthDef.connect(m_synth, i, buffer); controlInputIndex++; }; break; case kMethcla_Output: { sample_t* buffer = &m_controlBuffers[numControlInputs() + controlOutputIndex]; m_synthDef.connect(m_synth, i, buffer); controlOutputIndex++; }; break; }; break; case kMethcla_AudioPort: switch (port.direction) { case kMethcla_Input: { new (&m_audioInputConnections[audioInputIndex]) AudioInputConnection(audioInputIndex); sample_t* buffer = m_audioBuffers + audioInputIndex * env().blockSize(); assert(kBufferAlignment.isAligned(buffer)); m_synthDef.connect(m_synth, i, buffer); audioInputIndex++; }; break; case kMethcla_Output: { new (&m_audioOutputConnections[audioOutputIndex]) AudioOutputConnection(audioOutputIndex); sample_t* buffer = m_audioBuffers + (numAudioInputs() + audioOutputIndex) * env().blockSize(); assert(kBufferAlignment.isAligned(buffer)); m_synthDef.connect(m_synth, i, buffer); audioOutputIndex++; }; break; }; break; } } } template <class T> struct IfIndex { IfIndex(Methcla_PortCount index) : m_index(index) {} inline bool operator()(const T& x) const { return x.index() == m_index; } private: Methcla_PortCount m_index; }; template <class T> struct ByBusId { inline bool operator()(const T& a, const T& b) const { return a.busId() < b.busId(); } }; void Synth::mapInput(Methcla_PortCount index, const AudioBusId& busId, Methcla_BusMappingFlags flags) { AudioInputConnection* const begin = m_audioInputConnections; AudioInputConnection* const end = begin + numAudioInputs(); AudioInputConnection* conn = std::find_if(begin, end, IfIndex<AudioInputConnection>(index)); if (conn != end) { AudioBus* bus = flags & kMethcla_BusMappingExternal ? env().externalAudioInput(busId) : env().audioBus(busId); conn->connect(bus, flags); } } void Synth::mapOutput(Methcla_PortCount index, const AudioBusId& busId, Methcla_BusMappingFlags flags) { AudioOutputConnection* const begin = m_audioOutputConnections; AudioOutputConnection* const end = begin + numAudioOutputs(); AudioOutputConnection* conn = std::find_if(begin, end, IfIndex<AudioOutputConnection>(index)); if (conn != end) { AudioBus* bus = flags & kMethcla_BusMappingExternal ? env().externalAudioOutput(busId) : env().audioBus(busId); conn->connect(bus, flags); } } void Synth::activate(double sampleOffset) { if (m_flags.state == kStateInactive) { m_sampleOffset = sampleOffset; Methcla_World world(env()); m_synthDef.activate(&world, m_synth); m_flags.state = kStateActivating; } } void Synth::doProcess(size_t numFrames) { // Sort connections by bus id (if necessary) // Only needed for bus locking protocol in a parallel implementation // if (m_flags.audioInputConnectionsChanged) { // m_flags.audioInputConnectionsChanged = false; // std::sort( m_audioInputConnections // , m_audioInputConnections + numAudioInputs() // , ByBusId<AudioInputConnection>() ); // } // if (m_flags.audioOutputConnectionsChanged) { // m_flags.audioOutputConnectionsChanged = false; // std::sort( m_audioOutputConnections // , m_audioOutputConnections + numAudioOutputs() // , ByBusId<AudioOutputConnection>() ); // } Environment& env = this->env(); const size_t blockSize = env.blockSize(); sample_t* const inputBuffers = m_audioBuffers; sample_t* const outputBuffers = m_audioBuffers + numAudioInputs() * blockSize; if (m_flags.state == kStateActive) { // TODO: Iterate only over connected connections (by tracking number of // connections). for (size_t i = 0; i < numAudioInputs(); i++) { AudioInputConnection& x = m_audioInputConnections[i]; x.read(env, numFrames, inputBuffers + x.index() * blockSize); } Methcla_World world(env); m_synthDef.process(&world, m_synth, numFrames); for (size_t i = 0; i < numAudioOutputs(); i++) { AudioOutputConnection& x = m_audioOutputConnections[i]; x.write(env, numFrames, outputBuffers + x.index() * blockSize); } // Reset triggers // if (m_flags.test(kHasTriggerInput)) { // for (size_t i=0; i < numControlInputs(); i++) { // if (synthDef().controlInputSpec(i).flags & // kMethclaControlTrigger) { // *controlInput(i) = 0.f; // } // } // } } else if (m_flags.state == kStateActivating) { const size_t sampleOffset = std::floor(m_sampleOffset); assert(m_sampleOffset < (double)numFrames && sampleOffset < numFrames); const size_t remainingFrames = numFrames - sampleOffset; for (size_t i = 0; i < numAudioInputs(); i++) { AudioInputConnection& x = m_audioInputConnections[i]; x.read(env, remainingFrames, inputBuffers + x.index() * blockSize, sampleOffset); } Methcla_World world(env); m_synthDef.process(&world, m_synth, remainingFrames); for (size_t i = 0; i < numAudioOutputs(); i++) { AudioOutputConnection& x = m_audioOutputConnections[i]; x.write(env, remainingFrames, outputBuffers + x.index() * blockSize, sampleOffset); } m_flags.state = kStateActive; } }
samplecount/methcla
src/Methcla/Audio/Synth.cpp
C++
apache-2.0
14,017
/* * 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.marketplacecommerceanalytics.model; import java.io.Serializable; import javax.annotation.Generated; /** * Container for the result of the GenerateDataSet operation. * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/marketplacecommerceanalytics-2015-07-01/GenerateDataSet" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GenerateDataSetResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * A unique identifier representing a specific request to the GenerateDataSet operation. This identifier can be used * to correlate a request with notifications from the SNS topic. */ private String dataSetRequestId; /** * A unique identifier representing a specific request to the GenerateDataSet operation. This identifier can be used * to correlate a request with notifications from the SNS topic. * * @param dataSetRequestId * A unique identifier representing a specific request to the GenerateDataSet operation. This identifier can * be used to correlate a request with notifications from the SNS topic. */ public void setDataSetRequestId(String dataSetRequestId) { this.dataSetRequestId = dataSetRequestId; } /** * A unique identifier representing a specific request to the GenerateDataSet operation. This identifier can be used * to correlate a request with notifications from the SNS topic. * * @return A unique identifier representing a specific request to the GenerateDataSet operation. This identifier can * be used to correlate a request with notifications from the SNS topic. */ public String getDataSetRequestId() { return this.dataSetRequestId; } /** * A unique identifier representing a specific request to the GenerateDataSet operation. This identifier can be used * to correlate a request with notifications from the SNS topic. * * @param dataSetRequestId * A unique identifier representing a specific request to the GenerateDataSet operation. This identifier can * be used to correlate a request with notifications from the SNS topic. * @return Returns a reference to this object so that method calls can be chained together. */ public GenerateDataSetResult withDataSetRequestId(String dataSetRequestId) { setDataSetRequestId(dataSetRequestId); 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 (getDataSetRequestId() != null) sb.append("DataSetRequestId: ").append(getDataSetRequestId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GenerateDataSetResult == false) return false; GenerateDataSetResult other = (GenerateDataSetResult) obj; if (other.getDataSetRequestId() == null ^ this.getDataSetRequestId() == null) return false; if (other.getDataSetRequestId() != null && other.getDataSetRequestId().equals(this.getDataSetRequestId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDataSetRequestId() == null) ? 0 : getDataSetRequestId().hashCode()); return hashCode; } @Override public GenerateDataSetResult clone() { try { return (GenerateDataSetResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-marketplacecommerceanalytics/src/main/java/com/amazonaws/services/marketplacecommerceanalytics/model/GenerateDataSetResult.java
Java
apache-2.0
4,956
#region Copyright // Copyright 2014 Myrcon Pty. Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Potato.Database.Shared.Builders; using Potato.Database.Shared.Builders.Equalities; using Potato.Database.Shared.Builders.FieldTypes; using Potato.Database.Shared.Builders.Logicals; using Potato.Database.Shared.Builders.Methods.Data; using Potato.Database.Shared.Builders.Methods.Schema; using Potato.Database.Shared.Builders.Modifiers; using Potato.Database.Shared.Builders.Statements; using Potato.Database.Shared.Builders.Values; using Nullable = Potato.Database.Shared.Builders.Modifiers.Nullable; namespace Potato.Database.Shared.Serializers.Sql { /// <summary> /// Serializer for MySQL support. /// </summary> public class SerializerMySql : SerializerSql { /// <summary> /// Parses an index /// </summary> /// <param name="index"></param> /// <returns></returns> protected virtual String ParseIndex(Index index) { String parsed = String.Empty; // PRIMARY KEY (`Name`) if (index.Any(attribute => attribute is Primary)) { parsed = String.Format("PRIMARY KEY ({0})", String.Join(", ", this.ParseSortings(index))); } return parsed; } /// <summary> /// Parses the list of indexes /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseIndices(IDatabaseObject query) { return query.Where(statement => statement is Index).Union(new List<IDatabaseObject>() { query }.Where(owner => owner is Index)).Select(index => this.ParseIndex(index as Index)).Where(index => String.IsNullOrEmpty(index) == false).ToList(); } /// <summary> /// Formats the database name. /// </summary> /// <param name="database"></param> /// <returns></returns> protected virtual String ParseDatabase(Builders.Database database) { return String.Format("`{0}`", database.Name); } /// <summary> /// Parses the list of databases. /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseDatabases(IDatabaseObject query) { return query.Where(statement => statement is Builders.Database).Select(database => this.ParseDatabase(database as Builders.Database)).ToList(); } /// <summary> /// Fetches the method from the type of query /// </summary> /// <param name="method"></param> protected virtual List<string> ParseMethod(IMethod method) { List<string> parsed = new List<string>(); if (method is Find) { parsed.Add("SELECT"); } else if (method is Save || method is Merge) { parsed.Add("INSERT"); } else if (method is Create) { if (method.Any(statement => statement is Builders.Database) == true || method.Any(statement => statement is Collection) == true) { parsed.Add("CREATE"); } else if (method.Any(statement => statement is Field) == true) { parsed.Add("ADD"); } } else if (method is Modify) { parsed.Add("UPDATE"); } else if (method is Remove) { parsed.Add("DELETE"); } else if (method is Drop) { parsed.Add("DROP"); } else if (method is Index) { parsed.Add("ALTER"); } else if (method is Alter) { parsed.Add("ALTER"); } return parsed; } protected virtual String ParseCollection(Collection collection) { return String.Format("`{0}`", collection.Name); } protected virtual String ParseSort(Sort sort) { Collection collection = sort.FirstOrDefault(statement => statement is Collection) as Collection; List<String> parsed = new List<String> { collection == null ? String.Format("`{0}`", sort.Name) : String.Format("`{0}`.`{1}`", collection.Name, sort.Name) }; if (sort.Any(attribute => attribute is Descending)) { parsed.Add("DESC"); } return String.Join(" ", parsed); } protected virtual String ParseType(FieldType type) { List<String> parsed = new List<String>(); Length length = type.FirstOrDefault(attribute => attribute is Length) as Length; Unsigned unsigned = type.FirstOrDefault(attribute => attribute is Unsigned) as Unsigned; if (type is StringType) { parsed.Add(String.Format("VARCHAR({0})", length == null ? 255 : length.Value)); } else if (type is IntegerType) { parsed.Add("INT"); if (unsigned != null) { parsed.Add("UNSIGNED"); } } else if (type is DateTimeType) { parsed.Add("DATETIME"); } parsed.Add(type.Any(attribute => attribute is Nullable) == true ? "NULL" : "NOT NULL"); if (type.Any(attribute => attribute is AutoIncrement) == true) { parsed.Add("AUTO_INCREMENT"); } return String.Join(" ", parsed); } protected virtual String ParseField(Field field) { List<String> parsed = new List<String>(); if (field.Any(attribute => attribute is Distinct)) { parsed.Add("DISTINCT"); } Collection collection = field.FirstOrDefault(statement => statement is Collection) as Collection; parsed.Add(collection == null ? String.Format("`{0}`", field.Name) : String.Format("`{0}`.`{1}`", collection.Name, field.Name)); if (field.Any(attribute => attribute is FieldType)) { parsed.Add(this.ParseType(field.First(attribute => attribute is FieldType) as FieldType)); } return String.Join(" ", parsed); } protected virtual String ParseEquality(Equality equality) { String parsed = ""; if (equality is Equals) { parsed = "="; } else if (equality is GreaterThan) { parsed = ">"; } else if (equality is GreaterThanEquals) { parsed = ">="; } else if (equality is LessThan) { parsed = "<"; } else if (equality is LessThanEquals) { parsed = "<="; } return parsed; } protected virtual String ParseValue(Value value) { String parsed = ""; DateTimeValue dateTime = value as DateTimeValue; NumericValue numeric = value as NumericValue; StringValue @string = value as StringValue; RawValue raw = value as RawValue; if (dateTime != null) { parsed = String.Format(@"""{0}""", dateTime.Data.ToString("yyyy-MM-dd HH:mm:ss")); } else if (numeric != null) { if (numeric.Long.HasValue == true) { parsed = numeric.Long.Value.ToString(CultureInfo.InvariantCulture); } else if (numeric.Double.HasValue == true) { parsed = numeric.Double.Value.ToString(CultureInfo.InvariantCulture); } } else if (@string != null) { // Note that the string should have been parsed by the driver to escape it. parsed = String.Format(@"""{0}""", @string.Data); } else if (raw != null) { parsed = raw.Data; } return parsed; } protected virtual List<String> ParseFields(IDatabaseObject query) { List<String> parsed = new List<String>(); // If we have a distinct field, but no specific fields if (query.Any(attribute => attribute is Distinct) == true && query.Any(logical => logical is Field) == false) { parsed.Add("DISTINCT *"); } // If we have a distinct field and only one field available else if (query.Any(attribute => attribute is Distinct) == true && query.Count(logical => logical is Field) == 1) { Field field = query.First(logical => logical is Field) as Field; if (field != null) { field.Add(query.First(attribute => attribute is Distinct)); parsed.Add(this.ParseField(field)); } } // Else, no distinct in the global query space else { parsed.AddRange(query.Where(logical => logical is Field).Select(field => this.ParseField(field as Field))); } return parsed; } /// <summary> /// Parse collections for all methods, used like "FROM ..." /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseCollections(IDatabaseObject query) { return query.Where(logical => logical is Collection).Select(collection => this.ParseCollection(collection as Collection)).ToList(); } protected virtual List<String> ParseEqualities(IDatabaseObject query) { List<String> equalities = new List<String>(); foreach (Equality equality in query.Where(statement => statement is Equality)) { Field field = equality.FirstOrDefault(statement => statement is Field) as Field; Value value = equality.FirstOrDefault(statement => statement is Value) as Value; if (field != null && value != null) { equalities.Add(String.Format("{0} {1} {2}", this.ParseField(field), this.ParseEquality(equality), this.ParseValue(value))); } } return equalities; } /// <summary> /// Parse any logicals /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseLogicals(IDatabaseObject query) { List<String> logicals = new List<String>(); foreach (Logical logical in query.Where(logical => logical is Logical)) { String separator = logical is Or ? " OR " : " AND "; String childLogicals = String.Join(separator, this.ParseLogicals(logical)); String childEqualities = String.Join(separator, this.ParseEqualities(logical)); if (String.IsNullOrEmpty(childLogicals) == false) logicals.Add(String.Format("({0})", childLogicals)); if (String.IsNullOrEmpty(childEqualities) == false) logicals.Add(String.Format("({0})", childEqualities)); } return logicals; } /// <summary> /// Parse the conditions of a SELECT, UPDATE and DELETE query. Used like "SELECT ... " /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseConditions(IDatabaseObject query) { List<String> conditions = this.ParseLogicals(query); conditions.AddRange(this.ParseEqualities(query)); return conditions; } /// <summary> /// Parse field assignments, similar to conditions, but without the conditionals. /// </summary> /// <param name="query"></param> /// <returns></returns> protected virtual List<String> ParseAssignments(IDatabaseObject query) { List<String> assignments = new List<String>(); foreach (Assignment assignment in query.Where(statement => statement is Assignment)) { Field field = assignment.FirstOrDefault(statement => statement is Field) as Field; Value value = assignment.FirstOrDefault(statement => statement is Value) as Value; if (field != null && value != null) { assignments.Add(String.Format("{0} = {1}", this.ParseField(field), this.ParseValue(value))); } } return assignments; } protected virtual List<String> ParseSortings(IDatabaseObject query) { return query.Where(sort => sort is Sort).Select(sort => this.ParseSort(sort as Sort)).ToList(); } public override ICompiledQuery Compile(IParsedQuery parsed) { CompiledQuery serializedQuery = new CompiledQuery() { Children = parsed.Children.Select(this.Compile).Where(child => child != null).ToList(), Root = parsed.Root, Methods = parsed.Methods, Skip = parsed.Skip, Limit = parsed.Limit }; List<String> compiled = new List<String>() { parsed.Methods.FirstOrDefault() }; if (parsed.Root is Merge) { ICompiledQuery save = serializedQuery.Children.FirstOrDefault(child => child.Root is Save); ICompiledQuery modify = serializedQuery.Children.FirstOrDefault(child => child.Root is Modify); if (save != null && modify != null) { compiled.Add("INTO"); compiled.Add(save.Collections.FirstOrDefault()); compiled.Add("SET"); compiled.Add(save.Assignments.FirstOrDefault()); compiled.Add("ON DUPLICATE KEY UPDATE"); compiled.Add(modify.Assignments.FirstOrDefault()); } } else if (parsed.Root is Index) { Primary primary = parsed.Root.FirstOrDefault(attribute => attribute is Primary) as Primary; Unique unique = parsed.Root.FirstOrDefault(attribute => attribute is Unique) as Unique; if (primary == null) { compiled.Add("TABLE"); if (parsed.Collections.Any() == true) { serializedQuery.Collections.Add(String.Join(", ", parsed.Collections)); compiled.Add(serializedQuery.Collections.FirstOrDefault()); } if (unique != null) { compiled.Add("ADD UNIQUE INDEX"); // todo move the name element to a modifier? compiled.Add(String.Format("`{0}`", ((Index)parsed.Root).Name)); } // INDEX `Name_INDEX` (`Name` ASC) else { compiled.Add("ADD INDEX"); // todo move the name element to a modifier? compiled.Add(String.Format("`{0}`", ((Index)parsed.Root).Name)); } if (parsed.Sortings.Any() == true) { serializedQuery.Sortings.Add(String.Join(", ", parsed.Sortings)); compiled.Add(String.Format("({0})", serializedQuery.Sortings.FirstOrDefault())); } } else { serializedQuery = null; } } else if (parsed.Root is Alter) { if (parsed.Collections.Any() == true) { compiled.Add("TABLE"); serializedQuery.Collections.Add(String.Join(", ", parsed.Collections)); compiled.Add(serializedQuery.Collections.FirstOrDefault()); } compiled.Add(String.Join(", ", serializedQuery.Children.Where(child => child.Root is Create || child.Root is Drop).SelectMany(child => child.Compiled))); } else if (parsed.Root is Find) { serializedQuery.Fields = new List<String>(parsed.Fields); compiled.Add(parsed.Fields.Any() == true ? String.Join(", ", parsed.Fields) : "*"); if (parsed.Collections.Any() == true) { serializedQuery.Collections.Add(String.Join(", ", parsed.Collections)); compiled.Add("FROM"); compiled.Add(serializedQuery.Collections.FirstOrDefault()); } if (parsed.Conditions.Any() == true) { serializedQuery.Conditions.Add(String.Join(" AND ", parsed.Conditions)); compiled.Add("WHERE"); compiled.Add(serializedQuery.Conditions.FirstOrDefault()); } if (parsed.Sortings.Any() == true) { serializedQuery.Sortings.Add(String.Join(", ", parsed.Sortings)); compiled.Add("ORDER BY"); compiled.Add(serializedQuery.Sortings.FirstOrDefault()); } if (parsed.Limit != null) { compiled.Add("LIMIT"); compiled.Add(parsed.Limit.Value.ToString(CultureInfo.InvariantCulture)); } if (parsed.Skip != null) { compiled.Add("OFFSET"); compiled.Add(parsed.Skip.Value.ToString(CultureInfo.InvariantCulture)); } } else if (parsed.Root is Create) { if (parsed.Databases.Any() == true) { serializedQuery.Databases.Add(parsed.Databases.FirstOrDefault()); compiled.Add("DATABASE"); compiled.Add(serializedQuery.Databases.FirstOrDefault()); } else if (parsed.Collections.Any() == true) { compiled.Add("TABLE"); if (parsed.Root.Any(modifier => modifier is IfNotExists) == true) { compiled.Add("IF NOT EXISTS"); } compiled.Add(parsed.Collections.FirstOrDefault()); if (parsed.Indices.Any() == true) { List<String> fieldsIndicesCombination = new List<String>(parsed.Fields); fieldsIndicesCombination.AddRange(parsed.Indices); serializedQuery.Indices.Add(String.Join(", ", fieldsIndicesCombination.ToArray())); compiled.Add(String.Format("({0})", serializedQuery.Indices.FirstOrDefault())); } else { compiled.Add(String.Format("({0})", String.Join(", ", parsed.Fields.ToArray()))); } } else if (parsed.Fields.Any() == true) { compiled.Add("COLUMN"); compiled.Add(String.Join(", ", parsed.Fields.ToArray())); } } else if (parsed.Root is Save) { if (parsed.Collections.Any() == true) { compiled.Add("INTO"); serializedQuery.Collections.Add(parsed.Collections.FirstOrDefault()); compiled.Add(serializedQuery.Collections.FirstOrDefault()); } if (parsed.Assignments.Any() == true) { serializedQuery.Assignments.Add(String.Join(", ", parsed.Assignments)); compiled.Add("SET"); compiled.Add(serializedQuery.Assignments.FirstOrDefault()); } } else if (parsed.Root is Modify) { if (parsed.Collections.Any() == true) { serializedQuery.Collections.Add(String.Join(", ", parsed.Collections)); compiled.Add(serializedQuery.Collections.FirstOrDefault()); } if (parsed.Assignments.Any() == true) { serializedQuery.Assignments.Add(String.Join(", ", parsed.Assignments)); compiled.Add("SET"); compiled.Add(serializedQuery.Assignments.FirstOrDefault()); } if (parsed.Conditions.Any() == true) { serializedQuery.Conditions.Add(String.Join(" AND ", parsed.Conditions)); compiled.Add("WHERE"); compiled.Add(serializedQuery.Conditions.FirstOrDefault()); } } else if (parsed.Root is Remove) { if (parsed.Collections.Any() == true) { serializedQuery.Collections.Add(String.Join(", ", parsed.Collections)); compiled.Add("FROM"); compiled.Add(serializedQuery.Collections.FirstOrDefault()); } if (parsed.Conditions.Any() == true) { serializedQuery.Conditions.Add(String.Join(" AND ", parsed.Conditions)); compiled.Add("WHERE"); compiled.Add(serializedQuery.Conditions.FirstOrDefault()); } } else if (parsed.Root is Drop) { if (parsed.Databases.Any() == true) { serializedQuery.Databases.Add(parsed.Databases.FirstOrDefault()); compiled.Add("DATABASE"); compiled.Add(serializedQuery.Databases.FirstOrDefault()); } else if (parsed.Collections.Any() == true) { compiled.Add("TABLE"); serializedQuery.Collections.Add(parsed.Collections.FirstOrDefault()); compiled.Add(serializedQuery.Collections.FirstOrDefault()); } else if (parsed.Fields.Any() == true) { compiled.Add("COLUMN"); compiled.Add(String.Join(", ", parsed.Fields.ToArray())); } } if (serializedQuery != null) serializedQuery.Compiled.Add(String.Join(" ", compiled)); return serializedQuery; } public override ISerializer Parse(IMethod method, IParsedQuery parsed) { parsed.Root = method; parsed.Children = this.ParseChildren(method); parsed.Methods = this.ParseMethod(method); parsed.Skip = this.ParseSkip(method); parsed.Limit = this.ParseLimit(method); parsed.Databases = this.ParseDatabases(method); parsed.Indices = this.ParseIndices(method); parsed.Fields = this.ParseFields(method); parsed.Assignments = this.ParseAssignments(method); parsed.Conditions = this.ParseConditions(method); parsed.Collections = this.ParseCollections(method); parsed.Sortings = this.ParseSortings(method); return this; } } }
phogue/Potato
src/Potato.Database.Shared/Serializers/Sql/SerializerMySql.cs
C#
apache-2.0
23,724
# Chrysophyllum roxburghii G.Don SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Sapotaceae/Chrysophyllum/Chrysophyllum roxburghii/README.md
Markdown
apache-2.0
188
/** * @widgetClass Structure class * @package wof.bizWidget * @copyright author * @Time: 13-9-21 下午08:46 */ wof.bizWidget.ObjectInspector = function (root) { this.getDomInstance().mousedown(function (event) { event.stopPropagation(); }); }; wof.bizWidget.ObjectInspector.prototype = { _initFlag: null, _getCurrentStructureJson: function (root) { var convertInstanceToJson = function (instances) { var jsonArray = '[', index = 0; if (instances) { for (var i = 0; i < instances.length; i++) { var instance = instances[i], className = instance.getClassName(), id = instance.getId(); if (!id || !className || className.indexOf('Spanner') >= 0) { continue; } if (index > 0) { jsonArray += ','; } index++; var children = instance.childNodes(); if (children.length) { jsonArray += '{"name" : "' + className + '","oid" : "' + id + '"'; var childrenJson = convertInstanceToJson(children); if (childrenJson) { jsonArray += ',"children" : ' + childrenJson; } jsonArray += '}'; } else { jsonArray += '{"name" : "' + className + '","oid" : "' + id + '"}'; } } } if (index == 0) { return null; } return jsonArray += ']'; }, jsonStr = ''; if (root) { var instances = []; root.children().each(function () { var oid = jQuery(this).attr('oid'), instance = wof.util.ObjectManager.get(oid); if (instance) { instances.push(instance); } }); jsonStr = convertInstanceToJson(instances); return JSON.parse(jsonStr); } return []; }, //选择实现 beforeRender: function () { if (!this._initFlag) { var that = this, tree = new wof.widget.Tree(); tree.setIsInside(true); tree.setNodes(this._getCurrentStructureJson(jQuery('#content'))); tree.onClick = function (e, treeId, treeNode) { if (treeNode.oid) { var prevSelect = this.getZTreeObj().setting._prevSelect; if (prevSelect) { prevSelect.node.css('border', prevSelect.border); } var node = $('*[oid="' + treeNode.oid + '"]'); var oldBorder = node.css('border'); node.css('border', '1px solid red'); this.getZTreeObj().setting._prevSelect = {node: node, border: oldBorder}; } }; tree.appendTo(this); this._initFlag = true; } }, //----------必须实现---------- render: function () { }, //选择实现 afterRender: function () { }, /** * getData/setData 方法定义 */ //----------必须实现---------- getData: function () { return { }; }, //----------必须实现---------- setData: function (data) { } };
xlyyc/wof
src/wof/bizWidget/ObjectInspector.js
JavaScript
apache-2.0
3,841
package cmd import ( "fmt" "io/ioutil" "os" "path/filepath" "reflect" "sort" "strings" "testing" kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" buildapi "github.com/openshift/origin/pkg/build/api" client "github.com/openshift/origin/pkg/client/testclient" deploy "github.com/openshift/origin/pkg/deploy/api" "github.com/openshift/origin/pkg/dockerregistry" "github.com/openshift/origin/pkg/generate/app" "github.com/openshift/origin/pkg/generate/dockerfile" "github.com/openshift/origin/pkg/generate/source" imageapi "github.com/openshift/origin/pkg/image/api" ) func TestAddArguments(t *testing.T) { tmpDir, err := ioutil.TempDir("", "test-newapp") if err != nil { t.Fatalf("Unexpected error: %v", err) } defer os.RemoveAll(tmpDir) testDir := filepath.Join(tmpDir, "test/one/two/three") err = os.MkdirAll(testDir, 0777) if err != nil { t.Fatalf("Unexpected error: %v", err) } tests := map[string]struct { args []string env util.StringList parms util.StringList repos util.StringList components util.StringList unknown []string }{ "components": { args: []string{"one", "two+three", "four~five"}, components: util.StringList{"one", "two+three", "four~five"}, unknown: []string{}, }, "source": { args: []string{".", testDir, "git://server/repo.git"}, repos: util.StringList{".", testDir, "git://server/repo.git"}, unknown: []string{}, }, "env": { args: []string{"first=one", "second=two", "third=three"}, env: util.StringList{"first=one", "second=two", "third=three"}, unknown: []string{}, }, "mix 1": { args: []string{"git://server/repo.git", "mysql+ruby~git@test.server/repo.git", "env1=test", "ruby-helloworld-sample"}, repos: util.StringList{"git://server/repo.git"}, components: util.StringList{"mysql+ruby~git@test.server/repo.git", "ruby-helloworld-sample"}, env: util.StringList{"env1=test"}, unknown: []string{}, }, } for n, c := range tests { a := AppConfig{} unknown := a.AddArguments(c.args) if !reflect.DeepEqual(a.Environment, c.env) { t.Errorf("%s: Different env variables. Expected: %v, Actual: %v", n, c.env, a.Environment) } if !reflect.DeepEqual(a.SourceRepositories, c.repos) { t.Errorf("%s: Different source repos. Expected: %v, Actual: %v", n, c.repos, a.SourceRepositories) } if !reflect.DeepEqual(a.Components, c.components) { t.Errorf("%s: Different components. Expected: %v, Actual: %v", n, c.components, a.Components) } if !reflect.DeepEqual(unknown, c.unknown) { t.Errorf("%s: Different unknown result. Expected: %v, Actual: %v", n, c.unknown, unknown) } } } func TestValidate(t *testing.T) { tests := map[string]struct { cfg AppConfig componentValues []string sourceRepoLocations []string env map[string]string parms map[string]string }{ "components": { cfg: AppConfig{ Components: util.StringList{"one", "two", "three/four"}, }, componentValues: []string{"one", "two", "three/four"}, sourceRepoLocations: []string{}, env: map[string]string{}, parms: map[string]string{}, }, "sourcerepos": { cfg: AppConfig{ SourceRepositories: []string{".", "/test/var/src", "https://server/repo.git"}, }, componentValues: []string{}, sourceRepoLocations: []string{".", "/test/var/src", "https://server/repo.git"}, env: map[string]string{}, parms: map[string]string{}, }, "git+sshsourcerepos": { cfg: AppConfig{ SourceRepositories: []string{"git@github.com:openshift/ruby-hello-world.git"}, }, componentValues: []string{}, sourceRepoLocations: []string{"git@github.com:openshift/ruby-hello-world.git"}, env: map[string]string{}, parms: map[string]string{}, }, "envs": { cfg: AppConfig{ Environment: util.StringList{"one=first", "two=second", "three=third"}, }, componentValues: []string{}, sourceRepoLocations: []string{}, env: map[string]string{"one": "first", "two": "second", "three": "third"}, parms: map[string]string{}, }, "component+source": { cfg: AppConfig{ Components: util.StringList{"one~https://server/repo.git"}, }, componentValues: []string{"one"}, sourceRepoLocations: []string{"https://server/repo.git"}, env: map[string]string{}, parms: map[string]string{}, }, "components+source": { cfg: AppConfig{ Components: util.StringList{"mysql+ruby~git://github.com/namespace/repo.git"}, }, componentValues: []string{"mysql", "ruby"}, sourceRepoLocations: []string{"git://github.com/namespace/repo.git"}, env: map[string]string{}, parms: map[string]string{}, }, "components+parms": { cfg: AppConfig{ Components: util.StringList{"ruby-helloworld-sample"}, TemplateParameters: util.StringList{"one=first", "two=second"}, }, componentValues: []string{"ruby-helloworld-sample"}, sourceRepoLocations: []string{}, env: map[string]string{}, parms: map[string]string{ "one": "first", "two": "second", }, }, } for n, c := range tests { cr, repos, env, parms, err := c.cfg.validate() if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) } compValues := []string{} for _, r := range cr { compValues = append(compValues, r.Input().Value) } if !reflect.DeepEqual(c.componentValues, compValues) { t.Errorf("%s: Component values don't match. Expected: %v, Got: %v", n, c.componentValues, compValues) } repoLocations := []string{} for _, r := range repos { repoLocations = append(repoLocations, r.String()) } if !reflect.DeepEqual(c.sourceRepoLocations, repoLocations) { t.Errorf("%s: Repository locations don't match. Expected: %v, Got: %v", n, c.sourceRepoLocations, repoLocations) } if len(env) != len(c.env) { t.Errorf("%s: Environment variables don't match. Expected: %v, Got: %v", n, c.env, env) } for e, v := range env { if c.env[e] != v { t.Errorf("%s: Environment variables don't match. Expected: %v, Got: %v", n, c.env, env) break } } if len(parms) != len(c.parms) { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) } for p, v := range parms { if c.parms[p] != v { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) break } } } } func TestBuildTemplates(t *testing.T) { tests := map[string]struct { templateName string namespace string parms map[string]string }{ "simple": { templateName: "first-stored-template", namespace: "default", parms: map[string]string{}, }, } for n, c := range tests { appCfg := AppConfig{} appCfg.SetOpenShiftClient(&client.Fake{}, c.namespace) appCfg.AddArguments([]string{c.templateName}) appCfg.TemplateParameters = util.StringList{} for k, v := range c.parms { appCfg.TemplateParameters.Set(fmt.Sprintf("%v=%v", k, v)) } components, _, _, parms, err := appCfg.validate() if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) } err = appCfg.resolve(components) if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) } _, err = appCfg.buildTemplates(components, app.Environment(parms)) if err != nil { t.Errorf("%s: Unexpected error: %v", n, err) } for _, component := range components { match := component.Input().Match if !match.IsTemplate() { t.Errorf("%s: Expected template match, got: %v", n, match) } if c.templateName != match.Name { t.Errorf("%s: Expected template name %q, got: %q", n, c.templateName, match.Name) } if len(parms) != len(c.parms) { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) } for p, v := range parms { if c.parms[p] != v { t.Errorf("%s: Template parameters don't match. Expected: %v, Got: %v", n, c.parms, parms) break } } } } } func TestEnsureHasSource(t *testing.T) { tests := []struct { name string cfg AppConfig components app.ComponentReferences repositories []*app.SourceRepository expectedErr string }{ { name: "One requiresSource, multiple repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: app.MockSourceRepositories(), expectedErr: "there are multiple code locations provided - use one of the following suggestions", }, { name: "Multiple requiresSource, multiple repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: app.MockSourceRepositories(), expectedErr: "Use '[image]~[repo]' to declare which code goes with which image", }, { name: "One requiresSource, no repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: []*app.SourceRepository{}, expectedErr: "you must specify a repository via --code", }, { name: "Multiple requiresSource, no repositories", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), app.ComponentReference(&app.ComponentInput{ ExpectToBuild: true, }), }, repositories: []*app.SourceRepository{}, expectedErr: "you must provide at least one source code repository", }, { name: "Successful - one repository", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: false, }), }, repositories: []*app.SourceRepository{app.MockSourceRepositories()[0]}, expectedErr: "", }, { name: "Successful - no requiresSource", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ ExpectToBuild: false, }), }, repositories: app.MockSourceRepositories(), expectedErr: "", }, } for _, test := range tests { err := test.cfg.ensureHasSource(test.components, test.repositories) if err != nil { if !strings.Contains(err.Error(), test.expectedErr) { t.Errorf("%s: Invalid error: Expected %s, got %v", test.name, test.expectedErr, err) } } else if len(test.expectedErr) != 0 { t.Errorf("%s: Expected %s error but got none", test.name, test.expectedErr) } } } func TestResolve(t *testing.T) { tests := []struct { name string cfg AppConfig components app.ComponentReferences expectedErr string }{ { name: "Resolver error", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ Value: "mysql:invalid", Resolver: app.DockerRegistryResolver{ Client: dockerregistry.NewClient(), }, })}, expectedErr: `tag "invalid" has not been set`, }, { name: "Successful mysql builder", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ Value: "mysql", Match: &app.ComponentMatch{ Builder: true, }, })}, expectedErr: "", }, { name: "Unable to build source code", components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ Value: "mysql", ExpectToBuild: true, })}, expectedErr: "no resolver", }, { name: "Successful docker build", cfg: AppConfig{ Strategy: "docker", }, components: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ Value: "mysql", ExpectToBuild: true, })}, expectedErr: "", }, } for _, test := range tests { err := test.cfg.resolve(test.components) if err != nil { if !strings.Contains(err.Error(), test.expectedErr) { t.Errorf("%s: Invalid error: Expected %s, got %v", test.name, test.expectedErr, err) } } else if len(test.expectedErr) != 0 { t.Errorf("%s: Expected %s error but got none", test.name, test.expectedErr) } } } func TestDetectSource(t *testing.T) { dockerResolver := app.DockerRegistryResolver{ Client: dockerregistry.NewClient(), } tests := []struct { name string cfg *AppConfig repositories []*app.SourceRepository expectedRefs app.ComponentReferences expectedErr string }{ { name: "detect source - ruby", cfg: &AppConfig{ detector: app.SourceRepositoryEnumerator{ Detectors: source.DefaultDetectors, Tester: dockerfile.NewTester(), }, dockerResolver: dockerResolver, searcher: &simpleSearcher{dockerResolver}, }, repositories: []*app.SourceRepository{app.MockSourceRepositories()[1]}, expectedRefs: app.ComponentReferences{ app.ComponentReference(&app.ComponentInput{ Match: &app.ComponentMatch{ Value: "openshift/ruby-20-centos7", Image: &imageapi.DockerImage{ Config: imageapi.DockerConfig{ ExposedPorts: map[string]struct{}{"8080": {}}, }}, }, ExpectToBuild: true, Uses: app.MockSourceRepositories()[1], }, )}, expectedErr: "", }, } for _, test := range tests { refs, err := test.cfg.detectSource(test.repositories) if err != nil { if !strings.Contains(err.Error(), test.expectedErr) { t.Errorf("%s: Invalid error: Expected %s, got %v", test.name, test.expectedErr, err) } } else if len(test.expectedErr) != 0 { t.Errorf("%s: Expected %s error but got none", test.name, test.expectedErr) } if len(refs) != len(test.expectedRefs) { t.Fatalf("%s: Refs amount doesn't match. Expected %d, got %d", test.name, len(test.expectedRefs), len(refs)) } for i, ref := range refs { if reflect.DeepEqual(ref, test.expectedRefs[i]) { t.Errorf("%s: Refs don't match. Expected %v, got %v", test.name, test.expectedRefs[i], ref) } } } } func TestRunAll(t *testing.T) { dockerResolver := app.DockerRegistryResolver{ Client: dockerregistry.NewClient(), } tests := []struct { name string config *AppConfig expected map[string][]string expectedErr error }{ { name: "successful ruby app generation", config: &AppConfig{ SourceRepositories: util.StringList{"https://github.com/openshift/ruby-hello-world"}, dockerResolver: dockerResolver, imageStreamResolver: app.ImageStreamResolver{ Client: &client.Fake{}, ImageStreamImages: &client.Fake{}, Namespaces: []string{"default"}, }, templateResolver: app.TemplateResolver{ Client: &client.Fake{}, TemplateConfigsNamespacer: &client.Fake{}, Namespaces: []string{"openshift", "default"}, }, detector: app.SourceRepositoryEnumerator{ Detectors: source.DefaultDetectors, Tester: dockerfile.NewTester(), }, searcher: &simpleSearcher{dockerResolver}, typer: kapi.Scheme, osclient: &client.Fake{}, originNamespace: "default", }, expected: map[string][]string{ "imageStream": {"ruby-hello-world", "ruby-20-centos7"}, "buildConfig": {"ruby-hello-world"}, "deploymentConfig": {"ruby-hello-world"}, "service": {"ruby-hello-world"}, }, expectedErr: nil, }, { name: "app generation using context dir", config: &AppConfig{ SourceRepositories: util.StringList{"https://github.com/openshift/sti-ruby"}, ContextDir: "2.0/test/rack-test-app", dockerResolver: dockerResolver, imageStreamResolver: app.ImageStreamResolver{ Client: &client.Fake{}, ImageStreamImages: &client.Fake{}, Namespaces: []string{"default"}, }, templateResolver: app.TemplateResolver{ Client: &client.Fake{}, TemplateConfigsNamespacer: &client.Fake{}, Namespaces: []string{"openshift", "default"}, }, detector: app.SourceRepositoryEnumerator{ Detectors: source.DefaultDetectors, Tester: dockerfile.NewTester(), }, searcher: &simpleSearcher{dockerResolver}, typer: kapi.Scheme, osclient: &client.Fake{}, originNamespace: "default", }, expected: map[string][]string{ "imageStream": {"sti-ruby", "ruby-20-centos7"}, "buildConfig": {"sti-ruby"}, "deploymentConfig": {"sti-ruby"}, "service": {"sti-ruby"}, }, expectedErr: nil, }, } for _, test := range tests { res, err := test.config.RunAll(os.Stdout) if err != test.expectedErr { t.Errorf("%s: Error mismatch! Expected %v, got %v", test.name, test.expectedErr, err) continue } got := map[string][]string{} for _, obj := range res.List.Items { switch tp := obj.(type) { case *buildapi.BuildConfig: got["buildConfig"] = append(got["buildConfig"], tp.Name) case *kapi.Service: got["service"] = append(got["service"], tp.Name) case *imageapi.ImageStream: got["imageStream"] = append(got["imageStream"], tp.Name) case *deploy.DeploymentConfig: got["deploymentConfig"] = append(got["deploymentConfig"], tp.Name) } } if len(test.expected) != len(got) { t.Errorf("%s: Resource kind size mismatch! Expected %d, got %d", test.name, len(test.expected), len(got)) continue } for k, exp := range test.expected { g, ok := got[k] if !ok { t.Errorf("%s: Didn't find expected kind %s", test.name, k) } sort.Strings(g) sort.Strings(exp) if !reflect.DeepEqual(g, exp) { t.Errorf("%s: Resource names mismatch! Expected %v, got %v", test.name, exp, g) continue } } } } func TestRunBuild(t *testing.T) { dockerResolver := app.DockerRegistryResolver{ Client: dockerregistry.NewClient(), } tests := []struct { name string config *AppConfig expected map[string][]string expectedErr error }{ { name: "successful ruby app generation", config: &AppConfig{ SourceRepositories: util.StringList{"https://github.com/openshift/ruby-hello-world"}, OutputDocker: true, dockerResolver: dockerResolver, imageStreamResolver: app.ImageStreamResolver{ Client: &client.Fake{}, ImageStreamImages: &client.Fake{}, Namespaces: []string{"default"}, }, templateResolver: app.TemplateResolver{ Client: &client.Fake{}, TemplateConfigsNamespacer: &client.Fake{}, Namespaces: []string{"openshift", "default"}, }, detector: app.SourceRepositoryEnumerator{ Detectors: source.DefaultDetectors, Tester: dockerfile.NewTester(), }, searcher: &simpleSearcher{dockerResolver}, typer: kapi.Scheme, osclient: &client.Fake{}, originNamespace: "default", }, expected: map[string][]string{ "buildConfig": {"ruby-hello-world"}, }, expectedErr: nil, }, } for _, test := range tests { res, err := test.config.RunBuilds(os.Stdout) if err != test.expectedErr { t.Errorf("%s: Error mismatch! Expected %v, got %v", test.name, test.expectedErr, err) continue } got := map[string][]string{} for _, obj := range res.List.Items { switch tp := obj.(type) { case *buildapi.BuildConfig: got["buildConfig"] = append(got["buildConfig"], tp.Name) } } if len(test.expected) != len(got) { t.Errorf("%s: Resource kind size mismatch! Expected %d, got %d", test.name, len(test.expected), len(got)) continue } for k, exp := range test.expected { g, ok := got[k] if !ok { t.Errorf("%s: Didn't find expected kind %s", test.name, k) } sort.Strings(g) sort.Strings(exp) if !reflect.DeepEqual(g, exp) { t.Errorf("%s: Resource names mismatch! Expected %v, got %v", test.name, exp, g) continue } } } }
cgwalters/origin
pkg/generate/app/cmd/newapp_test.go
GO
apache-2.0
20,125
#region Copyright //======================================================================================= // Microsoft Azure Customer Advisory Team // // This sample is supplemental to the technical guidance published on my personal // blog at http://blogs.msdn.com/b/paolos/. // // Author: Paolo Salvatori //======================================================================================= // Copyright (c) Microsoft Corporation. All rights reserved. // // LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE // FILES 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. //======================================================================================= #endregion #region Using Directives using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using Microsoft.Azure.ServiceBusExplorer.Helpers; using Microsoft.Azure.ServiceBusExplorer.Properties; #endregion namespace Microsoft.Azure.ServiceBusExplorer.Forms { public partial class NewVersionAvailableForm : Form { #region Public Constructor public NewVersionAvailableForm() { InitializeComponent(); //This form is double buffered SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); } #endregion #region Event Handlers private void siteLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("https://github.com/paolosalvatori/ServiceBusExplorer"); } private void mailLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("mailto:paolos@microsoft.com?subject=Service%20Bus%20Explorer%20Feedback"); } private void blogLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://blogs.msdn.com/paolos"); } private void twitterLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("https://twitter.com/babosbird"); } private void NewVersionAvailableForm_Load(object sender, EventArgs e) { lblExeVersion.Text = VersionProvider.GetExeVersion(); if (!VersionProvider.IsLatestVersion(out var releaseInfo)) { labelLatestVersion.Text = $"New Release {releaseInfo.Version} Available"; linkLabelnewVersion.Text = releaseInfo.ReleaseUri.ToString(); linkLabelnewVersion.Visible = true; labelReleaseInfo.Text = releaseInfo.Body + Environment.NewLine + releaseInfo.ZipPackageUri; labelReleaseInfo.Visible = true; } else { labelLatestVersion.Text = "You have the latest version!"; linkLabelnewVersion.Visible = false; labelReleaseInfo.Visible = false; } } #endregion private void linkLabelnewVersion_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(linkLabelnewVersion.Text); } } }
lenardg/ServiceBusExplorer
src/ServiceBusExplorer/Forms/NewVersionAvailableForm.cs
C#
apache-2.0
3,865
/* * Licensed to GraphHopper and Peter Karich under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.reader.osgb.itn; import gnu.trove.list.TLongList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.map.TDoubleLongMap; import gnu.trove.map.TDoubleObjectMap; import gnu.trove.map.TLongObjectMap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.opengis.geometry.MismatchedDimensionException; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.graphhopper.reader.Way; /** * Represents an OSM Way * <p/> * * @author Nop */ public class OSITNWay extends OSITNElement implements Way { private static final long WAY_NODE_PREFIX_MOD = 100000000000000000L; protected final TLongList nodes = new TLongArrayList(5); protected String[] wayCoords; protected String startCoord; protected String endCoord; private static final Logger logger = LoggerFactory.getLogger(OSITNWay.class); /** * Constructor for XML Parser * @throws TransformException * @throws FactoryException * @throws MismatchedDimensionException */ public static OSITNWay create(long id, XMLStreamReader parser) throws XMLStreamException, MismatchedDimensionException, FactoryException, TransformException { OSITNWay way = new OSITNWay(id); parser.nextTag(); way.setTag("highway","road"); way.readTags(parser); logger.info(way.toString()); return way; } public OSITNWay(long id) { super(id, WAY); } public TLongList getNodes() { return nodes; } @Override public String toString() { return "Way (" + getId() + ", " + nodes.size() + " nodes)"; } @Override protected void parseCoords(String lineDefinition) { // Split on any number of whitespace characters // String[] lineSegments = lineDefinition.trim().replace('\n', ' ').replace('\t', ' ').split(" "); String[] lineSegments = lineDefinition.split("\\s+"); wayCoords = Arrays.copyOfRange(lineSegments, 1, lineSegments.length - 1); startCoord = lineSegments[0]; endCoord = lineSegments[lineSegments.length-1]; logger.info("startCoord [" + startCoord + "] endCoord [" + endCoord + "] num elements = "+ lineSegments.length); } @Override protected void parseCoords(int dimensions, String lineDefinition) { String[] lineSegments = lineDefinition.trim().split(" "); wayCoords = new String[lineSegments.length / dimensions]; StringBuilder curString = null; for (int i = 0; i < lineSegments.length; i++) { String string = lineSegments[i]; switch (i % dimensions) { case 0: { int coordNumber = i / dimensions; if (coordNumber > 0) { wayCoords[coordNumber - 1] = curString.toString(); } curString = new StringBuilder(); curString.append(string); break; } case 1: case 2: { curString.append(','); curString.append(string); } } } wayCoords[wayCoords.length - 1] = curString.toString(); logger.info(toString() + " " + ((wayCoords.length == 0) ? "0" : wayCoords[0])); } @Override protected void parseNetworkMember(String elementText) { throw new UnsupportedOperationException(); } @Override protected void addDirectedNode(String nodeId, String grade, String orientation) { String idStr = nodeId.substring(5); if (null != grade) { idStr = grade + idStr; } long id = Long.parseLong(idStr); if (0 == nodes.size()) { nodes.add(id); } else { addWayNodes(); nodes.add(id); } logger.info(toString()); } protected void addWayNodes() { for (int i = 1; i <= wayCoords.length; i++) { long idPrefix = i * WAY_NODE_PREFIX_MOD; long extraId = idPrefix + getId(); nodes.add(extraId); } } @Override protected void addDirectedLink(String nodeId, String orientation) { throw new UnsupportedOperationException(); } /** * Creates a new OSITNNode for each wayCoord. This also Looks for direction flags in edgeIdToXToYToNodeFlagsMap for the wayId, x, y combination. If it exists then * set the node tag TAG_KEY_NOENTRY_ORIENTATION to true and the TAG_KEY_ONEWAY_ORIENTATION node tag to -1 for one direction and true for the other. * * @param edgeIdToXToYToNodeFlagsMap * @return * @throws TransformException * @throws FactoryException * @throws MismatchedDimensionException */ public List<OSITNNode> evaluateWayNodes(TLongObjectMap<TDoubleObjectMap<TDoubleLongMap>> edgeIdToXToYToNodeFlagsMap) throws MismatchedDimensionException, FactoryException, TransformException { List<OSITNNode> wayNodes = new ArrayList<OSITNNode>(); for (int i = 0; i < wayCoords.length; i++) { String wayCoord = wayCoords[i]; long idPrefix = (i + 1) * WAY_NODE_PREFIX_MOD; long id = idPrefix + getId(); OSITNNode wayNode = new OSITNNode(id); wayNode.parseCoords(wayCoord); logger.info("Node " + getId() + " coords: " + wayCoord + " tags: "); for (String tagKey : wayNode.getTags().keySet()) { logger.info("\t " + tagKey + " : " + wayNode.getTag(tagKey)); } wayNodes.add(wayNode); } return wayNodes; } /** * Memory management method. Once a way is processed the stored string coordinates are no longer required so set them to null so they can be garbage collected */ public void clearStoredCoords() { wayCoords = null; startCoord = null; endCoord = null; } public String[] getWayCoords() { return wayCoords; } public String getStartCoord() { return startCoord; } public String getEndCoord() { return endCoord; } @Override protected void parseCoordinateString(String elementText, String elementSeparator) { throw new UnsupportedOperationException(); } }
engaric/graphhopper
core/src/main/java/com/graphhopper/reader/osgb/itn/OSITNWay.java
Java
apache-2.0
7,336
/* * Copyright (c) 2016. All rights reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS". * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. * * Author: Florin Bogdan Balint * */ package ac.at.tuwien.mt.datacontract; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bson.Document; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import ac.at.tuwien.mt.model.datacontract.DataContract; public class CreateDataContractTest { private static final Logger LOGGER = LogManager.getLogger(CreateDataContractTest.class); private static BasicCamelStarter camelStarter = new BasicCamelStarter(); private static final String HTTP_SERVER = "http://localhost:12770"; private static DataContract dataContract = getDataContract(); @BeforeClass public static void setUp() { camelStarter.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { LOGGER.error(e, e.getCause()); } } @AfterClass public static void tearDown() { camelStarter.cancel(); try { Thread.sleep(3000); } catch (InterruptedException e) { LOGGER.error(e, e.getCause()); } } @Test public void testCreateDataContract() { Client client = ClientBuilder.newClient(); WebTarget target = client.target(HTTP_SERVER).path("rest/datacontracts"); Entity<String> entity = Entity.entity(dataContract.getDocument().toJson(), MediaType.APPLICATION_JSON); Response response = target.request(MediaType.APPLICATION_JSON_TYPE).put(entity); int status = response.getStatus(); Assert.assertNotEquals(500, status); String responseAsString = response.readEntity(String.class); response.close(); Document doc = Document.parse(responseAsString); DataContract responseAsDataContract = new DataContract(doc); // check if the fields are set. Assert.assertFalse(responseAsDataContract.getDataContractMetaInfo().getActive()); Assert.assertNotNull(responseAsDataContract.getDataContractMetaInfo().getContractId()); Assert.assertNotNull(responseAsDataContract.getDataContractMetaInfo().getCreationDate()); Assert.assertEquals(1, responseAsDataContract.getDataContractMetaInfo().getRevision().intValue()); } private static DataContract getDataContract() { dataContract = new DataContract(); dataContract.getDataContractMetaInfo().setParty1Id("123"); dataContract.getDataContractMetaInfo().setParty2Id("234"); return dataContract; } }
e0725439/idac
prototype/ac.at.tuwien.mt.datacontract/src/test/java/ac/at/tuwien/mt/datacontract/CreateDataContractTest.java
Java
apache-2.0
2,835
package com.jdroid.android.debug; import android.app.FragmentTransaction; import android.os.Bundle; import com.jdroid.android.application.AbstractApplication; import com.jdroid.android.R; import com.jdroid.android.activity.AbstractFragmentActivity; import com.jdroid.android.fragment.AbstractPreferenceFragment; import com.jdroid.java.exception.UnexpectedException; public class DebugSettingsActivity extends AbstractFragmentActivity { /** * @see com.jdroid.android.activity.ActivityIf#getContentView() */ @Override public int getContentView() { return R.layout.fragment_container_activity; } /** * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.fragmentContainer, createNewFragment()); fragmentTransaction.commit(); } } protected AbstractPreferenceFragment createNewFragment() { return instanceAbstractPreferenceFragment(AbstractApplication.get().getDebugContext().getDebugSettingsFragmentClass(), getIntent().getExtras()); } private <E extends AbstractPreferenceFragment> E instanceAbstractPreferenceFragment(Class<E> fragmentClass, Bundle bundle) { E fragment; try { fragment = fragmentClass.newInstance(); } catch (InstantiationException e) { throw new UnexpectedException(e); } catch (IllegalAccessException e) { throw new UnexpectedException(e); } fragment.setArguments(bundle); return fragment; } /** * @see com.jdroid.android.activity.AbstractFragmentActivity#getMenuResourceId() */ @Override public Integer getMenuResourceId() { return null; } /** * @see com.jdroid.android.activity.AbstractFragmentActivity#requiresAuthentication() */ @Override public Boolean requiresAuthentication() { return false; } }
wskplho/jdroid
jdroid-android/src/debug/java/com/jdroid/android/debug/DebugSettingsActivity.java
Java
apache-2.0
1,981
# 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 pyspark_cassandra.util import as_java_object, as_java_array from pyspark.streaming.dstream import DStream from pyspark_cassandra.conf import WriteConf from pyspark_cassandra.util import helper from pyspark.serializers import AutoBatchedSerializer, PickleSerializer def saveToCassandra(dstream, keyspace, table, columns=None, row_format=None, keyed=None, write_conf=None, **write_conf_kwargs): ctx = dstream._ssc._sc gw = ctx._gateway # create write config as map write_conf = WriteConf.build(write_conf, **write_conf_kwargs) write_conf = as_java_object(gw, write_conf.settings()) # convert the columns to a string array columns = as_java_array(gw, "String", columns) if columns else None return helper(ctx).saveToCassandra(dstream._jdstream, keyspace, table, columns, row_format, keyed, write_conf) def joinWithCassandraTable(dstream, keyspace, table, selected_columns=None, join_columns=None): """Joins a DStream (a stream of RDDs) with a Cassandra table Arguments: @param dstream(DStream) The DStream to join. Equals to self when invoking joinWithCassandraTable on a monkey patched RDD. @param keyspace(string): The keyspace to join on. @param table(string): The CQL table to join on. @param selected_columns(string): The columns to select from the Cassandra table. @param join_columns(string): The columns used to join on from the Cassandra table. """ ssc = dstream._ssc ctx = ssc._sc gw = ctx._gateway selected_columns = as_java_array(gw, "String", selected_columns) if selected_columns else None join_columns = as_java_array(gw, "String", join_columns) if join_columns else None h = helper(ctx) dstream = h.joinWithCassandraTable(dstream._jdstream, keyspace, table, selected_columns, join_columns) dstream = h.pickleRows(dstream) dstream = h.javaDStream(dstream) return DStream(dstream, ssc, AutoBatchedSerializer(PickleSerializer())) # Monkey patch the default python DStream so that data in it can be stored to and joined with # Cassandra tables DStream.saveToCassandra = saveToCassandra DStream.joinWithCassandraTable = joinWithCassandraTable
TargetHolding/pyspark-cassandra
python/pyspark_cassandra/streaming.py
Python
apache-2.0
2,902
<!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 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package com.google.code.play2.provider.play21 (Play! 2.x Provider for Play! 2.1.x 1.0.0-rc2 API)</title> <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 Package com.google.code.play2.provider.play21 (Play! 2.x Provider for Play! 2.1.x 1.0.0-rc2 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="../../../../../../com/google/code/play2/provider/play21/package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/google/code/play2/provider/play21/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.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="Uses of Package com.google.code.play2.provider.play21" class="title">Uses of Package<br>com.google.code.play2.provider.play21</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"><a name="com.google.code.play2.provider.play21"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../com/google/code/play2/provider/play21/package-summary.html">com.google.code.play2.provider.play21</a> used by <a href="../../../../../../com/google/code/play2/provider/play21/package-summary.html">com.google.code.play2.provider.play21</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../com/google/code/play2/provider/play21/class-use/Play21JavascriptCompiler.CompileResult.html#com.google.code.play2.provider.play21">Play21JavascriptCompiler.CompileResult</a>&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="../../../../../../com/google/code/play2/provider/play21/package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/google/code/play2/provider/play21/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.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; 2013&#x2013;2018. All rights reserved.</small></p> </body> </html>
play2-maven-plugin/play2-maven-plugin.github.io
play2-maven-plugin/1.0.0-rc2/play2-providers/play2-provider-play21/apidocs/com/google/code/play2/provider/play21/package-use.html
HTML
apache-2.0
5,227
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>HcatException - dataworks.HcatException</title> <meta name="description" content="HcatException - dataworks.HcatException" /> <meta name="keywords" content="HcatException dataworks.HcatException" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript"> if(top === self) { var url = '../index.html'; var hash = 'dataworks.HcatException'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="type"> <div id="definition"> <img src="../lib/class_big.png" /> <p id="owner"><a href="package.html" class="extype" name="dataworks">dataworks</a></p> <h1>HcatException</h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <span class="name">HcatException</span><span class="result"> extends <a href="DataWorksException.html" class="extype" name="dataworks.DataWorksException">DataWorksException</a></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a href="DataWorksException.html" class="extype" name="dataworks.DataWorksException">DataWorksException</a>, <span class="extype" name="java.lang.Throwable">Throwable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="dataworks.HcatException"><span>HcatException</span></li><li class="in" name="dataworks.DataWorksException"><span>DataWorksException</span></li><li class="in" name="java.lang.Throwable"><span>Throwable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="dataworks.HcatException#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(msg:String):dataworks.HcatException"></a> <a id="&lt;init&gt;:HcatException"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">HcatException</span><span class="params">(<span name="msg">msg: <span class="extype" name="scala.Predef.String">String</span></span>)</span> </span> </h4> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:AnyRef):Boolean"></a> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:AnyRef):Boolean"></a> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="java.lang.Throwable#addSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="addSuppressed(x$1:Throwable):Unit"></a> <a id="addSuppressed(Throwable):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">addSuppressed</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#fillInStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="fillInStackTrace():Throwable"></a> <a id="fillInStackTrace():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">fillInStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="java.lang.Throwable#getCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getCause():Throwable"></a> <a id="getCause():Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getCause</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#getLocalizedMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getLocalizedMessage():String"></a> <a id="getLocalizedMessage():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getLocalizedMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getMessage" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getMessage():String"></a> <a id="getMessage():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getMessage</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getStackTrace():Array[StackTraceElement]"></a> <a id="getStackTrace():Array[StackTraceElement]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#getSuppressed" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getSuppressed():Array[Throwable]"></a> <a id="getSuppressed():Array[Throwable]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getSuppressed</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.Throwable">Throwable</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="java.lang.Throwable#initCause" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="initCause(x$1:Throwable):Throwable"></a> <a id="initCause(Throwable):Throwable"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">initCause</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.lang.Throwable">Throwable</span></span>)</span><span class="result">: <span class="extype" name="java.lang.Throwable">Throwable</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="dataworks.DataWorksException#params" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="params:scala.collection.mutable.HashMap[String,Object]"></a> <a id="params:HashMap[String,AnyRef]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">params</span><span class="result">: <span class="extype" name="scala.collection.mutable.HashMap">HashMap</span>[<span class="extype" name="scala.Predef.String">String</span>, <span class="extype" name="scala.AnyRef">AnyRef</span>]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="DataWorksException.html" class="extype" name="dataworks.DataWorksException">DataWorksException</a></dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintWriter):Unit"></a> <a id="printStackTrace(PrintWriter):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintWriter">PrintWriter</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace(x$1:java.io.PrintStream):Unit"></a> <a id="printStackTrace(PrintStream):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="java.io.PrintStream">PrintStream</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#printStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="printStackTrace():Unit"></a> <a id="printStackTrace():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">printStackTrace</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="java.lang.Throwable#setStackTrace" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="setStackTrace(x$1:Array[StackTraceElement]):Unit"></a> <a id="setStackTrace(Array[StackTraceElement]):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">setStackTrace</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Array">Array</span>[<span class="extype" name="java.lang.StackTraceElement">StackTraceElement</span>]</span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="java.lang.Throwable#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Throwable → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="dataworks.DataWorksException"> <h3>Inherited from <a href="DataWorksException.html" class="extype" name="dataworks.DataWorksException">DataWorksException</a></h3> </div><div class="parent" name="java.lang.Throwable"> <h3>Inherited from <span class="extype" name="java.lang.Throwable">Throwable</span></h3> </div><div class="parent" name="java.io.Serializable"> <h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> <script defer="defer" type="text/javascript" id="jquery-js" src="../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../lib/template.js"></script> </body> </html>
whlee21/docker
nable-dataworks/dataworks-core-0.1.0/share/doc/api/dataworks/HcatException.html
HTML
apache-2.0
33,521
/* * Copyright 2014, The Sporting Exchange Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.exemel.disco.core.api.exception; import uk.co.exemel.disco.api.ResponseCode; import uk.co.exemel.disco.api.security.CredentialFaultCode; // todo: would love to rename this to FaultCode (and FaultCode to FaultOrigin), but that would break hessian enum serialisation. // we really need to takeover hessian enum serialisation to allow us to change internal structures // in fact we really need to stop entrusting our internals to hessian public enum ServerFaultCode { StartupError(ResponseCode.InternalError, 1), FrameworkError(ResponseCode.InternalError, 2), InvocationResultIncorrect(ResponseCode.InternalError, 3), ServiceCheckedException(null, 4), // Response code defined by the checked exception ServiceRuntimeException(ResponseCode.InternalError, 5), /** * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or * {@link ServerFaultCode.ServerDeserialisationFailure} */ SOAPDeserialisationFailure(ResponseCode.BadRequest, 6), // not used - kept for compatibility with old client/servers /** * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or * {@link ServerFaultCode.ServerDeserialisationFailure} */ XMLDeserialisationFailure(ResponseCode.BadRequest, 7), // not used - kept for compatibility with old client/servers /** * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or * {@link ServerFaultCode.ServerDeserialisationFailure} */ JSONDeserialisationFailure(ResponseCode.BadRequest, 8), // not used - kept for compatibility with old client/servers /** * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or * {@link ServerFaultCode.ServerDeserialisationFailure} */ ClassConversionFailure(ResponseCode.BadRequest, 9), // not used - kept for compatibility with old client/servers InvalidInputMediaType(ResponseCode.UnsupportedMediaType, 10), ContentTypeNotValid(ResponseCode.UnsupportedMediaType, 11), MediaTypeParseFailure(ResponseCode.UnsupportedMediaType, 12), AcceptTypeNotValid(ResponseCode.MediaTypeNotAcceptable, 13), ResponseContentTypeNotValid(ResponseCode.InternalError, 14), SecurityException(ResponseCode.Forbidden, 15), MandatoryNotDefined(ResponseCode.BadRequest, 18), Timeout(ResponseCode.Timeout,19), /** * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or * {@link ServerFaultCode.ServerDeserialisationFailure} */ BinDeserialisationFailure(ResponseCode.BadRequest, 20), // not used - kept for compatibility with old client/servers NoSuchOperation(ResponseCode.NotFound, 21), SubscriptionAlreadyActiveForEvent(ResponseCode.InternalError, 22), NoSuchService(ResponseCode.NotFound, 23), /** * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or * {@link ServerFaultCode.ServerDeserialisationFailure} */ RescriptDeserialisationFailure(ResponseCode.BadRequest, 24), // not used - kept for compatibility with old client/servers JMSTransportCommunicationFailure(ResponseCode.InternalError, 25), RemoteDiscoCommunicationFailure(ResponseCode.ServiceUnavailable, 26), OutputChannelClosedCantWrite(ResponseCode.CantWriteToSocket, 27), /** * @deprecated Replaced by either {@link ServerFaultCode.ClientSerialisationFailure} or * {@link ServerFaultCode.ServerSerialisationFailure} */ XMLSerialisationFailure(ResponseCode.InternalError, 28), // not used - kept for compatibility with old client/servers /** * @deprecated Replaced by either {@link ServerFaultCode.ClientSerialisationFailure} or * {@link ServerFaultCode.ServerSerialisationFailure} */ JSONSerialisationFailure(ResponseCode.InternalError, 29), // not used - kept for compatibility with old client/servers /** * @deprecated Replaced by either {@link ServerFaultCode.ClientSerialisationFailure} or * {@link ServerFaultCode.ServerSerialisationFailure} */ SOAPSerialisationFailure(ResponseCode.InternalError, 30), // not used - kept for compatibility with old client/servers NoRequestsFound(ResponseCode.BadRequest, 31), UnidentifiedCaller(ResponseCode.BadRequest, 33, CredentialFaultCode.UnidentifiedCaller), UnknownCaller(ResponseCode.BadRequest, 34, CredentialFaultCode.UnknownCaller), UnrecognisedCredentials(ResponseCode.BadRequest, 35, CredentialFaultCode.UnrecognisedCredentials), InvalidCredentials(ResponseCode.BadRequest, 36, CredentialFaultCode.InvalidCredentials), SubscriptionRequired(ResponseCode.Forbidden, 37, CredentialFaultCode.SubscriptionRequired), OperationForbidden(ResponseCode.Forbidden, 38, CredentialFaultCode.OperationForbidden), NoLocationSupplied(ResponseCode.BadRequest, 39, CredentialFaultCode.NoLocationSupplied), BannedLocation(ResponseCode.Forbidden, 40, CredentialFaultCode.BannedLocation), ClientSerialisationFailure(ResponseCode.BadRequest, 41), ClientDeserialisationFailure(ResponseCode.BadResponse, 42), ServerSerialisationFailure(ResponseCode.BadResponse, 43), ServerDeserialisationFailure(ResponseCode.BadRequest, 44); private final ResponseCode errorCode; private final String errorString; private final String toString; private final CredentialFaultCode cfc; public static final String DISCO_EXCEPTION_PREFIX="DSC"; private ServerFaultCode(ResponseCode errorCode, int detailCode) { this(errorCode, detailCode, null); } private ServerFaultCode(ResponseCode errorCode, int detailCode, CredentialFaultCode cfc) { this.errorCode = errorCode; errorString = DISCO_EXCEPTION_PREFIX+"-"+String.format("%04d", detailCode); toString = name() + "(" + errorString + ")"; this.cfc = cfc; } public String getDetail() { return errorString; } public ResponseCode getResponseCode() { return errorCode; } public CredentialFaultCode getCredentialFaultCode() { return cfc; } public static ServerFaultCode getByDetailCode(String prefix) { for (ServerFaultCode sfc : ServerFaultCode.values()) { if (sfc.getDetail().equals(prefix)) { return sfc; } } return null; } public static ServerFaultCode getByCredentialFaultCode(CredentialFaultCode credentialFaultCode) { for (ServerFaultCode sfc : ServerFaultCode.values()) { CredentialFaultCode cfc = sfc.getCredentialFaultCode(); if (cfc != null && cfc.equals(credentialFaultCode)) { return sfc; } } return null; } @Override public String toString() { return toString; } }
eswdd/disco
disco-framework/disco-core-api/src/main/java/uk/co/exemel/disco/core/api/exception/ServerFaultCode.java
Java
apache-2.0
7,508
/* * $Id$ * * Copyright 2009 Hiroki Ata * * 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.aexlib.gae.datastore; import org.aexlib.gae.LocalDataStoreTestCase; import org.aexlib.gae.datastore.EntityChildNameBase; import org.aexlib.gae.datastore.EntityCreator; import org.aexlib.gae.datastore.EntityFactory; import org.aexlib.gae.datastore.EntityNameBase; import org.aexlib.gae.datastore.EntityNameFactory; import org.aexlib.gae.datastore.impl.TestDocument; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; public class EntityBaseTest extends LocalDataStoreTestCase { public static class ParentEntity extends EntityNameBase<ParentEntity> { public static final EntityNameFactory<ParentEntity> NAME_FACTORY = EntityFactory.getEntityNameFactory(ParentEntity.class, new EntityCreator<ParentEntity>() { public ParentEntity newInstance() { return new ParentEntity(); } }); } public class ChildEntity extends EntityChildNameBase<ChildEntity, ParentEntity> { } public class SubChildEntity extends EntityChildNameBase<SubChildEntity, ChildEntity> { } ParentEntity doc; protected void setUp() throws Exception { super.setUp(); doc = ParentEntity.NAME_FACTORY.initInstance("doc1"); doc.putIfAbsent(); } protected void tearDown() throws Exception { super.tearDown(); } public void testUser() throws Exception { for (int i = 0;i < 10;i++) { TestUser user = TestUser.FACTORY.initInstance("test" + i); assertTrue(user.putIfAbsent()); user.title.set("title" + i); user.text.set("text" + i); assertEquals("title" + i, user.title.get()); assertEquals("text" + i, user.text.get()); } for (TestUser test : TestUser.QUERY.query().filter(TestUser.TITLE.equal("test5")).asIterable()) { assertEquals("test5", test.title.get()); } } public void testInitKey() { Key key = doc.getKey(); assertEquals("doc1", key.getName()); doc.init(KeyFactory.createKey("ParentEntity", "doc2")); assertEquals("doc2", doc.getKey().getName()); } public void testInitEntity() { Key key = doc.getKey(); assertEquals("doc1", key.getName()); doc.init(new Entity(KeyFactory.createKey("ParentEntity", "doc2"))); assertEquals("doc2", doc.getKey().getName()); } public void testSetVersion() throws Exception { Entity entity = new Entity(KeyFactory.createKey("ParentEntity", "doc2")); doc.getEntityPropertyAccess().setVersion("version", 2L); doc.init(entity); assertEquals(2L, entity.getProperty("version")); // doc.title.set("title2"); doc.getEntityPropertyAccess().setVersion("version", 3L); doc.init(entity); assertEquals((Long)3L, entity.getProperty("version")); } public void testGetProperty() throws Exception { doc.getEntityPropertyAccess().setProperty("Title", "title2"); assertEquals("title2", doc.getEntityPropertyAccess().getProperty("Title")); } public void testSetProperty() throws Exception { doc.getEntityPropertyAccess().setProperty("Title", "title2"); doc.put(); Entity entity = DatastoreServiceFactory.getDatastoreService().get(doc.getKey()); assertEquals("title2", entity.getProperty("Title")); } }
hata/aexlib
aexlib-datastore/src/test/java/org/aexlib/gae/datastore/EntityBaseTest.java
Java
apache-2.0
4,235
package cn.xishan.oftenporter.oftendb.data; import cn.xishan.oftenporter.oftendb.annotation.DBField; import cn.xishan.oftenporter.oftendb.annotation.ExceptDBField; import cn.xishan.oftenporter.oftendb.db.MultiNameValues; import cn.xishan.oftenporter.oftendb.db.NameValues; import cn.xishan.oftenporter.porter.core.JResponse; import cn.xishan.oftenporter.porter.core.ResultCode; import cn.xishan.oftenporter.porter.core.annotation.PortInObj; import cn.xishan.oftenporter.porter.core.annotation.PortInObj.JsonField; import cn.xishan.oftenporter.porter.core.annotation.PortInObj.JsonObj; import cn.xishan.oftenporter.porter.core.base.InNames; import cn.xishan.oftenporter.porter.core.base.PortUtil; import cn.xishan.oftenporter.porter.core.base.WObject; import cn.xishan.oftenporter.porter.core.util.WPTool; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.util.Map; public class DataUtil { private static final Logger LOGGER = LoggerFactory.getLogger(DataUtil.class); /** * 见{@linkplain #toNameValues(Object, boolean, boolean, String...)} * * @param object * @return * @throws IllegalAccessException */ public static NameValues toNameValues(Object object, boolean filterNullAndEmpty) { return toNameValues(object, filterNullAndEmpty, true); } /** * @param object 用于提取的实例,见{@linkplain #getTiedName(Field)}、{@linkplain JsonField}、{@linkplain JsonObj} * @param filterNullAndEmpty 是否过滤null或空字符串 * @param isExcept * @param keyNames * @return */ public static NameValues toNameValues(Object object, boolean filterNullAndEmpty, boolean isExcept, String... keyNames) { try { return _toNameValues(object, filterNullAndEmpty, isExcept, keyNames); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private static boolean isJsonFieldOrJson(Object object, Field field, NameValues nameValues) throws IllegalAccessException { if (field.isAnnotationPresent(JsonObj.class)) { JsonObj jsonObj = field.getAnnotation(JsonObj.class); String name = jsonObj.value(); if (name.equals("")) { name = field.getName(); } field.setAccessible(true); Object fieldObj = field.get(object); if (fieldObj != null) { nameValues.append(name, _toNameValues(fieldObj, jsonObj.filterNullAndEmpty(), true).toJSON()); } return true; } else if (field.isAnnotationPresent(JsonField.class)) { JsonField jsonField = field.getAnnotation(JsonField.class); String name = jsonField.value(); if (name.equals("")) { name = field.getName(); } field.setAccessible(true); Object fieldObj = field.get(object); if (!jsonField.filterNullAndEmpty() || WPTool.notNullAndEmpty(fieldObj)) { nameValues.append(name, fieldObj); } return true; } return false; } private static NameValues _toNameValues(Object object, boolean filterNullAndEmpty, boolean isExcept, String... keyNames) throws IllegalAccessException { Field[] fields = WPTool.getAllFields(object.getClass()); NameValues nameValues = new NameValues(fields.length); nameValues.filterNullAndEmpty(filterNullAndEmpty); if (isExcept) { for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (isJsonFieldOrJson(object, field, nameValues)) { continue; } String name = getTiedName(field); if (name == null) { continue; } for (String e : keyNames) { if (e.equals(name)) { name = null; break; } } if (name != null) { field.setAccessible(true); nameValues.append(name, field.get(object)); } } } else { String[] contains = keyNames; for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (isJsonFieldOrJson(object, field, nameValues)) { continue; } String name = getTiedName(field); if (name == null) { continue; } for (String c : contains) { if (c.equals(name)) { field.setAccessible(true); nameValues.append(name, field.get(object)); break; } } } } return nameValues; } /** * 得到字段的绑定名称,如果含有{@linkplain ExceptDBField}注解则会返回null。 * * @param field 使用{@linkplain PortInObj.Nece}、{@linkplain DBField}或{@linkplain PortInObj.UnNece * }注解标注字段,使用{@linkplain DBField}来映射数据库字段名。 */ public static String getTiedName(Field field) { if (field.isAnnotationPresent(ExceptDBField.class)) { return null; } field.setAccessible(true); String name = null; if (field.isAnnotationPresent(PortInObj.Nece.class)) { name = PortUtil.tied(field.getAnnotation(PortInObj.Nece.class), field, true); } else if (field.isAnnotationPresent(PortInObj.UnNece.class)) { name = PortUtil.tied(field.getAnnotation(PortInObj.UnNece.class), field, true); } else if (field.isAnnotationPresent(DBField.class)) { name = field.getName(); DBField dbField = field.getAnnotation(DBField.class); if (!dbField.value().equals("")) { name = dbField.value(); } } if (name != null) { int index = name.indexOf('('); if (index >= 0)//去除参数。 { name = name.substring(0, index); } } return name; } /** * 普通搜索 * * @param array 查找的数组 * @param obj 待查找的值 * @return 找到返回对应索引,否则返回-1. */ public static int indexOf(Object[] array, Object obj) throws NullPointerException { int index = -1; for (int i = 0; i < array.length; i++) { if (array[i].equals(obj)) { index = i; break; } } return index; } public static NameValues toNameValues(JSONObject jsonObject) { NameValues nameValues = new NameValues(jsonObject.size()); for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { nameValues.append(entry.getKey(), entry.getValue()); } return nameValues; } public static MultiNameValues toMultiNameValues(JSONArray jsonArray) { JSONObject jsonObject = jsonArray.getJSONObject(0); String[] names = jsonObject.keySet().toArray(new String[0]); MultiNameValues multiNameValues = new MultiNameValues(); multiNameValues.names(names); for (int i = 0; i < jsonArray.size(); i++) { jsonObject = jsonArray.getJSONObject(i); Object[] values = new Object[names.length]; multiNameValues.addValues(values); for (int k = 0; k < names.length; k++) { values[k] = jsonObject.get(names[k]); } } return multiNameValues; } /** * 若结果码为成功,且结果为JSONObject(不为null)时返回true. */ public static boolean resultJSON(JResponse jResponse) { if (jResponse.isSuccess()) { Object object = jResponse.getResult(); if (object != null && (object instanceof JSONObject)) { return true; } } return false; } /** * 返回-1:结果码不为成功,0:结果码为成功且结果为null,1:结果码为成功且结果不为null。 * * @param jResponse * @return */ public static int checkResult(JResponse jResponse) { if (jResponse.isSuccess()) { if (jResponse.getResult() == null) { return 0; } else { return 1; } } else { return -1; } } /** * 当且仅当结果码为成功,且结果为true时返回真;否则返回false。 * * @param jResponse JSONResponse * @return 判断结果 */ public static boolean resultTrue(JResponse jResponse) { Object rs = jResponse.getResult(); if (jResponse.isSuccess() && rs != null && (rs instanceof Boolean) && (Boolean) rs) { return true; } else { return false; } } /** * 当且仅当结果码为成功、且结果为int或long、且值大于0返回true * * @param jResponse * @return */ public static boolean resultIntOrLongGtZero(JResponse jResponse) { if (jResponse.isNotSuccess()) { return false; } Object rs = jResponse.getResult(); if (rs == null) { return false; } if (rs instanceof Integer) { int n = (int) rs; return n > 0; } else if (rs instanceof Long) { long n = (long) rs; return n > 0; } else { return false; } } /** * 当且仅当结果码为成功且结果不为null时返回true * * @param jResponse JSONResponse * @return 判断结果 */ public static boolean resultNotNull(JResponse jResponse) { if (jResponse.isSuccess() && jResponse.getResult() != null) { return true; } else { return false; } } /** * 把fns、finner和fus转换成NameValues对象 * * @param wObject * @param wObject * @param containsNull 是否包含null值键值对 * @return */ public static NameValues toNameValues(WObject wObject, boolean containsNull) { NameValues nameValues = new NameValues(); try { InNames.Name[] names = wObject.fInNames.nece; for (int i = 0; i < names.length; i++) { if (!containsNull && wObject.fn[i] == null) { continue; } nameValues.append(names[i].varName, wObject.fn[i]); } names = wObject.fInNames.unece; for (int i = 0; i < names.length; i++) { if (!containsNull && wObject.fu[i] == null) { continue; } nameValues.append(names[i].varName, wObject.fu[i]); } names = wObject.fInNames.inner; for (int i = 0; i < names.length; i++) { if (!containsNull && wObject.finner[i] == null) { continue; } nameValues.append(names[i].varName, wObject.finner[i]); } } catch (JSONException e) { LOGGER.warn(e.getMessage(), e); } return nameValues; } /** * 把fns、finner和fus转换成json对象 * * @param wObject * @param wObject * @param containsNull 是否包含null值键值对 * @return */ public static JSONObject toJsonObject(WObject wObject, boolean containsNull) { JSONObject jsonObject = new JSONObject(); try { InNames.Name[] names = wObject.fInNames.nece; for (int i = 0; i < names.length; i++) { if (!containsNull && wObject.fn[i] == null) { continue; } jsonObject.put(names[i].varName, wObject.fn[i]); } names = wObject.fInNames.unece; for (int i = 0; i < names.length; i++) { if (!containsNull && wObject.fu[i] == null) { continue; } jsonObject.put(names[i].varName, wObject.fu[i]); } names = wObject.fInNames.inner; for (int i = 0; i < names.length; i++) { if (!containsNull && wObject.finner[i] == null) { continue; } jsonObject.put(names[i].varName, wObject.finner[i]); } } catch (JSONException e) { throw e; } return jsonObject; } public JResponse simpleDeal(SimpleDealt simpleDealt, Object... objects) { JResponse jResponse = new JResponse(); try { simpleDealt.deal(jResponse, objects); jResponse.setCode(ResultCode.SUCCESS); } catch (Exception e) { jResponse.setCode(ResultCode.SERVER_EXCEPTION); jResponse.setDescription(e.toString()); simpleDealt.onException(e, jResponse, objects); } return jResponse; } /** * 返回表名,会去掉Porter、Unit、UnitApi、Dao等后缀。 * * @param tablePrefix * @param configed * @return */ public static String getTableName(String tablePrefix, Configed configed) { String tableName; Object unit = configed.getUnit(); String name = unit.getClass().getSimpleName(); int index = name.endsWith("Unit") ? name.lastIndexOf("Unit") : -1; if (index < 0) { index = name.endsWith("Porter") ? name.lastIndexOf("Porter") : -1; } if (index < 0) { index = name.endsWith("Dao") ? name.lastIndexOf("Dao") : -1; } if (index < 0) { index = name.endsWith("UnitApi") ? name.lastIndexOf("UnitApi") : -1; } if (index > 0) { tableName = name.substring(0, index); } else { tableName = name; } tableName = tablePrefix + tableName; return tableName; } }
CLovinr/OftenPorter-1
Porter-DB/src/main/java/cn/xishan/oftenporter/oftendb/data/DataUtil.java
Java
apache-2.0
15,368
/** * */ package com.github.typesafe_query; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; import com.github.typesafe_query.query.Exp; import com.github.typesafe_query.query.Order; /** * モデルの検索を行います。 * <p>検索を行うクラスです</p> * * @author Takahiko Sato(MOSA architect Inc.) */ public interface Finder<I,T> { Finder<I,T> includeDefault(); T requiredById(I id); /** * プライマリーキーで検索します * @param id プライマリーキー * @return Model */ Optional<T> byId(I id); /** * 件数を返します。 * @return 件数 */ long count(); /** * 条件を指定して件数を返します。 * @param expressions 検索条件 * @return 件数 */ long countWhere(Exp... expressions); /** * 一覧を返します * @param orders ソート順 * @return 一覧 */ List<T> list(Order...orders); /** * 件数を指定して一覧を返します。 * @param limit 最大件数 * @param orders ソート順 * @return 一覧 */ List<T> list(int limit,Order...orders); /** * 開始位置と件数を指定して一覧を返します。 * @param offset 開始位置 * @param limit 最大件数 * @param orders ソート順 * @return 一覧 */ List<T> list(int offset,int limit,Order...orders); T requiredWhere(Exp... expressions); /** * 条件を指定して1件取得します * @param expressions 条件 * @return 1件の結果 */ Optional<T> where(Exp... expressions); /** * 条件を指定して一覧を返します。 * @param expression 条件 * @param orders ソート順 * @return 一覧 */ List<T> listWhere(Exp expression,Order...orders); /** * 条件、件数を指定して一覧を返します。 * @param expression 条件 * @param limit 最大件数 * @param orders ソート順 * @return 一覧 */ List<T> listWhere(Exp expression,Integer limit,Order...orders); /** * 条件、開始位置、件数を指定して一覧を返します。 * @param expression 条件 * @param offset 開始位置 * @param limit 件数 * @param orders ソート順 * @return 一覧 */ List<T> listWhere(Exp expression,Integer offset,Integer limit,Order...orders); void fetch(Predicate<T> p, Order...orders); void fetch(Predicate<T> p,int limit,Order...orders); void fetch(Predicate<T> p,int offset,int limit,Order...orders); void fetch(Consumer<T> p,Order...orders); void fetch(Consumer<T> p,int limit,Order...orders); void fetch(Consumer<T> p,int offset,int limit,Order...orders); void fetchWhere(Exp expression,Predicate<T> p,Order...orders); void fetchWhere(Exp expression,Predicate<T> p,Integer limit,Order...orders); void fetchWhere(Exp expression,Predicate<T> p,Integer offset,Integer limit,Order...orders); void fetchWhere(Exp expression,Consumer<T> p,Order...orders); void fetchWhere(Exp expression,Consumer<T> p,Integer limit,Order...orders); void fetchWhere(Exp expression,Consumer<T> p,Integer offset,Integer limit,Order...orders); }
typesafe-query/typesafe-query
typesafe-query-core/src/main/java/com/github/typesafe_query/Finder.java
Java
apache-2.0
3,127
#region License /* * Copyright 2010 Miloš Anđelković * * 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. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using MessyLab.PicoComputer; namespace MessyLab.Debugger.Target.Pico { /// <summary> /// Implements all Breakpoint Checker interfaces for the picoComputer. /// </summary> public class PicoBreakpointChecker : IMemoryBreakpointChecker, IRegisterBreakpointChecker, IStepBreakpointChecker, IIOBreakpointChecker { /// <summary> /// Creates object using the specified PicoTarget. /// </summary> /// <param name="target">PicoTarget object</param> public PicoBreakpointChecker(PicoTarget target) { Target = target; } /// <summary> /// Debugging target used to get the reference to the VM, /// more specifically its Data object. /// </summary> public PicoTarget Target { get; set; } /// <summary> /// NullDevice is used to probe I/O instructions. /// </summary> private NullIODevice _nullDevice = new NullIODevice(); /// <summary> /// A picoComputer processor used for probing. /// </summary> /// <remarks> /// Probing is the process of executing and undoing the next instruction /// in order to collect data on its effects. /// The data is stored in a DataDelta object and it is used to check if /// specifics breakpoints are hit. /// </remarks> private Processor _processor; /// <summary> /// Calculates the effects of the next instruction. /// </summary> /// <remarks> /// This calculation in advance allows breakpoints to be hit BEFORE the /// actual execution. /// </remarks> /// <returns>A value holding the effects of the instruction.</returns> protected DataDelta CalculateNextDelta() { Data data = Target.VirtualMachine.Data; if (_processor == null || _processor.Data != data) { _processor = new Processor(data, _nullDevice); } data.Commit(); // Commits any previous changes try { _processor.Step(); } // Execute next instruction (breakpoint probe). catch (Exception) { } DataDelta result = data.Delta; // Delta object holds the changes made by the probe if (!data.Uncommit()) // Uncommit restores previous Delta object from history and discards the probe changes. { // If uncommit fails, we need to manually discard probe changes by calling Rollback(). data.Rollback(); } return result; } /// <summary> /// In order to avoid unnecessary recalculation of the next delta, /// a reference to the object is stored for further use. /// </summary> private DataDelta _nextDelta; /// <summary> /// The address of the instruction corresponding to the _nextDelta object. /// </summary> private ushort _nextDeltaPC; /// <summary> /// Return the Delta (effect) of the instruction that will be executed next. /// </summary> /// <remarks> /// The value is recalculated by calling CalculateNextDelta() if necessary; /// otherwise _nextDelta is returned. /// </remarks> public DataDelta NextDelta { get { ushort pc = Target.VirtualMachine.Data.DirectPC; if (_nextDelta == null || _nextDeltaPC != pc) { _nextDeltaPC = pc; _nextDelta = CalculateNextDelta(); } return _nextDelta; } } /// <summary> /// Sets the NextDelta and the corresponding PC. /// </summary> /// <remarks> /// This method should be used when stepping back to avoid /// reexecuting the undone instruction in CalculateNextDelta. /// </remarks> /// <param name="nextDelta">The Delta of the next instruction</param> /// <param name="pc">The address of the instruction</param> public void SetNextDelta(DataDelta nextDelta, ushort pc) { _nextDelta = nextDelta; _nextDeltaPC = pc; } #region IMemoryBreakpointChecker Members public bool IsAboutToExecute(long address) { return Target.VirtualMachine.Data.DirectPC == address; } public bool IsAboutToRead(long address) { return NextDelta.ReadLocations.Contains((ushort)address); } public bool IsAboutToWrite(long address) { return NextDelta.WrittenLocations.ContainsKey((ushort)address); } public bool IsAboutToExecute(long address, int count) { if (count < 1) return false; if (count == 1) return IsAboutToExecute(address); long lastAddress = address + count - 1; ushort pc = Target.VirtualMachine.Data.DirectPC; return pc >= address && pc <= lastAddress; } public bool IsAboutToRead(long address, int count) { if (count < 1) return false; if (count == 1) return IsAboutToRead(address); long lastAddress = address + count - 1; foreach (ushort loc in NextDelta.ReadLocations) { if (loc >= address && loc <= lastAddress) return true; } return false; } public bool IsAboutToWrite(long address, int count) { if (count < 1) return false; if (count == 1) return IsAboutToWrite(address); long lastAddress = address + count - 1; foreach (ushort loc in NextDelta.WrittenLocations.Keys) { if (loc >= address && loc <= lastAddress) return true; } return false; } #endregion #region IRegisterBreakpointChecker Members /// <summary> /// Pico Computer VM does NOT support on read breakpoints from registers. /// </summary> /// <param name="register">Register name</param> /// <returns>Always return false.</returns> public bool IsAboutToRead(string register) { return false; } public bool IsAboutToWrite(string register) { switch (register.ToLower()) { case "pc": return NextDelta.PCWritten; case "sp": return NextDelta.SPWritten; default: return false; } } #endregion #region IStepBreakpointChecker Members public bool IsStepCompleted(IProgramLocation originLocation, StepKind stepKind) { PicoProgramLocation loc = (PicoProgramLocation)originLocation; ushort pc = Target.VirtualMachine.Data.DirectPC; ushort sp = Target.VirtualMachine.Data.DirectSP; switch (stepKind) { case StepKind.Into: // If PC is changed, a step is performed. return pc != loc.PC; case StepKind.Over: // To complete a step over PC has to change, and the call stack has to remain the same. return pc != loc.PC && sp == loc.SP; case StepKind.Out: // To step out of a subroutine, SP needs to increment (Pop RetAddress). return sp > loc.SP; } return false; // Unreachable, but makes the compiler happy. :) } #endregion #region IIOBreakpointChecker Members /// <summary> /// Checks whether the I/O operation is about to commence. /// </summary> /// <remarks> /// Works by decoding the next instruction and checking whether it is IN or OUT. /// </remarks> /// <param name="input">Indicates if the operation is Input; otherwise Output.</param> /// <param name="address">Address is ignored, because picoComputer has only one I/O device.</param> /// <returns>A value indicating whether the specified I/O operation is about to commence.</returns> public bool IsAboutToPerformIO(bool input, long address) { ushort instruction = Target.VirtualMachine.Data.DirectMemoryRead(Target.VirtualMachine.Data.DirectPC); instruction >>= 12; // OP Code. ushort lookingFor = (ushort)(input ? 7 : 8); // In: 0111 (0x7), Out: 1000 (0x8) return instruction == lookingFor; } #endregion } }
drstorm/messylab
Debugger/Target/Pico/PicoBreakpointChecker.cs
C#
apache-2.0
8,177
/* * Copyright 2017 Zhihu 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.youquan.selector.filter; import android.content.Context; import android.graphics.Point; import com.youquan.selector.MimeType; import com.youquan.selector.R; import com.youquan.selector.internal.entity.IncapableCause; import com.youquan.selector.internal.entity.Item; import com.youquan.selector.internal.utils.PhotoMetadataUtils; import java.util.HashSet; import java.util.Set; public class GifSizeFilter extends Filter { private int mMinWidth; private int mMinHeight; private int mMaxSize; public GifSizeFilter(int minWidth, int minHeight, int maxSizeInBytes) { mMinWidth = minWidth; mMinHeight = minHeight; mMaxSize = maxSizeInBytes; } @Override public Set<MimeType> constraintTypes() { return new HashSet<MimeType>() {{ add(MimeType.GIF); }}; } @Override public IncapableCause filter(Context context, Item item) { if (!needFiltering(context, item)) return null; Point size = PhotoMetadataUtils.getBitmapBound(context.getContentResolver(), item.getContentUri()); if (size.x < mMinWidth || size.y < mMinHeight || item.size > mMaxSize) { return new IncapableCause(IncapableCause.DIALOG, context.getString(R.string.error_gif, mMinWidth, String.valueOf(PhotoMetadataUtils.getSizeInMB(mMaxSize)))); } return null; } }
newbieandroid/AppBase
photoselector/src/main/java/com/youquan/selector/filter/GifSizeFilter.java
Java
apache-2.0
2,013
/* * 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. * * Copyright 2013 Near Infinity Corporation. */ package com.nearinfinity.honeycomb.hbase; import com.google.inject.AbstractModule; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.multibindings.MapBinder; import com.google.inject.name.Names; import com.nearinfinity.honeycomb.Store; import com.nearinfinity.honeycomb.Table; import com.nearinfinity.honeycomb.config.AdapterType; import com.nearinfinity.honeycomb.exceptions.RuntimeIOException; import com.nearinfinity.honeycomb.hbase.config.ConfigConstants; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Map; /** * Wires up the required classes for the HBase backend */ public class HBaseModule extends AbstractModule { private static final Logger logger = Logger.getLogger(HBaseModule.class); private final HTableProvider hTableProvider; private final Configuration configuration; public HBaseModule(final Map<String, String> options) { // Add the HBase resources to the core application configuration configuration = HBaseConfiguration.create(); for (Map.Entry<String, String> option : options.entrySet()) { configuration.set(option.getKey(), option.getValue()); } hTableProvider = new HTableProvider(configuration); try { TableCreator.createTable(configuration); } catch (IOException e) { logger.fatal("Could not create HBase table. Aborting initialization."); logger.fatal(configuration.toString()); throw new RuntimeIOException(e); } } @Override protected void configure() { final MapBinder<AdapterType, Store> storeMapBinder = MapBinder.newMapBinder(binder(), AdapterType.class, Store.class); storeMapBinder.addBinding(AdapterType.HBASE).to(HBaseStore.class); install(new FactoryModuleBuilder() .implement(Table.class, HBaseTable.class) .build(HBaseTableFactory.class)); bind(HTableProvider.class).toInstance(hTableProvider); bind(HTableInterface.class).toProvider(hTableProvider); bind(Long.class).annotatedWith(Names.named(ConfigConstants.WRITE_BUFFER)) .toInstance(configuration.getLong(ConfigConstants.WRITE_BUFFER, ConfigConstants.DEFAULT_WRITE_BUFFER)); bind(String.class).annotatedWith(Names.named(ConfigConstants.COLUMN_FAMILY)) .toInstance(configuration.get(ConfigConstants.COLUMN_FAMILY)); } }
altamiracorp/honeycomb
storage-engine-backends/hbase/src/main/java/com/nearinfinity/honeycomb/hbase/HBaseModule.java
Java
apache-2.0
3,520
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.test.web.servlet.request; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests.Config.class) @WebAppConfiguration public class SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests { @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setup() { mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } // SEC-2593 @Test public void userRequestPostProcessorWorksWithStateless() throws Exception { mvc.perform(get("/").with(user("user"))).andExpect(status().is2xxSuccessful()); } // SEC-2593 @WithMockUser @Test public void withMockUserWorksWithStateless() throws Exception { mvc.perform(get("/")).andExpect(status().is2xxSuccessful()); } @EnableWebSecurity @EnableWebMvc static class Config extends WebSecurityConfigurerAdapter { // @formatter:off @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); } // @formatter:on // @formatter:off @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication(); } // @formatter:on @RestController static class Controller { @RequestMapping public String hello() { return "Hello"; } } } }
eddumelendez/spring-security
test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationStatelessTests.java
Java
apache-2.0
3,760
/* * 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.lexmodelsv2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/models.lex.v2-2020-08-07/CreateSlot" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateSlotRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the slot. Slot names must be unique within the bot that contains the slot. * </p> */ private String slotName; /** * <p> * A description of the slot. Use this to help identify the slot in lists. * </p> */ private String description; /** * <p> * The unique identifier for the slot type associated with this slot. The slot type determines the values that can * be entered into the slot. * </p> */ private String slotTypeId; /** * <p> * Specifies prompts that Amazon Lex sends to the user to elicit a response that provides the value for the slot. * </p> */ private SlotValueElicitationSetting valueElicitationSetting; /** * <p> * Determines how slot values are used in Amazon CloudWatch logs. If the value of the * <code>obfuscationSetting</code> parameter is <code>DefaultObfuscation</code>, slot values are obfuscated in the * log output. If the value is <code>None</code>, the actual value is present in the log output. * </p> * <p> * The default is to obfuscate values in the CloudWatch logs. * </p> */ private ObfuscationSetting obfuscationSetting; /** * <p> * The identifier of the bot associated with the slot. * </p> */ private String botId; /** * <p> * The version of the bot associated with the slot. * </p> */ private String botVersion; /** * <p> * The identifier of the language and locale that the slot will be used in. The string must match one of the * supported locales. All of the bots, intents, slot types used by the slot must have the same locale. For more * information, see <a href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a>. * </p> */ private String localeId; /** * <p> * The identifier of the intent that contains the slot. * </p> */ private String intentId; /** * <p> * Indicates whether the slot returns multiple values in one response. Multi-value slots are only available in the * en-US locale. If you set this value to <code>true</code> in any other locale, Amazon Lex throws a * <code>ValidationException</code>. * </p> * <p> * If the <code>multipleValuesSetting</code> is not set, the default value is <code>false</code>. * </p> */ private MultipleValuesSetting multipleValuesSetting; /** * <p> * The name of the slot. Slot names must be unique within the bot that contains the slot. * </p> * * @param slotName * The name of the slot. Slot names must be unique within the bot that contains the slot. */ public void setSlotName(String slotName) { this.slotName = slotName; } /** * <p> * The name of the slot. Slot names must be unique within the bot that contains the slot. * </p> * * @return The name of the slot. Slot names must be unique within the bot that contains the slot. */ public String getSlotName() { return this.slotName; } /** * <p> * The name of the slot. Slot names must be unique within the bot that contains the slot. * </p> * * @param slotName * The name of the slot. Slot names must be unique within the bot that contains the slot. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withSlotName(String slotName) { setSlotName(slotName); return this; } /** * <p> * A description of the slot. Use this to help identify the slot in lists. * </p> * * @param description * A description of the slot. Use this to help identify the slot in lists. */ public void setDescription(String description) { this.description = description; } /** * <p> * A description of the slot. Use this to help identify the slot in lists. * </p> * * @return A description of the slot. Use this to help identify the slot in lists. */ public String getDescription() { return this.description; } /** * <p> * A description of the slot. Use this to help identify the slot in lists. * </p> * * @param description * A description of the slot. Use this to help identify the slot in lists. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * The unique identifier for the slot type associated with this slot. The slot type determines the values that can * be entered into the slot. * </p> * * @param slotTypeId * The unique identifier for the slot type associated with this slot. The slot type determines the values * that can be entered into the slot. */ public void setSlotTypeId(String slotTypeId) { this.slotTypeId = slotTypeId; } /** * <p> * The unique identifier for the slot type associated with this slot. The slot type determines the values that can * be entered into the slot. * </p> * * @return The unique identifier for the slot type associated with this slot. The slot type determines the values * that can be entered into the slot. */ public String getSlotTypeId() { return this.slotTypeId; } /** * <p> * The unique identifier for the slot type associated with this slot. The slot type determines the values that can * be entered into the slot. * </p> * * @param slotTypeId * The unique identifier for the slot type associated with this slot. The slot type determines the values * that can be entered into the slot. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withSlotTypeId(String slotTypeId) { setSlotTypeId(slotTypeId); return this; } /** * <p> * Specifies prompts that Amazon Lex sends to the user to elicit a response that provides the value for the slot. * </p> * * @param valueElicitationSetting * Specifies prompts that Amazon Lex sends to the user to elicit a response that provides the value for the * slot. */ public void setValueElicitationSetting(SlotValueElicitationSetting valueElicitationSetting) { this.valueElicitationSetting = valueElicitationSetting; } /** * <p> * Specifies prompts that Amazon Lex sends to the user to elicit a response that provides the value for the slot. * </p> * * @return Specifies prompts that Amazon Lex sends to the user to elicit a response that provides the value for the * slot. */ public SlotValueElicitationSetting getValueElicitationSetting() { return this.valueElicitationSetting; } /** * <p> * Specifies prompts that Amazon Lex sends to the user to elicit a response that provides the value for the slot. * </p> * * @param valueElicitationSetting * Specifies prompts that Amazon Lex sends to the user to elicit a response that provides the value for the * slot. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withValueElicitationSetting(SlotValueElicitationSetting valueElicitationSetting) { setValueElicitationSetting(valueElicitationSetting); return this; } /** * <p> * Determines how slot values are used in Amazon CloudWatch logs. If the value of the * <code>obfuscationSetting</code> parameter is <code>DefaultObfuscation</code>, slot values are obfuscated in the * log output. If the value is <code>None</code>, the actual value is present in the log output. * </p> * <p> * The default is to obfuscate values in the CloudWatch logs. * </p> * * @param obfuscationSetting * Determines how slot values are used in Amazon CloudWatch logs. If the value of the * <code>obfuscationSetting</code> parameter is <code>DefaultObfuscation</code>, slot values are obfuscated * in the log output. If the value is <code>None</code>, the actual value is present in the log output.</p> * <p> * The default is to obfuscate values in the CloudWatch logs. */ public void setObfuscationSetting(ObfuscationSetting obfuscationSetting) { this.obfuscationSetting = obfuscationSetting; } /** * <p> * Determines how slot values are used in Amazon CloudWatch logs. If the value of the * <code>obfuscationSetting</code> parameter is <code>DefaultObfuscation</code>, slot values are obfuscated in the * log output. If the value is <code>None</code>, the actual value is present in the log output. * </p> * <p> * The default is to obfuscate values in the CloudWatch logs. * </p> * * @return Determines how slot values are used in Amazon CloudWatch logs. If the value of the * <code>obfuscationSetting</code> parameter is <code>DefaultObfuscation</code>, slot values are obfuscated * in the log output. If the value is <code>None</code>, the actual value is present in the log output.</p> * <p> * The default is to obfuscate values in the CloudWatch logs. */ public ObfuscationSetting getObfuscationSetting() { return this.obfuscationSetting; } /** * <p> * Determines how slot values are used in Amazon CloudWatch logs. If the value of the * <code>obfuscationSetting</code> parameter is <code>DefaultObfuscation</code>, slot values are obfuscated in the * log output. If the value is <code>None</code>, the actual value is present in the log output. * </p> * <p> * The default is to obfuscate values in the CloudWatch logs. * </p> * * @param obfuscationSetting * Determines how slot values are used in Amazon CloudWatch logs. If the value of the * <code>obfuscationSetting</code> parameter is <code>DefaultObfuscation</code>, slot values are obfuscated * in the log output. If the value is <code>None</code>, the actual value is present in the log output.</p> * <p> * The default is to obfuscate values in the CloudWatch logs. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withObfuscationSetting(ObfuscationSetting obfuscationSetting) { setObfuscationSetting(obfuscationSetting); return this; } /** * <p> * The identifier of the bot associated with the slot. * </p> * * @param botId * The identifier of the bot associated with the slot. */ public void setBotId(String botId) { this.botId = botId; } /** * <p> * The identifier of the bot associated with the slot. * </p> * * @return The identifier of the bot associated with the slot. */ public String getBotId() { return this.botId; } /** * <p> * The identifier of the bot associated with the slot. * </p> * * @param botId * The identifier of the bot associated with the slot. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withBotId(String botId) { setBotId(botId); return this; } /** * <p> * The version of the bot associated with the slot. * </p> * * @param botVersion * The version of the bot associated with the slot. */ public void setBotVersion(String botVersion) { this.botVersion = botVersion; } /** * <p> * The version of the bot associated with the slot. * </p> * * @return The version of the bot associated with the slot. */ public String getBotVersion() { return this.botVersion; } /** * <p> * The version of the bot associated with the slot. * </p> * * @param botVersion * The version of the bot associated with the slot. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withBotVersion(String botVersion) { setBotVersion(botVersion); return this; } /** * <p> * The identifier of the language and locale that the slot will be used in. The string must match one of the * supported locales. All of the bots, intents, slot types used by the slot must have the same locale. For more * information, see <a href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a>. * </p> * * @param localeId * The identifier of the language and locale that the slot will be used in. The string must match one of the * supported locales. All of the bots, intents, slot types used by the slot must have the same locale. For * more information, see <a href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a>. */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * <p> * The identifier of the language and locale that the slot will be used in. The string must match one of the * supported locales. All of the bots, intents, slot types used by the slot must have the same locale. For more * information, see <a href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a>. * </p> * * @return The identifier of the language and locale that the slot will be used in. The string must match one of the * supported locales. All of the bots, intents, slot types used by the slot must have the same locale. For * more information, see <a href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a>. */ public String getLocaleId() { return this.localeId; } /** * <p> * The identifier of the language and locale that the slot will be used in. The string must match one of the * supported locales. All of the bots, intents, slot types used by the slot must have the same locale. For more * information, see <a href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a>. * </p> * * @param localeId * The identifier of the language and locale that the slot will be used in. The string must match one of the * supported locales. All of the bots, intents, slot types used by the slot must have the same locale. For * more information, see <a href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withLocaleId(String localeId) { setLocaleId(localeId); return this; } /** * <p> * The identifier of the intent that contains the slot. * </p> * * @param intentId * The identifier of the intent that contains the slot. */ public void setIntentId(String intentId) { this.intentId = intentId; } /** * <p> * The identifier of the intent that contains the slot. * </p> * * @return The identifier of the intent that contains the slot. */ public String getIntentId() { return this.intentId; } /** * <p> * The identifier of the intent that contains the slot. * </p> * * @param intentId * The identifier of the intent that contains the slot. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withIntentId(String intentId) { setIntentId(intentId); return this; } /** * <p> * Indicates whether the slot returns multiple values in one response. Multi-value slots are only available in the * en-US locale. If you set this value to <code>true</code> in any other locale, Amazon Lex throws a * <code>ValidationException</code>. * </p> * <p> * If the <code>multipleValuesSetting</code> is not set, the default value is <code>false</code>. * </p> * * @param multipleValuesSetting * Indicates whether the slot returns multiple values in one response. Multi-value slots are only available * in the en-US locale. If you set this value to <code>true</code> in any other locale, Amazon Lex throws a * <code>ValidationException</code>. </p> * <p> * If the <code>multipleValuesSetting</code> is not set, the default value is <code>false</code>. */ public void setMultipleValuesSetting(MultipleValuesSetting multipleValuesSetting) { this.multipleValuesSetting = multipleValuesSetting; } /** * <p> * Indicates whether the slot returns multiple values in one response. Multi-value slots are only available in the * en-US locale. If you set this value to <code>true</code> in any other locale, Amazon Lex throws a * <code>ValidationException</code>. * </p> * <p> * If the <code>multipleValuesSetting</code> is not set, the default value is <code>false</code>. * </p> * * @return Indicates whether the slot returns multiple values in one response. Multi-value slots are only available * in the en-US locale. If you set this value to <code>true</code> in any other locale, Amazon Lex throws a * <code>ValidationException</code>. </p> * <p> * If the <code>multipleValuesSetting</code> is not set, the default value is <code>false</code>. */ public MultipleValuesSetting getMultipleValuesSetting() { return this.multipleValuesSetting; } /** * <p> * Indicates whether the slot returns multiple values in one response. Multi-value slots are only available in the * en-US locale. If you set this value to <code>true</code> in any other locale, Amazon Lex throws a * <code>ValidationException</code>. * </p> * <p> * If the <code>multipleValuesSetting</code> is not set, the default value is <code>false</code>. * </p> * * @param multipleValuesSetting * Indicates whether the slot returns multiple values in one response. Multi-value slots are only available * in the en-US locale. If you set this value to <code>true</code> in any other locale, Amazon Lex throws a * <code>ValidationException</code>. </p> * <p> * If the <code>multipleValuesSetting</code> is not set, the default value is <code>false</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateSlotRequest withMultipleValuesSetting(MultipleValuesSetting multipleValuesSetting) { setMultipleValuesSetting(multipleValuesSetting); 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 (getSlotName() != null) sb.append("SlotName: ").append(getSlotName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getSlotTypeId() != null) sb.append("SlotTypeId: ").append(getSlotTypeId()).append(","); if (getValueElicitationSetting() != null) sb.append("ValueElicitationSetting: ").append(getValueElicitationSetting()).append(","); if (getObfuscationSetting() != null) sb.append("ObfuscationSetting: ").append(getObfuscationSetting()).append(","); if (getBotId() != null) sb.append("BotId: ").append(getBotId()).append(","); if (getBotVersion() != null) sb.append("BotVersion: ").append(getBotVersion()).append(","); if (getLocaleId() != null) sb.append("LocaleId: ").append(getLocaleId()).append(","); if (getIntentId() != null) sb.append("IntentId: ").append(getIntentId()).append(","); if (getMultipleValuesSetting() != null) sb.append("MultipleValuesSetting: ").append(getMultipleValuesSetting()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateSlotRequest == false) return false; CreateSlotRequest other = (CreateSlotRequest) obj; if (other.getSlotName() == null ^ this.getSlotName() == null) return false; if (other.getSlotName() != null && other.getSlotName().equals(this.getSlotName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getSlotTypeId() == null ^ this.getSlotTypeId() == null) return false; if (other.getSlotTypeId() != null && other.getSlotTypeId().equals(this.getSlotTypeId()) == false) return false; if (other.getValueElicitationSetting() == null ^ this.getValueElicitationSetting() == null) return false; if (other.getValueElicitationSetting() != null && other.getValueElicitationSetting().equals(this.getValueElicitationSetting()) == false) return false; if (other.getObfuscationSetting() == null ^ this.getObfuscationSetting() == null) return false; if (other.getObfuscationSetting() != null && other.getObfuscationSetting().equals(this.getObfuscationSetting()) == false) return false; if (other.getBotId() == null ^ this.getBotId() == null) return false; if (other.getBotId() != null && other.getBotId().equals(this.getBotId()) == false) return false; if (other.getBotVersion() == null ^ this.getBotVersion() == null) return false; if (other.getBotVersion() != null && other.getBotVersion().equals(this.getBotVersion()) == false) return false; if (other.getLocaleId() == null ^ this.getLocaleId() == null) return false; if (other.getLocaleId() != null && other.getLocaleId().equals(this.getLocaleId()) == false) return false; if (other.getIntentId() == null ^ this.getIntentId() == null) return false; if (other.getIntentId() != null && other.getIntentId().equals(this.getIntentId()) == false) return false; if (other.getMultipleValuesSetting() == null ^ this.getMultipleValuesSetting() == null) return false; if (other.getMultipleValuesSetting() != null && other.getMultipleValuesSetting().equals(this.getMultipleValuesSetting()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSlotName() == null) ? 0 : getSlotName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getSlotTypeId() == null) ? 0 : getSlotTypeId().hashCode()); hashCode = prime * hashCode + ((getValueElicitationSetting() == null) ? 0 : getValueElicitationSetting().hashCode()); hashCode = prime * hashCode + ((getObfuscationSetting() == null) ? 0 : getObfuscationSetting().hashCode()); hashCode = prime * hashCode + ((getBotId() == null) ? 0 : getBotId().hashCode()); hashCode = prime * hashCode + ((getBotVersion() == null) ? 0 : getBotVersion().hashCode()); hashCode = prime * hashCode + ((getLocaleId() == null) ? 0 : getLocaleId().hashCode()); hashCode = prime * hashCode + ((getIntentId() == null) ? 0 : getIntentId().hashCode()); hashCode = prime * hashCode + ((getMultipleValuesSetting() == null) ? 0 : getMultipleValuesSetting().hashCode()); return hashCode; } @Override public CreateSlotRequest clone() { return (CreateSlotRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-lexmodelsv2/src/main/java/com/amazonaws/services/lexmodelsv2/model/CreateSlotRequest.java
Java
apache-2.0
26,672
# Codium tomentosum var. elongatum (Turner) Ardissone VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Chlorophyta/Bryopsidophyceae/Bryopsidales/Codiaceae/Codium/Codium decorticatum/ Syn. Codium tomentosum elongatum/README.md
Markdown
apache-2.0
208
# Copyright 2018 Rackspace, US Inc. # Copyright 2019 Red Hat, 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. import errno import os import socketserver import threading from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from octavia.api.drivers.driver_agent import driver_get from octavia.api.drivers.driver_agent import driver_updater CONF = cfg.CONF LOG = logging.getLogger(__name__) def _recv(recv_socket): size_str = b'' char = recv_socket.recv(1) while char != b'\n': size_str += char char = recv_socket.recv(1) payload_size = int(size_str) mv_buffer = memoryview(bytearray(payload_size)) next_offset = 0 while payload_size - next_offset > 0: recv_size = recv_socket.recv_into(mv_buffer[next_offset:], payload_size - next_offset) next_offset += recv_size return jsonutils.loads(mv_buffer.tobytes()) class StatusRequestHandler(socketserver.BaseRequestHandler): def handle(self): # Get the update data status = _recv(self.request) # Process the update updater = driver_updater.DriverUpdater() response = updater.update_loadbalancer_status(status) # Send the response json_data = jsonutils.dump_as_bytes(response) len_str = '{}\n'.format(len(json_data)).encode('utf-8') self.request.send(len_str) self.request.sendall(json_data) class StatsRequestHandler(socketserver.BaseRequestHandler): def handle(self): # Get the update data stats = _recv(self.request) # Process the update updater = driver_updater.DriverUpdater() response = updater.update_listener_statistics(stats) # Send the response json_data = jsonutils.dump_as_bytes(response) len_str = '{}\n'.format(len(json_data)).encode('utf-8') self.request.send(len_str) self.request.sendall(json_data) class GetRequestHandler(socketserver.BaseRequestHandler): def handle(self): # Get the data request get_data = _recv(self.request) # Process the get response = driver_get.process_get(get_data) # Send the response json_data = jsonutils.dump_as_bytes(response) len_str = '{}\n'.format(len(json_data)).encode('utf-8') self.request.send(len_str) self.request.sendall(json_data) class ForkingUDSServer(socketserver.ForkingMixIn, socketserver.UnixStreamServer): pass def _cleanup_socket_file(filename): # Remove the socket file if it already exists try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: raise def status_listener(exit_event): _cleanup_socket_file(CONF.driver_agent.status_socket_path) server = ForkingUDSServer(CONF.driver_agent.status_socket_path, StatusRequestHandler) server.timeout = CONF.driver_agent.status_request_timeout server.max_children = CONF.driver_agent.status_max_processes while not exit_event.is_set(): server.handle_request() LOG.info('Waiting for driver status listener to shutdown...') # Can't shut ourselves down as we would deadlock, spawn a thread threading.Thread(target=server.shutdown).start() LOG.info('Driver status listener shutdown finished.') server.server_close() _cleanup_socket_file(CONF.driver_agent.status_socket_path) def stats_listener(exit_event): _cleanup_socket_file(CONF.driver_agent.stats_socket_path) server = ForkingUDSServer(CONF.driver_agent.stats_socket_path, StatsRequestHandler) server.timeout = CONF.driver_agent.stats_request_timeout server.max_children = CONF.driver_agent.stats_max_processes while not exit_event.is_set(): server.handle_request() LOG.info('Waiting for driver statistics listener to shutdown...') # Can't shut ourselves down as we would deadlock, spawn a thread threading.Thread(target=server.shutdown).start() LOG.info('Driver statistics listener shutdown finished.') server.server_close() _cleanup_socket_file(CONF.driver_agent.stats_socket_path) def get_listener(exit_event): _cleanup_socket_file(CONF.driver_agent.get_socket_path) server = ForkingUDSServer(CONF.driver_agent.get_socket_path, GetRequestHandler) server.timeout = CONF.driver_agent.get_request_timeout server.max_children = CONF.driver_agent.get_max_processes while not exit_event.is_set(): server.handle_request() LOG.info('Waiting for driver get listener to shutdown...') # Can't shut ourselves down as we would deadlock, spawn a thread threading.Thread(target=server.shutdown).start() LOG.info('Driver get listener shutdown finished.') server.server_close() _cleanup_socket_file(CONF.driver_agent.get_socket_path) LOG.info("UDS server was closed and socket was cleaned up.")
openstack/octavia
octavia/api/drivers/driver_agent/driver_listener.py
Python
apache-2.0
5,587
// ERRORS_KEY = 'signinErrors' Template.signin.onCreated(function() { // Session.set(ERRORS_KEY, {}) }); Template.signin.helpers({ userName: function() { // if (!$('input[name="name"]').val()) { // return ; // } else { return "guest"; // } }, avator: function() { return "/images/avator.png"; } // errorMessages: function() { // return _.values(Session.get(ERRORS_KEY)); // }, // errorClass: function(key) { // Session.get(ERRORS_KEY)[key] && 'error'; // } }); Template.signin.events({ 'click .fa-google-plus-square': function() { return Meteor.loginWithGoogle({ requestPermissions: ['email'] }, function(error) { if (error) { console.log(error); swal("验证失败!"); return ; } else { Meteor.call("updateGooleAccount", Meteor.userId(), function(err, res) { if (err || !res) { console.log(err); console.log("google account create err"); } else { console.log(res); } }); if (Session.get("SESSION_URL_HREF")) { Router.go(Session.get("SESSION_URL_HREF")); } else { Router.go("home"); } } }); }, 'click .fa-weixin': function() { Meteor.loginWithWechat(function(err, res) { if (!err) { if (Session.get("SESSION_URL_HREF")) { Router.go(Session.get("SESSION_URL_HREF")); } else { Router.go("home"); } } else{ console.log('login failed ' + err); } }); }, 'click .fa-weibo': function() { Meteor.loginWithWeibo(function(err, res) { if (!err) { if (Session.get("SESSION_URL_HREF")) { Router.go(Session.get("SESSION_URL_HREF")); } else { Router.go("home"); } console.log('sucess ' + res) } else { console.log('login failed ' + err) } }); }, 'submit': function(event, template) { event.preventDefault(); userName = template.$('input[name="name"]').val(); password = template.$('input[name="password"]').val(); errors = {} if (!userName) { errors.userName = '用户名不能为空!'; swal(errors.userName); } if (!password) { errors.password = '密码能为空!'; swal(errors.userName); } // Session.set(ERRORS_KEY, errors); if (errors.userName) { return; } template.$('.submit').val("logining..."); Meteor.loginWithPassword(userName, password, function(error) { if (error) { // var phoneAccount = PhonesColl.findOne({phoneNum: userName}); // if (phoneAccount) { /*** need hack ***/ // Meteor.call("isExistUser", userName, function(error, result) { // if (error || !result) { swal("登录失败,账号不存在"); // } else { // Meteor.loginWithPassword(result, password, function(error) { // if (error) { // swal(error.reason); // return; // } else { // Router.go('home'); // } // }); // } // }); // } else { // swal(error.reason); // } // console.log(error); // Session.set(ERRORS_KEY, { // 'none': error.reason // }); } else { Router.go('home'); } }); template.$('.submit').val("LOGIN"); } }); Template.signin.onRendered(function() { // $('.ui.sidebar').sidebar('attach events', '.sidebar.icon'); })
YY030913/start
client/templates/register/signin.js
JavaScript
apache-2.0
4,473
package com.example.pgg.weather; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.pgg.weather.db.City; import com.example.pgg.weather.db.County; import com.example.pgg.weather.db.Province; import com.example.pgg.weather.util.HttpUtil; import com.example.pgg.weather.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by PGG on 2017/2/26. */ public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private TextView text_title; private ListView list_view; private Button back_button; private List<String> dataList = new ArrayList<>(); private ArrayAdapter<String> adapter; /** * 省列表 */ private List<Province> provinceList; /** * 市列表 */ private List<City> cityList; /** * 县列表 */ private List<County> countyList; /** * 当前选中的级别 */ private int currentLevel; /** * 选中的级别为省份 */ private Province selectedProvince; /** * 选中级别为城市 */ private City selectedCity; private ProgressDialog progressDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area, container, false); text_title = (TextView) view.findViewById(R.id.text_title); list_view = (ListView) view.findViewById(R.id.list_view); back_button = (Button) view.findViewById(R.id.back_button); adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList); list_view.setAdapter(adapter); return view; } @Override public void onActivityCreated( Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(position); querryCity(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); querryCounty(); }else if (currentLevel == LEVEL_COUNTY){ String weatherId = countyList.get(position).getWeatherId(); Intent intent = new Intent(getActivity(), WeatherActivity.class); intent.putExtra("weather_id",weatherId); startActivity(intent); getActivity().finish(); } } }); back_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY) { querryCity(); } else if (currentLevel == LEVEL_CITY) { queryProvince(); } } }); queryProvince(); } /** * 查询全国的省份,优先数据库,没有再去服务器 */ private void queryProvince() { text_title.setText("中国"); back_button.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); list_view.setSelection(0); currentLevel = LEVEL_PROVINCE; } else { String address = "http://guolin.tech/api/china"; querryFromServe(address, "province"); } } /** * 查询全国的县,优先数据库,没有再去服务器 */ private void querryCounty() { text_title.setText(selectedCity.getCityName()); back_button.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); list_view.setSelection(0); currentLevel = LEVEL_COUNTY; } else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china" + provinceCode + cityCode; querryFromServe(address, "county"); } } /** * 查询全国的城市,优先数据库,没有再去服务器 */ private void querryCity() { text_title.setText(selectedProvince.getProvinceName()); back_button.setVisibility(View.VISIBLE); cityList = DataSupport.where("province = ?", String.valueOf(selectedProvince.getId())).find(City.class); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); list_view.setSelection(0); currentLevel = LEVEL_CITY; } else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china" + provinceCode; querryFromServe(address, "city"); } } /** * 从服务器获取数据 */ private void querryFromServe(String address, final String type) { showProgressDialog(); HttpUtil.sendOKHttpReuset(address, new Callback() { @Override public void onFailure(Call call, IOException e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String responseTest = response.body().toString(); boolean result = false; if ("province".equals(type)){ result = Utility.handleProvinceResponce(responseTest); }else if("city".equals(type)){ result = Utility.handleCityResponce(responseTest, selectedProvince.getId()); }else if ("county".equals(type)){ result = Utility.handleCountyResponce(responseTest, selectedCity.getId()); } if (result){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)){ queryProvince(); }else if ("city".equals(type)){ querryCity(); }else if("county".equals(type)){ querryCounty(); } } }); } } }); } private void closeProgressDialog() { if (progressDialog == null){ progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载。。。"); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } private void showProgressDialog() { if (progressDialog != null){ progressDialog.dismiss(); } } }
pgga/Weather
app/src/main/java/com/example/pgg/weather/ChooseAreaFragment.java
Java
apache-2.0
8,707
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>{{fsdocs-page-title}}</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="author" content="{{fsdocs-authors}}"> <link rel="stylesheet" id="theme_link" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.6.0/materia/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML"></script> <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico"> <link type="text/css" rel="stylesheet" href="{{root}}content/navbar-{{fsdocs-navbar-position}}.css" /> <link type="text/css" rel="stylesheet" href="{{root}}content/fsdocs-{{fsdocs-theme}}.css" /> <link type="text/css" rel="stylesheet" href="{{root}}content/fsdocs-custom.css" /> <script type="text/javascript" src="{{root}}content/fsdocs-tips.js"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- BEGIN SEARCH BOX: this adds support for the search box --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/JavaScript-autoComplete/1.0.4/auto-complete.css" /> <!-- END SEARCH BOX: this adds support for the search box --> {{fsdocs-watch-script}} </head> <body> <nav class="navbar navbar-expand-md navbar-light bg-secondary navbar-nav-scroll {{fsdocs-navbar-position}}" id="fsdocs-nav"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <a href="{{fsdocs-logo-link}}"><img id="fsdocs-logo" src="{{fsdocs-logo-src}}" /></a> <!-- BEGIN SEARCH BOX: this adds support for the search box --> <div id="header"> <div class="searchbox" id="fsdocs-searchbox"> <label for="search-by"> <i class="fas fa-search"></i> </label> <input data-search-input="" id="search-by" type="search" placeholder="Search..." /> <span data-search-clear=""> <i class="fas fa-times"></i> </span> </div> </div> <!-- END SEARCH BOX: this adds support for the search box --> <ul class="navbar-nav"> <li class="nav-header">Links</li> <li class="nav-item" id="fsdocs-license-link"><a class="nav-link" href="{{fsdocs-license-link}}">License</a></li> <li class="nav-item" id="fsdocs-release-notes-link"><a class="nav-link" href="{{fsdocs-release-notes-link}}">Release Notes</a></li> <li class="nav-item" id="fsdocs-repository-link"><a class="nav-link" href="{{fsdocs-repository-link}}">Source Repository</a></li> {{fsdocs-list-of-documents}} {{fsdocs-list-of-namespaces}} </ul> </div> </nav> <div class="container"> <div class="masthead"> <h3 class="muted"><a href="{{fsdocs-collection-name-link}}">{{fsdocs-collection-name}}</a></h3> </div> <hr /> <div class="container" id="fsdocs-content"> {{fsdocs-content}} {{fsdocs-tooltips}} </div> <!-- BEGIN SEARCH BOX: this adds support for the search box --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/JavaScript-autoComplete/1.0.4/auto-complete.css" /> <script type="text/javascript">var fsdocs_search_baseurl = '{{root}}';</script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lunr.js/2.3.8/lunr.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/JavaScript-autoComplete/1.0.4/auto-complete.min.js"></script> <script type="text/javascript" src="{{root}}content/fsdocs-search.js"></script> <!-- END SEARCH BOX: this adds support for the search box --> </div> </body> </html>
tpetricek/FSharp.Formatting
docs/_template.html
HTML
apache-2.0
4,689
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.w3.org/1999/xhtml"> <head th:replace="fragments/head :: head"> <title>BioSamples &lt; EMBL-EBI</title> <!-- A few keywords that relate to the content of THIS PAGE (not the whole project) --> <meta name="keywords" content="biosamples, europe, EBI" /> <!-- Describe what this page is about --> <meta name="description" content="EMBL-EBI" /> <meta name="ebi:last-review" content="2016-12-20" /> <!-- The last time the content was reviewed --> <meta name="ebi:expiry" content="2017-12-20" /> <!-- When this content is no longer relevant --> </head> <body> <div th:insert="fragments/header :: header"></div> <div layout:fragment="content" id="content"> <th:block th:include="fragments/header :: masterhead"></th:block> <div id="main-content-area" class="row padding-top-xlarge padding-left-xlarge padding-right-xlarge columns"> <h2>About BioSamples</h2> <h3 class="icon icon-spacer icon-generic" data-icon="}">The team</h3> <p>The BioSamples team is part of the <a href="/about/people/helen-parkinson">Helen Parkinson's team</a> at EMBL-EBI. The team consists of bioinformaticians, ontologists, software engineers and web developers.</p> <h3 class='icon icon-spacer icon-generic' data-icon='E'>Contact us</h3> <p>If you want to contact us, please email <a href="mailto:biosamples@ebi.ac.uk">biosamples@ebi.ac.uk</a>. We welcome enquiries on data submission and data access, as well as more technical issues, e.g. integration with other data bases, linked open data, etc. We aim to respond to all emails within 1 working day.</p> <h3 class='icon icon-spacer icon-generic' data-icon='m'>Announcements</h3> <p>If you use the Biosamples Database regularly, or maintain software that interacts with it, you may want to keep up to date with any changes and improvements by <a href="//listserver.ebi.ac.uk/mailman/listinfo/biosamples-announce">subscribing to the announcement mailing list</a>. </p> <h3 class="icon icon-spacer icon-generic" data-icon="P">Privacy Notices and Terms of Use</h3> <p>This website requires cookies, and the limited processing of your personal data in order to function. By using the site you are agreeing to this as outlined in our <a href="https://www.ebi.ac.uk/data-protection/privacy-notice/embl-ebi-public-website">Privacy Notice</a> and <a href="https://www.ebi.ac.uk/about/terms-of-use">Terms of Use.</a></p> <p>If you submit information to BioSamples please note that we will handle your submission in accordance with our <a href="https://www.ebi.ac.uk/data-protection/privacy-notice/biosamples-submissions">Submission Privacy Notice</a>.</p> <h3 class="icon icon-spacer icon-generic" data-icon="U">Publications / how to cite</h3> <ul> <li><strong>Citing BioSamples database</strong>: please use the following publication: Courtot M, Gupta D, Liyanage I, Xu F, Burdett T. <a href="https://academic.oup.com/nar/advance-article/doi/10.1093/nar/gkab1046/6423179?rss=1"> BioSamples database: FAIRer samples metadata to accelerate research data management.</a> Nucleic Acids Research. 2021 Nov 8. <a href="https://doi.org/10.1093/nar/gkab1046">https://doi.org/10.1093/nar/gkab1046</a> </li> <li><strong>Citing BioSamples records in your manuscript</strong>: please include your sample and group accession numbers and the URL to BioSamples home page e.g. "Sample meta-data are available in the BioSamples database (http://www.ebi.ac.uk/biosamples) under accession numbers SAMxxxxxx, SAMxxxxxx, SAMxxxxxx, and SAMxxxxxx." </li> <li><strong>Previous publications</strong>: Melanie Courtot, Luca Cherubin, Adam Faulconbridge, Daniel Vaughan, Matthew Green, David Richardson, Peter Harrison, Patricia L Whetzel, Helen Parkinson, Tony Burdett; <a href="https://europepmc.org/abstract/MED/30407529">BioSamples database: an updated sample metadata hub</a>, Nucleic Acids Research, Volume 47, Issue D1, 8 January 2019, Pages D1172–D1178, <a href="https://doi.org/10.1093/nar/gky1061">https://doi.org/10.1093/nar/gky1061</a> </li> </ul> <h3 class="icon icon-spacer icon-generic" data-icon="I">Acknowledgements</h3> <p>BioSamples has been made possible with the support of our funders:</p> <ul> <li>European Molecular Biology Laboratory - European Bioinformatics Institute core funds</li> <li>European Commission ELIXIR-EXCELERATE</li> <li>Wellcome Trust (WT) and Medical Research Council (MRC) - Human Induced Pluripotent Stem Cells Initiative (HipSci)</li> <li>Innovative Medicines Initiative (IMI) - European Bank for induced pluripotent Stem Cells (EBiSC)</li> <li>ELIXIR Meta Data implementation study</li> <li>Wellcome Trust (WT) - Global Alliance for Genomics and Health (GA4GH)</li> </ul> <p>The BioSamples team would like to thank the following companies for their support:</p> <ul> <li><a href="http://www.atlassian.com" target="_blank">Atlassian</a> for <a href="http://www.atlassian.com/software/bamboo/overview" target="_blank">Bamboo</a> - Continuous Integration and Release Management tool.</li> <li><a href="http://www.browserstack.com" target="_blank">BrowserStack</a> for providing the infrastructure that allows us to test our service in real browsers. <a href="http://www.browserstack.com" target="_blank"><img src="https://www.browserstack.com/images/mail/browserstack-logo-footer.png" width="120"></a></li> </ul> </div> </div> <div th:insert="fragments/footer :: footer"></div> </body> </html>
EBIBioSamples/biosamples-v4
webapps/core/src/main/resources/templates/about.html
HTML
apache-2.0
5,934
/* * #%L * BroadleafCommerce Common Libraries * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.common.site.dao; import org.broadleafcommerce.common.persistence.EntityConfiguration; import org.broadleafcommerce.common.site.domain.Catalog; import org.broadleafcommerce.common.site.domain.CatalogImpl; import org.broadleafcommerce.common.site.domain.Site; import org.broadleafcommerce.common.site.domain.SiteImpl; import org.broadleafcommerce.common.site.service.type.SiteResolutionType; import org.hibernate.ejb.QueryHints; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; @Repository("blSiteDao") public class SiteDaoImpl implements SiteDao { @PersistenceContext(unitName = "blPU") protected EntityManager em; @Resource(name = "blEntityConfiguration") protected EntityConfiguration entityConfiguration; @Override public Site create() { return (Site) entityConfiguration.createEntityInstance(Site.class.getName()); } @Override public Site retrieve(Long id) { return em.find(SiteImpl.class, id); } @Override public Catalog retrieveCatalog(Long id) { return em.find(CatalogImpl.class, id); } @Override public List<Site> readAllActiveSites() { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Site> criteria = builder.createQuery(Site.class); Root<SiteImpl> site = criteria.from(SiteImpl.class); criteria.select(site); criteria.where( builder.and( builder.or(builder.isNull(site.get("archiveStatus").get("archived").as(String.class)), builder.notEqual(site.get("archiveStatus").get("archived").as(Character.class), 'Y')), builder.or(builder.isNull(site.get("deactivated").as(Boolean.class)), builder.notEqual(site.get("deactivated").as(Boolean.class), true)) ) ); TypedQuery<Site> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getResultList(); } @Override public Site retrieveSiteByDomainOrDomainPrefix(String domain, String domainPrefix) { if (domain == null) { return null; } List<String> siteIdentifiers = new ArrayList<String>(); siteIdentifiers.add(domain); siteIdentifiers.add(domainPrefix); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Site> criteria = builder.createQuery(Site.class); Root<SiteImpl> site = criteria.from(SiteImpl.class); criteria.select(site); criteria.where(site.get("siteIdentifierValue").as(String.class).in(siteIdentifiers)); TypedQuery<Site> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); List<Site> results = query.getResultList(); for (Site currentSite : results) { if (SiteResolutionType.DOMAIN.equals(currentSite.getSiteResolutionType())) { if (domain.equals(currentSite.getSiteIdentifierValue())) { return currentSite; } } if (SiteResolutionType.DOMAIN_PREFIX.equals(currentSite.getSiteResolutionType())) { if (domainPrefix.equals(currentSite.getSiteIdentifierValue())) { return currentSite; } } // We need to forcefully load this collection. currentSite.getCatalogs().size(); } return null; } @Override public Site save(Site site) { return em.merge(site); } @Override public Site retrieveDefaultSite() { return null; } @Override public Catalog save(Catalog catalog) { return em.merge(catalog); } }
jiman94/BroadleafCommerce-BroadleafCommerce2014
common/src/main/java/org/broadleafcommerce/common/site/dao/SiteDaoImpl.java
Java
apache-2.0
4,826
/* * Copyright (C) 2017 * Michael Mosmann <michael@mosmann.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. */ package de.flapdoodle.solid.theme.mustache; import java.util.List; import java.util.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.DefaultCollector; import com.samskivert.mustache.Mustache.VariableFetcher; import de.flapdoodle.solid.theme.MapLike; import de.flapdoodle.solid.types.Maybe; import de.flapdoodle.solid.types.reflection.Inspector; import de.flapdoodle.solid.types.tree.PropertyTree; import de.flapdoodle.types.Either; final class CustomCollector extends DefaultCollector { /** * */ private final MustacheTheme mustacheTheme; /** * @param mustacheTheme */ CustomCollector(MustacheTheme mustacheTheme) { this.mustacheTheme = mustacheTheme; } @Override public VariableFetcher createFetcher(Object ctx, String name) { return wrapWithMaybeAndOptionalExtractor(internal(ctx, name)); } private VariableFetcher internal(Object ctx, String name) { try { // Preconditions.checkArgument(!name.isEmpty(),"you should not use something like {{ .Foo }}"); if (name.isEmpty()) { return (c,n) -> c; } VariableFetcher ret = super.createFetcher(ctx, name); if (ret==null) { // System.out.println(""+ctx.getClass()+".'"+name+"'"); if ("*".equals(name)) { return (c,n) -> Inspector.propertyNamesOf(c.getClass()); } if (ctx instanceof MapLike) { Maybe<Object> value = ((MapLike) ctx).get(name); if (value.isPresent()) { return (c,n) -> value.get(); } } if (ctx instanceof PropertyTree) { return (c,n) -> ((PropertyTree) c).get(n); } if (ctx instanceof MustacheFormating) { ImmutableMap<String, de.flapdoodle.solid.formatter.Formatter> map = Preconditions.checkNotNull(this.mustacheTheme.formatter.get(),"formatter map not set"); de.flapdoodle.solid.formatter.Formatter formatter = map.get(name); return (c,n) ->formatter.format(((MustacheFormating) c).value()).orElse(() -> ""); } if (name.equals("formatWith")) { return (c,n) -> CustomCollector.singleValue(c).map(MustacheFormating::of).orElse(null); } } return ret; } catch (RuntimeException rx) { throw new RuntimeException("ctx.class: "+ctx.getClass()+", name: '"+name+"'",rx); } } private VariableFetcher wrapWithMaybeAndOptionalExtractor(VariableFetcher src) { if (src!=null) { return (ctx,name) -> { Object ret = src.get(ctx, name); if (ret instanceof Maybe) { Maybe maybe = (Maybe) ret; return maybe.isPresent() ? maybe.get() : null; } if (ret instanceof Optional) { Optional maybe = (Optional) ret; return maybe.isPresent() ? maybe.get() : null; } if (ret instanceof com.google.common.base.Optional) { com.google.common.base.Optional maybe = (com.google.common.base.Optional) ret; return maybe.isPresent() ? maybe.get() : null; } return ret; }; } return src; } protected static Maybe<Object> singleValue(Object c) { if (c instanceof List) { List l=(List) c; if (l.size()==1) { return singleValue(l.get(0)); } return Maybe.empty(); } if (c instanceof Either) { Either e=(Either) c; return e.isLeft() ? singleValue(e.left()) : singleValue(e.right()); } return Maybe.ofNullable(c); } }
flapdoodle-oss/de.flapdoodle.solid
src/main/java/de/flapdoodle/solid/theme/mustache/CustomCollector.java
Java
apache-2.0
4,011
using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Controller { public partial class Main : Form { private BeamerOutput beamerForm; private PrinterProcess processor; private IPrinterInterface printerInterface; private MonitorPrinterStatus monitorPrinter; private MachineConfig machineConfig; public Main() { InitializeComponent(); SetBeamerBoundsAndPosition(); SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged; this.machineConfig = new MachineConfig(); this.txtProjectionTimeMs.Text = this.projectionTimeMs.ToString(); this.txtProjectionTimeMsFirstGroup.Text = this.projectionTimeMsFirstGroup.ToString(); this.txtProjectionTimeMsSecondGroup.Text = this.projectionTimeMsSecondGroup.ToString(); this.txtFirstGroupCount.Text = this.projectionTimeMsFirstGroupCount.ToString(); this.txtSecondGroupCount.Text = this.projectionTimeMsSecondGroupCount.ToString(); } void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e) { SetBeamerBoundsAndPosition(); } private void SetBeamerBoundsAndPosition() { if (this.beamerForm != null) { this.beamerForm.ForceClose(); this.beamerForm = null; } this.beamerForm = new BeamerOutput(); this.beamerForm.StartPosition = FormStartPosition.Manual; var beamerScreen = GetBeamerScreen(); Rectangle bounds; if (beamerScreen != null) { bounds = beamerScreen.Bounds; } else { beamerForm.WindowState = FormWindowState.Normal; beamerForm.FormBorderStyle = FormBorderStyle.Sizable; beamerForm.TopMost = false; bounds = new Rectangle(500, 10, 400, 400); } this.beamerForm.SetBounds(bounds.X, bounds.Y, bounds.Width, bounds.Height); this.beamerForm.Show(); } private static Screen GetBeamerScreen() { var screens = Screen.AllScreens; Screen beamer = null; foreach (var screen in screens) { if (!screen.Primary) { beamer = screen; } } return beamer; } private void btnSliceFolder_Click(object sender, EventArgs e) { if (sliceFolderDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtFolder.Text = Path.GetFileName(sliceFolderDlg.SelectedPath); } } private DateTime startTime = DateTime.Now; private void btnStart_Click(object sender, EventArgs e) { if (this.processor == null) { if (string.IsNullOrWhiteSpace(sliceFolderDlg.SelectedPath)) { MessageBox.Show("Select a folder with images first."); } else { this.processor = new PrinterProcess( sliceFolderDlg.SelectedPath, this.beamerForm, this, this.printerInterface, this.machineConfig); this.processor.SetProjectionTime(this.projectionTimeMs); if (this.projectionTimeMsFirstGroup > 0) { this.processor.SetProjectionTimeFirstGroup(this.projectionTimeMsFirstGroup, this.projectionTimeMsFirstGroupCount); } if (this.projectionTimeMsSecondGroup > 0) { this.processor.SetProjectionTimeSecondGroup(this.projectionTimeMsSecondGroup, this.projectionTimeMsSecondGroupCount, this.cbDipForSecondLayer.Checked); } this.processor.SetDelicateMode(this.cbDelicateMode.Checked); btnStart.Image = Properties.Resources.glyphicons_175_stop; btnStart.Text = "Stop"; ToolTipHelp.SetToolTip(btnStart, "Stop printing process."); this.processor.Start(); this.startTime = DateTime.Now; } } else { this.StatusMessage("Stopping printer process, please wait..."); this.processor.Stop(); btnStart.Enabled = false; btnPause.Enabled = false; } } private delegate void StatusMessageInvoker(string message); public void StatusMessage(string message) { if (this.InvokeRequired) { var invoker = new StatusMessageInvoker(StatusMessage); this.Invoke(invoker, message); } else { var formattedMessage = DateTime.Now.ToString("hh:mm:ss") + ": " + message + Environment.NewLine; this.txtStatus.AppendText(formattedMessage); Trace.Write(formattedMessage); } } private delegate void ProcessorDoneInvoker(); public void ProcessorDone() { if (this.InvokeRequired) { var invoker = new ProcessorDoneInvoker(ProcessorDone); this.Invoke(invoker); } else { processor = null; progressBar.Value = 0; SetTotalSlices(0); SetCurrentSlice(0); StatusMessage("Done..."); SetThumbnail(null); btnStart.Enabled = true; btnPause.Enabled = true; btnStart.Image = Properties.Resources.glyphicons_173_play; btnStart.Text = "Start"; ToolTipHelp.SetToolTip(btnStart, "Start printing process."); btnPause.Image = Properties.Resources.glyphicons_174_pause; btnPause.Text = "Pause"; if (this.mainFormClosing) { this.Close(); } } } private delegate void MonitoringDoneInvoker(); public void MonitoringDone() { if (this.InvokeRequired) { var invoker = new MonitoringDoneInvoker(MonitoringDone); this.Invoke(invoker); } else { this.monitorPrinter = null; if (this.mainFormClosing) { this.Close(); } } } private delegate void SetThumbnailInvoke(Image thumb); internal void SetThumbnail(Image thumb) { if (this.InvokeRequired) { var invoker = new SetThumbnailInvoke(SetThumbnail); this.Invoke(invoker, thumb); } else { this.pbLayerThumbnail.BackgroundImage = thumb; } } private int projectionTimeMs = 3000; private void txtProjectionTimeMs_TextChanged(object sender, EventArgs e) { var oldValue = txtProjectionTimeMs.Text; this.projectionTimeMs = ValidateTextInputIsNumberAndReturnValue(txtProjectionTimeMs, 3000); if (this.processor != null) { if (!this.processor.SetProjectionTime(projectionTimeMs)) { this.projectionTimeMs = int.Parse(oldValue); this.txtProjectionTimeMs.Text = oldValue; } } } private int ValidateTextInputIsNumberAndReturnValue(TextBox txtBox, int defaultValue) { int value = defaultValue; var timeMs = Regex.Replace(txtBox.Text, @"[^0-9]", ""); if (!string.IsNullOrWhiteSpace(timeMs)) { value = int.Parse(timeMs); } txtBox.Text = value.ToString(); return value; } private int projectionTimeMsFirstGroup = 50000; private int projectionTimeMsFirstGroupCount = 1; private void txtProjectionTimeMsFirstGroup_TextChanged(object sender, EventArgs e) { var oldValue = txtProjectionTimeMsFirstGroup.Text; this.projectionTimeMsFirstGroup = ValidateTextInputIsNumberAndReturnValue(txtProjectionTimeMsFirstGroup, 50000); if (this.processor != null && this.projectionTimeMsFirstGroupCount > 0) { if (!this.processor.SetProjectionTimeFirstGroup(this.projectionTimeMsFirstGroup, this.projectionTimeMsFirstGroupCount)) { this.projectionTimeMsFirstGroup = int.Parse(oldValue); this.txtProjectionTimeMsFirstGroup.Text = oldValue; } } } private void txtFirstGroupCount_TextChanged(object sender, EventArgs e) { var oldValue = txtFirstGroupCount.Text; this.projectionTimeMsFirstGroupCount = ValidateTextInputIsNumberAndReturnValue(txtFirstGroupCount, 1); if (this.processor != null && this.projectionTimeMsFirstGroup > 0) { if (!this.processor.SetProjectionTimeFirstGroup(this.projectionTimeMsFirstGroup, this.projectionTimeMsFirstGroupCount)) { this.projectionTimeMsFirstGroupCount = int.Parse(oldValue); this.txtFirstGroupCount.Text = oldValue; } } } private int projectionTimeMsSecondGroup = 5000; private int projectionTimeMsSecondGroupCount = 30; private void txtProjectionTimeMsSecondGroup_TextChanged(object sender, EventArgs e) { var oldValue = txtProjectionTimeMsSecondGroup.Text; this.projectionTimeMsSecondGroup = ValidateTextInputIsNumberAndReturnValue(txtProjectionTimeMsSecondGroup, 5000); if (this.processor != null && this.projectionTimeMsSecondGroupCount > 0) { if (!this.processor.SetProjectionTimeSecondGroup(this.projectionTimeMsSecondGroup, this.projectionTimeMsSecondGroupCount, this.cbDipForSecondLayer.Checked)) { this.projectionTimeMsSecondGroup = int.Parse(oldValue); this.txtProjectionTimeMsSecondGroup.Text = oldValue; } } } private void txtSecondGroupCount_TextChanged(object sender, EventArgs e) { var oldValue = txtSecondGroupCount.Text; this.projectionTimeMsSecondGroupCount = ValidateTextInputIsNumberAndReturnValue(txtSecondGroupCount, 30); if (this.processor != null && this.projectionTimeMsSecondGroup > 0) { if (!this.processor.SetProjectionTimeSecondGroup(this.projectionTimeMsSecondGroup, this.projectionTimeMsSecondGroupCount, this.cbDipForSecondLayer.Checked)) { this.projectionTimeMsSecondGroupCount = int.Parse(oldValue); this.txtSecondGroupCount.Text = oldValue; } } } private void cbDipForSecondLayer_Click(object sender, EventArgs e) { if (this.processor != null && this.projectionTimeMsSecondGroupCount > 0) { if (this.processor.SetProjectionTimeSecondGroup(this.projectionTimeMsSecondGroup, this.projectionTimeMsSecondGroupCount, this.cbDipForSecondLayer.Checked)) { this.cbDipForSecondLayer.Checked = !this.cbDipForSecondLayer.Checked; } } else { this.cbDipForSecondLayer.Checked = !this.cbDipForSecondLayer.Checked; } } private void btnPause_Click(object sender, EventArgs e) { if (processor == null) { return; } processor.Pause = !processor.Pause; if (processor.Pause) { btnPause.Image = Properties.Resources.glyphicons_173_play; btnPause.Text = "Continue"; ToolTipHelp.SetToolTip(btnPause, "Continue the printing process."); } else { txtTimeRemaining.Text = CalculateRemainingTime(); btnPause.Image = Properties.Resources.glyphicons_174_pause; btnPause.Text = "Pause"; ToolTipHelp.SetToolTip(btnPause, "Pause the printing process."); } } private bool mainFormClosing = false; private void Main_FormClosing(object sender, FormClosingEventArgs e) { this.mainFormClosing = true; if (this.monitorPrinter != null) { this.monitorPrinter.Stop(); e.Cancel = true; } else if (this.processor != null) { this.processor.Stop(); e.Cancel = true; } else { SystemEvents.DisplaySettingsChanged -= SystemEvents_DisplaySettingsChanged; } } private delegate void SetProgressInvoker(int percentage); internal void SetProgress(int percentage) { if (this.InvokeRequired) { var invoker = new SetProgressInvoker(SetProgress); this.Invoke(invoker, percentage); } else { progressBar.Value = percentage; } } private delegate void SetTotalSlicesInvoker(int total); private int totalSlices = 0; internal void SetTotalSlices(int total) { if (this.InvokeRequired) { var invoker = new SetTotalSlicesInvoker(SetTotalSlices); this.Invoke(invoker, total); } else { this.totalSlices = total; txtTotalSlices.Text = total.ToString("##0000"); txtTimeRemaining.Text = CalculateRemainingTime(); txtTimePassed.Text = CalculateTimePassed(); } } private string CalculateRemainingTime() { var timePerLayerMs = (double)(projectionTimeMs + this.machineConfig.DipDepthMu * 2 / 4 + this.machineConfig.PauseTimeBetweenLayersMs); var remainingMs = (this.totalSlices - this.currentSlice) * timePerLayerMs; var timeSpan = TimeSpan.FromMilliseconds(remainingMs); return timeSpan.ToString(@"hh\:mm\:ss"); } private delegate void SetCurrentSliceInvoker(int current); private int currentSlice = 0; internal void SetCurrentSlice(int current) { if (this.InvokeRequired) { var invoker = new SetCurrentSliceInvoker(SetCurrentSlice); this.Invoke(invoker, current); } else { this.currentSlice = current; txtCurrentSlice.Text = current.ToString("##0000"); txtTimeRemaining.Text = CalculateRemainingTime(); txtTimePassed.Text = CalculateTimePassed(); } } private string CalculateTimePassed() { var timePassed = DateTime.Now - startTime; return timePassed.ToString(@"hh\:mm\:ss"); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { new AboutForm().ShowDialog(); } private void simulatePrinterToolStripMenuItem_Click(object sender, EventArgs e) { if (this.processor != null) { MessageBox.Show("Printer is active, stop first and allow process to finish before changing simulation mode.", "Cannot switch simulation mode", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var simulationText = " - Simulating printer"; this.simulatePrinterToolStripMenuItem.Checked = !this.simulatePrinterToolStripMenuItem.Checked; if (this.simulatePrinterToolStripMenuItem.Checked) { this.Text += simulationText; } else { this.Text = this.Text.Replace(simulationText, ""); } } private bool emergencyStopPressed = false; private void btnEmergencyStop_Click(object sender, EventArgs e) { this.emergencyStopPressed = !this.emergencyStopPressed; if (this.emergencyStopPressed) { this.btnEmergencyStop.Image = Properties.Resources.continue_after_emergency; this.btnEmergencyStop.Text = "CONTINUE"; if (this.printerInterface != null) { this.printerInterface.LiftEnabled = false; if (this.resinPumpDrain) { this.btnInkPumpDrain_Click(this, null); } if (this.resinPumpFill) { this.btnInkPumpFill_Click(this, null); } } if (this.processor != null) { if (!this.processor.Pause) { this.btnPause_Click(this, null); } } } else { this.btnEmergencyStop.Image = Properties.Resources.emergency_stop; this.btnEmergencyStop.Text = "EMERGENCY\nSTOP"; if (this.printerInterface != null) { this.printerInterface.LiftEnabled = true; } } } private void btnConnect_Click(object sender, EventArgs e) { try { if (this.btnConnect.Text == "Connect") { if (this.simulatePrinterToolStripMenuItem.Checked) { this.printerInterface = new SimulatedPrinterInterface(this); } else { this.printerInterface = new LabjackPrinterInterface(); } string errors; if (!this.printerInterface.TryConnect(out errors)) { this.StatusMessage("Error connecting: " + errors); this.printerInterface = null; } else { this.btnStart.Enabled = true; this.btnPause.Enabled = true; btnConnect.Image = Properties.Resources.glyphicons_265_electrical_plug_on; btnConnect.Text = "Disconnect"; this.monitorPrinter = new MonitorPrinterStatus(this.printerInterface, this); } } else { if (this.processor != null) { if (MessageBox.Show("Are you sure you want to disconnect now?", "Are you sure?", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel ) { return; } this.processor.Stop(); } if (this.monitorPrinter != null) { this.monitorPrinter.Close(); } if (this.printerInterface != null) { this.printerInterface.Disconnect(); } this.printerInterface = null; this.btnStart.Enabled = false; this.btnPause.Enabled = false; btnConnect.Image = Properties.Resources.glyphicons_265_electrical_plug; btnConnect.Text = "Connect"; } } catch (Exception err) { this.StatusMessage("Unexpected error while trying to connect:" + Environment.NewLine + err); } } private delegate void SetBottomStateInvoker(bool state); internal void SetBottomSensor(bool state) { if (this.InvokeRequired) { var handle = new SetBottomStateInvoker(SetBottomSensor); this.Invoke(handle, state); } else { if (state) { this.ledBottomSensor.BackgroundImage = Properties.Resources.led_red; } else { this.ledBottomSensor.BackgroundImage = Properties.Resources.led_off; } } } internal void SetTopSensor(bool state) { if (this.InvokeRequired) { var handle = new SetBottomStateInvoker(SetTopSensor); this.Invoke(handle, state); } else { if (state) { this.ledTopSensor.BackgroundImage = Properties.Resources.led_red; } else { this.ledTopSensor.BackgroundImage = Properties.Resources.led_off; } } } internal void SetResinPump(bool state) { if (this.InvokeRequired) { var handle = new SetBottomStateInvoker(SetResinPump); this.Invoke(handle, state); } else { if (state) { this.ledInkPump.BackgroundImage = Properties.Resources.led_red; } else { this.ledInkPump.BackgroundImage = Properties.Resources.led_off; } } } private delegate void SetLiftPositionInvoker(decimal position); internal void SetLiftPosition(decimal position) { if (this.InvokeRequired) { var invoker = new SetLiftPositionInvoker(SetLiftPosition); this.Invoke(invoker, position); } else { this.lblPositionFromTopMm.Text = position.ToString("####0.0"); } } private async void btnMoveToTop_Click(object sender, EventArgs e) { if (this.printerInterface != null && this.processor == null) { this.printerInterface.DelicateMode = false; this.btnMoveToTop.Enabled = false; this.btnMoveToBottom.Enabled = false; await Task.Run(new Action(this.printerInterface.MoveLiftToTop)); this.btnMoveToBottom.Enabled = true; this.btnMoveToTop.Enabled = true; } } private async void btnInitialize_Click(object sender, EventArgs e) { if (this.printerInterface != null && this.processor == null) { this.printerInterface.DelicateMode = false; this.btnInitialize.Enabled = false; this.printerInterface.InitializePrintHeightUm = this.machineConfig.InitializePositionFromTopSensorMu; this.printerInterface.ResinPumpFill = this.machineConfig.RunPumpWhileInitializing; await Task.Run(new Action(this.printerInterface.InitializePrinter)); this.printerInterface.ResinPumpFill = true; this.StatusMessage("Allow resin pump to run a bit longer to fill reservoir. (" + this.machineConfig.PumpTimeAfterInitializeSeconds + " seconds)"); await Task.Run(() => { Thread.Sleep(this.machineConfig.PumpTimeAfterInitializeSeconds * 1000); this.printerInterface.ResinPumpFill = false; }); this.btnInitialize.Enabled = true; } } private bool resinPumpDrain = false; private bool resinPumpFill = false; private async void btnInkPumpDrain_Click(object sender, EventArgs e) { if (this.resinPumpFill) { this.btnInkPumpFill_Click(this, null); if (this.resinPumpFill) { return; } } if (this.printerInterface != null) { this.resinPumpDrain = !this.resinPumpDrain; if (this.resinPumpDrain && this.emergencyStopPressed) { this.resinPumpDrain = false; return; } if (this.resinPumpDrain) { await Task.Delay(500); this.printerInterface.ResinPumpDrain = true; this.btnInkPumpDrain.Image = Properties.Resources.fill_on; } else { await Task.Delay(200); this.printerInterface.ResinPumpDrain = false; await Task.Delay(500); this.btnInkPumpDrain.Image = Properties.Resources.fill; await Task.Delay(500); } } } private async void btnInkPumpFill_Click(object sender, EventArgs e) { if (this.resinPumpDrain) { this.btnInkPumpDrain_Click(this, null); if (this.resinPumpDrain) { return; } } if (this.printerInterface != null) { this.resinPumpFill = !this.resinPumpFill; if (this.resinPumpFill && this.emergencyStopPressed) { this.resinPumpFill = false; return; } if (this.resinPumpFill) { await Task.Delay(500); this.printerInterface.ResinPumpFill = true; this.btnInkPumpFill.Image = Properties.Resources.fill_on; } else { this.printerInterface.ResinPumpFill = false; this.btnInkPumpFill.Image = Properties.Resources.fill; await Task.Delay(500); } } } private async void btnMoveToBottom_Click(object sender, EventArgs e) { if (this.printerInterface != null && this.processor == null) { this.printerInterface.DelicateMode = false; this.btnMoveToTop.Enabled = false; this.btnMoveToBottom.Enabled = false; await Task.Run(new Action(this.printerInterface.MoveLiftToBottom)); this.btnMoveToBottom.Enabled = true; this.btnMoveToTop.Enabled = true; } } private void btnLiftUp_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.StatusMessage("Begin manual lift moving up."); BeginMoveUp(); } } private bool liftMovingUp = false; private void BeginMoveUp() { this.liftMovingUp = true; new Thread(() => { while (this.liftMovingUp && this.printerInterface != null && this.processor == null) { this.printerInterface.MoveLiftUp(200); } }).Start(); } private void btnLiftUp_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { EndMoveUp(); } } private void EndMoveUp() { if (this.liftMovingUp) { this.StatusMessage("End manual lift moving up."); this.liftMovingUp = false; } } private void btnLiftUp_MouseLeave(object sender, EventArgs e) { EndMoveUp(); } private void btnLiftDown_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.StatusMessage("Begin manual lift moving down."); BeginMoveDown(); } } private bool liftMovingDown = false; private void BeginMoveDown() { this.liftMovingDown = true; new Thread(() => { while (this.liftMovingDown && this.printerInterface != null && this.processor == null) { this.printerInterface.MoveLiftDown(200); } }).Start(); } private void btnLiftDown_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { EndMoveDown(); } } private void EndMoveDown() { if (this.liftMovingDown) { this.StatusMessage("End manual lift moving down."); this.liftMovingDown = false; } } private void btnLiftDown_MouseLeave(object sender, EventArgs e) { EndMoveDown(); } private void hardwareConfigurationToolStripMenuItem_Click(object sender, EventArgs e) { if (this.printerInterface == null && this.processor == null) { this.machineConfig.StartPosition = FormStartPosition.Manual; this.machineConfig.Location = new Point(this.Location.X + 40, this.Location.Y + 30); this.machineConfig.ShowDialog(this); } else { MessageBox.Show("Only change when not connected to the printer, stop printing and disconnect first.", "Disconnect...", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void btnSaveAsInitialPos_Click(object sender, EventArgs e) { if (this.printerInterface != null && this.printerInterface.LiftPositionInUMFromTopSensor > 0) { var dialogResult = MessageBox.Show("Are you sure you want to set the initial position to the current lift position (" + this.printerInterface.LiftPositionInUMFromTopSensor.ToString() + "um from top sensor)?", "Are you sure?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dialogResult == System.Windows.Forms.DialogResult.OK) { this.machineConfig.InitializePositionFromTopSensorMu = this.printerInterface.LiftPositionInUMFromTopSensor; } } else { MessageBox.Show("Cannot store position, make sure printer is connected and position is not -1", "Warning, no changes made", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void newToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Not implemented yet. Scheduled for next release."); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Not implemented yet. Scheduled for next release."); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Not implemented yet. Scheduled for next release."); } private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Not implemented yet. Scheduled for next release."); } private void cbDelicateMode_CheckedChanged(object sender, EventArgs e) { if (this.processor != null) { this.processor.SetDelicateMode(this.cbDelicateMode.Checked); } } private delegate void SetMaxPrintheightInvoker(decimal position); internal void SetMaxPrintheight(decimal position) { if (this.InvokeRequired) { var invoker = new SetMaxPrintheightInvoker(SetMaxPrintheight); this.Invoke(invoker, position); } else { this.lblMaxPrintHeightMm.Text = position.ToString("####0.0"); } } } }
wouter1981/PortobelloController
Controller/Main.cs
C#
apache-2.0
32,343
// // AppDelegate.h // LZThreadPro04GCD // // Created by comst on 15/10/7. // Copyright (c) 2015年 com.comst1314. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
comst007/testOC
LZThreadPro/LZThreadPro04GCD/AppDelegate.h
C
apache-2.0
287
package com.suscipio_solutions.consecro_mud.Abilities.Druid; import java.util.List; import java.util.Vector; import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability; import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg; import com.suscipio_solutions.consecro_mud.Items.interfaces.Item; import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial; import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB; import com.suscipio_solutions.consecro_mud.core.CMClass; import com.suscipio_solutions.consecro_mud.core.CMLib; import com.suscipio_solutions.consecro_mud.core.CMParms; import com.suscipio_solutions.consecro_mud.core.CMStrings; import com.suscipio_solutions.consecro_mud.core.interfaces.Physical; @SuppressWarnings("rawtypes") public class Chant_SummonSeed extends Chant { @Override public String ID() { return "Chant_SummonSeed"; } private final static String localizedName = CMLib.lang().L("Summon Seeds"); @Override public String name() { return localizedName; } @Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;} @Override protected int canAffectCode(){return 0;} @Override protected int canTargetCode(){return 0;} @Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_PLANTGROWTH;} public static final Integer[] NON_SEEDS={Integer.valueOf(RawMaterial.RESOURCE_ASH), Integer.valueOf(RawMaterial.RESOURCE_SOAP), Integer.valueOf(RawMaterial.RESOURCE_CHEESE), Integer.valueOf(RawMaterial.RESOURCE_BREAD), Integer.valueOf( RawMaterial.RESOURCE_CRACKER), }; @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { final String s=CMParms.combine(commands,0); final StringBuffer buf=new StringBuffer(L("Seed types known:\n\r")); int material=0; String foundShortName=null; int col=0; final List<Integer> codes = RawMaterial.CODES.COMPOSE_RESOURCES(RawMaterial.MATERIAL_VEGETATION); for(final Integer code : codes) { if(!CMParms.contains(Chant_SummonSeed.NON_SEEDS,code)) { final String str=RawMaterial.CODES.NAME(code.intValue()); if(str.toUpperCase().equalsIgnoreCase(s)) { material=code.intValue(); foundShortName=CMStrings.capitalizeAndLower(str); break; } if(col==4){ buf.append("\n\r"); col=0;} col++; buf.append(CMStrings.padRight(CMStrings.capitalizeAndLower(str),15)); } } if(s.equalsIgnoreCase("list")) { mob.tell(buf.toString()+"\n\r\n\r"); return true; } if(s.length()==0) { mob.tell(L("Summon what kind of seed? Try LIST as a parameter...")); return false; } if(foundShortName==null) { mob.tell(L("'@x1' is an unknown type of vegetation.",s)); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; // now see if it worked final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> chant(s) to <S-HIS-HER> hands.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); for(int i=2;i<(2+(adjustedLevel(mob,asLevel)/4));i++) { final Item newItem=CMClass.getBasicItem("GenResource"); String name=foundShortName.toLowerCase(); if(name.endsWith("ies")) name=name.substring(0,name.length()-3)+"y"; if(name.endsWith("s")) name=name.substring(0,name.length()-1); newItem.setName(CMLib.english().startWithAorAn(name+" seed")); newItem.setDisplayText(L("@x1 is here.",newItem.name())); newItem.setDescription(""); newItem.setMaterial(material); newItem.basePhyStats().setWeight(0); newItem.recoverPhyStats(); newItem.setMiscText(newItem.text()); mob.addItem(newItem); } mob.location().showHappens(CMMsg.MSG_OK_ACTION,L("Some seeds appear!")); mob.location().recoverPhyStats(); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s) to <S-HIS-HER> hands, but nothing happens.")); // return whether it worked return success; } }
ConsecroMUD/ConsecroMUD
com/suscipio_solutions/consecro_mud/Abilities/Druid/Chant_SummonSeed.java
Java
apache-2.0
4,149
/* Copyright IBM Corp. 2016 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package utils import ( "errors" "fmt" "time" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/timestamp" "github.com/hyperledger/fabric/common/crypto" cb "github.com/hyperledger/fabric/protos/common" pb "github.com/hyperledger/fabric/protos/peer" ) // MarshalOrPanic serializes a protobuf message and panics if this operation fails. func MarshalOrPanic(pb proto.Message) []byte { data, err := proto.Marshal(pb) if err != nil { panic(err) } return data } // Marshal serializes a protobuf message. func Marshal(pb proto.Message) ([]byte, error) { return proto.Marshal(pb) } // CreateNonceOrPanic generates a nonce using the common/crypto package // and panics if this operation fails. func CreateNonceOrPanic() []byte { nonce, err := crypto.GetRandomNonce() if err != nil { panic(fmt.Errorf("Cannot generate random nonce: %s", err)) } return nonce } // CreateNonce generates a nonce using the common/crypto package. func CreateNonce() ([]byte, error) { nonce, err := crypto.GetRandomNonce() if err != nil { return nil, fmt.Errorf("Cannot generate random nonce: %s", err) } return nonce, nil } // UnmarshalPayloadOrPanic unmarshals bytes to a Payload structure or panics on error func UnmarshalPayloadOrPanic(encoded []byte) *cb.Payload { payload, err := UnmarshalPayload(encoded) if err != nil { panic(fmt.Errorf("Error unmarshaling data to payload: %s", err)) } return payload } // UnmarshalPayload unmarshals bytes to a Payload structure func UnmarshalPayload(encoded []byte) (*cb.Payload, error) { payload := &cb.Payload{} err := proto.Unmarshal(encoded, payload) if err != nil { return nil, err } return payload, err } // UnmarshalEnvelopeOrPanic unmarshals bytes to an Envelope structure or panics on error func UnmarshalEnvelopeOrPanic(encoded []byte) *cb.Envelope { envelope, err := UnmarshalEnvelope(encoded) if err != nil { panic(fmt.Errorf("Error unmarshaling data to envelope: %s", err)) } return envelope } // UnmarshalEnvelope unmarshals bytes to an Envelope structure func UnmarshalEnvelope(encoded []byte) (*cb.Envelope, error) { envelope := &cb.Envelope{} err := proto.Unmarshal(encoded, envelope) if err != nil { return nil, err } return envelope, err } // UnmarshalEnvelopeOfType unmarshals an envelope of the specified type, including // the unmarshaling the payload data func UnmarshalEnvelopeOfType(envelope *cb.Envelope, headerType cb.HeaderType, message proto.Message) (*cb.ChannelHeader, error) { payload, err := UnmarshalPayload(envelope.Payload) if err != nil { return nil, err } if payload.Header == nil { return nil, fmt.Errorf("Envelope must have a Header") } chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader) if err != nil { return nil, fmt.Errorf("Invalid ChannelHeader") } if chdr.Type != int32(headerType) { return nil, fmt.Errorf("Not a tx of type %v", headerType) } if err = proto.Unmarshal(payload.Data, message); err != nil { return nil, fmt.Errorf("Error unmarshaling message for type %v: %s", headerType, err) } return chdr, nil } // ExtractEnvelopeOrPanic retrieves the requested envelope from a given block and unmarshals it -- it panics if either of these operation fail. func ExtractEnvelopeOrPanic(block *cb.Block, index int) *cb.Envelope { envelope, err := ExtractEnvelope(block, index) if err != nil { panic(err) } return envelope } // ExtractEnvelope retrieves the requested envelope from a given block and unmarshals it. func ExtractEnvelope(block *cb.Block, index int) (*cb.Envelope, error) { if block.Data == nil { return nil, fmt.Errorf("No data in block") } envelopeCount := len(block.Data.Data) if index < 0 || index >= envelopeCount { return nil, fmt.Errorf("Envelope index out of bounds") } marshaledEnvelope := block.Data.Data[index] envelope, err := GetEnvelopeFromBlock(marshaledEnvelope) if err != nil { return nil, fmt.Errorf("Block data does not carry an envelope at index %d: %s", index, err) } return envelope, nil } // ExtractPayloadOrPanic retrieves the payload of a given envelope and unmarshals it -- it panics if either of these operations fail. func ExtractPayloadOrPanic(envelope *cb.Envelope) *cb.Payload { payload, err := ExtractPayload(envelope) if err != nil { panic(err) } return payload } // ExtractPayload retrieves the payload of a given envelope and unmarshals it. func ExtractPayload(envelope *cb.Envelope) (*cb.Payload, error) { payload := &cb.Payload{} if err := proto.Unmarshal(envelope.Payload, payload); err != nil { return nil, fmt.Errorf("Envelope does not carry a Payload: %s", err) } return payload, nil } // MakeChannelHeader creates a ChannelHeader. func MakeChannelHeader(headerType cb.HeaderType, version int32, chainID string, epoch uint64) *cb.ChannelHeader { return &cb.ChannelHeader{ Type: int32(headerType), Version: version, Timestamp: &timestamp.Timestamp{ Seconds: time.Now().Unix(), Nanos: 0, }, ChannelId: chainID, Epoch: epoch, } } // MakeSignatureHeader creates a SignatureHeader. func MakeSignatureHeader(serializedCreatorCertChain []byte, nonce []byte) *cb.SignatureHeader { return &cb.SignatureHeader{ Creator: serializedCreatorCertChain, Nonce: nonce, } } func SetTxID(channelHeader *cb.ChannelHeader, signatureHeader *cb.SignatureHeader) error { txid, err := ComputeProposalTxID( signatureHeader.Nonce, signatureHeader.Creator, ) if err != nil { return err } channelHeader.TxId = txid return nil } // MakePayloadHeader creates a Payload Header. func MakePayloadHeader(ch *cb.ChannelHeader, sh *cb.SignatureHeader) *cb.Header { return &cb.Header{ ChannelHeader: MarshalOrPanic(ch), SignatureHeader: MarshalOrPanic(sh), } } // NewSignatureHeaderOrPanic returns a signature header and panics on error. func NewSignatureHeaderOrPanic(signer crypto.LocalSigner) *cb.SignatureHeader { if signer == nil { panic(errors.New("Invalid signer. Must be different from nil.")) } signatureHeader, err := signer.NewSignatureHeader() if err != nil { panic(fmt.Errorf("Failed generating a new SignatureHeader [%s]", err)) } return signatureHeader } // SignOrPanic signs a message and panics on error. func SignOrPanic(signer crypto.LocalSigner, msg []byte) []byte { if signer == nil { panic(errors.New("Invalid signer. Must be different from nil.")) } sigma, err := signer.Sign(msg) if err != nil { panic(fmt.Errorf("Failed generting signature [%s]", err)) } return sigma } // UnmarshalChannelHeader returns a ChannelHeader from bytes func UnmarshalChannelHeader(bytes []byte) (*cb.ChannelHeader, error) { chdr := &cb.ChannelHeader{} err := proto.Unmarshal(bytes, chdr) if err != nil { return nil, fmt.Errorf("UnmarshalChannelHeader failed, err %s", err) } return chdr, nil } // UnmarshalChaincodeID returns a ChaincodeID from bytes func UnmarshalChaincodeID(bytes []byte) (*pb.ChaincodeID, error) { ccid := &pb.ChaincodeID{} err := proto.Unmarshal(bytes, ccid) if err != nil { return nil, fmt.Errorf("UnmarshalChaincodeID failed, err %s", err) } return ccid, nil } // IsConfigBlock validates whenever given block contains configuration // update transaction func IsConfigBlock(block *cb.Block) bool { envelope, err := ExtractEnvelope(block, 0) if err != nil { return false } payload, err := GetPayload(envelope) if err != nil { return false } hdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader) if err != nil { return false } return cb.HeaderType(hdr.Type) == cb.HeaderType_CONFIG }
magg/fabric
protos/utils/commonutils.go
GO
apache-2.0
8,169
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_ValueType3507792607.h" // System.Collections.Generic.List`1<UnityEngine.EventSystems.IEventSystemHandler> struct List_1_t2110309450; // UnityEngine.EventSystems.IEventSystemHandler struct IEventSystemHandler_t2741188318; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.List`1/Enumerator<UnityEngine.EventSystems.IEventSystemHandler> struct Enumerator_t1645039124 { public: // System.Collections.Generic.List`1<T> System.Collections.Generic.List`1/Enumerator::l List_1_t2110309450 * ___l_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::next int32_t ___next_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::ver int32_t ___ver_2; // T System.Collections.Generic.List`1/Enumerator::current Il2CppObject * ___current_3; public: inline static int32_t get_offset_of_l_0() { return static_cast<int32_t>(offsetof(Enumerator_t1645039124, ___l_0)); } inline List_1_t2110309450 * get_l_0() const { return ___l_0; } inline List_1_t2110309450 ** get_address_of_l_0() { return &___l_0; } inline void set_l_0(List_1_t2110309450 * value) { ___l_0 = value; Il2CppCodeGenWriteBarrier(&___l_0, value); } inline static int32_t get_offset_of_next_1() { return static_cast<int32_t>(offsetof(Enumerator_t1645039124, ___next_1)); } inline int32_t get_next_1() const { return ___next_1; } inline int32_t* get_address_of_next_1() { return &___next_1; } inline void set_next_1(int32_t value) { ___next_1 = value; } inline static int32_t get_offset_of_ver_2() { return static_cast<int32_t>(offsetof(Enumerator_t1645039124, ___ver_2)); } inline int32_t get_ver_2() const { return ___ver_2; } inline int32_t* get_address_of_ver_2() { return &___ver_2; } inline void set_ver_2(int32_t value) { ___ver_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast<int32_t>(offsetof(Enumerator_t1645039124, ___current_3)); } inline Il2CppObject * get_current_3() const { return ___current_3; } inline Il2CppObject ** get_address_of_current_3() { return &___current_3; } inline void set_current_3(Il2CppObject * value) { ___current_3 = value; Il2CppCodeGenWriteBarrier(&___current_3, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
BPenzar/SuperDinoBros.
Unity_Code/DinoRun_Final/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Collections_Generic_List_1_Enumera1645039124.h
C
apache-2.0
2,533
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Sun Jun 06 00:15:53 JST 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> クラス org.apache.mina.filter.logging.MdcInjectionFilter.MdcKey の使用 (Apache MINA Core 2.0.0-RC1 API) </TITLE> <META NAME="date" CONTENT="2010-06-06"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="クラス org.apache.mina.filter.logging.MdcInjectionFilter.MdcKey の使用 (Apache MINA Core 2.0.0-RC1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="ナビゲーションリンクをスキップ"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>概要</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>パッケージ</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型"><FONT CLASS="NavBarFont1"><B>クラス</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>使用</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>階層ツリー</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>非推奨 API</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>索引</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>ヘルプ</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;前&nbsp; &nbsp;次</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/mina/filter/logging//class-useMdcInjectionFilter.MdcKey.html" target="_top"><B>フレームあり</B></A> &nbsp; &nbsp;<A HREF="MdcInjectionFilter.MdcKey.html" target="_top"><B>フレームなし</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>クラス<br>org.apache.mina.filter.logging.MdcInjectionFilter.MdcKey の使用</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A> を使用しているパッケージ</FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.mina.filter.logging"><B>org.apache.mina.filter.logging</B></A></TD> <TD><tt>IoFilter</tt> を実装し、MINA ベースのシステムを流れるイベントとデータのログ出力を提供するクラス群です。&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.mina.filter.logging"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <A HREF="../../../../../../org/apache/mina/filter/logging/package-summary.html">org.apache.mina.filter.logging</A> での <A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A> の使用</FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A> を返す <A HREF="../../../../../../org/apache/mina/filter/logging/package-summary.html">org.apache.mina.filter.logging</A> のメソッド</FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A></CODE></FONT></TD> <TD><CODE><B>MdcInjectionFilter.MdcKey.</B><B><A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html#valueOf(java.lang.String)">valueOf</A></B>(java.lang.String&nbsp;name)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;指定した名前を持つこの型の列挙型定数を返します。</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A>[]</CODE></FONT></TD> <TD><CODE><B>MdcInjectionFilter.MdcKey.</B><B><A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html#values()">values</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;この列挙型の定数を含む配列を宣言されている順序で返します。</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A> 型のパラメータを持つ <A HREF="../../../../../../org/apache/mina/filter/logging/package-summary.html">org.apache.mina.filter.logging</A> のコンストラクタ</FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.html#MdcInjectionFilter(org.apache.mina.filter.logging.MdcInjectionFilter.MdcKey...)">MdcInjectionFilter</A></B>(<A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A>...&nbsp;keys)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Use this constructor when you want to specify which keys to add to the MDC You could still add custom keys via <A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.html#setProperty(org.apache.mina.core.session.IoSession, java.lang.String, java.lang.String)"><CODE>MdcInjectionFilter.setProperty(IoSession, String, String)</CODE></A></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A> 型の型引数を持つ <A HREF="../../../../../../org/apache/mina/filter/logging/package-summary.html">org.apache.mina.filter.logging</A> のコンストラクタパラメータ</FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.html#MdcInjectionFilter(java.util.EnumSet)">MdcInjectionFilter</A></B>(java.util.EnumSet&lt;<A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型">MdcInjectionFilter.MdcKey</A>&gt;&nbsp;keys)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Use this constructor when you want to specify which keys to add to the MDC.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="ナビゲーションリンクをスキップ"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>概要</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>パッケージ</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/filter/logging/MdcInjectionFilter.MdcKey.html" title="org.apache.mina.filter.logging 内の列挙型"><FONT CLASS="NavBarFont1"><B>クラス</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>使用</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>階層ツリー</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>非推奨 API</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>索引</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>ヘルプ</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;前&nbsp; &nbsp;次</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/mina/filter/logging//class-useMdcInjectionFilter.MdcKey.html" target="_top"><B>フレームあり</B></A> &nbsp; &nbsp;<A HREF="MdcInjectionFilter.MdcKey.html" target="_top"><B>フレームなし</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>すべてのクラス</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2004-2010 <a href="http://mina.apache.org/">Apache MINA Project</a>. All Rights Reserved. </BODY> </HTML>
sardine/mina-ja
docs/apidocs/org/apache/mina/filter/logging/class-use/MdcInjectionFilter.MdcKey.html
HTML
apache-2.0
12,204
/* Copyright 2014-2016 Intel 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. */ package apple.mapkit; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; @Generated @Library("MapKit") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class MKRoute extends NSObject { static { NatJ.register(); } @Generated protected MKRoute(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native MKRoute alloc(); @Owned @Generated @Selector("allocWithZone:") public static native MKRoute allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") public static native MKRoute new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); /** * localized notices of route conditions. e.g. "Avoid during winter storms" */ @Generated @Selector("advisoryNotices") public native NSArray<String> advisoryNotices(); /** * overall route distance in meters */ @Generated @Selector("distance") public native double distance(); @Generated @Selector("expectedTravelTime") public native double expectedTravelTime(); @Generated @Selector("init") public native MKRoute init(); /** * localized description of the route's significant feature, e.g. "US-101" */ @Generated @Selector("name") public native String name(); /** * detailed route geometry */ @Generated @Selector("polyline") public native MKPolyline polyline(); @Generated @Selector("steps") public native NSArray<? extends MKRouteStep> steps(); /** * overall route transport type */ @Generated @Selector("transportType") @NUInt public native long transportType(); }
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/mapkit/MKRoute.java
Java
apache-2.0
5,698
using WorkingWithVisualStudio.Models; using Xunit; namespace WorkingWithVisualStudio.Tests { public class ProductTests { [Fact] public void CanChangeProductName() { // Arrange var p = new Product { Name = "Test", Price = 100M }; // Act p.Name = "New Name"; // Assert Assert.Equal("New Name", p.Name); } [Fact] public void CanChangeProductPrice() { // Arrange var p = new Product { Name = "Test", Price = 100M }; // Act p.Price = 200M; // Asset Assert.Equal(200M, p.Price); } } }
Azuredrop/Pro-ASP.NET-Core-MVC
WorkingWithVisualStudio/test/WorkingWithVisualStudio.Tests/ProductTests.cs
C#
apache-2.0
708
package com.bei.androidtools; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
beiliubei/androidtools
src/com/bei/androidtools/MainActivity.java
Java
apache-2.0
560
package de.philipphager.disclosure.database.util.adapters; import android.support.annotation.NonNull; import com.squareup.sqldelight.ColumnAdapter; import org.threeten.bp.Instant; import org.threeten.bp.OffsetDateTime; import org.threeten.bp.ZoneOffset; public class OffsetDateTimeColumnAdapter implements ColumnAdapter<OffsetDateTime, Long> { @NonNull @Override public OffsetDateTime decode(Long databaseValue) { return Instant.ofEpochMilli(databaseValue).atOffset(ZoneOffset.UTC); } @Override public Long encode(@NonNull OffsetDateTime value) { return value.toInstant().toEpochMilli(); } }
philipphager/disclosure-android-app
app/src/main/java/de/philipphager/disclosure/database/util/adapters/OffsetDateTimeColumnAdapter.java
Java
apache-2.0
611
/* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mytdev.cliqui.util; import com.mytdev.cliqui.resources.Images; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.plaf.basic.BasicButtonUI; /** * Component to be used as tabComponent; Contains a JLabel to show the text and * a JButton to close the tab it belongs to * * @author Yann D'Isanto */ public final class ButtonTabComponent extends JPanel { private final JTabbedPane pane; public ButtonTabComponent(final JTabbedPane pane) { super(new BorderLayout()); if (pane == null) { throw new NullPointerException("TabbedPane is null"); } this.pane = pane; setOpaque(false); //make JLabel read titles from JTabbedPane final JLabel label = new JLabel() { @Override public String getText() { int i = pane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { return pane.getTitleAt(i); } return null; } }; add(label, BorderLayout.CENTER); //add more space between the label and the button label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); //tab button final JButton button = new TabButton(); add(button, BorderLayout.EAST); //add more space to the top of the component setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); } private final class TabButton extends JButton implements ActionListener { public TabButton() { int size = 15; setPreferredSize(new Dimension(size, size)); //Make the button looks the same for all Laf's setUI(new BasicButtonUI()); //Make it transparent setContentAreaFilled(false); setFocusable(false); setRolloverEnabled(true); addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { int i = pane.indexOfTabComponent(ButtonTabComponent.this); if (i != -1) { pane.remove(i); } } //we don't want to update UI for this button @Override public void updateUI() { } //paint the cross @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); //shift the image for pressed buttons if (getModel().isPressed()) { g2.translate(1, 1); } g2.drawImage(getCloseImage(), null, null); g2.dispose(); } private Image getCloseImage() { if (getModel().isPressed()) { return Images.CLOSE_PRESSED; } else if (getModel().isRollover()) { return Images.CLOSE_ROLLOVER; } else { return Images.CLOSE_ENABLED; } } } }
le-yams/cliqui-app
src/main/java/com/mytdev/cliqui/util/ButtonTabComponent.java
Java
apache-2.0
4,928
/** * @license * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import '../../../test/common-test-setup-karma'; import './gr-thread-list'; import {CommentSide, SpecialFilePath} from '../../../constants/constants'; import {CommentTabState} from '../../../types/events'; import { compareThreads, GrThreadList, __testOnly_SortDropdownState, } from './gr-thread-list'; import {queryAll} from '../../../test/test-utils'; import {accountOrGroupKey} from '../../../utils/account-util'; import {tap} from '@polymer/iron-test-helpers/mock-interactions'; import { createAccountDetailWithId, createParsedChange, createThread, } from '../../../test/test-data-generators'; import { AccountId, NumericChangeId, PatchSetNum, Timestamp, } from '../../../api/rest-api'; import {RobotId, UrlEncodedCommentId} from '../../../types/common'; import {CommentThread} from '../../../utils/comment-util'; import {query, queryAndAssert} from '../../../utils/common-util'; import {GrAccountLabel} from '../../shared/gr-account-label/gr-account-label'; const basicFixture = fixtureFromElement('gr-thread-list'); suite('gr-thread-list tests', () => { let element: GrThreadList; setup(async () => { element = basicFixture.instantiate(); element.changeNum = 123 as NumericChangeId; element.change = createParsedChange(); element.account = createAccountDetailWithId(); element.threads = [ { comments: [ { path: '/COMMIT_MSG', author: { _account_id: 1000001 as AccountId, name: 'user', username: 'user', }, patch_set: 4 as PatchSetNum, id: 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId, line: 5, updated: '2015-12-01 15:15:15.000000000' as Timestamp, message: 'test', unresolved: true, }, { id: '503008e2_0ab203ee' as UrlEncodedCommentId, path: '/COMMIT_MSG', line: 5, in_reply_to: 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId, updated: '2015-12-01 15:16:15.000000000' as Timestamp, message: 'draft', unresolved: true, __draft: true, patch_set: '2' as PatchSetNum, }, ], patchNum: 4 as PatchSetNum, path: '/COMMIT_MSG', line: 5, rootId: 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { path: 'test.txt', author: { _account_id: 1000002 as AccountId, name: 'user', username: 'user', }, patch_set: 3 as PatchSetNum, id: '09a9fb0a_1484e6cf' as UrlEncodedCommentId, updated: '2015-12-02 15:16:15.000000000' as Timestamp, message: 'Some comment on another patchset.', unresolved: false, }, ], patchNum: 3 as PatchSetNum, path: 'test.txt', rootId: '09a9fb0a_1484e6cf' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { path: '/COMMIT_MSG', author: { _account_id: 1000002 as AccountId, name: 'user', username: 'user', }, patch_set: 2 as PatchSetNum, id: '8caddf38_44770ec1' as UrlEncodedCommentId, updated: '2015-12-03 15:16:15.000000000' as Timestamp, message: 'Another unresolved comment', unresolved: false, }, ], patchNum: 2 as PatchSetNum, path: '/COMMIT_MSG', rootId: '8caddf38_44770ec1' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { path: '/COMMIT_MSG', author: { _account_id: 1000003 as AccountId, name: 'user', username: 'user', }, patch_set: 2 as PatchSetNum, id: 'scaddf38_44770ec1' as UrlEncodedCommentId, line: 4, updated: '2015-12-04 15:16:15.000000000' as Timestamp, message: 'Yet another unresolved comment', unresolved: true, }, ], patchNum: 2 as PatchSetNum, path: '/COMMIT_MSG', line: 4, rootId: 'scaddf38_44770ec1' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { id: 'zcf0b9fa_fe1a5f62' as UrlEncodedCommentId, path: '/COMMIT_MSG', line: 6, updated: '2015-12-05 15:16:15.000000000' as Timestamp, message: 'resolved draft', unresolved: false, __draft: true, patch_set: '2' as PatchSetNum, }, ], patchNum: 4 as PatchSetNum, path: '/COMMIT_MSG', line: 6, rootId: 'zcf0b9fa_fe1a5f62' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { id: 'patchset_level_1' as UrlEncodedCommentId, path: SpecialFilePath.PATCHSET_LEVEL_COMMENTS, updated: '2015-12-06 15:16:15.000000000' as Timestamp, message: 'patchset comment 1', unresolved: false, patch_set: '2' as PatchSetNum, }, ], patchNum: 2 as PatchSetNum, path: SpecialFilePath.PATCHSET_LEVEL_COMMENTS, rootId: 'patchset_level_1' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { id: 'patchset_level_2' as UrlEncodedCommentId, path: SpecialFilePath.PATCHSET_LEVEL_COMMENTS, updated: '2015-12-07 15:16:15.000000000' as Timestamp, message: 'patchset comment 2', unresolved: false, patch_set: '3' as PatchSetNum, }, ], patchNum: 3 as PatchSetNum, path: SpecialFilePath.PATCHSET_LEVEL_COMMENTS, rootId: 'patchset_level_2' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { path: '/COMMIT_MSG', author: { _account_id: 1000000 as AccountId, name: 'user', username: 'user', }, patch_set: 4 as PatchSetNum, id: 'rc1' as UrlEncodedCommentId, line: 5, updated: '2015-12-08 15:16:15.000000000' as Timestamp, message: 'test', unresolved: true, robot_id: 'rc1' as RobotId, }, ], patchNum: 4 as PatchSetNum, path: '/COMMIT_MSG', line: 5, rootId: 'rc1' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, { comments: [ { path: '/COMMIT_MSG', author: { _account_id: 1000000 as AccountId, name: 'user', username: 'user', }, patch_set: 4 as PatchSetNum, id: 'rc2' as UrlEncodedCommentId, line: 7, updated: '2015-12-09 15:16:15.000000000' as Timestamp, message: 'test', unresolved: true, robot_id: 'rc2' as RobotId, }, { path: '/COMMIT_MSG', author: { _account_id: 1000000 as AccountId, name: 'user', username: 'user', }, patch_set: 4 as PatchSetNum, id: 'c2_1' as UrlEncodedCommentId, line: 5, updated: '2015-12-10 15:16:15.000000000' as Timestamp, message: 'test', unresolved: true, }, ], patchNum: 4 as PatchSetNum, path: '/COMMIT_MSG', line: 7, rootId: 'rc2' as UrlEncodedCommentId, commentSide: CommentSide.REVISION, }, ]; await element.updateComplete; }); suite('sort threads', () => { test('sort all threads', () => { element.sortDropdownValue = __testOnly_SortDropdownState.FILES; assert.equal(element.getDisplayedThreads().length, 9); const expected: UrlEncodedCommentId[] = [ 'patchset_level_2' as UrlEncodedCommentId, // Posted on Patchset 3 'patchset_level_1' as UrlEncodedCommentId, // Posted on Patchset 2 '8caddf38_44770ec1' as UrlEncodedCommentId, // File level on COMMIT_MSG 'scaddf38_44770ec1' as UrlEncodedCommentId, // Line 4 on COMMIT_MSG 'rc1' as UrlEncodedCommentId, // Line 5 on COMMIT_MESSAGE newer 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId, // Line 5 on COMMIT_MESSAGE older 'zcf0b9fa_fe1a5f62' as UrlEncodedCommentId, // Line 6 on COMMIT_MSG 'rc2' as UrlEncodedCommentId, // Line 7 on COMMIT_MSG '09a9fb0a_1484e6cf' as UrlEncodedCommentId, // File level on test.txt ]; const actual = element.getDisplayedThreads().map(t => t.rootId); assert.sameOrderedMembers(actual, expected); }); test('sort all threads by timestamp', () => { element.sortDropdownValue = __testOnly_SortDropdownState.TIMESTAMP; assert.equal(element.getDisplayedThreads().length, 9); const expected: UrlEncodedCommentId[] = [ 'rc2' as UrlEncodedCommentId, 'rc1' as UrlEncodedCommentId, 'patchset_level_2' as UrlEncodedCommentId, 'patchset_level_1' as UrlEncodedCommentId, 'zcf0b9fa_fe1a5f62' as UrlEncodedCommentId, 'scaddf38_44770ec1' as UrlEncodedCommentId, '8caddf38_44770ec1' as UrlEncodedCommentId, '09a9fb0a_1484e6cf' as UrlEncodedCommentId, 'ecf0b9fa_fe1a5f62' as UrlEncodedCommentId, ]; const actual = element.getDisplayedThreads().map(t => t.rootId); assert.sameOrderedMembers(actual, expected); }); }); test('renders', async () => { await element.updateComplete; expect(element).shadowDom.to.equal(/* HTML */ ` <div class="header"> <span class="sort-text">Sort By:</span> <gr-dropdown-list id="sortDropdown"></gr-dropdown-list> <span class="separator"></span> <span class="filter-text">Filter By:</span> <gr-dropdown-list id="filterDropdown"></gr-dropdown-list> <span class="author-text">From:</span> <gr-account-label deselected="" selectionchipstyle="" nostatusicons="" ></gr-account-label> <gr-account-label deselected="" selectionchipstyle="" nostatusicons="" ></gr-account-label> <gr-account-label deselected="" selectionchipstyle="" nostatusicons="" ></gr-account-label> <gr-account-label deselected="" selectionchipstyle="" nostatusicons="" ></gr-account-label> <gr-account-label deselected="" selectionchipstyle="" nostatusicons="" ></gr-account-label> </div> <div id="threads" part="threads"> <gr-comment-thread show-file-name="" show-file-path="" ></gr-comment-thread> <gr-comment-thread show-file-path=""></gr-comment-thread> <div class="thread-separator"></div> <gr-comment-thread show-file-name="" show-file-path="" ></gr-comment-thread> <gr-comment-thread show-file-path=""></gr-comment-thread> <div class="thread-separator"></div> <gr-comment-thread has-draft="" show-file-name="" show-file-path="" ></gr-comment-thread> <gr-comment-thread show-file-path=""></gr-comment-thread> <gr-comment-thread show-file-path=""></gr-comment-thread> <div class="thread-separator"></div> <gr-comment-thread show-file-name="" show-file-path="" ></gr-comment-thread> <div class="thread-separator"></div> <gr-comment-thread has-draft="" show-file-name="" show-file-path="" ></gr-comment-thread> </div> `); }); test('renders empty', async () => { element.threads = []; await element.updateComplete; expect(queryAndAssert(element, 'div#threads')).dom.to.equal(/* HTML */ ` <div id="threads" part="threads"> <div><span>No comments</span></div> </div> `); }); test('tapping single author chips', async () => { element.account = createAccountDetailWithId(1); await element.updateComplete; const chips = Array.from( queryAll<GrAccountLabel>(element, 'gr-account-label') ); const authors = chips.map(chip => accountOrGroupKey(chip.account!)).sort(); assert.deepEqual(authors, [ 1 as AccountId, 1000000 as AccountId, 1000001 as AccountId, 1000002 as AccountId, 1000003 as AccountId, ]); assert.equal(element.threads.length, 9); assert.equal(element.getDisplayedThreads().length, 9); const chip = chips.find(chip => chip.account!._account_id === 1000001); tap(chip!); await element.updateComplete; assert.equal(element.threads.length, 9); assert.equal(element.getDisplayedThreads().length, 1); assert.equal( element.getDisplayedThreads()[0].comments[0].author?._account_id, 1000001 as AccountId ); tap(chip!); await element.updateComplete; assert.equal(element.threads.length, 9); assert.equal(element.getDisplayedThreads().length, 9); }); test('tapping multiple author chips', async () => { element.account = createAccountDetailWithId(1); await element.updateComplete; const chips = Array.from( queryAll<GrAccountLabel>(element, 'gr-account-label') ); tap(chips.find(chip => chip.account?._account_id === 1000001)!); tap(chips.find(chip => chip.account?._account_id === 1000002)!); await element.updateComplete; assert.equal(element.threads.length, 9); assert.equal(element.getDisplayedThreads().length, 3); assert.equal( element.getDisplayedThreads()[0].comments[0].author?._account_id, 1000002 as AccountId ); assert.equal( element.getDisplayedThreads()[1].comments[0].author?._account_id, 1000002 as AccountId ); assert.equal( element.getDisplayedThreads()[2].comments[0].author?._account_id, 1000001 as AccountId ); }); test('show all comments', async () => { const event = new CustomEvent('value-changed', { detail: {value: CommentTabState.SHOW_ALL}, }); element.handleCommentsDropdownValueChange(event); await element.updateComplete; assert.equal(element.getDisplayedThreads().length, 9); }); test('unresolved shows all unresolved comments', async () => { const event = new CustomEvent('value-changed', { detail: {value: CommentTabState.UNRESOLVED}, }); element.handleCommentsDropdownValueChange(event); await element.updateComplete; assert.equal(element.getDisplayedThreads().length, 4); }); test('toggle drafts only shows threads with draft comments', async () => { const event = new CustomEvent('value-changed', { detail: {value: CommentTabState.DRAFTS}, }); element.handleCommentsDropdownValueChange(event); await element.updateComplete; assert.equal(element.getDisplayedThreads().length, 2); }); suite('hideDropdown', () => { test('header hidden for hideDropdown=true', async () => { element.hideDropdown = true; await element.updateComplete; assert.isUndefined(query(element, '.header')); }); test('header shown for hideDropdown=false', async () => { element.hideDropdown = false; await element.updateComplete; assert.isDefined(query(element, '.header')); }); }); suite('empty thread', () => { setup(async () => { element.threads = []; await element.updateComplete; }); test('default empty message should show', () => { const threadsEl = queryAndAssert(element, '#threads'); assert.isTrue(threadsEl.textContent?.trim().includes('No comments')); }); }); }); suite('compareThreads', () => { let t1: CommentThread; let t2: CommentThread; const sortPredicate = (thread1: CommentThread, thread2: CommentThread) => compareThreads(thread1, thread2); const checkOrder = (expected: CommentThread[]) => { assert.sameOrderedMembers([t1, t2].sort(sortPredicate), expected); assert.sameOrderedMembers([t2, t1].sort(sortPredicate), expected); }; setup(() => { t1 = createThread({}); t2 = createThread({}); }); test('patchset-level before file comments', () => { t1.path = SpecialFilePath.PATCHSET_LEVEL_COMMENTS; t2.path = SpecialFilePath.COMMIT_MESSAGE; checkOrder([t1, t2]); }); test('paths lexicographically', () => { t1.path = 'a.txt'; t2.path = 'b.txt'; checkOrder([t1, t2]); }); test('patchsets in reverse order', () => { t1.patchNum = 2 as PatchSetNum; t2.patchNum = 3 as PatchSetNum; checkOrder([t2, t1]); }); test('file level comment before line', () => { t1.line = 123; t2.line = 'FILE'; checkOrder([t2, t1]); }); test('comments sorted by line', () => { t1.line = 123; t2.line = 321; checkOrder([t1, t2]); }); });
GerritCodeReview/gerrit
polygerrit-ui/app/elements/change/gr-thread-list/gr-thread-list_test.ts
TypeScript
apache-2.0
18,089
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.security.tools.scanmanager.common.external.model; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** * Model class to represent an HTML field for a scanner. */ @Entity @Table(name = "SCANNER_FIELD", uniqueConstraints = @UniqueConstraint(columnNames = {"FIELD_ID", "SCANNER_ID"})) public class ScannerField { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", nullable = false) private Integer id; @Column(name = "FIELD_ID", nullable = false) private String fieldId; @ManyToOne @JoinColumn(name = "SCANNER_ID") @JsonBackReference @JsonIgnoreProperties(ignoreUnknown = true) private Scanner scanner; @Column(name = "FIELD_NAME") private String displayName; @Column(name = "FIELD_DESCRIPTION") private String description; @Column(name = "FIELD_TYPE") private String type; @Column(name = "FIELD_ORDER") private Integer order; @Column(name = "IS_REQUIRED") private boolean isRequired; @Column(name = "FIELD_VALUE") private String propertyValueList; public ScannerField() { } public ScannerField(String fieldId, Scanner scanner, String displayName, String description, String type, Integer order, boolean isRequired, String propertyValueList) { this.fieldId = fieldId; this.scanner = scanner; this.displayName = displayName; this.description = description; this.type = type; this.order = order; this.isRequired = isRequired; this.propertyValueList = propertyValueList; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Scanner getScanner() { return scanner; } public void setScanner(Scanner scanner) { this.scanner = scanner; } public String getFieldId() { return fieldId; } public void setFieldId(String fieldId) { this.fieldId = fieldId; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getOrder() { return order; } public void setOrder(Integer order) { this.order = order; } public boolean isRequired() { return isRequired; } public void setRequired(boolean required) { isRequired = required; } public String getPropertyValueList() { return propertyValueList; } public void setPropertyValueList(String propertyValueList) { this.propertyValueList = propertyValueList; } }
wso2/security-tools
internal/scan-manager/common/external/src/main/java/org/wso2/security/tools/scanmanager/common/external/model/ScannerField.java
Java
apache-2.0
4,084
# servkeeper ## Microservice Curator Server Can you imagine how difficult it must be to efficiently deploy micro services with elastic scalability, continuous delivery and active monitoring? * How will you scale up, down? * How will you manage multiple instances? ServKeeper is the answer to your problem! Using the champion formula: - Apache ZooKeeper for coordinating distributed services; - Docker, to climb LXC containers on demand; - Apache Curator, to facilitate the use of ZooKeeper; - Jenkins, to deploy and verify instances. ## What servkeeper do? Well, I think the picture explains better: ![Image of architecture](https://lh3.googleusercontent.com/-a7NHCDkkrGk/VYk6V38hNqI/AAAAAAAAGLw/Z6cmKiY0Iow/s800/arquitetura.png) ServKeeper controls and coordinates micro services instances. You configure ServKeeper to "watch" some micro service. It then takes care of scalling up (creating more instances, when needed), scalling down (remove some instances when needed), and check every instance. It uses Zookeeper (via Apache Curator) to register instances. When a User needs an instance, he asks Zookeper (via Apache Curator) and get one address (it uses Round robin). ServKeeper runs the instances on a Docker environment. ## So many projects... Ok, let me explain that: - servkeeper : The Micro services curator REST server; - ServiceClient : The API for micro services. They use it to increment the shared request counter; - signature : A micro service sample. ## Using ServKeeper: Build and run the server. It has some REST routes: - ../servkeeper/requests : Show the total requests received by all services instances; - ../servkeper/stopall : Stop all services instances, and removes them from Docker and Zookeeper; - ../servkeeper/stopserver : Stop the ServKeeper REST server; - ../servkeeper/supervise : Run a supervisation over all micro services instances. Deletes "trashed" instances, verifies the shared request counter, and scales up or down the number of instances. This must be invoked periodically; - ../servkeeper/getinstance : Return one of the instances, by making a request to Zookeeper. You don't need to use it from the server, and you can query zookeeper instead. It is just a convenience method; - ../servkeeper/setcounter?value=<value> : Set the shared requests counter to the provided value. Default is zero; - ../servkeeper/instancescount : Return the number of micro services instances, in zookeeper and in docker. They may be different if the server is scalling down; - ../servkeeper/start : Starts the server, booting all minimum micro services instances and reseting the shared request counter; ## Configuring ServKeeper ServKeeper is a Dropwizard Server, so, we have a "servkeeper.yml" file, that controls it. When starting ServKeeper, the command line is: `java -jar <servkeeper.shaded.jar> server <path to servkeeper.yml file>` The YML file have this options: ``` # Docker host. If using boot2docker, this is the vm address: dockerHost: "https://192.168.59.103:2376" # Docker certificate path, to logon on docker: dockerCertPath: "/Users/cleutonsampaio/.boot2docker/certs/boot2docker-vm" # Zookeper host address and port: zkHost: "localhost:2181" # Path to where Jenkins deploy the compiled jars. This is the "appfolder", where Jenkins deploy the artifacts: path: "/Users/cleutonsampaio/Documents/projetos/dockertest" # Docker image name. There must be a Dockerfile in the path, and this will be the generated image name: imageName: "signatureimage" # Docker container name. This is the service name, used to search for instances on Zookeeper: containerBaseName: "signatureserver" # Micro service source port. Must be exposed in the Docker file and will be mapped to a host port: sourcePortNumber: 3000 # Minimum micro service instances when starting ServKeeper. They will be launched on startL startServerInstances: 2 # Minimum micro service instances that must exist: minServerInstances: 1 # Maximm server instances to scale up: maxServerInstances: 5 # Maximum request limit before scalling up: maxRequestLimit: 10 # Minimum request limit before scalling down: minRequestLimit: 5 # Micro service test REST route: serviceTestPah: "/signature/checkstatus" # Array of micro service possible addresses and ports: serverAddresses: - host: "192.168.59.103" port: 3000 - host: "192.168.59.103" port: 3001 - host: "192.168.59.103" port: 3002 - host: "192.168.59.103" port: 3003 - host: "192.168.59.103" port: 3004 - host: "192.168.59.103" port: 3005 # ServKeeper configuration: server: applicationConnectors: - type: http port: 3000 adminConnectors: - type: http port: 3300 ``` ## Jenkins Jobs: Each project has a jenkins xml job file, at the root path. You can import this jobs to a Jenkins server using the Jenkins CLI command: java -jar jenkins-cli.jar -s http://localhost:8080/ create-job NAME (reads a xml from stin). The Jobs are: - ServiceClient/serviceclient_build_install.xml : Build ServiceClient and install it on the Jenkins .m2 folder; - servkeeper/servkeeper_build.xml : Build ServKeeper and deploy it to the app folder. - servkeeper/servkeeper_run_and_start.xml : Run ServKeeper process and, after a while, send a "start" request; - servkeeper/servkeeper_stop_and_destroy.xml : Stop all micro services instances and stop ServKeeper process; - servkeeper/servkeeper_supervise.xml : Send a supervise request to ServKeeper. It must be schedulled; - signature/signaturejob.xml : Build and deploy the sample micro service to the app folder; ## The micro service: You can use SerKeeper to take care of any micro service, written on any language. I am using Java with Dropwizard. The ServiceClient project creates a JAR file with a class. This class can be used even in Node.js (using node-java). If you want, you can use Apache Curator RPC Proxy, which is generated by Apache Thrift, and create a proxy for any language.
neviim/servkeeper
README.md
Markdown
apache-2.0
5,956
# Embelia gamblei Kurz ex C.B.Clarke SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Primulaceae/Embelia/Embelia gamblei/README.md
Markdown
apache-2.0
184
# ipf-xsede %VER%-%REL% # README ## Overview The Information Publishing Framework (IPF) is a generic framework for gathering and publishing information. IPF focuses narrowly on gatethering and publishing, and not on analyzing or visualizing information. IPF grew out of work to publish information about TeraGrid compute resources using the [GLUE 2 specification](http://www.ogf.org/documents/GFD.147.pdf). IPF continues to support data gathering and publishing in the XSEDE program which succeeded TeraGrid. IPF gathers and publishes information using simple workflows. These workflows are defined using JSON (see the etc/workflows directory) and steps in the workflows are implemented as Python classes. Each step in the workflow can require input Data, can produce output Data, and can publish Representations of Data. A typical workflow consists of a number of information gathering steps and a few steps that publish Representations to files or to remote services (e.g. REST, messaging). Workflow steps specify what Data they require and what Data they produce. This allows IPF to construct workflows based on partial information - in the case where there are not steps that produce the same Data, an entire workflow can be constructed from a single publish step and its required input Data. At the other extreme, workflows can be exactly specified with specific steps identified and the outputs of steps bound to the inputs of other steps. A typical workflow (e.g. GLUE 2) specifies what steps to include but lets IPF automatically link outputs to inputs of these steps. Workflows can run to completion relatively quickly or they can continuously run. The first type of workflow can be used to run a few commands or look at status files and publish that information. The second type of workflow can be used to monitor log files and publish entries written to those files. Workflows are typically run periodically as cron jobs. The program libexec/run_workflow.py is for executing workflows that complete quickly and the program libexec/run_workflow_daemon.py is used to manage long-running workflows. The daemon ## License This software is licensed under Version 2.0 of the Apache License. ## Installation Installation instructions are in [docs/INSTALL.md](docs/INSTALL.md). ## Contact Information This software is maintained by [XSEDE](https://www.github.com/XSEDE). and you can contact the XSEDE helpdesk if you need help using it. If you have problems with this software you are welcome to submit an [issue](https://github.com/XSEDE/ipf/issues). ## Acknowledgements This work was supported by the TeraGrid, XSEDE, FutureGrid, and XSEDE 2 projects under National Science Foundation grants 0503697, 1053575, 0910812, and 1548562.
ericblau/ipf-xsede
README.md
Markdown
apache-2.0
2,752
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "KytheGraphObserver.h" #include "clang/AST/Attr.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclFriend.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TemplateBase.h" #include "clang/AST/TemplateName.h" #include "clang/AST/Type.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/SourceManager.h" #include "kythe/cxx/common/path_utils.h" #include "IndexerASTHooks.h" #include "KytheGraphRecorder.h" namespace kythe { using clang::SourceLocation; using kythe::proto::Entry; using llvm::StringRef; static const char *CompletenessToString( KytheGraphObserver::Completeness completeness) { switch (completeness) { case KytheGraphObserver::Completeness::Definition: return "definition"; case KytheGraphObserver::Completeness::Complete: return "complete"; case KytheGraphObserver::Completeness::Incomplete: return "incomplete"; } assert(0 && "Invalid enumerator passed to CompletenessToString."); return "invalid-completeness"; } static const char *FunctionSubkindToString( KytheGraphObserver::FunctionSubkind subkind) { switch (subkind) { case KytheGraphObserver::FunctionSubkind::None: return "none"; case KytheGraphObserver::FunctionSubkind::Constructor: return "constructor"; case KytheGraphObserver::FunctionSubkind::Destructor: return "destructor"; } assert(0 && "Invalid enumerator passed to FunctionSubkindToString."); return "invalid-fn-subkind"; } kythe::proto::VName KytheGraphObserver::VNameFromFileEntry( const clang::FileEntry *file_entry) { kythe::proto::VName out_name; if (!vfs_->get_vname(file_entry, &out_name)) { out_name.set_language("c++"); llvm::StringRef working_directory = vfs_->working_directory(); llvm::StringRef file_name(file_entry->getName()); if (file_name.startswith(working_directory)) { out_name.set_path(RelativizePath(file_name, working_directory)); } else { out_name.set_path(file_entry->getName()); } } return out_name; } void KytheGraphObserver::AppendFileBufferSliceHashToStream( clang::SourceLocation loc, llvm::raw_ostream &Ostream) { // TODO(zarko): Does this mechanism produce sufficiently unique // identifiers? Ideally, we would hash the full buffer segment into // which `loc` points, then record `loc`'s offset. bool was_invalid = false; auto *buffer = SourceManager->getCharacterData(loc, &was_invalid); size_t offset = SourceManager->getFileOffset(loc); if (was_invalid) { Ostream << "!invalid[" << offset << "]"; return; } auto loc_end = clang::Lexer::getLocForEndOfToken( loc, 0 /* offset from end of token */, *SourceManager, *getLangOptions()); size_t offset_end = SourceManager->getFileOffset(loc_end); Ostream << HashToString( llvm::hash_value(llvm::StringRef(buffer, offset_end - offset))); } void KytheGraphObserver::AppendFullLocationToStream( std::vector<clang::FileID> *posted_fileids, clang::SourceLocation loc, llvm::raw_ostream &Ostream) { if (!loc.isValid()) { Ostream << "invalid"; return; } if (loc.isFileID()) { clang::FileID file_id = SourceManager->getFileID(loc); const clang::FileEntry *file_entry = SourceManager->getFileEntryForID(file_id); // Don't use getPresumedLoc() since we want to ignore #line-style // directives. if (file_entry) { size_t offset = SourceManager->getFileOffset(loc); Ostream << offset; } else { AppendFileBufferSliceHashToStream(loc, Ostream); } size_t file_id_count = posted_fileids->size(); // Don't inline the same fileid multiple times. // Right now we don't emit preprocessor version information, but we // do distinguish between FileIDs for the same FileEntry. for (size_t old_id = 0; old_id < file_id_count; ++old_id) { if (file_id == (*posted_fileids)[old_id]) { Ostream << "@." << old_id; return; } } posted_fileids->push_back(file_id); if (file_entry) { kythe::proto::VName file_vname(VNameFromFileEntry(file_entry)); if (!file_vname.corpus().empty()) { Ostream << file_vname.corpus() << "/"; } if (!file_vname.root().empty()) { Ostream << file_vname.root() << "/"; } Ostream << file_vname.path(); } } else { AppendFullLocationToStream(posted_fileids, SourceManager->getExpansionLoc(loc), Ostream); Ostream << "@"; AppendFullLocationToStream(posted_fileids, SourceManager->getSpellingLoc(loc), Ostream); } } bool KytheGraphObserver::AppendRangeToStream(llvm::raw_ostream &Ostream, const Range &Range) { std::vector<clang::FileID> posted_fileids; // We want to override this here so that the names we use are filtered // through the vname definitions we got from the compilation unit. if (Range.PhysicalRange.isInvalid()) { return false; } AppendFullLocationToStream(&posted_fileids, Range.PhysicalRange.getBegin(), Ostream); if (Range.PhysicalRange.getEnd() != Range.PhysicalRange.getBegin()) { AppendFullLocationToStream(&posted_fileids, Range.PhysicalRange.getEnd(), Ostream); } if (Range.Kind == GraphObserver::Range::RangeKind::Wraith) { Ostream << Range.Context.ToClaimedString(); } return true; } /// \brief Attempt to associate a `SourceLocation` with a `FileEntry` by /// searching through the location's macro expansion history. /// \param loc The location to associate. Any `SourceLocation` is acceptable. /// \param source_manager The `SourceManager` that generated `loc`. /// \return a `FileEntry` if one was found, null otherwise. static const clang::FileEntry *SearchForFileEntry( clang::SourceLocation loc, clang::SourceManager *source_manager) { clang::FileID file_id = source_manager->getFileID(loc); const clang::FileEntry *out = loc.isFileID() && loc.isValid() ? source_manager->getFileEntryForID(file_id) : nullptr; if (out) { return out; } auto expansion = source_manager->getExpansionLoc(loc); if (expansion.isValid() && expansion != loc) { out = SearchForFileEntry(expansion, source_manager); if (out) { return out; } } auto spelling = source_manager->getSpellingLoc(loc); if (spelling.isValid() && spelling != loc) { out = SearchForFileEntry(spelling, source_manager); } return out; } kythe::proto::VName KytheGraphObserver::VNameFromRange( const GraphObserver::Range &range) { const clang::SourceRange &source_range = range.PhysicalRange; clang::SourceLocation begin = source_range.getBegin(); clang::SourceLocation end = source_range.getEnd(); assert(begin.isValid()); if (!end.isValid()) { begin = end; } if (begin.isMacroID()) { begin = SourceManager->getExpansionLoc(begin); } if (end.isMacroID()) { end = SourceManager->getExpansionLoc(end); } kythe::proto::VName out_name; if (const clang::FileEntry *file_entry = SearchForFileEntry(begin, SourceManager)) { out_name.CopyFrom(VNameFromFileEntry(file_entry)); } else if (range.Kind == GraphObserver::Range::RangeKind::Wraith) { VNameRefFromNodeId(range.Context).Expand(&out_name); } else { out_name.set_language("c++"); } size_t begin_offset = SourceManager->getFileOffset(begin); size_t end_offset = SourceManager->getFileOffset(end); auto *const signature = out_name.mutable_signature(); signature->append("@"); signature->append(std::to_string(begin_offset)); signature->append(":"); signature->append(std::to_string(end_offset)); if (range.Kind == GraphObserver::Range::RangeKind::Wraith) { signature->append("@"); signature->append(range.Context.ToClaimedString()); } out_name.set_signature(CompressString(out_name.signature())); return out_name; } void KytheGraphObserver::RecordSourceLocation( const VNameRef &vname, clang::SourceLocation source_location, PropertyID offset_id) { if (source_location.isMacroID()) { source_location = SourceManager->getExpansionLoc(source_location); } size_t offset = SourceManager->getFileOffset(source_location); recorder_->AddProperty(vname, offset_id, offset); } void KytheGraphObserver::recordMacroNode(const NodeId &macro_id) { recorder_->AddProperty(VNameRefFromNodeId(macro_id), NodeKindID::kMacro); } void KytheGraphObserver::recordExpandsRange(const Range &source_range, const NodeId &macro_id) { RecordAnchor(source_range, macro_id, EdgeKindID::kRefExpands, Claimability::Claimable); } void KytheGraphObserver::recordIndirectlyExpandsRange(const Range &source_range, const NodeId &macro_id) { RecordAnchor(source_range, macro_id, EdgeKindID::kRefExpandsTransitive, Claimability::Claimable); } void KytheGraphObserver::recordUndefinesRange(const Range &source_range, const NodeId &macro_id) { RecordAnchor(source_range, macro_id, EdgeKindID::kUndefines, Claimability::Claimable); } void KytheGraphObserver::recordBoundQueryRange(const Range &source_range, const NodeId &macro_id) { RecordAnchor(source_range, macro_id, EdgeKindID::kRefQueries, Claimability::Claimable); } void KytheGraphObserver::recordUnboundQueryRange(const Range &source_range, const NameId &macro_name) { RecordAnchor(source_range, RecordName(macro_name), EdgeKindID::kRefQueries, Claimability::Claimable); } void KytheGraphObserver::recordIncludesRange(const Range &source_range, const clang::FileEntry *File) { RecordAnchor(source_range, VNameFromFileEntry(File), EdgeKindID::kRefIncludes, Claimability::Claimable); } void KytheGraphObserver::recordUserDefinedNode(const NameId &name, const NodeId &node, const llvm::StringRef &kind, Completeness completeness) { proto::VName name_vname = RecordName(name); VNameRef node_vname = VNameRefFromNodeId(node); recorder_->AddProperty(node_vname, PropertyID::kNodeKind, kind); recorder_->AddProperty(node_vname, PropertyID::kComplete, CompletenessToString(completeness)); recorder_->AddEdge(node_vname, EdgeKindID::kNamed, VNameRef(name_vname)); } void KytheGraphObserver::recordVariableNode(const NameId &name, const NodeId &node, Completeness completeness, VariableSubkind subkind) { proto::VName name_vname = RecordName(name); VNameRef node_vname = VNameRefFromNodeId(node); recorder_->AddProperty(node_vname, NodeKindID::kVariable); recorder_->AddProperty(node_vname, PropertyID::kComplete, CompletenessToString(completeness)); switch (subkind) { case VariableSubkind::Field: recorder_->AddProperty(node_vname, PropertyID::kSubkind, "field"); break; case VariableSubkind::None: break; } recorder_->AddEdge(node_vname, EdgeKindID::kNamed, VNameRef(name_vname)); } void KytheGraphObserver::RecordRange(const proto::VName &anchor_name, const GraphObserver::Range &range) { if (!deferring_nodes_ || deferred_anchors_.insert(range).second) { VNameRef anchor_name_ref(anchor_name); recorder_->AddProperty(anchor_name_ref, NodeKindID::kAnchor); RecordSourceLocation(anchor_name_ref, range.PhysicalRange.getBegin(), PropertyID::kLocationStartOffset); RecordSourceLocation(anchor_name_ref, range.PhysicalRange.getEnd(), PropertyID::kLocationEndOffset); if (const auto *file_entry = SourceManager->getFileEntryForID( SourceManager->getFileID(range.PhysicalRange.getBegin()))) { recorder_->AddEdge(anchor_name_ref, EdgeKindID::kChildOf, VNameRef(VNameFromFileEntry(file_entry))); } if (range.Kind == GraphObserver::Range::RangeKind::Wraith) { recorder_->AddEdge(anchor_name_ref, EdgeKindID::kChildOf, VNameRefFromNodeId(range.Context)); } } } void KytheGraphObserver::MetaHookDefines(const MetadataFile &meta, const VNameRef &anchor, unsigned range_begin, unsigned range_end, const VNameRef &def) { auto rules = meta.rules().equal_range(range_begin); for (auto rule = rules.first; rule != rules.second; ++rule) { if (rule->second.begin == range_begin && rule->second.end == range_end && rule->second.edge_in == "/kythe/edge/defines") { EdgeKindID edge_kind; if (of_spelling(rule->second.edge_out, &edge_kind)) { if (rule->second.reverse_edge) { recorder_->AddEdge(VNameRef(rule->second.vname), edge_kind, def); } else { recorder_->AddEdge(def, edge_kind, VNameRef(rule->second.vname)); } } else { fprintf(stderr, "Unknown edge kind %s from metadata\n", rule->second.edge_out.c_str()); } } } } proto::VName KytheGraphObserver::RecordAnchor( const GraphObserver::Range &source_range, const GraphObserver::NodeId &primary_anchored_to, EdgeKindID anchor_edge_kind, Claimability cl) { assert(!file_stack_.empty()); proto::VName anchor_name = VNameFromRange(source_range); if (claimRange(source_range) || claimNode(primary_anchored_to)) { RecordRange(anchor_name, source_range); cl = Claimability::Unclaimable; } if (cl == Claimability::Unclaimable) { recorder_->AddEdge(VNameRef(anchor_name), anchor_edge_kind, VNameRefFromNodeId(primary_anchored_to)); if (source_range.Kind == Range::RangeKind::Physical) { if (anchor_edge_kind == EdgeKindID::kDefinesBinding) { clang::FileID def_file = SourceManager->getFileID(source_range.PhysicalRange.getBegin()); const auto metas = meta_.equal_range(def_file); if (metas.first != metas.second) { auto begin = source_range.PhysicalRange.getBegin(); if (begin.isMacroID()) { begin = SourceManager->getExpansionLoc(begin); } auto end = source_range.PhysicalRange.getEnd(); if (end.isMacroID()) { end = SourceManager->getExpansionLoc(end); } unsigned range_begin = SourceManager->getFileOffset(begin); unsigned range_end = SourceManager->getFileOffset(end); for (auto meta = metas.first; meta != metas.second; ++meta) { MetaHookDefines(*meta->second, VNameRef(anchor_name), range_begin, range_end, VNameRefFromNodeId(primary_anchored_to)); } } } } } return anchor_name; } proto::VName KytheGraphObserver::RecordAnchor( const GraphObserver::Range &source_range, const kythe::proto::VName &primary_anchored_to, EdgeKindID anchor_edge_kind, Claimability cl) { assert(!file_stack_.empty()); proto::VName anchor_name = VNameFromRange(source_range); if (claimRange(source_range)) { RecordRange(anchor_name, source_range); cl = Claimability::Unclaimable; } if (cl == Claimability::Unclaimable) { recorder_->AddEdge(VNameRef(anchor_name), anchor_edge_kind, VNameRef(primary_anchored_to)); } return anchor_name; } void KytheGraphObserver::recordCallEdge( const GraphObserver::Range &source_range, const NodeId &caller_id, const NodeId &callee_id) { proto::VName anchor_name = RecordAnchor( source_range, caller_id, EdgeKindID::kChildOf, Claimability::Claimable); recorder_->AddEdge(VNameRef(anchor_name), EdgeKindID::kRefCall, VNameRefFromNodeId(callee_id)); } static constexpr char const kLangCpp[] = "c++"; VNameRef KytheGraphObserver::VNameRefFromNodeId( const GraphObserver::NodeId &node_id) { VNameRef out_ref; out_ref.language = llvm::StringRef(kLangCpp, 3); if (const auto *token = clang::dyn_cast<KytheClaimToken>(node_id.getToken())) { token->DecorateVName(&out_ref); } out_ref.signature = node_id.IdentityRef(); return out_ref; } kythe::proto::VName KytheGraphObserver::RecordName( const GraphObserver::NameId &name_id) { proto::VName out_vname; // Names don't have corpus, path or root set. out_vname.set_language("c++"); const std::string name_id_string = name_id.ToString(); out_vname.set_signature(name_id_string); if (!deferring_nodes_ || written_name_ids_.insert(name_id_string).second) { recorder_->AddProperty(VNameRef(out_vname), NodeKindID::kName); } return out_vname; } void KytheGraphObserver::recordParamEdge(const NodeId &param_of_id, uint32_t ordinal, const NodeId &param_id) { recorder_->AddEdge(VNameRefFromNodeId(param_of_id), EdgeKindID::kParam, VNameRefFromNodeId(param_id), ordinal); } void KytheGraphObserver::recordChildOfEdge(const NodeId &child_id, const NodeId &parent_id) { recorder_->AddEdge(VNameRefFromNodeId(child_id), EdgeKindID::kChildOf, VNameRefFromNodeId(parent_id)); } void KytheGraphObserver::recordTypeEdge(const NodeId &term_id, const NodeId &type_id) { recorder_->AddEdge(VNameRefFromNodeId(term_id), EdgeKindID::kHasType, VNameRefFromNodeId(type_id)); } void KytheGraphObserver::recordCallableAsEdge(const NodeId &from_id, const NodeId &to_id) { recorder_->AddEdge(VNameRefFromNodeId(from_id), EdgeKindID::kCallableAs, VNameRefFromNodeId(to_id)); } void KytheGraphObserver::recordSpecEdge(const NodeId &term_id, const NodeId &type_id, Confidence conf) { switch (conf) { case Confidence::NonSpeculative: recorder_->AddEdge(VNameRefFromNodeId(term_id), EdgeKindID::kSpecializes, VNameRefFromNodeId(type_id)); break; case Confidence::Speculative: recorder_->AddEdge(VNameRefFromNodeId(term_id), EdgeKindID::kSpecializesSpeculative, VNameRefFromNodeId(type_id)); break; } } void KytheGraphObserver::recordInstEdge(const NodeId &term_id, const NodeId &type_id, Confidence conf) { switch (conf) { case Confidence::NonSpeculative: recorder_->AddEdge(VNameRefFromNodeId(term_id), EdgeKindID::kInstantiates, VNameRefFromNodeId(type_id)); break; case Confidence::Speculative: recorder_->AddEdge(VNameRefFromNodeId(term_id), EdgeKindID::kInstantiatesSpeculative, VNameRefFromNodeId(type_id)); break; } } GraphObserver::NodeId KytheGraphObserver::nodeIdForTypeAliasNode( const NameId &alias_name, const NodeId &aliased_type) { return NodeId(&type_token_, "talias(" + alias_name.ToString() + "," + aliased_type.ToClaimedString() + ")"); } GraphObserver::NodeId KytheGraphObserver::recordTypeAliasNode( const NameId &alias_name, const NodeId &aliased_type) { NodeId type_id = nodeIdForTypeAliasNode(alias_name, aliased_type); if (!deferring_nodes_ || written_types_.insert(type_id.ToClaimedString()).second) { VNameRef type_vname(VNameRefFromNodeId(type_id)); recorder_->AddProperty(type_vname, NodeKindID::kTAlias); kythe::proto::VName alias_name_vname(RecordName(alias_name)); recorder_->AddEdge(type_vname, EdgeKindID::kNamed, VNameRef(alias_name_vname)); VNameRef aliased_type_vname(VNameRefFromNodeId(aliased_type)); recorder_->AddEdge(type_vname, EdgeKindID::kAliases, VNameRef(aliased_type_vname)); } return type_id; } void KytheGraphObserver::recordDocumentationRange( const GraphObserver::Range &source_range, const NodeId &node) { RecordAnchor(source_range, node, EdgeKindID::kDocuments, Claimability::Claimable); } void KytheGraphObserver::recordFullDefinitionRange( const GraphObserver::Range &source_range, const NodeId &node) { RecordAnchor(source_range, node, EdgeKindID::kDefinesFull, Claimability::Claimable); } void KytheGraphObserver::recordDefinitionBindingRange( const GraphObserver::Range &binding_range, const NodeId &node) { RecordAnchor(binding_range, node, EdgeKindID::kDefinesBinding, Claimability::Claimable); } void KytheGraphObserver::recordDefinitionRangeWithBinding( const GraphObserver::Range &source_range, const GraphObserver::Range &binding_range, const NodeId &node) { RecordAnchor(source_range, node, EdgeKindID::kDefinesFull, Claimability::Claimable); RecordAnchor(binding_range, node, EdgeKindID::kDefinesBinding, Claimability::Claimable); } void KytheGraphObserver::recordCompletionRange( const GraphObserver::Range &source_range, const NodeId &node, Specificity spec) { RecordAnchor(source_range, node, spec == Specificity::UniquelyCompletes ? EdgeKindID::kUniquelyCompletes : EdgeKindID::kCompletes, Claimability::Unclaimable); } void KytheGraphObserver::recordNamedEdge(const NodeId &node, const NameId &name) { recorder_->AddEdge(VNameRefFromNodeId(node), EdgeKindID::kNamed, VNameRef(RecordName(name))); } GraphObserver::NodeId KytheGraphObserver::nodeIdForNominalTypeNode( const NameId &name_id) { // Appending #t to a name produces the VName signature of the nominal // type node referring to that name. For example, the VName for a // forward-declared class type will look like "C#c#t". return NodeId(&type_token_, name_id.ToString() + "#t"); } GraphObserver::NodeId KytheGraphObserver::recordNominalTypeNode( const NameId &name_id) { NodeId id_out = nodeIdForNominalTypeNode(name_id); if (!deferring_nodes_ || written_types_.insert(id_out.ToClaimedString()).second) { VNameRef type_vname(VNameRefFromNodeId(id_out)); recorder_->AddProperty(type_vname, NodeKindID::kTNominal); recorder_->AddEdge(type_vname, EdgeKindID::kNamed, VNameRef(RecordName(name_id))); } return id_out; } GraphObserver::NodeId KytheGraphObserver::recordTappNode( const NodeId &tycon_id, const std::vector<const NodeId *> &params) { // We can't just use juxtaposition here because it leads to ambiguity // as we can't assume that we have kind information, eg // foo bar baz // might be // foo (bar baz) // We'll turn it into a C-style function application: // foo(bar,baz) || foo(bar(baz)) std::string identity; llvm::raw_string_ostream ostream(identity); bool comma = false; ostream << tycon_id.ToClaimedString(); ostream << "("; for (const auto *next_id : params) { if (comma) { ostream << ","; } ostream << next_id->ToClaimedString(); comma = true; } ostream << ")"; GraphObserver::NodeId id_out(&type_token_, ostream.str()); if (!deferring_nodes_ || written_types_.insert(id_out.ToClaimedString()).second) { VNameRef tapp_vname(VNameRefFromNodeId(id_out)); recorder_->AddProperty(tapp_vname, NodeKindID::kTApp); recorder_->AddEdge(tapp_vname, EdgeKindID::kParam, VNameRefFromNodeId(tycon_id), 0); for (uint32_t param_index = 0; param_index < params.size(); ++param_index) { recorder_->AddEdge(tapp_vname, EdgeKindID::kParam, VNameRefFromNodeId(*params[param_index]), param_index + 1); } } return id_out; } void KytheGraphObserver::recordEnumNode(const NodeId &node_id, Completeness completeness, EnumKind enum_kind) { VNameRef node_vname = VNameRefFromNodeId(node_id); recorder_->AddProperty(node_vname, NodeKindID::kSum); recorder_->AddProperty(node_vname, PropertyID::kComplete, CompletenessToString(completeness)); recorder_->AddProperty(node_vname, PropertyID::kSubkind, enum_kind == EnumKind::Scoped ? "enumClass" : "enum"); } void KytheGraphObserver::recordIntegerConstantNode(const NodeId &node_id, const llvm::APSInt &Value) { VNameRef node_vname(VNameRefFromNodeId(node_id)); recorder_->AddProperty(node_vname, NodeKindID::kConstant); recorder_->AddProperty(node_vname, PropertyID::kText, Value.toString(10)); } void KytheGraphObserver::recordFunctionNode(const NodeId &node_id, Completeness completeness, FunctionSubkind subkind) { VNameRef node_vname = VNameRefFromNodeId(node_id); recorder_->AddProperty(node_vname, NodeKindID::kFunction); recorder_->AddProperty(node_vname, PropertyID::kComplete, CompletenessToString(completeness)); if (subkind != FunctionSubkind::None) { recorder_->AddProperty(node_vname, PropertyID::kSubkind, FunctionSubkindToString(subkind)); } } void KytheGraphObserver::recordCallableNode(const NodeId &node_id) { recorder_->AddProperty(VNameRefFromNodeId(node_id), NodeKindID::kCallable); } void KytheGraphObserver::recordAbsNode(const NodeId &node_id) { recorder_->AddProperty(VNameRefFromNodeId(node_id), NodeKindID::kAbs); } void KytheGraphObserver::recordAbsVarNode(const NodeId &node_id) { recorder_->AddProperty(VNameRefFromNodeId(node_id), NodeKindID::kAbsVar); } void KytheGraphObserver::recordLookupNode(const NodeId &node_id, const llvm::StringRef &Name) { VNameRef node_vname = VNameRefFromNodeId(node_id); recorder_->AddProperty(node_vname, NodeKindID::kLookup); recorder_->AddProperty(node_vname, PropertyID::kText, Name); } void KytheGraphObserver::recordRecordNode(const NodeId &node_id, RecordKind kind, Completeness completeness) { VNameRef node_vname = VNameRefFromNodeId(node_id); recorder_->AddProperty(node_vname, NodeKindID::kRecord); switch (kind) { case RecordKind::Class: recorder_->AddProperty(node_vname, PropertyID::kSubkind, "class"); break; case RecordKind::Struct: recorder_->AddProperty(node_vname, PropertyID::kSubkind, "struct"); break; case RecordKind::Union: recorder_->AddProperty(node_vname, PropertyID::kSubkind, "union"); break; }; recorder_->AddProperty(node_vname, PropertyID::kComplete, CompletenessToString(completeness)); } void KytheGraphObserver::recordTypeSpellingLocation( const GraphObserver::Range &type_source_range, const NodeId &type_id, Claimability claimability) { RecordAnchor(type_source_range, type_id, EdgeKindID::kRef, claimability); } void KytheGraphObserver::recordExtendsEdge(const NodeId &from, const NodeId &to, bool is_virtual, clang::AccessSpecifier specifier) { switch (specifier) { case clang::AccessSpecifier::AS_public: recorder_->AddEdge(VNameRefFromNodeId(from), is_virtual ? EdgeKindID::kExtendsPublicVirtual : EdgeKindID::kExtendsPublic, VNameRefFromNodeId(to)); break; case clang::AccessSpecifier::AS_protected: recorder_->AddEdge(VNameRefFromNodeId(from), is_virtual ? EdgeKindID::kExtendsProtectedVirtual : EdgeKindID::kExtendsProtected, VNameRefFromNodeId(to)); break; case clang::AccessSpecifier::AS_private: recorder_->AddEdge(VNameRefFromNodeId(from), is_virtual ? EdgeKindID::kExtendsPrivateVirtual : EdgeKindID::kExtendsPrivate, VNameRefFromNodeId(to)); break; default: recorder_->AddEdge( VNameRefFromNodeId(from), is_virtual ? EdgeKindID::kExtendsVirtual : EdgeKindID::kExtends, VNameRefFromNodeId(to)); } } void KytheGraphObserver::recordDeclUseLocationInDocumentation( const GraphObserver::Range &source_range, const NodeId &node) { RecordAnchor(source_range, node, EdgeKindID::kRefDoc, Claimability::Claimable); } void KytheGraphObserver::recordDeclUseLocation( const GraphObserver::Range &source_range, const NodeId &node, Claimability claimability) { RecordAnchor(source_range, node, EdgeKindID::kRef, claimability); } void KytheGraphObserver::applyMetadataFile(clang::FileID id, const clang::FileEntry *file) { const llvm::MemoryBuffer *buffer = SourceManager->getMemoryBufferForFile(file); if (!buffer) { fprintf(stderr, "Couldn't get content for %s\n", file->getName()); return; } std::string error; auto metadata = MetadataFile::LoadFromJSON(buffer->getBuffer(), &error); if (metadata) { meta_.emplace(id, std::move(metadata)); } else { fprintf(stderr, "Couldn't load %s: %s\n", file->getName(), error.c_str()); } } void KytheGraphObserver::pushFile(clang::SourceLocation blame_location, clang::SourceLocation source_location) { PreprocessorContext previous_context = file_stack_.empty() ? starting_context_ : file_stack_.back().context; bool has_previous_uid = !file_stack_.empty(); llvm::sys::fs::UniqueID previous_uid; if (has_previous_uid) { previous_uid = file_stack_.back().uid; } file_stack_.push_back(FileState{}); FileState &state = file_stack_.back(); state.claimed = true; if (source_location.isValid()) { if (source_location.isMacroID()) { source_location = SourceManager->getExpansionLoc(source_location); } assert(source_location.isFileID()); clang::FileID file = SourceManager->getFileID(source_location); if (file.isInvalid()) { // An actually invalid location. } else { const clang::FileEntry *entry = SourceManager->getFileEntryForID(file); if (entry) { // An actual file. state.vname = state.base_vname = VNameFromFileEntry(entry); state.uid = entry->getUniqueID(); // Attempt to compute the state-amended VName using the state table. // If we aren't working under any context, we won't end up making the // VName more specific. if (file_stack_.size() == 1) { // Start state. state.context = starting_context_; } else if (has_previous_uid && !previous_context.empty() && blame_location.isValid() && blame_location.isFileID()) { unsigned offset = SourceManager->getFileOffset(blame_location); const auto path_info = path_to_context_data_.find(previous_uid); if (path_info != path_to_context_data_.end()) { const auto context_info = path_info->second.find(previous_context); if (context_info != path_info->second.end()) { const auto offset_info = context_info->second.find(offset); if (offset_info != context_info->second.end()) { state.context = offset_info->second; } else { fprintf(stderr, "Warning: when looking for %s[%s]:%u: missing source " "offset\n", vfs_->get_debug_uid_string(previous_uid).c_str(), previous_context.c_str(), offset); } } else { fprintf(stderr, "Warning: when looking for %s[%s]:%u: missing source " "context\n", vfs_->get_debug_uid_string(previous_uid).c_str(), previous_context.c_str(), offset); } } else { fprintf( stderr, "Warning: when looking for %s[%s]:%u: missing source path\n", vfs_->get_debug_uid_string(previous_uid).c_str(), previous_context.c_str(), offset); } } state.vname.set_signature(state.context + state.vname.signature()); if (client_->Claim(claimant_, state.vname)) { if (recorded_files_.insert(entry).second) { bool was_invalid = false; const llvm::MemoryBuffer *buf = SourceManager->getMemoryBufferForFile(entry, &was_invalid); if (was_invalid || !buf) { // TODO(zarko): diagnostic logging. } else { recorder_->AddFileContent(VNameRef(state.base_vname), buf->getBuffer()); } } } else { state.claimed = false; } KytheClaimToken token; token.set_vname(state.vname); token.set_rough_claimed(state.claimed); claim_checked_files_.emplace(file, token); } else { // A builtin location. } } } } void KytheGraphObserver::popFile() { assert(!file_stack_.empty()); FileState state = file_stack_.back(); file_stack_.pop_back(); if (file_stack_.empty()) { deferred_anchors_.clear(); } } bool KytheGraphObserver::claimRange(const GraphObserver::Range &range) { return (range.Kind == GraphObserver::Range::RangeKind::Wraith && claimNode(range.Context)) || claimLocation(range.PhysicalRange.getBegin()); } bool KytheGraphObserver::claimLocation(clang::SourceLocation source_location) { if (!source_location.isValid()) { return true; } if (source_location.isMacroID()) { source_location = SourceManager->getExpansionLoc(source_location); } assert(source_location.isFileID()); clang::FileID file = SourceManager->getFileID(source_location); if (file.isInvalid()) { return true; } auto token = claim_checked_files_.find(file); return token != claim_checked_files_.end() ? token->second.rough_claimed() : false; } void KytheGraphObserver::AddContextInformation( const std::string &path, const PreprocessorContext &context, unsigned offset, const PreprocessorContext &dest_context) { auto found_file = vfs_->status(path); if (found_file) { path_to_context_data_[found_file->getUniqueID()][context][offset] = dest_context; } else { fprintf(stderr, "WARNING: Path %s could not be mapped to a VFS record.\n", path.c_str()); } } const GraphObserver::ClaimToken *KytheGraphObserver::getClaimTokenForLocation( clang::SourceLocation source_location) { if (!source_location.isValid()) { return getDefaultClaimToken(); } if (source_location.isMacroID()) { source_location = SourceManager->getExpansionLoc(source_location); } assert(source_location.isFileID()); clang::FileID file = SourceManager->getFileID(source_location); if (file.isInvalid()) { return getDefaultClaimToken(); } auto token = claim_checked_files_.find(file); return token != claim_checked_files_.end() ? &token->second : getDefaultClaimToken(); } const GraphObserver::ClaimToken *KytheGraphObserver::getClaimTokenForRange( const clang::SourceRange &range) { return getClaimTokenForLocation(range.getBegin()); } void *KytheClaimToken::clazz_ = nullptr; } // namespace kythe
kidaa/kythe
kythe/cxx/indexer/cxx/KytheGraphObserver.cc
C++
apache-2.0
37,465
# coding=utf-8 # Copyright 2018 The DisentanglementLib 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. """Hyperparameter sweeps and configs for stage 1 of "abstract_reasoning_study". Are Disentangled Representations Helpful for Abstract Visual Reasoning? Sjoerd van Steenkiste, Francesco Locatello, Juergen Schmidhuber, Olivier Bachem. NeurIPS, 2019. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.config import study from disentanglement_lib.utils import resources import disentanglement_lib.utils.hyperparams as h from six.moves import range def get_datasets(): """Returns all the data sets.""" return h.sweep( "dataset.name", h.categorical(["shapes3d", "abstract_dsprites"])) def get_num_latent(sweep): return h.sweep("encoder.num_latent", h.discrete(sweep)) def get_seeds(num): """Returns random seeds.""" return h.sweep("model.random_seed", h.categorical(list(range(num)))) def get_default_models(): """Our default set of models (6 model * 6 hyperparameters=36 models).""" # BetaVAE config. model_name = h.fixed("model.name", "beta_vae") model_fn = h.fixed("model.model", "@vae()") betas = h.sweep("vae.beta", h.discrete([1., 2., 4., 6., 8., 16.])) config_beta_vae = h.zipit([model_name, betas, model_fn]) # AnnealedVAE config. model_name = h.fixed("model.name", "annealed_vae") model_fn = h.fixed("model.model", "@annealed_vae()") iteration_threshold = h.fixed("annealed_vae.iteration_threshold", 100000) c = h.sweep("annealed_vae.c_max", h.discrete([5., 10., 25., 50., 75., 100.])) gamma = h.fixed("annealed_vae.gamma", 1000) config_annealed_beta_vae = h.zipit( [model_name, c, iteration_threshold, gamma, model_fn]) # FactorVAE config. model_name = h.fixed("model.name", "factor_vae") model_fn = h.fixed("model.model", "@factor_vae()") discr_fn = h.fixed("discriminator.discriminator_fn", "@fc_discriminator") gammas = h.sweep("factor_vae.gamma", h.discrete([10., 20., 30., 40., 50., 100.])) config_factor_vae = h.zipit([model_name, gammas, model_fn, discr_fn]) # DIP-VAE-I config. model_name = h.fixed("model.name", "dip_vae_i") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 10.) dip_type = h.fixed("dip_vae.dip_type", "i") config_dip_vae_i = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # DIP-VAE-II config. model_name = h.fixed("model.name", "dip_vae_ii") model_fn = h.fixed("model.model", "@dip_vae()") lambda_od = h.sweep("dip_vae.lambda_od", h.discrete([1., 2., 5., 10., 20., 50.])) lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 1.) dip_type = h.fixed("dip_vae.dip_type", "ii") config_dip_vae_ii = h.zipit( [model_name, model_fn, lambda_od, lambda_d_factor, dip_type]) # BetaTCVAE config. model_name = h.fixed("model.name", "beta_tc_vae") model_fn = h.fixed("model.model", "@beta_tc_vae()") betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.])) config_beta_tc_vae = h.zipit([model_name, model_fn, betas]) all_models = h.chainit([ config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii, config_beta_tc_vae, config_annealed_beta_vae ]) return all_models def get_config(): """Returns the hyperparameter configs for different experiments.""" arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1) arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1) architecture = h.zipit([arch_enc, arch_dec]) return h.product([ get_datasets(), architecture, get_default_models(), get_seeds(5), ]) class AbstractReasoningStudyV1(study.Study): """Defines the study for the paper.""" def get_model_config(self, model_num=0): """Returns model bindings and config file.""" config = get_config()[model_num] model_bindings = h.to_bindings(config) model_config_file = resources.get_file( "config/abstract_reasoning_study_v1/stage1/model_configs/shared.gin") return model_bindings, model_config_file def get_postprocess_config_files(self): """Returns postprocessing config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/postprocess_configs/")) def get_eval_config_files(self): """Returns evaluation config files.""" return list( resources.get_files_in_folder( "config/abstract_reasoning_study_v1/stage1/metric_configs/"))
google-research/disentanglement_lib
disentanglement_lib/config/abstract_reasoning_study_v1/stage1/sweep.py
Python
apache-2.0
5,267
package edu.cmu.lti.oaqa.cse import edu.cmu.lti.oaqa.cse.scala.configuration.Configuration._ import edu.cmu.lti.oaqa.cse.scala.configuration._ import edu.cmu.lti.oaqa.cse.scala.configuration.Parameters._ object CommonTesting { trait yamls { val ex0 = """ configuration: name: oaqa-tutorial author: oaqa collection-reader: inherit: collection_reader.filesystem-collection-reader""" val ex1 = ex0 + """ pipeline: - inherit: phases.phase name: RoomNumberAnnotators options: - inherit: tutorial.ex1.RoomNumberAnnotator""" val ex2 = ex1 + """ - inherit: tutorial.ex2.RoomNumberAnnotator""" val exPhase2 = """ - inherit: phases.phase name: DateTimeAnnotators options: - inherit: tutorial.ex3.SimpleTutorialDateTime - inherit: tutorial.ex3.TutorialDateTime""" val ex3 = ex1 + exPhase2 val ex4 = ex2 + exPhase2 } trait progConfigs { //Collection reader val collectionReaderParams = Map("Language" -> StringParameter("en"), "BrowseSubdirectories" -> BooleanParameter(false), "Encoding" -> StringParameter("UTF-8")) val collectionReader = CollectionReaderDescriptor("org.apache.uima.examples.cpe.FileSystemCollectionReader", collectionReaderParams) val config = Configuration("oaqa-tutorial", "oaqa") private val classPath = "org.apache.uima.tutorial" private def getPath(exNum: Int, name: String) = classPath + ".ex%d.%s" format (exNum, name) //params val testParams = Map("test" -> StringParameter("param1")) val locations = List("Watson - Yorktown", "Watson - Hawthorne I", "Watson - Hawthorne II") val patterns = Map("numbered" -> "\\b[0-4]\\d[0-2]\\d\\d\\b") val roomannotator2Params = Map[String, Parameter]("Locations" -> locations, "Patterns" -> patterns) //annotators //Ex1: RoomNumberAnnotator: val roomAnnotator1 = ComponentDescriptor(getPath(1, "RoomNumberAnnotator"), testParams) //Ex2: RoomNumberAnnotator val roomAnnotator2 = ComponentDescriptor(getPath(2, "RoomNumberAnnotator"), roomannotator2Params) val simpleDateTimeAnnotator = ComponentDescriptor(getPath(3, "SimpleTutorialDateTime"), testParams) val dateTimeAnnotator = ComponentDescriptor(getPath(3, "TutorialDateTime"), testParams) //phases val phase1 = PhaseDescriptor("RoomNumberAnnotators", List(roomAnnotator1)) val phase2 = PhaseDescriptor("RoomNumberAnnotators", List(roomAnnotator1, roomAnnotator2)) val phase3 = PhaseDescriptor("DateTimeAnnotators", List(simpleDateTimeAnnotator, dateTimeAnnotator)) //examples val confEx0 = ConfigurationDescriptor(config, collectionReader, Nil) val confEx1 = ConfigurationDescriptor(config, collectionReader, List(phase1)) val confEx2 = ConfigurationDescriptor(config, collectionReader, List(phase2)) val confEx3 = ConfigurationDescriptor(config, collectionReader, List(phase1, phase3)) val confEx4 = ConfigurationDescriptor(config, collectionReader, List(phase2, phase3)) } trait yamlsAndParsedConfigs extends progConfigs with yamls }
oaqa/bagpipes-old
src/test/scala/edu/cmu/lti/oaqa/cse/CommonTesting.scala
Scala
apache-2.0
3,056
#!/bin/sh python3 setup.py register sdist upload
oxo42/FpTest
release.sh
Shell
apache-2.0
51
package com.fishercoder.solutions; public class _471 { public static class Solution1 { /** * credit: https://discuss.leetcode.com/topic/71963/accepted-solution-in-java */ public String encode(String s) { String[][] dp = new String[s.length()][s.length()]; for (int l = 0; l < s.length(); l++) { for (int i = 0; i < s.length() - l; i++) { int j = i + l; String substr = s.substring(i, j + 1); // Checking if string length < 5. In that case, we know that encoding will not help. if (j - i < 4) { dp[i][j] = substr; } else { dp[i][j] = substr; // Loop for trying all results that we get after dividing the strings into 2 and combine the results of 2 substrings for (int k = i; k < j; k++) { if ((dp[i][k] + dp[k + 1][j]).length() < dp[i][j].length()) { dp[i][j] = dp[i][k] + dp[k + 1][j]; } } // Loop for checking if string can itself found some pattern in it which could be repeated. for (int k = 0; k < substr.length(); k++) { String repeatStr = substr.substring(0, k + 1); if (repeatStr != null && substr.length() % repeatStr.length() == 0 && substr.replaceAll(repeatStr, "").length() == 0) { String ss = substr.length() / repeatStr.length() + "[" + dp[i][i + k] + "]"; if (ss.length() < dp[i][j].length()) { dp[i][j] = ss; } } } } } } return dp[0][s.length() - 1]; } } }
fishercoder1534/Leetcode
src/main/java/com/fishercoder/solutions/_471.java
Java
apache-2.0
2,097
package com.khs.sherpa.servlet; /* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static com.khs.sherpa.util.Util.msg; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.khs.sherpa.context.ApplicationContext; import com.khs.sherpa.servlet.request.SherpaRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.khs.sherpa.context.GenericApplicationContext; import com.khs.sherpa.exception.SherpaInvalidUsernamePassword; import com.khs.sherpa.exception.SherpaRuntimeException; import com.khs.sherpa.servlet.request.DefaultSherpaRequest; public class SherpaServlet extends HttpServlet { private static final long serialVersionUID = 4345668988238038540L; private static final Logger LOGGER = LoggerFactory.getLogger(SherpaServlet.class); @Override public void init() throws ServletException { super.init(); } private void doService(HttpServletRequest request, HttpServletResponse response) throws RuntimeException, IOException { try { ApplicationContext applicationContext = GenericApplicationContext.getApplicationContext(getServletContext()); SherpaRequest sherpaRequest = applicationContext.getManagedBean(DefaultSherpaRequest.class); sherpaRequest.setApplicationContext(applicationContext); sherpaRequest.doService(request, response); } catch (SherpaInvalidUsernamePassword e) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json"); LOGGER.info(msg("INFO "+e.getMessage() )); } catch (SherpaRuntimeException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("application/json"); LOGGER.error(msg("ERROR "+e.getMessage() )); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("application/json"); } finally { // do nothing right now } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doService(request, response); } @Override protected long getLastModified(HttpServletRequest req) { return super.getLastModified(req); } @Override protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doHead(req, resp); } @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doOptions(req, resp); } @Override protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doTrace(req, resp); } }
in-the-keyhole/khs-sherpa
src/main/java/com/khs/sherpa/servlet/SherpaServlet.java
Java
apache-2.0
4,104
package xm.qa.sql; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xm.qa.Evidence; import xm.qa.Question; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * @author xuming */ public class SqlUtil { private static final Logger LOG = LoggerFactory.getLogger(SqlUtil.class); public static final String DRIVIER = "com.mysql.jdbc.Driver"; public static final String URL = "jdbc:mysql://127.0.0.1:3306/qa?useUnicode=true&characterEncoding=utf8"; public static final String USER = "root"; public static final String PASSWORD = "root"; static { try{ Class.forName(DRIVIER); }catch (ClassNotFoundException e){ LOG.error(e.toString()); } } private SqlUtil(){} public static Connection getConnection(){ Connection conn = null; try{ conn = DriverManager.getConnection(URL,USER,PASSWORD); }catch (SQLException e){ LOG.error("get mysql nosql connection error."+e); } return conn; } public static void close(Statement statement){ close(null,statement,null); } public static void close(Statement statement,ResultSet resultSet){ close(null,statement,resultSet); } public static void close(Connection conn, Statement st) { close(conn, st, null); } public static void close(Connection conn) { close(conn, null, null); } public static void close(Connection conn, Statement statement,ResultSet resultSet){ try{ if(resultSet!=null){ resultSet.close(); } if(statement !=null){ statement .close(); } if(conn!=null){ conn.close(); } }catch (SQLException e){ LOG.error("close nosql error.",e); } } public static String getRewindEvidenceText(String question, String answer){ String sql = "select text,id from rewind where question=?"; Connection conn = getConnection(); if(conn ==null){ return null; } PreparedStatement pst = null; ResultSet rs = null; try{ // select pst = conn.prepareStatement(sql); pst.setString(1,question+answer); rs = pst.executeQuery(); if(rs.next()){ String text = rs.getString(1); return text; } }catch (SQLException e){ LOG.error("select error.",e); }finally{ close(conn,pst,rs); } return null; } public static void saveRewindEvidenceText(String question, String answer, String text) { String sql = "insert into rewind (question, text) values (?, ?)"; Connection con = getConnection(); if (con == null) { return; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, question + answer); pst.setString(2, text); ////1、保存回带文本 int count = pst.executeUpdate(); if (count == 1) { LOG.info("保存回带文本成功"); } else { LOG.error("保存回带文本失败"); } } catch (SQLException e) { LOG.debug("保存回带文本失败", e); } finally { close(con, pst, rs); } } public static List<Question> getHistoryQuestionsFromDatabase() { List<Question> questions = new ArrayList<>(); String questionSql = "select question from question"; Connection con = getConnection(); if (con == null) { return questions; } PreparedStatement pst = null; ResultSet rs = null; try { //查询问题 pst = con.prepareStatement(questionSql); rs = pst.executeQuery(); while (rs.next()) { String que = rs.getString(1); int index = que.indexOf(":"); if (index > 0) { que = que.substring(index + 1); } if (que == null || "".equals(que.trim())) { continue; } Question question = new Question(); question.setQuestion(que); questions.add(question); } } catch (SQLException e) { LOG.error("查询问题失败", e); } finally { close(con, pst, rs); } return questions; } public static Question getQuestionFromDatabase(String pre, String questionStr) { String questionSql = "select id,question from question where question=?"; String evidenceSql = "select title,snippet from evidence where question=?"; Connection con = getConnection(); if (con == null) { return null; } PreparedStatement pst = null; ResultSet rs = null; try { //1、查询问题 pst = con.prepareStatement(questionSql); pst.setString(1, pre + questionStr.trim().replace("?", "").replace("?", "")); rs = pst.executeQuery(); if (rs.next()) { int id = rs.getInt(1); //去掉前缀 String que = rs.getString(2).replace(pre, ""); Question question = new Question(); question.setQuestion(que); close(pst, rs); //2、查询证据 pst = con.prepareStatement(evidenceSql); pst.setInt(1, id); rs = pst.executeQuery(); while (rs.next()) { String title = rs.getString(1); String snippet = rs.getString(2); } return question; } else { LOG.info("没有从数据库中查询到问题:" + questionStr); } } catch (SQLException e) { LOG.error("查询问题失败", e); } finally { close(con, pst, rs); } return null; } public static void saveQuestionToDatabase(String pre, Question question) { //保存 String questionSql = "insert into question (question) values (?)"; String evidenceSql = "insert into evidence (title, snippet, question) values (?, ?, ?)"; Connection con = getConnection(); if (con == null) { return; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(questionSql, Statement.RETURN_GENERATED_KEYS); pst.setString(1, pre + question.getQuestion().trim().replace("?", "").replace("?", "")); //1、保存问题 int count = pst.executeUpdate(); if (count == 1) { LOG.info("保存问题成功"); //2、获取自动生成的主键值 rs = pst.getGeneratedKeys(); long primaryKey = 0; if (rs.next()) { primaryKey = (Long) rs.getObject(1); } //关闭pst和rs close(pst, rs); if (primaryKey == 0) { LOG.error("获取问题自动生成的主键失败"); return; } int i = 1; //3、保存证据 for (Evidence evidence : question.getEvidences()) { try { pst = con.prepareStatement(evidenceSql); pst.setString(1, evidence.getTitle()); pst.setString(2, evidence.getSnippet()); pst.setLong(3, primaryKey); count = pst.executeUpdate(); if (count == 1) { // LOG.info("保存证据 " + i + " 成功"); } else { LOG.warn("保存证据 " + i + " 失败"); } close(null, pst, null); } catch (Exception e) { LOG.error("保存证据 " + i + " 出错:", e); } i++; } } else { LOG.error("保存问题失败"); } } catch (SQLException e) { LOG.error("保存问题失败", e); } finally { close(con, pst, rs); } } public static void main(String[] args) throws Exception { List<Question> text = getHistoryQuestionsFromDatabase(); if (text != null) { for(Question q:text) System.out.println(q.getQuestion()); } else { System.out.println("问题不在数据库中."); } } }
shibing624/BlogCode
src/main/java/xm/qa/sql/SqlUtil.java
Java
apache-2.0
9,051
package org.ovirt.engine.api.restapi.resource.gluster; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.Response; import org.ovirt.engine.api.common.util.QueryHelper; import org.ovirt.engine.api.model.Cluster; import org.ovirt.engine.api.model.GlusterBrick; import org.ovirt.engine.api.model.GlusterVolume; import org.ovirt.engine.api.model.GlusterVolumes; import org.ovirt.engine.api.resource.ClusterResource; import org.ovirt.engine.api.resource.gluster.GlusterVolumeResource; import org.ovirt.engine.api.resource.gluster.GlusterVolumesResource; import org.ovirt.engine.api.restapi.resource.AbstractBackendCollectionResource; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.gluster.CreateGlusterVolumeParameters; import org.ovirt.engine.core.common.businessentities.gluster.GlusterBrickEntity; import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity; import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeType; import org.ovirt.engine.core.common.businessentities.gluster.TransportType; import org.ovirt.engine.core.common.interfaces.SearchType; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; /** * Implementation of the "glustervolumes" resource */ public class BackendGlusterVolumesResource extends AbstractBackendCollectionResource<GlusterVolume, GlusterVolumeEntity> implements GlusterVolumesResource { static final String[] SUB_COLLECTIONS = { "bricks" }; private ClusterResource parent; private String clusterId; public BackendGlusterVolumesResource() { super(GlusterVolume.class, GlusterVolumeEntity.class, SUB_COLLECTIONS); } public BackendGlusterVolumesResource(ClusterResource parent) { this(); setParent(parent); } public BackendGlusterVolumesResource(ClusterResource parent, String clusterId) { this(); setParent(parent); this.clusterId = clusterId; } public ClusterResource getParent() { return parent; } public void setParent(ClusterResource parent) { this.parent = parent; } @Override public GlusterVolumes list() { String constraint = QueryHelper.getConstraint(getUriInfo(), "cluster = " + parent.get().getName(), GlusterVolume.class); return mapCollection(getBackendCollection(SearchType.GlusterVolume, constraint)); } private GlusterVolumes mapCollection(List<GlusterVolumeEntity> entities) { GlusterVolumes collection = new GlusterVolumes(); for (GlusterVolumeEntity entity : entities) { collection.getGlusterVolumes().add(addLinks(populate(map(entity), entity))); } return collection; } @Override protected GlusterVolume addParents(GlusterVolume volume) { volume.setCluster(new Cluster()); volume.getCluster().setId(clusterId); return volume; } @Override public Response add(GlusterVolume volume) { validateParameters(volume, "name", "volumeType", "bricks"); validateEnumParameters(volume); GlusterVolumeEntity volumeEntity = getMapper(GlusterVolume.class, GlusterVolumeEntity.class).map(volume, null); volumeEntity.setClusterId(asGuid(parent.get().getId())); mapBricks(volume, volumeEntity); return performCreate(VdcActionType.CreateGlusterVolume, new CreateGlusterVolumeParameters(volumeEntity, isForce()), new QueryIdResolver<Guid>(VdcQueryType.GetGlusterVolumeById, IdQueryParameters.class), true); } private void validateEnumParameters(GlusterVolume volume) { validateEnum(GlusterVolumeType.class, volume.getVolumeType().toUpperCase()); if (volume.isSetTransportTypes()) { validateEnumValues(TransportType.class, convertToUppercase(volume.getTransportTypes().getTransportTypes())); } } public static List<String> convertToUppercase(List<String> list) { ArrayList<String> result = new ArrayList<>(); for (String string : list) { result.add(string.toUpperCase()); } return result; } private void mapBricks(GlusterVolume volume, GlusterVolumeEntity volumeEntity) { List<GlusterBrickEntity> bricks = new ArrayList<>(); for(GlusterBrick brick : volume.getBricks().getGlusterBricks()) { bricks.add(getMapper(GlusterBrick.class, GlusterBrickEntity.class).map(brick, null)); } volumeEntity.setBricks(bricks); } @Override public GlusterVolumeResource getVolumeResource(String id) { return inject(new BackendGlusterVolumeResource(id, this)); } }
OpenUniversity/ovirt-engine
backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/resource/gluster/BackendGlusterVolumesResource.java
Java
apache-2.0
4,866
const passport = require('passport'); const request = require('request'); const LocalStrategy = require('passport-local').Strategy; const User = require('../models').User; const INVALID_CREDENTIALS_MESSAGE = 'Invalid email and/or password.'; const UNAUTHORIZED_MESSAGE = 'You are not authorized.'; passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser((id, done) => { User.findById(id) .then(user => done(null, user)) .catch(err => done(err)); }); /** * Sign in using email and password. */ passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => { User.findOne({ where: { email: email.toLowerCase() } }) .then(user => { if (!user) { return done(null, false, { msg: INVALID_CREDENTIALS_MESSAGE }); } user.comparePassword(password, (err, isMatch) => { if (err) { return done(err); } if (isMatch) { return done(null, user); } return done(null, false, { msg: INVALID_CREDENTIALS_MESSAGE }); }); }) .catch(err => done(err)); })); /** * Login Required middleware. */ exports.isAuthenticated = (req, res, next) => { if (req.isAuthenticated()) { return next(); } res.status(401).json({ msg: UNAUTHORIZED_MESSAGE }); };
kklisura/project-neumann
server/app/config/passport.js
JavaScript
apache-2.0
1,301
/** * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.katta.master; import java.util.Collection; import java.util.List; import java.util.UUID; import net.sf.katta.operation.master.CheckIndicesOperation; import net.sf.katta.operation.master.RemoveObsoleteShardsOperation; import net.sf.katta.protocol.ConnectedComponent; import net.sf.katta.protocol.IAddRemoveListener; import net.sf.katta.protocol.InteractionProtocol; import net.sf.katta.protocol.MasterQueue; import net.sf.katta.protocol.metadata.Version; import net.sf.katta.protocol.upgrade.UpgradeAction; import net.sf.katta.protocol.upgrade.UpgradeRegistry; import net.sf.katta.util.KattaException; import net.sf.katta.util.MasterConfiguration; import net.sf.katta.util.ZkConfiguration.PathDef; import org.I0Itec.zkclient.NetworkUtil; import org.I0Itec.zkclient.ZkServer; import org.apache.log4j.Logger; import com.google.common.base.Preconditions; public class Master implements ConnectedComponent { protected final static Logger LOG = Logger.getLogger(Master.class); protected volatile OperatorThread _operatorThread; private String _masterName; private ZkServer _zkServer; private boolean _shutdownClient; protected InteractionProtocol _protocol; private IDeployPolicy _deployPolicy; private long _safeModeMaxTime; public Master(InteractionProtocol interactionProtocol, ZkServer zkServer) throws KattaException { this(interactionProtocol, false); _zkServer = zkServer; } public Master(InteractionProtocol interactionProtocol, boolean shutdownClient) throws KattaException { this(interactionProtocol, shutdownClient, new MasterConfiguration()); } @SuppressWarnings("unchecked") public Master(InteractionProtocol protocol, boolean shutdownClient, MasterConfiguration masterConfiguration) throws KattaException { _protocol = protocol; _masterName = NetworkUtil.getLocalhostName() + "_" + UUID.randomUUID().toString(); _shutdownClient = shutdownClient; protocol.registerComponent(this); final String deployPolicyClassName = masterConfiguration.getDeployPolicy(); try { final Class<IDeployPolicy> policyClazz = (Class<IDeployPolicy>) Class.forName(deployPolicyClassName); _deployPolicy = policyClazz.newInstance(); } catch (final Exception e) { throw new KattaException("Unable to instantiate deploy policy", e); } _safeModeMaxTime = masterConfiguration.getInt(MasterConfiguration.SAFE_MODE_MAX_TIME); } public synchronized void start() { Preconditions.checkState(!isShutdown(), "master was already shut-down"); becomePrimaryOrSecondaryMaster(); } @Override public synchronized void reconnect() { disconnect();// just to be sure we do not open a 2nd operator thread becomePrimaryOrSecondaryMaster(); } @Override public synchronized void disconnect() { if (isMaster()) { _operatorThread.interrupt(); try { _operatorThread.join(); } catch (InterruptedException e) { Thread.interrupted(); // proceed } _operatorThread = null; } } private synchronized void becomePrimaryOrSecondaryMaster() { if (isShutdown()) { return; } MasterQueue queue = _protocol.publishMaster(this); if (queue != null) { UpgradeAction upgradeAction = UpgradeRegistry.findUpgradeAction(_protocol, Version.readFromJar()); if (upgradeAction != null) { upgradeAction.upgrade(_protocol); } _protocol.setVersion(Version.readFromJar()); LOG.info(getMasterName() + " became master with " + queue.size() + " waiting master operations"); startNodeManagement(); MasterContext masterContext = new MasterContext(_protocol, this, _deployPolicy, queue); _operatorThread = new OperatorThread(masterContext, _safeModeMaxTime); _operatorThread.start(); } } public synchronized boolean isInSafeMode() { if (!isMaster()) { return true; } return _operatorThread.isInSafeMode(); } public Collection<String> getConnectedNodes() { return _protocol.getLiveNodes(); } public synchronized MasterContext getContext() { if (!isMaster()) { return null; } return _operatorThread.getContext(); } public synchronized boolean isMaster() { return _operatorThread != null; } private synchronized boolean isShutdown() { return _protocol == null; } public String getMasterName() { return _masterName; } public void handleMasterDisappearedEvent() { becomePrimaryOrSecondaryMaster(); } private void startNodeManagement() { LOG.info("start managing nodes..."); List<String> nodes = _protocol.registerChildListener(this, PathDef.NODES_LIVE, new IAddRemoveListener() { @Override public void removed(String name) { synchronized (Master.this) { if (!isInSafeMode()) { _protocol.addMasterOperation(new CheckIndicesOperation()); } } } @Override public void added(String name) { synchronized (Master.this) { if (!isMaster()) { return; } _protocol.addMasterOperation(new RemoveObsoleteShardsOperation(name)); if (!isInSafeMode()) { _protocol.addMasterOperation(new CheckIndicesOperation()); } } } }); _protocol.addMasterOperation(new CheckIndicesOperation()); for (String node : nodes) { _protocol.addMasterOperation(new RemoveObsoleteShardsOperation(node)); } LOG.info("found following nodes connected: " + nodes); } public synchronized void shutdown() { if (_protocol != null) { _protocol.unregisterComponent(this); if (isMaster()) { _operatorThread.interrupt(); try { _operatorThread.join(); _operatorThread = null; } catch (final InterruptedException e1) { // proceed } } if (_shutdownClient) { _protocol.disconnect(); } _protocol = null; if (_zkServer != null) { _zkServer.shutdown(); } } } }
sgroschupf/katta
modules/katta-core/src/main/java/net/sf/katta/master/Master.java
Java
apache-2.0
6,699
--- title: Automatically setting up and connect Raspberry Pi to a Wifi network description: Automatically setting up your raspberry to connect to your wifi, with a static ip or DHCP! Only via SSH tunnel! permalink: automatically-connect-wifi-raspberry-dhcp-and-staticip icon: 17HaOLLOXYM date: 2017-05-17 category: raspberry tags: [raspberry, wifi, static, dhcp] --- # Automatically setting up and connect Raspberry Pi to a Wifi network <div class="mx-auto"> <img class="max-w-full" src="https://source.unsplash.com/17HaOLLOXYM/960x680" /> </div> So you have bought your Raspberry and you want to figure out how it is working! If you wanna be cool, you don't install GUI and do your things only by CLI and via SSH... but! You need a connection to your local network!! How connect automatically our raspberry on boot to our wifi network? Easy, with cron (or service) and via WPA config. Here is how. First of all, you need to identify your network name. If you boot Raspbian to desktop, you can launch the wpa_gui (WiFi config) application and click 'Scan'. You'll find a list that has your network too with all flags you need. You know, I don't like this solution so, if you wanna be cool, you can do like this: `sudo iwlist wlan0 scan` and find out your wifi ESSID and proto. SSID is your network name. After you found it, you need to update your /etc/wpa_supplicant/wpa_supplicant.conf file. Here is an example: {% highlight bash %} network={ ssid="YOUR_NETWORK_NAME" psk="YOUR_NETWORK_PASSWORD" proto=RSN priority=1 key_mgmt=WPA-PSK pairwise=CCMP auth_alg=OPEN } {% endhighlight %} psk is your network password. You need to write it there. The other parameters are network specific, I can't tell you what you need. - proto could be either RSN (WPA2) or WPA (WPA1). - key_mgmt could be either WPA-PSK (most probably) or WPA-EAP (enterprise networks) - pairwise could be either CCMP (WPA2) or TKIP (WPA1) - auth_alg is most probably OPEN, other options are LEAP and SHARED - priority is an incremental flag because you can specify more network connetions (just by duplicate the "network object"). Priority is an ascending field. After doing this you can run `sudo ifdown wlan0 and sudo ifup wlan0` and verify your connection by ping another ip. Now you have connected your RPi via DHCP. What if you wanna have a static ip? Here we go. We need to update our /etc/dhcpd.conf (for info about this file run `man dhcpcd.conf`) as the follow: /etc/dhcpcd.conf: {% highlight bash %} # A sample configuration for dhcpcd. # See dhcpcd.conf(5) for details. # Allow users of this group to interact with dhcpcd via the control socket. #controlgroup wheel # Inform the DHCP server of our hostname for DDNS. hostname # Use the hardware address of the interface for the Client ID. clientid # or # Use the same DUID + IAID as set in DHCPv6 for DHCPv4 ClientID as per RFC4361. #duid # Persist interface configuration when dhcpcd exits. persistent # Rapid commit support. # Safe to enable by default because it requires the equivalent option set # on the server to actually work. option rapid_commit # A list of options to request from the DHCP server. option domain_name_servers, domain_name, domain_search, host_name option classless_static_routes # Most distributions have NTP support. option ntp_servers # Respect the network MTU. # Some interface drivers reset when changing the MTU so disabled by default. #option interface_mtu # A ServerID is required by RFC2131. require dhcp_server_identifier # Generate Stable Private IPv6 Addresses instead of hardware based ones slaac private # A hook script is provided to lookup the hostname if not set by the DHCP # server, but it should not be run by default. nohook lookup-hostname # look, I configured the static also per ethernet connection (just in case) interface eth0 static ip_address=192.168.1.10/24 static routers=192.168.1.1 static domain_name_servers=192.168.1.1 # here is for wifi interface interface wlan0 # ip/subnet class static ip_address=192.168.1.10/24 static routers=192.168.1.1 static domain_name_servers=192.168.1.1 {% endhighlight %} It's pretty simply here, you need just specify your static ip and gateway. Then reboot your wifi connection. So, now you have configured your RPi with your wifi network and static ip but... what if the wifi network goes down and reup after 5min? You need to re-connect manually... BUT! If you wanna be a cool guy: check every minute (via crontab) if we are still connected to our wifi network and it's all up: {% highlight bash %} #!/bin/bash if ifconfig wlan0 | grep -q "inet addr:" ; then echo "connected" else echo "Network connection down! Attempting reconnection." ifup --force wlan0 sleep 10 fi {% endhighlight %} You need to program this script in your crontab like this: ``*/10 * * * * root /bin/bash /home/pi/check-wifi.sh``
TheJoin95/thejoin95.github.io
public/articles/2017-05-17-automatically-connect-wifi-raspberry-dhcp-and-staticip.md
Markdown
apache-2.0
4,890
"hey iam there yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyy"
6mandati6/6mandati6
tt.py
Python
apache-2.0
135
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.progress.util; import com.intellij.openapi.progress.ProgressIndicator; import org.jetbrains.annotations.NotNull; import org.mustbe.consulo.RequiredReadAction; /** * A computation that needs to be run in background and inside a read action, and canceled whenever a write action is about to occur. * * @see com.intellij.openapi.progress.util.ProgressIndicatorUtils#scheduleWithWriteActionPriority(ReadTask) * */ public interface ReadTask { /** * Performs the computation. * Is invoked inside a read action and under a progress indicator that's canceled when a write action is about to occur. */ @RequiredReadAction void computeInReadAction(@NotNull ProgressIndicator indicator); /** * Is invoked on the background computation thread whenever the computation is canceled by a write action. * A likely implementation is to restart the computation, maybe based on the new state of the system. */ void onCanceled(@NotNull ProgressIndicator indicator); }
ernestp/consulo
platform/platform-impl/src/com/intellij/openapi/progress/util/ReadTask.java
Java
apache-2.0
1,616
/** Code generated by EriLex */ package databook.edsl.map; public class DmapEqAxiom { public <E,S,T> F<Dmap<S,E>,Dmap<T,E>> appl( final F<S,T> eq) { return ((F<Dmap<S,E>,Dmap<T,E>>) eq) ; } public <t,S,T> F<Dmap<t,T>,Dmap<t,T>> appr( final F<S,T> eq) { return ((F<Dmap<t,T>,Dmap<t,T>>) eq) ; } }
DICE-UNC/indexing
src/databook/edsl/map/DmapEqAxiom.java
Java
apache-2.0
308
package com.pengrad.telegrambot.impl; import com.google.gson.Gson; import com.pengrad.telegrambot.Callback; import com.pengrad.telegrambot.request.BaseRequest; import com.pengrad.telegrambot.response.BaseResponse; import okhttp3.Call; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; /** * stas * 5/1/16. */ public class TelegramBotClient { private final OkHttpClient client; private OkHttpClient clientWithTimeout; private final Gson gson; private final String baseUrl; public TelegramBotClient(OkHttpClient client, Gson gson, String baseUrl) { this.client = client; this.gson = gson; this.baseUrl = baseUrl; this.clientWithTimeout = client; } public <T extends BaseRequest<T, R>, R extends BaseResponse> void send(final T request, final Callback<T, R> callback) { OkHttpClient client = getOkHttpClient(request); client.newCall(createRequest(request)).enqueue(new okhttp3.Callback() { @Override public void onResponse(Call call, Response response) { R result = null; Exception exception = null; try { result = gson.fromJson(response.body().string(), request.getResponseType()); } catch (Exception e) { exception = e; } if (result != null) { callback.onResponse(request, result); } else if (exception != null) { IOException ioEx = exception instanceof IOException ? (IOException) exception : new IOException(exception); callback.onFailure(request, ioEx); } else { callback.onFailure(request, new IOException("Empty response")); } } @Override public void onFailure(Call call, IOException e) { callback.onFailure(request, e); } }); } public <T extends BaseRequest<T, R>, R extends BaseResponse> R send(final BaseRequest<T, R> request) { try { OkHttpClient client = getOkHttpClient(request); Response response = client.newCall(createRequest(request)).execute(); return gson.fromJson(response.body().string(), request.getResponseType()); } catch (IOException e) { throw new RuntimeException(e); } } public void shutdown() { client.dispatcher().executorService().shutdown(); } private OkHttpClient getOkHttpClient(BaseRequest<?, ?> request) { int timeoutMillis = request.getTimeoutSeconds() * 1000; if (client.readTimeoutMillis() == 0 || client.readTimeoutMillis() > timeoutMillis) return client; if (clientWithTimeout.readTimeoutMillis() > timeoutMillis) return clientWithTimeout; clientWithTimeout = client.newBuilder().readTimeout(timeoutMillis + 1000, TimeUnit.MILLISECONDS).build(); return clientWithTimeout; } private Request createRequest(BaseRequest<?, ?> request) { return new Request.Builder() .url(baseUrl + request.getMethod()) .post(createRequestBody(request)) .build(); } private RequestBody createRequestBody(BaseRequest<?, ?> request) { if (request.isMultipart()) { MediaType contentType = MediaType.parse(request.getContentType()); MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (Map.Entry<String, Object> parameter : request.getParameters().entrySet()) { String name = parameter.getKey(); Object value = parameter.getValue(); if (value instanceof byte[]) { builder.addFormDataPart(name, request.getFileName(), RequestBody.create(contentType, (byte[]) value)); } else if (value instanceof File) { builder.addFormDataPart(name, request.getFileName(), RequestBody.create(contentType, (File) value)); } else { builder.addFormDataPart(name, toParamValue(value)); } } return builder.build(); } else { FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry<String, Object> parameter : request.getParameters().entrySet()) { builder.add(parameter.getKey(), toParamValue(parameter.getValue())); } return builder.build(); } } private String toParamValue(Object obj) { if (obj.getClass().isPrimitive() || obj.getClass().isEnum() || obj.getClass().getName().startsWith("java.lang")) { return String.valueOf(obj); } return gson.toJson(obj); } }
pengrad/java-telegram-bot-api
library/src/main/java/com/pengrad/telegrambot/impl/TelegramBotClient.java
Java
apache-2.0
5,105
/* * Copyright 2013 Ray Holder * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rholder.gradle.log; /** * Implementations of this interface are meant to process tool logging * information in some way. */ public interface ToolingLogger { /** * Log the given message. * * @param message the message to be logged */ void log(String message); }
rholder/gradle-view
src/main/java/com/github/rholder/gradle/log/ToolingLogger.java
Java
apache-2.0
906
// +build linux // +build mips mipsle mips64 mips64le package signal // import "github.com/tiborvass/docker/pkg/signal" import ( "syscall" "golang.org/x/sys/unix" ) const ( sigrtmin = 34 sigrtmax = 127 ) // SignalMap is a map of Linux signals. var SignalMap = map[string]syscall.Signal{ "ABRT": unix.SIGABRT, "ALRM": unix.SIGALRM, "BUS": unix.SIGBUS, "CHLD": unix.SIGCHLD, "CLD": unix.SIGCLD, "CONT": unix.SIGCONT, "FPE": unix.SIGFPE, "HUP": unix.SIGHUP, "ILL": unix.SIGILL, "INT": unix.SIGINT, "IO": unix.SIGIO, "IOT": unix.SIGIOT, "KILL": unix.SIGKILL, "PIPE": unix.SIGPIPE, "POLL": unix.SIGPOLL, "PROF": unix.SIGPROF, "PWR": unix.SIGPWR, "QUIT": unix.SIGQUIT, "SEGV": unix.SIGSEGV, "EMT": unix.SIGEMT, "STOP": unix.SIGSTOP, "SYS": unix.SIGSYS, "TERM": unix.SIGTERM, "TRAP": unix.SIGTRAP, "TSTP": unix.SIGTSTP, "TTIN": unix.SIGTTIN, "TTOU": unix.SIGTTOU, "URG": unix.SIGURG, "USR1": unix.SIGUSR1, "USR2": unix.SIGUSR2, "VTALRM": unix.SIGVTALRM, "WINCH": unix.SIGWINCH, "XCPU": unix.SIGXCPU, "XFSZ": unix.SIGXFSZ, "RTMIN": sigrtmin, "RTMIN+1": sigrtmin + 1, "RTMIN+2": sigrtmin + 2, "RTMIN+3": sigrtmin + 3, "RTMIN+4": sigrtmin + 4, "RTMIN+5": sigrtmin + 5, "RTMIN+6": sigrtmin + 6, "RTMIN+7": sigrtmin + 7, "RTMIN+8": sigrtmin + 8, "RTMIN+9": sigrtmin + 9, "RTMIN+10": sigrtmin + 10, "RTMIN+11": sigrtmin + 11, "RTMIN+12": sigrtmin + 12, "RTMIN+13": sigrtmin + 13, "RTMIN+14": sigrtmin + 14, "RTMIN+15": sigrtmin + 15, "RTMAX-14": sigrtmax - 14, "RTMAX-13": sigrtmax - 13, "RTMAX-12": sigrtmax - 12, "RTMAX-11": sigrtmax - 11, "RTMAX-10": sigrtmax - 10, "RTMAX-9": sigrtmax - 9, "RTMAX-8": sigrtmax - 8, "RTMAX-7": sigrtmax - 7, "RTMAX-6": sigrtmax - 6, "RTMAX-5": sigrtmax - 5, "RTMAX-4": sigrtmax - 4, "RTMAX-3": sigrtmax - 3, "RTMAX-2": sigrtmax - 2, "RTMAX-1": sigrtmax - 1, "RTMAX": sigrtmax, }
tiborvass/docker
pkg/signal/signal_linux_mipsx.go
GO
apache-2.0
2,046
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.routing.querygraph; import com.graphhopper.routing.ev.*; import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.storage.IntsRef; import com.graphhopper.util.EdgeIterator; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.FetchMode; import com.graphhopper.util.PointList; import java.util.List; /** * @author Peter Karich */ class VirtualEdgeIterator implements EdgeIterator { private final EdgeFilter edgeFilter; private List<EdgeIteratorState> edges; private int current; VirtualEdgeIterator(EdgeFilter edgeFilter, List<EdgeIteratorState> edges) { this.edges = edges; this.current = -1; this.edgeFilter = edgeFilter; } EdgeIterator reset(List<EdgeIteratorState> edges) { this.edges = edges; current = -1; return this; } @Override public boolean next() { current++; while (current < edges.size() && !edgeFilter.accept(edges.get(current))) { current++; } return current < edges.size(); } @Override public EdgeIteratorState detach(boolean reverse) { if (reverse) throw new IllegalStateException("Not yet supported"); return getCurrentEdge(); } @Override public int getEdge() { return getCurrentEdge().getEdge(); } @Override public int getEdgeKey() { return getCurrentEdge().getEdgeKey(); } @Override public int getBaseNode() { return getCurrentEdge().getBaseNode(); } @Override public int getAdjNode() { return getCurrentEdge().getAdjNode(); } @Override public PointList fetchWayGeometry(FetchMode mode) { return getCurrentEdge().fetchWayGeometry(mode); } @Override public EdgeIteratorState setWayGeometry(PointList list) { return getCurrentEdge().setWayGeometry(list); } @Override public double getDistance() { return getCurrentEdge().getDistance(); } @Override public EdgeIteratorState setDistance(double dist) { return getCurrentEdge().setDistance(dist); } @Override public IntsRef getFlags() { return getCurrentEdge().getFlags(); } @Override public EdgeIteratorState setFlags(IntsRef flags) { return getCurrentEdge().setFlags(flags); } @Override public EdgeIteratorState set(BooleanEncodedValue property, boolean value) { getCurrentEdge().set(property, value); return this; } @Override public boolean get(BooleanEncodedValue property) { return getCurrentEdge().get(property); } @Override public EdgeIteratorState setReverse(BooleanEncodedValue property, boolean value) { getCurrentEdge().setReverse(property, value); return this; } @Override public boolean getReverse(BooleanEncodedValue property) { return getCurrentEdge().getReverse(property); } @Override public EdgeIteratorState set(BooleanEncodedValue property, boolean fwd, boolean bwd) { getCurrentEdge().set(property, fwd, bwd); return this; } @Override public EdgeIteratorState set(IntEncodedValue property, int value) { getCurrentEdge().set(property, value); return this; } @Override public int get(IntEncodedValue property) { return getCurrentEdge().get(property); } @Override public EdgeIteratorState setReverse(IntEncodedValue property, int value) { getCurrentEdge().setReverse(property, value); return this; } @Override public int getReverse(IntEncodedValue property) { return getCurrentEdge().getReverse(property); } @Override public EdgeIteratorState set(IntEncodedValue property, int fwd, int bwd) { getCurrentEdge().set(property, fwd, bwd); return this; } @Override public EdgeIteratorState set(DecimalEncodedValue property, double value) { getCurrentEdge().set(property, value); return this; } @Override public double get(DecimalEncodedValue property) { return getCurrentEdge().get(property); } @Override public EdgeIteratorState setReverse(DecimalEncodedValue property, double value) { getCurrentEdge().setReverse(property, value); return this; } @Override public double getReverse(DecimalEncodedValue property) { return getCurrentEdge().getReverse(property); } @Override public EdgeIteratorState set(DecimalEncodedValue property, double fwd, double bwd) { getCurrentEdge().set(property, fwd, bwd); return this; } @Override public <T extends Enum<?>> EdgeIteratorState set(EnumEncodedValue<T> property, T value) { getCurrentEdge().set(property, value); return this; } @Override public <T extends Enum<?>> T get(EnumEncodedValue<T> property) { return getCurrentEdge().get(property); } @Override public <T extends Enum<?>> EdgeIteratorState setReverse(EnumEncodedValue<T> property, T value) { getCurrentEdge().setReverse(property, value); return this; } @Override public <T extends Enum<?>> T getReverse(EnumEncodedValue<T> property) { return getCurrentEdge().getReverse(property); } @Override public <T extends Enum<?>> EdgeIteratorState set(EnumEncodedValue<T> property, T fwd, T bwd) { getCurrentEdge().set(property, fwd, bwd); return this; } @Override public String get(StringEncodedValue property) { return getCurrentEdge().get(property); } @Override public EdgeIteratorState set(StringEncodedValue property, String value) { return getCurrentEdge().set(property, value); } @Override public String getReverse(StringEncodedValue property) { return getCurrentEdge().getReverse(property); } @Override public EdgeIteratorState setReverse(StringEncodedValue property, String value) { return getCurrentEdge().setReverse(property, value); } @Override public EdgeIteratorState set(StringEncodedValue property, String fwd, String bwd) { return getCurrentEdge().set(property, fwd, bwd); } @Override public String getName() { return getCurrentEdge().getName(); } @Override public EdgeIteratorState setName(String name) { return getCurrentEdge().setName(name); } @Override public String toString() { if (current >= 0 && current < edges.size()) { return "virtual edge: " + getCurrentEdge() + ", all: " + edges.toString(); } else { return "virtual edge: (invalid)" + ", all: " + edges.toString(); } } @Override public EdgeIteratorState copyPropertiesFrom(EdgeIteratorState edge) { return getCurrentEdge().copyPropertiesFrom(edge); } @Override public int getOrigEdgeFirst() { return getCurrentEdge().getOrigEdgeFirst(); } @Override public int getOrigEdgeLast() { return getCurrentEdge().getOrigEdgeLast(); } private EdgeIteratorState getCurrentEdge() { return edges.get(current); } public List<EdgeIteratorState> getEdges() { return edges; } }
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/querygraph/VirtualEdgeIterator.java
Java
apache-2.0
8,185
package com.wenyu.loadingrecyclerview; public interface LoadingEvent { void onEventStart(); void onEventSuccess(); void onEventFailure(); void onEventNull(); }
ChanJLee/android_live
loadingrecyclerview/src/main/java/com/wenyu/loadingrecyclerview/LoadingEvent.java
Java
apache-2.0
168
--- external help file: Microsoft.Azure.Commands.ServiceBus.dll-Help.xml Module Name: AzureRM.ServiceBus online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.servicebus/get-azurermservicebusnamespace schema: 2.0.0 --- # Get-AzureRmServiceBusNamespace ## SYNOPSIS Gets a description for the specified Service Bus namespace within the resource group. ## SYNTAX ``` Get-AzureRmServiceBusNamespace [[-ResourceGroupName] <String>] [[-Name] <String>] [-DefaultProfile <IAzureContextContainer>] [<CommonParameters>] ``` ## DESCRIPTION The **Get-AzureRmServiceBusNamespace** cmdlet gets a description for the specified Service Bus namespace within the resource group. ## EXAMPLES ### Example 1 ``` PS C:\> Get-AzureRmServiceBusNamespace -ResourceGroup Default-ServiceBus-WestUS -NamespaceName SB-Example1 Name : SB-Example1 Id : /subscriptions/{subscription id}/resourceGroups/Default-ServiceBus-WestUS/providers/Microsoft.ServiceBus/namespaces/SB-Example1 ResourceGroup : Default-ServiceBus-WestUS Location : West US Tags : {TesttingTags, TestingTagValue, TestTag, TestTagValue} Sku : Name : Premium , Tier : Premium ProvisioningState : Succeeded CreatedAt : 1/20/2017 1:40:01 AM UpdatedAt : 1/20/2017 1:40:24 AM ServiceBusEndpoint : https://SB-Example1.servicebus.windows.net:443/ ``` ## PARAMETERS ### -DefaultProfile The credentials, account, tenant, and subscription used for communication with azure. ```yaml Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer Parameter Sets: (All) Aliases: AzureRmContext, AzureCredential Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Namespace Name. ```yaml Type: System.String Parameter Sets: (All) Aliases: NamespaceName Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceGroupName The name of the resource group ```yaml Type: System.String Parameter Sets: (All) Aliases: ResourceGroup Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String ## OUTPUTS ### Microsoft.Azure.Commands.ServiceBus.Models.PSNamespaceAttributes ## NOTES ## RELATED LINKS
AzureAutomationTeam/azure-powershell
src/ResourceManager/ServiceBus/Commands.ServiceBus/help/Get-AzureRmServiceBusNamespace.md
Markdown
apache-2.0
2,778
/* * 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.codecommit.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Represents the input of a get repository triggers operation. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetRepositoryTriggers" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetRepositoryTriggersRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the repository for which the trigger is configured. * </p> */ private String repositoryName; /** * <p> * The name of the repository for which the trigger is configured. * </p> * * @param repositoryName * The name of the repository for which the trigger is configured. */ public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } /** * <p> * The name of the repository for which the trigger is configured. * </p> * * @return The name of the repository for which the trigger is configured. */ public String getRepositoryName() { return this.repositoryName; } /** * <p> * The name of the repository for which the trigger is configured. * </p> * * @param repositoryName * The name of the repository for which the trigger is configured. * @return Returns a reference to this object so that method calls can be chained together. */ public GetRepositoryTriggersRequest withRepositoryName(String repositoryName) { setRepositoryName(repositoryName); 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 (getRepositoryName() != null) sb.append("RepositoryName: ").append(getRepositoryName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetRepositoryTriggersRequest == false) return false; GetRepositoryTriggersRequest other = (GetRepositoryTriggersRequest) obj; if (other.getRepositoryName() == null ^ this.getRepositoryName() == null) return false; if (other.getRepositoryName() != null && other.getRepositoryName().equals(this.getRepositoryName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRepositoryName() == null) ? 0 : getRepositoryName().hashCode()); return hashCode; } @Override public GetRepositoryTriggersRequest clone() { return (GetRepositoryTriggersRequest) super.clone(); } }
jentfoo/aws-sdk-java
aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/GetRepositoryTriggersRequest.java
Java
apache-2.0
3,984
# ./MARC21relaxed.py # -*- coding: utf-8 -*- # PyXB bindings for NM:5e592dacc0cf5bbbe827fb7d980f3324ca92c3dc # Generated 2016-12-21 00:24:34.092428 by PyXB version 1.2.4 using Python 2.7.12.final.0 # Namespace http://www.loc.gov/MARC21/slim from __future__ import unicode_literals import pyxb import pyxb.binding import pyxb.binding.saxer import io import pyxb.utils.utility import pyxb.utils.domutils import sys import pyxb.utils.six as _six # Unique identifier for bindings created at the same time _GenerationUID = pyxb.utils.utility.UniqueIdentifier('urn:uuid:773ffeee-c70b-11e6-9daf-00e1020040ea') # Version of PyXB used to generate the bindings _PyXBVersion = '1.2.4' # Generated bindings are not compatible across PyXB versions #if pyxb.__version__ != _PyXBVersion: # raise pyxb.PyXBVersionError(_PyXBVersion) # Import bindings for namespaces imported into schema import pyxb.binding.datatypes # NOTE: All namespace declarations are reserved within the binding Namespace = pyxb.namespace.NamespaceForURI('http://www.loc.gov/MARC21/slim', create_if_missing=True) Namespace.configureCategories(['typeBinding', 'elementBinding']) def CreateFromDocument (xml_text, default_namespace=None, location_base=None): """Parse the given XML and use the document element to create a Python instance. @param xml_text An XML document. This should be data (Python 2 str or Python 3 bytes), or a text (Python 2 unicode or Python 3 str) in the L{pyxb._InputEncoding} encoding. @keyword default_namespace The L{pyxb.Namespace} instance to use as the default namespace where there is no default namespace in scope. If unspecified or C{None}, the namespace of the module containing this function will be used. @keyword location_base: An object to be recorded as the base of all L{pyxb.utils.utility.Location} instances associated with events and objects handled by the parser. You might pass the URI from which the document was obtained. """ if pyxb.XMLStyle_saxer != pyxb._XMLStyle: dom = pyxb.utils.domutils.StringToDOM(xml_text) return CreateFromDOM(dom.documentElement, default_namespace=default_namespace) if default_namespace is None: default_namespace = Namespace.fallbackNamespace() saxer = pyxb.binding.saxer.make_parser(fallback_namespace=default_namespace, location_base=location_base) handler = saxer.getContentHandler() xmld = xml_text if isinstance(xmld, _six.text_type): xmld = xmld.encode(pyxb._InputEncoding) saxer.parse(io.BytesIO(xmld)) instance = handler.rootObject() return instance def CreateFromDOM (node, default_namespace=None): """Create a Python instance from the given DOM node. The node tag must correspond to an element declaration in this module. @deprecated: Forcing use of DOM interface is unnecessary; use L{CreateFromDocument}.""" if default_namespace is None: default_namespace = Namespace.fallbackNamespace() return pyxb.binding.basis.element.AnyCreateFromDOM(node, default_namespace) # Atomic simple type: {http://www.loc.gov/MARC21/slim}recordTypeType class recordTypeType (pyxb.binding.datatypes.NMTOKEN, pyxb.binding.basis.enumeration_mixin): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'recordTypeType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 63, 2) _Documentation = None recordTypeType._CF_enumeration = pyxb.binding.facets.CF_enumeration(value_datatype=recordTypeType, enum_prefix=None) recordTypeType.Bibliographic = recordTypeType._CF_enumeration.addEnumeration(unicode_value='Bibliographic', tag='Bibliographic') recordTypeType.Authority = recordTypeType._CF_enumeration.addEnumeration(unicode_value='Authority', tag='Authority') recordTypeType.Holdings = recordTypeType._CF_enumeration.addEnumeration(unicode_value='Holdings', tag='Holdings') recordTypeType.Classification = recordTypeType._CF_enumeration.addEnumeration(unicode_value='Classification', tag='Classification') recordTypeType.Community = recordTypeType._CF_enumeration.addEnumeration(unicode_value='Community', tag='Community') recordTypeType._InitializeFacetMap(recordTypeType._CF_enumeration) Namespace.addCategoryObject('typeBinding', 'recordTypeType', recordTypeType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}leaderDataType class leaderDataType (pyxb.binding.datatypes.string): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'leaderDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 82, 2) _Documentation = None leaderDataType._CF_pattern = pyxb.binding.facets.CF_pattern() leaderDataType._CF_pattern.addPattern(pattern='[\\dA-Za-z\\.| ]{24}') leaderDataType._CF_whiteSpace = pyxb.binding.facets.CF_whiteSpace(value=pyxb.binding.facets._WhiteSpace_enum.preserve) leaderDataType._InitializeFacetMap(leaderDataType._CF_pattern, leaderDataType._CF_whiteSpace) Namespace.addCategoryObject('typeBinding', 'leaderDataType', leaderDataType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}controlDataType class controlDataType (pyxb.binding.datatypes.string): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'controlDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 99, 2) _Documentation = None controlDataType._CF_whiteSpace = pyxb.binding.facets.CF_whiteSpace(value=pyxb.binding.facets._WhiteSpace_enum.preserve) controlDataType._InitializeFacetMap(controlDataType._CF_whiteSpace) Namespace.addCategoryObject('typeBinding', 'controlDataType', controlDataType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}controltagDataType class controltagDataType (pyxb.binding.datatypes.string): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'controltagDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 104, 2) _Documentation = None controltagDataType._CF_pattern = pyxb.binding.facets.CF_pattern() controltagDataType._CF_pattern.addPattern(pattern='[0-9A-Za-z]{3}') controltagDataType._CF_whiteSpace = pyxb.binding.facets.CF_whiteSpace(value=pyxb.binding.facets._WhiteSpace_enum.preserve) controltagDataType._InitializeFacetMap(controltagDataType._CF_pattern, controltagDataType._CF_whiteSpace) Namespace.addCategoryObject('typeBinding', 'controltagDataType', controltagDataType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}tagDataType class tagDataType (pyxb.binding.datatypes.string): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'tagDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 122, 2) _Documentation = None tagDataType._CF_pattern = pyxb.binding.facets.CF_pattern() tagDataType._CF_pattern.addPattern(pattern='(0([0-9A-Z][0-9A-Z])|0([1-9a-z][0-9a-z]))|(([1-9A-Z][0-9A-Z]{2})|([1-9a-z][0-9a-z]{2}))') tagDataType._CF_whiteSpace = pyxb.binding.facets.CF_whiteSpace(value=pyxb.binding.facets._WhiteSpace_enum.preserve) tagDataType._InitializeFacetMap(tagDataType._CF_pattern, tagDataType._CF_whiteSpace) Namespace.addCategoryObject('typeBinding', 'tagDataType', tagDataType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}indicatorDataType class indicatorDataType (pyxb.binding.datatypes.string): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'indicatorDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 128, 2) _Documentation = None indicatorDataType._CF_pattern = pyxb.binding.facets.CF_pattern() indicatorDataType._CF_pattern.addPattern(pattern='[\\da-zA-Z_ ]{1}') indicatorDataType._CF_whiteSpace = pyxb.binding.facets.CF_whiteSpace(value=pyxb.binding.facets._WhiteSpace_enum.preserve) indicatorDataType._InitializeFacetMap(indicatorDataType._CF_pattern, indicatorDataType._CF_whiteSpace) Namespace.addCategoryObject('typeBinding', 'indicatorDataType', indicatorDataType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}subfieldDataType class subfieldDataType (pyxb.binding.datatypes.string): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'subfieldDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 142, 2) _Documentation = None subfieldDataType._CF_whiteSpace = pyxb.binding.facets.CF_whiteSpace(value=pyxb.binding.facets._WhiteSpace_enum.preserve) subfieldDataType._InitializeFacetMap(subfieldDataType._CF_whiteSpace) Namespace.addCategoryObject('typeBinding', 'subfieldDataType', subfieldDataType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}subfieldcodeDataType class subfieldcodeDataType (pyxb.binding.datatypes.string): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'subfieldcodeDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 147, 2) _Documentation = None subfieldcodeDataType._CF_pattern = pyxb.binding.facets.CF_pattern() subfieldcodeDataType._CF_pattern.addPattern(pattern='[\\dA-Za-z!"#$%&\'()*+,-./:;<=>?{}_^`~\\[\\]\\\\]{1}') subfieldcodeDataType._CF_whiteSpace = pyxb.binding.facets.CF_whiteSpace(value=pyxb.binding.facets._WhiteSpace_enum.preserve) subfieldcodeDataType._InitializeFacetMap(subfieldcodeDataType._CF_pattern, subfieldcodeDataType._CF_whiteSpace) Namespace.addCategoryObject('typeBinding', 'subfieldcodeDataType', subfieldcodeDataType) # Atomic simple type: {http://www.loc.gov/MARC21/slim}idDataType class idDataType (pyxb.binding.datatypes.ID): """An atomic simple type.""" _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'idDataType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 154, 2) _Documentation = None idDataType._InitializeFacetMap() Namespace.addCategoryObject('typeBinding', 'idDataType', idDataType) # Complex type {http://www.loc.gov/MARC21/slim}collectionType with content type ELEMENT_ONLY class collectionType (pyxb.binding.basis.complexTypeDefinition): """Complex type {http://www.loc.gov/MARC21/slim}collectionType with content type ELEMENT_ONLY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'collectionType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 46, 2) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.anyType # Element {http://www.loc.gov/MARC21/slim}record uses Python identifier record __record = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'record'), 'record', '__httpwww_loc_govMARC21slim_collectionType_httpwww_loc_govMARC21slimrecord', True, pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 36, 2), ) record = property(__record.value, __record.set, None, 'record is a top level container element for all of the field elements which compose the record') # Attribute id uses Python identifier id __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpwww_loc_govMARC21slim_collectionType_id', idDataType) __id._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 50, 4) __id._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 50, 4) id = property(__id.value, __id.set, None, None) _ElementMap.update({ __record.name() : __record }) _AttributeMap.update({ __id.name() : __id }) Namespace.addCategoryObject('typeBinding', 'collectionType', collectionType) # Complex type {http://www.loc.gov/MARC21/slim}recordType with content type ELEMENT_ONLY class recordType (pyxb.binding.basis.complexTypeDefinition): """Complex type {http://www.loc.gov/MARC21/slim}recordType with content type ELEMENT_ONLY""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'recordType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 52, 2) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.anyType # Element {http://www.loc.gov/MARC21/slim}leader uses Python identifier leader __leader = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'leader'), 'leader', '__httpwww_loc_govMARC21slim_recordType_httpwww_loc_govMARC21slimleader', True, pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 55, 8), ) leader = property(__leader.value, __leader.set, None, None) # Element {http://www.loc.gov/MARC21/slim}controlfield uses Python identifier controlfield __controlfield = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'controlfield'), 'controlfield', '__httpwww_loc_govMARC21slim_recordType_httpwww_loc_govMARC21slimcontrolfield', True, pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 56, 8), ) controlfield = property(__controlfield.value, __controlfield.set, None, None) # Element {http://www.loc.gov/MARC21/slim}datafield uses Python identifier datafield __datafield = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'datafield'), 'datafield', '__httpwww_loc_govMARC21slim_recordType_httpwww_loc_govMARC21slimdatafield', True, pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 57, 8), ) datafield = property(__datafield.value, __datafield.set, None, None) # Attribute type uses Python identifier type __type = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'type'), 'type', '__httpwww_loc_govMARC21slim_recordType_type', recordTypeType) __type._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 60, 4) __type._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 60, 4) type = property(__type.value, __type.set, None, None) # Attribute id uses Python identifier id __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpwww_loc_govMARC21slim_recordType_id', idDataType) __id._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 61, 4) __id._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 61, 4) id = property(__id.value, __id.set, None, None) _ElementMap.update({ __leader.name() : __leader, __controlfield.name() : __controlfield, __datafield.name() : __datafield }) _AttributeMap.update({ __type.name() : __type, __id.name() : __id }) Namespace.addCategoryObject('typeBinding', 'recordType', recordType) # Complex type {http://www.loc.gov/MARC21/slim}leaderFieldType with content type SIMPLE class leaderFieldType (pyxb.binding.basis.complexTypeDefinition): """MARC21 Leader, 24 bytes""" _TypeDefinition = leaderDataType _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_SIMPLE _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'leaderFieldType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 72, 2) _ElementMap = {} _AttributeMap = {} # Base type is leaderDataType # Attribute id uses Python identifier id __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpwww_loc_govMARC21slim_leaderFieldType_id', idDataType) __id._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 78, 8) __id._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 78, 8) id = property(__id.value, __id.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __id.name() : __id }) Namespace.addCategoryObject('typeBinding', 'leaderFieldType', leaderFieldType) # Complex type {http://www.loc.gov/MARC21/slim}controlFieldType with content type SIMPLE class controlFieldType (pyxb.binding.basis.complexTypeDefinition): """MARC21 Fields 001-009""" _TypeDefinition = controlDataType _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_SIMPLE _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'controlFieldType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 88, 2) _ElementMap = {} _AttributeMap = {} # Base type is controlDataType # Attribute id uses Python identifier id __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpwww_loc_govMARC21slim_controlFieldType_id', idDataType) __id._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 94, 8) __id._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 94, 8) id = property(__id.value, __id.set, None, None) # Attribute tag uses Python identifier tag __tag = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'tag'), 'tag', '__httpwww_loc_govMARC21slim_controlFieldType_tag', controltagDataType, required=True) __tag._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 95, 8) __tag._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 95, 8) tag = property(__tag.value, __tag.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __id.name() : __id, __tag.name() : __tag }) Namespace.addCategoryObject('typeBinding', 'controlFieldType', controlFieldType) # Complex type {http://www.loc.gov/MARC21/slim}dataFieldType with content type ELEMENT_ONLY class dataFieldType (pyxb.binding.basis.complexTypeDefinition): """MARC21 Variable Data Fields 010-999""" _TypeDefinition = None _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'dataFieldType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 110, 2) _ElementMap = {} _AttributeMap = {} # Base type is pyxb.binding.datatypes.anyType # Element {http://www.loc.gov/MARC21/slim}subfield uses Python identifier subfield __subfield = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'subfield'), 'subfield', '__httpwww_loc_govMARC21slim_dataFieldType_httpwww_loc_govMARC21slimsubfield', True, pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 115, 6), ) subfield = property(__subfield.value, __subfield.set, None, None) # Attribute id uses Python identifier id __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpwww_loc_govMARC21slim_dataFieldType_id', idDataType) __id._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 117, 4) __id._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 117, 4) id = property(__id.value, __id.set, None, None) # Attribute tag uses Python identifier tag __tag = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'tag'), 'tag', '__httpwww_loc_govMARC21slim_dataFieldType_tag', tagDataType, required=True) __tag._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 118, 4) __tag._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 118, 4) tag = property(__tag.value, __tag.set, None, None) # Attribute ind1 uses Python identifier ind1 __ind1 = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'ind1'), 'ind1', '__httpwww_loc_govMARC21slim_dataFieldType_ind1', indicatorDataType, required=True) __ind1._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 119, 4) __ind1._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 119, 4) ind1 = property(__ind1.value, __ind1.set, None, None) # Attribute ind2 uses Python identifier ind2 __ind2 = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'ind2'), 'ind2', '__httpwww_loc_govMARC21slim_dataFieldType_ind2', indicatorDataType, required=True) __ind2._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 120, 4) __ind2._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 120, 4) ind2 = property(__ind2.value, __ind2.set, None, None) _ElementMap.update({ __subfield.name() : __subfield }) _AttributeMap.update({ __id.name() : __id, __tag.name() : __tag, __ind1.name() : __ind1, __ind2.name() : __ind2 }) Namespace.addCategoryObject('typeBinding', 'dataFieldType', dataFieldType) # Complex type {http://www.loc.gov/MARC21/slim}subfieldatafieldType with content type SIMPLE class subfieldatafieldType (pyxb.binding.basis.complexTypeDefinition): """Complex type {http://www.loc.gov/MARC21/slim}subfieldatafieldType with content type SIMPLE""" _TypeDefinition = subfieldDataType _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_SIMPLE _Abstract = False _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'subfieldatafieldType') _XSDLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 134, 2) _ElementMap = {} _AttributeMap = {} # Base type is subfieldDataType # Attribute id uses Python identifier id __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpwww_loc_govMARC21slim_subfieldatafieldType_id', idDataType) __id._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 137, 8) __id._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 137, 8) id = property(__id.value, __id.set, None, None) # Attribute code uses Python identifier code __code = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'code'), 'code', '__httpwww_loc_govMARC21slim_subfieldatafieldType_code', subfieldcodeDataType, required=True) __code._DeclarationLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 138, 8) __code._UseLocation = pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 138, 8) code = property(__code.value, __code.set, None, None) _ElementMap.update({ }) _AttributeMap.update({ __id.name() : __id, __code.name() : __code }) Namespace.addCategoryObject('typeBinding', 'subfieldatafieldType', subfieldatafieldType) record = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'record'), recordType, nillable=pyxb.binding.datatypes.boolean(1), documentation='record is a top level container element for all of the field elements which compose the record', location=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 36, 2)) Namespace.addCategoryObject('elementBinding', record.name().localName(), record) collection = pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'collection'), collectionType, nillable=pyxb.binding.datatypes.boolean(1), documentation='collection is a top level container element for 0 or many records', location=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 41, 2)) Namespace.addCategoryObject('elementBinding', collection.name().localName(), collection) collectionType._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'record'), recordType, nillable=pyxb.binding.datatypes.boolean(1), scope=collectionType, documentation='record is a top level container element for all of the field elements which compose the record', location=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 36, 2))) def _BuildAutomaton (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton del _BuildAutomaton import pyxb.utils.fac as fac counters = set() cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 47, 4)) counters.add(cc_0) states = [] final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(collectionType._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'record')), pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 48, 6)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_0) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) st_0._set_transitionSet(transitions) return fac.Automaton(states, counters, True, containing_state=None) collectionType._Automaton = _BuildAutomaton() recordType._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'leader'), leaderFieldType, scope=recordType, location=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 55, 8))) recordType._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'controlfield'), controlFieldType, scope=recordType, location=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 56, 8))) recordType._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'datafield'), dataFieldType, scope=recordType, location=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 57, 8))) def _BuildAutomaton_ (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton_ del _BuildAutomaton_ import pyxb.utils.fac as fac counters = set() cc_0 = fac.CounterCondition(min=0, max=None, metadata=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 54, 6)) counters.add(cc_0) states = [] final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(recordType._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'leader')), pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 55, 8)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_0) final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(recordType._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'controlfield')), pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 56, 8)) st_1 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_1) final_update = set() final_update.add(fac.UpdateInstruction(cc_0, False)) symbol = pyxb.binding.content.ElementUse(recordType._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'datafield')), pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 57, 8)) st_2 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_2) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_1, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_2, [ fac.UpdateInstruction(cc_0, True) ])) st_0._set_transitionSet(transitions) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_1, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_2, [ fac.UpdateInstruction(cc_0, True) ])) st_1._set_transitionSet(transitions) transitions = [] transitions.append(fac.Transition(st_0, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_1, [ fac.UpdateInstruction(cc_0, True) ])) transitions.append(fac.Transition(st_2, [ fac.UpdateInstruction(cc_0, True) ])) st_2._set_transitionSet(transitions) return fac.Automaton(states, counters, True, containing_state=None) recordType._Automaton = _BuildAutomaton_() dataFieldType._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'subfield'), subfieldatafieldType, scope=dataFieldType, location=pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 115, 6))) def _BuildAutomaton_2 (): # Remove this helper function from the namespace after it is invoked global _BuildAutomaton_2 del _BuildAutomaton_2 import pyxb.utils.fac as fac counters = set() states = [] final_update = set() symbol = pyxb.binding.content.ElementUse(dataFieldType._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'subfield')), pyxb.utils.utility.Location('/data/code/pyMARC/xsd/MARC21relaxed.xsd', 115, 6)) st_0 = fac.State(symbol, is_initial=True, final_update=final_update, is_unordered_catenation=False) states.append(st_0) transitions = [] transitions.append(fac.Transition(st_0, [ ])) st_0._set_transitionSet(transitions) return fac.Automaton(states, counters, False, containing_state=None) dataFieldType._Automaton = _BuildAutomaton_2()
PixelDragon/pixeldragon
MARC21relaxed.py
Python
apache-2.0
30,253
package resources import ( "fmt" "strings" ) // Description holds information about information of the SKU description, whith strings to be included/omitted. type Description struct { Contains []string Omits []string } func (d *Description) fillForComputeInstance(machineType, usageType string) error { anythingButN1 := []string{"N2", "N2D", "E2", "Compute", "Memory", "Sole Tenancy"} if usageType == "Preemptible" { d.Contains = append(d.Contains, "Preemptible") } else { d.Omits = append(d.Omits, "Preemptible") } // Commitment N1 machines don't have "Commitment" specified. if strings.HasPrefix(usageType, "Commit") { d.Contains = append(d.Contains, "Commitment") if strings.Contains(machineType, "n1") { d.Omits = append(d.Omits, "N1") d.Omits = append(d.Omits, anythingButN1...) } } else { d.Omits = append(d.Omits, "Commitment") } // Custom E2 machines don't have separate SKUs. if strings.Contains(machineType, "custom") { if !strings.HasPrefix(machineType, "e2") { d.Contains = append(d.Contains, "Custom") } } else { d.Omits = append(d.Omits, "Custom") } // Custom N1 machines don't have any type specified, so all types must be excluded. if strings.HasPrefix(machineType, "custom") { d.Omits = append(d.Omits, "N1") d.Omits = append(d.Omits, anythingButN1...) } else { switch { case strings.HasPrefix(machineType, "c2-"): d.Contains = append(d.Contains, "Compute") case strings.HasPrefix(machineType, "m1-") || strings.HasPrefix(machineType, "m2-"): d.Contains = append(d.Contains, "Memory") d.Omits = append(d.Omits, "Upgrade") case strings.HasPrefix(machineType, "n1-mega") || strings.HasPrefix(machineType, "n1-ultra"): d.Contains = append(d.Contains, "Memory") d.Omits = append(d.Omits, "Upgrade") case strings.HasPrefix(machineType, "n1-") || strings.HasPrefix(machineType, "f1-") || strings.HasPrefix(machineType, "g1-"): if !strings.HasPrefix(usageType, "Commit") { d.Contains = append(d.Contains, "N1") } default: // All other machines have their type specified. i := strings.Index(machineType, "-") if i < 0 { return fmt.Errorf("wrong machine type format") } d.Contains = append(d.Contains, strings.ToUpper(machineType[:i])+" ") } } return nil } func (d *Description) fillForComputeDisk(diskType string, regional bool) { switch diskType { case "pd-standard": d.Contains = []string{"Storage PD Capacity"} case "pd-ssd": d.Contains = []string{"SSD backed PD Capacity"} default: } if regional { d.Contains = append(d.Contains, "Regional") } else { d.Omits = append(d.Omits, "Regional") } }
googleinterns/terraform-cost-estimation
resources/description.go
GO
apache-2.0
2,651
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skyframe; import com.google.devtools.build.lib.causes.LabelCause; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.packages.SkylarkAspect; import com.google.devtools.build.lib.skyframe.AspectValueKey.SkylarkAspectLoadingKey; import com.google.devtools.build.skyframe.SkyFunction; import com.google.devtools.build.skyframe.SkyFunctionException; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.SkyValue; import javax.annotation.Nullable; /** * SkyFunction to load aspects from Starlark extensions and calculate their values. * * <p>Used for loading top-level aspects. At top level, in {@link * com.google.devtools.build.lib.analysis.BuildView}, we cannot invoke two SkyFunctions one after * another, so BuildView calls this function to do the work. */ public class ToplevelSkylarkAspectFunction implements SkyFunction { ToplevelSkylarkAspectFunction() {} @Nullable @Override public SkyValue compute(SkyKey skyKey, Environment env) throws LoadSkylarkAspectFunctionException, InterruptedException { SkylarkAspectLoadingKey aspectLoadingKey = (SkylarkAspectLoadingKey) skyKey.argument(); String skylarkValueName = aspectLoadingKey.getSkylarkValueName(); Label skylarkFileLabel = aspectLoadingKey.getSkylarkFileLabel(); SkylarkAspect skylarkAspect; try { skylarkAspect = AspectFunction.loadSkylarkAspect(env, skylarkFileLabel, skylarkValueName); if (skylarkAspect == null) { return null; } if (!skylarkAspect.getParamAttributes().isEmpty()) { String msg = "Cannot instantiate parameterized aspect " + skylarkAspect.getName() + " at the top level."; throw new AspectCreationException(msg, new LabelCause(skylarkFileLabel, msg)); } } catch (AspectCreationException e) { throw new LoadSkylarkAspectFunctionException(e); } SkyKey aspectKey = aspectLoadingKey.toAspectKey(skylarkAspect.getAspectClass()); return env.getValue(aspectKey); } @Nullable @Override public String extractTag(SkyKey skyKey) { return null; } /** * Exceptions thrown from ToplevelSkylarkAspectFunction. */ public class LoadSkylarkAspectFunctionException extends SkyFunctionException { public LoadSkylarkAspectFunctionException(AspectCreationException cause) { super(cause, Transience.PERSISTENT); } } }
akira-baruah/bazel
src/main/java/com/google/devtools/build/lib/skyframe/ToplevelSkylarkAspectFunction.java
Java
apache-2.0
3,078
package com.wpx.ipad_server.entity; public class Dish { /* 0 dish_no varchar 20 0 1 0 0 dish_name varchar 20 0 1 0 0 dish_price float 0 0 1 0 0 0 dish_class int 11 0 1 0 0 0 0 dish_discount float 0 0 1 0 0 * */ private String dish_no; private String dish_name; private double dish_price; public String getDish_pic() { return dish_pic; } public void setDish_pic(String dish_pic) { this.dish_pic = dish_pic; } private int dish_class; private double dish_discount; private String dish_pic; @Override public String toString() { return "Dish [dish_no=" + dish_no + ", dish_name=" + dish_name + ", dish_price=" + dish_price + ", dish_class=" + dish_class + ", dish_discount=" + dish_discount + "]"; } public String getDish_no() { return dish_no; } public void setDish_no(String dish_no) { this.dish_no = dish_no; } public String getDish_name() { return dish_name; } public void setDish_name(String dish_name) { this.dish_name = dish_name; } public double getDish_price() { return dish_price; } public void setDish_price(double dish_price) { this.dish_price = dish_price; } public int getDish_class() { return dish_class; } public void setDish_class(int dish_class) { this.dish_class = dish_class; } public double getDish_discount() { return dish_discount; } public void setDish_discount(double dish_discount) { this.dish_discount = dish_discount; } }
jhvip/iPad_Server
iPad_Server/src/com/wpx/ipad_server/entity/Dish.java
Java
apache-2.0
1,432
package com.hanyee.androidlib.widgets.recycler; public enum SwipeRefreshLayoutDirection { TOP(0), // 只有下拉刷新 BOTTOM(1), // 只有加载更多 BOTH(2);// 全都有 private int mValue; SwipeRefreshLayoutDirection(int value) { this.mValue = value; } public static SwipeRefreshLayoutDirection getFromInt(int value) { for (SwipeRefreshLayoutDirection direction : SwipeRefreshLayoutDirection .values()) { if (direction.mValue == value) { return direction; } } return BOTH; } }
HanyeeWang/GeekZone
BaseLib/src/main/java/com/hanyee/androidlib/widgets/recycler/SwipeRefreshLayoutDirection.java
Java
apache-2.0
608
# Peperomia reflexa var. coriacea C.DC. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Peperomia/Peperomia reflexa/Peperomia reflexa coriacea/README.md
Markdown
apache-2.0
187
package ru.spb.kpit.kivan.Parser; import ru.spb.kpit.kivan.General.Strings.StringUtils; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: Kivan * Date: 17.03.13 * Time: 19:12 * To change this template use File | Settings | File Templates. */ public class WordTypeMineStrategy implements MyStemMineStrategy<WordInfo> { HashSet<WType> wTypes; public WordTypeMineStrategy(HashSet<WType> wordTypes) { this.wTypes = wordTypes; if (wTypes == null) wTypes = new HashSet<WType>(); } public WordTypeMineStrategy(WType... wordTypes) { wTypes = new HashSet<WType>(); for (WType wordType : wordTypes) { wTypes.add(wordType); } } public String myStemOptions() { return "ni"; } public List<WordInfo> processStemedFile(String filePath) { Scanner sc = null; //List<String> words = new ArrayList<String>(); List<WordInfo> finalResults = new ArrayList<WordInfo>(); try { sc = new Scanner(new File(filePath)); while (sc.hasNextLine()) { String newLine = sc.nextLine(); String oldWord = newLine.substring(0, newLine.indexOf("{")); /*if(oldWord.startsWith("ãëàâí")){ int k = 0; }*/ String line = newLine.substring(newLine.indexOf("{") + 1, newLine.indexOf("}")); String parsedWord = ""; HashSet<String> types = new HashSet<String>(); if (line.contains("??")) { /*continue;*/ int k = 0; parsedWord = line; types.add("UNK"); } else { parsedWord = line.substring(0, line.indexOf("=")); int zpja = line.indexOf(","); int ravno = line.indexOf("=", line.indexOf("=") + 1); int index = -1; if (zpja == -1 && ravno == -1) index = line.length() - 1; else if (zpja == -1) index = ravno; else if (ravno == -1) index = zpja; else index = Math.min(zpja, ravno); String type = line.substring(line.indexOf("=") + 1, index); boolean checkType = checkType(type); if (!checkType) continue; types.add(type); String thisType = type; int pointer = -1; while (line.indexOf("|", pointer) > -1) { int newIndex = line.indexOf("|", pointer + 1); zpja = line.indexOf(",", newIndex); ravno = line.indexOf("=", line.indexOf("=", newIndex) + 1); index = -1; if (zpja == -1 && ravno == -1) index = line.length() - 1; else if (zpja == -1) index = ravno; else if (ravno == -1) index = zpja; else index = Math.min(zpja, ravno); type = line.substring(line.indexOf("=", newIndex) + 1, index); pointer = newIndex + 1; types.add(type); } } parsedWord = parsedWord.replace("?", ""); if (parsedWord.length() > 0) finalResults.add(new WordInfo(oldWord, parsedWord, StringUtils.gStrFrColEls(types, "+"))); } } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { sc.close(); } return finalResults; } private boolean checkType(String type) { if (type == null) return false; if (wTypes.size() == 0) return true; for (WType wType : wTypes) { if (wType.getMstVal().equalsIgnoreCase(type)) return true; } return false; } }
kivan-mih/generalLib
src/ru/spb/kpit/kivan/Parser/WordTypeMineStrategy.java
Java
apache-2.0
4,196
/* Copyright 2013 Daniel Manzke (devsurf) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package de.devsurf.common.lang.converter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; @Target( { ElementType.FIELD, ElementType.TYPE } ) @Retention( RetentionPolicy.RUNTIME ) @Qualifier public @interface InfoConverter { }
manzke/common-lang
src/main/java/de/devsurf/common/lang/converter/InfoConverter.java
Java
apache-2.0
973
# Iresine hassleriana var. macrophylla (R.E.Fr.) Suess. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Iresine/Iresine hassleriana/Iresine hassleriana macrophylla/README.md
Markdown
apache-2.0
203
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.GroupData; import ru.stqa.pft.addressbook.model.Groups; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.testng.Assert.assertEquals; public class GroupDeletionTests extends TestBase { @BeforeMethod public void ensurePreconditions() { if (app.db().groups().size() == 0) { app.goTo().groupPage(); app.group().create(new GroupData().withName("test1")); } } @Test public void testGroupDeletion() { Groups before = app.db().groups(); GroupData deletedGroup = before.iterator().next(); app.goTo().groupPage(); app.group().delete(deletedGroup); assertThat(app.group().count(), equalTo(before.size() - 1)); Groups after = app.db().groups(); assertThat(after, equalTo(before.without(deletedGroup))); verifyGroupListInUI(); } }
dmitrykustikov/java_pft
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupDeletionTests.java
Java
apache-2.0
1,014