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
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 Greenplum, Inc. // // @filename: // CDXLScalarLimitOffset.cpp // // @doc: // Implementation of DXL Scalar Limit Offset // //--------------------------------------------------------------------------- #include "naucrates/dxl/operators/CDXLScalarLimitOffset.h" #include "naucrates/dxl/operators/CDXLNode.h" #include "naucrates/dxl/xml/CXMLSerializer.h" using namespace gpos; using namespace gpdxl; //--------------------------------------------------------------------------- // @function: // CDXLScalarLimitOffset::CDXLScalarLimitOffset // // @doc: // Constructs a scalar Limit Offset node // //--------------------------------------------------------------------------- CDXLScalarLimitOffset::CDXLScalarLimitOffset ( IMemoryPool *pmp ) : CDXLScalar(pmp) { } //--------------------------------------------------------------------------- // @function: // CDXLScalarLimitOffset::Edxlop // // @doc: // Operator type // //--------------------------------------------------------------------------- Edxlopid CDXLScalarLimitOffset::Edxlop() const { return EdxlopScalarLimitOffset; } //--------------------------------------------------------------------------- // @function: // CDXLScalarLimitOffset::PstrOpName // // @doc: // Operator name // //--------------------------------------------------------------------------- const CWStringConst * CDXLScalarLimitOffset::PstrOpName() const { return CDXLTokens::PstrToken(EdxltokenScalarLimitOffset); } //--------------------------------------------------------------------------- // @function: // CDXLScalarLimitOffset::SerializeToDXL // // @doc: // Serialize operator in DXL format // //--------------------------------------------------------------------------- void CDXLScalarLimitOffset::SerializeToDXL ( CXMLSerializer *pxmlser, const CDXLNode *pdxln ) const { const CWStringConst *pstrElemName = PstrOpName(); pxmlser->OpenElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName); pdxln->SerializeChildrenToDXL(pxmlser); pxmlser->CloseElement(CDXLTokens::PstrToken(EdxltokenNamespacePrefix), pstrElemName); } #ifdef GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CDXLScalarLimitOffset::AssertValid // // @doc: // Checks whether operator node is well-structured // //--------------------------------------------------------------------------- void CDXLScalarLimitOffset::AssertValid ( const CDXLNode *pdxln, BOOL fValidateChildren ) const { const ULONG ulArity = pdxln->UlArity(); GPOS_ASSERT(1 >= ulArity); for (ULONG ul = 0; ul < ulArity; ++ul) { CDXLNode *pdxlnArg = (*pdxln)[ul]; GPOS_ASSERT(EdxloptypeScalar == pdxlnArg->Pdxlop()->Edxloperatortype()); if (fValidateChildren) { pdxlnArg->Pdxlop()->AssertValid(pdxlnArg, fValidateChildren); } } } #endif // GPOS_DEBUG // EOF
PengJi/gporca-comments
libnaucrates/src/operators/CDXLScalarLimitOffset.cpp
C++
apache-2.0
2,989
__author__ = 'mpetyx' from tastypie.authorization import DjangoAuthorization from .models import OpeniQuestion from OPENiapp.APIS.OpeniGenericResource import GenericResource from OPENiapp.APIS.OPENiAuthorization import Authorization from OPENiapp.APIS.OPENiAuthentication import Authentication class QuestionResource(GenericResource): class Meta: queryset = OpeniQuestion.objects.all() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['get', 'post', 'put', 'delete'] resource_name = 'question' authentication = Authentication() authorization = Authorization() # filtering = { # 'slug': ALL, # 'user': ALL_WITH_RELATIONS, # 'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'], # } extra_actions = [ { "name": "comments", "http_method": "GET", "resource_type": "list", "description": "comments from CBS", "fields": { "cbs": { "type": "string", "required": True, "description": "list of selected CBS" } } }, { "name": "likes", "http_method": "GET", "resource_type": "list", "description": "likes from CBS", "fields": { "cbs": { "type": "string", "required": True, "description": "list of selected CBS" } } }, { "name": "dislikes", "http_method": "GET", "resource_type": "list", "description": "dislikes from CBS", "fields": { "cbs": { "type": "string", "required": True, "description": "list of selected CBS" } } } ]
OPENi-ict/ntua_demo
openiPrototype/openiPrototype/APIS/Activity/Question/Resources.py
Python
apache-2.0
2,158
"use strict"; import HTTP from "./http"; import endpoint from "./endpoint"; import * as requests from "./requests"; import * as optionUtils from "./options"; import Tenant from "./tenant"; import Admin from "./admin/admin"; import LocationService from "./location"; /** * HTTP client for the Business Elements API. * * @example * const client = new BusinessElementsClient("https://api.business-elements.com"); */ export default class BusinessElementsClientBase { /** * Constructor. * * @param {String} remote The remote URL. * @param {Object} options The options object. * @param {Object} options.headers The key-value headers to pass to each request (default: `{}`). * @param {String} options.requestMode The HTTP request mode (from ES6 fetch spec). */ constructor(remote, options = {}) { this.remote = remote; /** * Default request options container. * @private * @type {Object} */ this.defaultReqOptions = { headers: options.headers || {} }; /** * The remote server base URL. * @ignore * @type {String} */ this.remote = remote; /** * Current server information. * @ignore * @type {Object|null} */ this.serverInfo = null; /** * Current authentication token. * @ignore * @type {String|null} */ this.authenticationToken = null; /** * The HTTP instance. * @ignore * @type {HTTP} */ this.http = new HTTP({requestMode: options.requestMode}); this.locationService = new LocationService(); } /** * The remote endpoint base URL. * @type {String} */ get remote() { return this._remote; } /** * Sets the remote url. Trailing slashes will be removed. * * @param {String} url the remote url to set. */ set remote(url) { if (typeof(url) !== "string" || !url.length) { throw new Error("Invalid remote URL: " + url); } this._remote = url; if (this._remote[this._remote.length - 1] === "/") { this._remote = this._remote.slice(0, -1); } } /** * Generates a request options object, deeply merging the client configured defaults with the ones provided as argument. * * Note: Headers won't be overridden but merged with instance default ones. * * @param {Object} options The request options. * @return {Object} * @property {Object} headers The extended headers object option. */ getRequestOptions(options = {}) { const authenticationTokenHeaders = this.authenticationToken ? {"Authentication-Token": this.authenticationToken} : {}; return { ...this.defaultReqOptions, ...options, // Note: headers should never be overridden but extended headers: { ...authenticationTokenHeaders, ...this.defaultReqOptions.headers, ...options.headers } }; } /** * Retrieves server information and store locally. This operation is * usually performed a single time during the instance life cycle. * * @return {Promise<Object, Error>} */ fetchServerInfo() { if (this.serverInfo) { return Promise.resolve(this.serverInfo); } return this.http.request(this.remote + endpoint("root"), { headers: this.defaultReqOptions.headers }) .then(({json}) => { this.serverInfo = json; return this.serverInfo; }); } /** * Retrieves Business elements server version. * * @return {Promise<String, Error>} */ fetchServerVersion() { return this.fetchServerInfo().then(({platform}) => platform.version); } /** * Retrieves Business elements server build time. * * @return {Promise<Number, Error>} */ fetchServerBuildTime() { return this.fetchServerInfo().then(({platform}) => platform.build.millis); } /** * Retrieves Business Elements server settings. * * @return {Promise<Object, Error>} */ fetchServerSettings() { return this.fetchServerInfo().then(({settings}) => settings); } /** * Executes an atomic HTTP request. * * @param {Object} request The request object. * @param {Object} options Optional options will be merged into the request, allowing the user to override any request option. * @param {boolean} [raw] Resolve with full response object, including json body and headers (Default: `false`, so only the json body is retrieved). * @return {Promise<Object, Error>} */ execute(request, options, raw = false) { const requestOptions = this.getRequestOptions(options); const locationPromise = this.authenticationToken ? this.locationService.currentLocation : Promise.resolve(null); const responsePromise = locationPromise.then(location => { const locationHeaders = (location !== null && typeof location === "object") ? {"BE-Geolocation": `(${location.latitude}, ${location.longitude})`} : {}; const completeRequest = { ...request, body: JSON.stringify(request.body), ...requestOptions, headers: { ...request.headers, ...requestOptions.headers, ...locationHeaders } }; return this.http.request(`${this.remote}${completeRequest.path}`, completeRequest); }); return raw ? responsePromise : responsePromise.then(({json}) => json); } /** * Listen to http event and execute function * * @param {String} event the event to listen to * @param {Function} callBack the function to execute when the event is fired */ onHttpEvent(event, callBack){ this.http.on(event, callBack); } /** * Authenticates the account on the server. * * The generated authentication token is stored in the instance and will be send with each subsequent request. * * @param {String} emailAddress The account email address. * @param {String} password The account password. * @param {Object} options The options object. * @return {Promise<String, Error>} With the authentication token. */ login(emailAddress, password, options = {}) { return this.execute(requests.login(emailAddress, password), options, true) .then((response) => { this.authenticationToken = response.headers.get("Authentication-Token"); return this.authenticationToken; }); } /** * Logs out the account on the server. * * When the account is logged out the authentication token is invalidated. * * @param {Object} options The options object. * @return {Promise<undefined, Error>} */ logout(options = {}) { return this.execute(requests.logout(), options) .then(() => { this.authenticationToken = undefined; }); } /** * Checks the authentication for the specified authentication token. * * If the authentication is valid, the token is stored. * * @param {String} authenticationToken The authentication token to check. * @param {Object} options The options object. * @return {Promise<Object[], Error>} */ checkAuthenticationToken(authenticationToken, options = {}) { return this .execute({ path: endpoint("currentAuthentication") }, optionUtils.join({"Authentication-Token": authenticationToken}, options) ) .then(() => { this.authenticationToken = authenticationToken; return authenticationToken; }); } /** * Retrieve a tenant object to perform operations on it. * * @param {String} domainName The tenant domain name. * @return {Tenant} */ tenant(domainName) { return new Tenant(this, domainName); } /** * Retrieve a admin object to perform operations on it. * * @return {Admin} */ admin() { return new Admin(this); } /** * Retrieve event names emitted in the request flow * * @returns {string[]} */ httpEvents(){ return this.http.httpEvents; } }
Product-Foundry/business-elements-client-js
src/base.js
JavaScript
apache-2.0
8,012
--- path: "/docs/sessions/raw-session" title: Raw Routing Session --- #Raw Routing Session HTTP is a stateless connection protocol, that is the server can't distinguish one request from another. Sessions and cookies provide HTTP with state, they allow the server to know who is making a specific request and respond accordingly. This guide demonstrates how to use the [Kitura-Session](https://github.com/Kitura/Kitura-Session) package to manage user sessions in Kitura with Raw routing. If you are using Codable routing, follow the guide for [Kitura Session with type-safe sessions](./codable-session). --- ##Step 1: Create your session routes In this guide we are going to create two Kitura routes: - A GET route, where we retrieve the books from our session. - A POST route, where we store a book in our session. We are using [the Book model from the routing guide](/docs/routing/what-is-routing#codable-model) in our routes, however you could use any codable object. To use Kitura-Session from a server, we need to [add Kitura-Session to our dependencies](https://github.com/Kitura/Kitura-Session#add-dependencies). > If you don't have a server, follow our [Create a server](../getting-started/create-server-cli) guide. Once that is complete, open your `Application.swift` file in your default text editor (or Xcode if you prefer): ``` open Sources/Application/Application.swift ``` Inside the `postInit()` function add: ```swift initializeSessionRawRoutes(app: self) ``` Create a new file called `SessionRawRoutes.swift` to define the session routes in: ``` touch Sources/Application/Routes/SessionRawRoutes.swift ``` Open the `SessionRawRoutes.swift` file: ``` open Sources/Application/Routes/SessionRawRoutes.swift ``` Inside this file we will add the code for our session routes: ```swift import KituraSession func initializeSessionRawRoutes(app: App) { // Define the Session here app.router.get("/session") { request, response, next in // Get the books from the session here next() } app.router.post("/session") { request, response, next in // Add books to the session here next() } } ``` --- ##Step 2: Set up a session We will use a session to persist data between the user's requests. The session will provide the user with a cookie that the user will attach to future requests. That cookie is then linked to a session store, where we keep data we want to be associated with that user's cookie. This allows us to add features such as an online shopping cart, where multiple requests add items to the cart until we are ready to checkout. When we create our session we can configure it with the following parameters: - `secret`: A `String` to be used for session encoding. This is your session's password and should be treated as such. - `cookie`: A list of options for the session's cookies. In this example we will use this to set the cookie's name. - `store`: A session backing store that implements the `Store` protocol. This determines where session data is persisted. In this example we do not set this, meaning the data is persisted on the server. > For live applications, you should use a persistent store, such as a database, or [Kitura-Session-Redis](https://github.com/Kitura/Kitura-Session-Redis). To set up our session, we create a `Session` middleware with our desired parameters. Inside your `initializeSessionRawRoutes`, add the following code: ```swift let session = Session(secret: "password", cookie: [CookieParameter.name("Raw-cookie")]) ``` Below this line, register the middleware on our router: ```swift app.router.all(middleware: session) ``` We should now have access to our session using `request.session`. Add the following `guard` statement to both route handlers to ensure that this is the case: ```swift guard let session = request.session else { return try response.status(.internalServerError).end() } ``` Our `SessionRawRoutes.swift` file should now look as follows: ```swift import KituraSession func initializeSessionRawRoutes(app: App) { let session = Session(secret: "password", cookie: [CookieParameter.name("Raw-cookie")]) app.router.all(middleware: session) app.router.get("/session") { request, response, next in guard let session = request.session else { return try response.status(.internalServerError).end() } // Get the books from the session here next() } app.router.post("/session") { request, response, next in guard let session = request.session else { return try response.status(.internalServerError).end() } // Add books to the session here next() } } ``` --- ##Step 3: Add the session GET route Now we have access to our session, we can use it to persist data. We are going to be persisting the `Book` model, but you can use any `Codable` Swift type. The session is stored as a `[String: Any]` dictionary, however by declaring the expected type, we can directly decode our model from the session. In our case, we decode an array of books by adding the following code to our GET handler: ```swift let books: [Book] = session["books"] ?? [] ``` This will get all the books stored for the "books" key in our model. If there are no books it returns an empty array. Once we have our books, we send them to the user in the response: ```swift response.send(books) ``` Our completed GET route should now look as follows: ```swift app.router.get("/session") { request, response, next in guard let session = request.session else { return try response.status(.internalServerError).end() } let books: [Book] = session["books"] ?? [] response.send(books) next() } ``` --- ##Step 4: Add the session POST route Now we need some books to retrieve. We will do this by adding a book that has been posted into our route. The first thing we need to do is decode the book. We do this by adding the following code to our POST handler: ```swift let inputBook = try request.read(as: Book.self) ``` Next we need to get the books that are currently in the session: ```swift var books: [Book] = session["books"] ?? [] ``` Now we append our new book to the existing books and store it in the session for the "books" key: ```swift books.append(inputBook) session["books"] = books ``` Finally we respond with the book which we added to the session, to represent a successful request. ```swift response.status(.created) response.send(inputBook) ``` Our completed POST route should now look as follows: ```swift app.router.post("/session") { request, response, next in guard let session = request.session else { return try response.status(.internalServerError).end() } let inputBook = try request.read(as: Book.self) var books: [Book] = session["books"] ?? [] books.append(inputBook) session["books"] = books response.status(.created) response.send(inputBook) next() } ``` --- ##Step 5: Test our Session We have now completed the code for our session. This will allow us to add books to our cart and persist them between requests. Our completed `SessionRawRoutes.swift` file should now look as follows: ```swift import KituraSession func initializeSessionRawRoutes(app: App) { let session = Session(secret: "password", cookie: [CookieParameter.name("Raw-cookie")]) app.router.all(middleware: session) app.router.get("/session") { request, response, next in guard let session = request.session else { return try response.status(.internalServerError).end() } let books: [Book] = session["books"] ?? [] response.send(books) next() } app.router.post("/session") { request, response, next in guard let session = request.session else { return try response.status(.internalServerError).end() } let inputBook = try request.read(as: Book.self) var books: [Book] = session["books"] ?? [] books.append(inputBook) session["books"] = books response.status(.created) response.send(inputBook) next() } } ``` To test our POST route, we will send a request using curl, with cookies enabled. Open Terminal and enter the following: ``` curl -X POST \ http://localhost:8080/session \ -b cookies.txt -c cookies.txt \ -H 'content-type: application/json' \ -d '{ "id": 1, "title": "War and Peace", "price": 10.99, "genre": "Historical drama" }' ``` If our request was successful, our book will be returned to us: ``` {"id":1,"title":"War and Peace","price":10.99,"genre":"Historical drama"} ``` We will also have a cookie that curl has stored in the `cookies.txt` file. To retrieve our book, we make another curl request to our server: ``` curl -X GET \ http://localhost:8080/session \ -b cookies.txt -c cookies.txt ``` If the request is successful, it will return the book we just sent to the server. ``` [{"id":1,"title":"War and Peace","price":10.99,"genre":"Historical drama"}] ``` The cookie we sent with our request has identifed our session, so that our saved book can be returned. Each user making requests to these routes will create their own basket of books. We can demonstrate this by deleting our cookie: ``` rm cookies.txt ``` Followed by making a new GET request: ``` curl -X GET \ http://localhost:8080/session \ -b cookies.txt -c cookies.txt ``` This represents a user without a session so we are returned an empty array: ``` [] ``` --- ##Next steps [Authentication](../authentication/what-is-authentication): Learn about authentication and what Kitura provides.
IBM-Swift/kitura.io
content/docs/guides/sessions/raw-sessions.md
Markdown
apache-2.0
9,700
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # Copyright 2012 OpenStack LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Views for managing Images and Snapshots. """ import logging from django.utils.translation import ugettext_lazy as _ from horizon import api from horizon import exceptions from horizon import tables from horizon import tabs from .images.tables import ImagesTable from .snapshots.tables import SnapshotsTable from .volume_snapshots.tables import VolumeSnapshotsTable from .volume_snapshots.tabs import SnapshotDetailTabs LOG = logging.getLogger(__name__) class IndexView(tables.MultiTableView): table_classes = (ImagesTable, SnapshotsTable, VolumeSnapshotsTable) template_name = 'project/images_and_snapshots/index.html' def has_more_data(self, table): return getattr(self, "_more_%s" % table.name, False) def get_images_data(self): marker = self.request.GET.get(ImagesTable._meta.pagination_param, None) try: # FIXME(gabriel): The paging is going to be strange here due to # our filtering after the fact. (all_images, self._more_images) = api.image_list_detailed(self.request, marker=marker) images = [im for im in all_images if im.container_format not in ['aki', 'ari'] and im.properties.get("image_type", '') != "snapshot"] except: images = [] exceptions.handle(self.request, _("Unable to retrieve images.")) return images def get_snapshots_data(self): req = self.request marker = req.GET.get(SnapshotsTable._meta.pagination_param, None) try: snaps, self._more_snapshots = api.snapshot_list_detailed(req, marker=marker) except: snaps = [] exceptions.handle(req, _("Unable to retrieve snapshots.")) return snaps def get_volume_snapshots_data(self): try: snapshots = api.volume_snapshot_list(self.request) except: snapshots = [] exceptions.handle(self.request, _("Unable to retrieve " "volume snapshots.")) return snapshots class DetailView(tabs.TabView): tab_group_class = SnapshotDetailTabs template_name = 'project/images_and_snapshots/snapshots/detail.html'
1ukash/horizon
horizon/dashboards/project/images_and_snapshots/views.py
Python
apache-2.0
3,222
# Senecio longeligulatus H.Lév. & Vaniot 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/Magnoliopsida/Asterales/Asteraceae/Tephroseris flammea/ Syn. Senecio longeligulatus/README.md
Markdown
apache-2.0
196
package org.gridkit.util.formating; import static org.assertj.core.api.Assertions.assertThat; import java.text.DecimalFormat; import java.util.TimeZone; import org.junit.Test; public class SimpleNumberFormatterTest { private static char localeDecimalSeparator = ((DecimalFormat)DecimalFormat.getInstance()).getDecimalFormatSymbols().getDecimalSeparator(); @Test public void verify_decimal() { SimpleNumberFormatter snf = new SimpleNumberFormatter("D00.##"); assertThat(snf.formatLong(1000)).isEqualTo("1000"); assertThat(snf.formatLong(1)).isEqualTo("01"); assertThat(snf.formatDouble(1000)).isEqualTo("1000"); assertThat(snf.formatDouble(1)).isEqualTo("01"); assertThat(snf.formatDouble(1.1)).isEqualTo("01" + localeDecimalSeparator + "1"); assertThat(snf.formatDouble(1.55)).isEqualTo("01" + localeDecimalSeparator + "55"); assertThat(snf.formatDouble(1.5555)).isEqualTo("01" + localeDecimalSeparator + "56"); assertThat(snf.formatDouble(10.5555)).isEqualTo("10" + localeDecimalSeparator + "56"); } @Test public void verify_date_format() { SimpleNumberFormatter snf = new SimpleNumberFormatter("Tyyyy", TimeZone.getTimeZone("UTC")); assertThat(snf.formatLong(0)).isEqualTo("1970"); assertThat(snf.formatDouble(0d)).isEqualTo("1970"); } @Test public void verify_string_format() { SimpleNumberFormatter snf; snf = new SimpleNumberFormatter("F%d"); assertThat(snf.formatLong(100)).isEqualTo("100"); snf = new SimpleNumberFormatter("F%g"); assertThat(snf.formatDouble(100)).isEqualTo("100.000"); } }
aragozin/jvm-tools
sjk-core/src/test/java/org/gridkit/util/formating/SimpleNumberFormatterTest.java
Java
apache-2.0
1,691
<?php /** * Transfers a result set from the last query * * @phpstub * * @param resource $link * * @return resource */ function maxdb_store_result($link) { } /** * Transfers a result set from the last query * * @phpstub * * @return object */ function maxdb_store_result() { }
schmittjoh/php-stubs
res/php/maxdb/functions/maxdb-store-result.php
PHP
apache-2.0
290
#include <QThread> #include "Worker.h" #include "services/ftp/FtpConnection.h" Worker::Worker(QObject *parent) : QObject(parent) { } //void Worker::run() //{ // qDebug() << "Thread running"; // exec(); //} void Worker::addConnection(IncomingConnection incomingConnection) { // connectionQueue.enqueue(connection); // qDebug() << "Connection queued in thread" << QThread::currentThread(); BaseConnection *con; switch(incomingConnection.serviceType) { #ifdef SERVICE_FTP case BaseTcpServer::FtpService: { con = new FtpConnection(this); break; } #endif #ifdef SERVICE_SSH case BaseTcpServer::SshService: { break; } #endif default: return; } con->applySettings(incomingConnection.settings); con->setLogFormatter(incomingConnection.logFormatter); con->setSocketDescriptor(incomingConnection.socketDescriptor); connect(con, SIGNAL(disconnected(BaseConnection*)), this, SLOT(connectionDisconnected(BaseConnection*))); connections << con; qDebug() << "Connection created in thread" << QThread::currentThread(); } //void Worker::processIncomingConnections() //{ // if(connectionQueue.isEmpty()) // { // qDebug() << "Queue empty"; // return; // } // IncomingConnection incomingConnection = connectionQueue.dequeue(); // BaseConnection *con; // switch(incomingConnection.serviceType) // { //#ifdef SERVICE_FTP // case BaseTcpServer::FtpService: // { // con = new FtpConnection(this); // break; // } //#endif //#ifdef SERVICE_SSH // case BaseTcpServer::SshService: // { // break; // } //#endif // default: // return; // } // con->setSocketDescriptor(incomingConnection.socketDescriptor); // connect(con, SIGNAL(disconnected(BaseConnection*)), this, SLOT(connectionDisconnected(BaseConnection*))); // connections << con; // qDebug() << "Connection created in thread" << QThread::currentThread(); //} int Worker::connectionCount() { return connections.count(); } void Worker::connectionDisconnected(BaseConnection *connection) { connections.removeOne(connection); connection->deleteLater(); qDebug() << "Connection scheduled for deletion"; }
relbit/bitoxy
src/Worker.cpp
C++
apache-2.0
2,092
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.allterms; import org.elasticsearch.action.Action; import org.elasticsearch.client.ElasticsearchClient; /** */ public class AllTermsAction extends Action<AllTermsRequest, AllTermsResponse, AllTermsRequestBuilder> { public static final AllTermsAction INSTANCE = new AllTermsAction(); public static final String NAME = "indices:data/read/allterms"; private AllTermsAction() { super(NAME); } @Override public AllTermsResponse newResponse() { return new AllTermsResponse(); } @Override public AllTermsRequestBuilder newRequestBuilder(ElasticsearchClient client) { return new AllTermsRequestBuilder(client); } }
brwe/es-token-plugin
src/main/java/org/elasticsearch/action/allterms/AllTermsAction.java
Java
apache-2.0
1,500
package com.gscopetech.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; import org.springframework.stereotype.Component; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.TimeZone; /** * Created with airsim. * Author 秋杰 * Email yaoqiujie@gscopetech.com * Date 2017/3/23 */ @Table(name="wifidevice") @Entity @Component @Data @EqualsAndHashCode(callSuper = false) public class WiFiDevice implements Serializable { @GeneratedValue @Id private Long id; // 设备IMEI号 International Mobile Equipment Identity @Column(length = 32) private String imei; // 设备密码 @Column(length = 32) private String password; // 设备类型 @Column(length = 32) private String type; // 设备版本 @Column(length = 64) private String swVersion; // 导入时间 private Date importDate; // 是否激活 private Boolean isAlive; // 是否已经绑定用户 private Boolean isBound; // 绑定的套餐 @ManyToOne @JoinColumn(name = "uPkg_id") @JsonBackReference private UCloudPackage uPkg; // 已经绑定的用户 @OneToOne(cascade = CascadeType.ALL, mappedBy = "wifiDevice") @JsonManagedReference(value = "user-device") private WiFiUser wifiUser; }
iyaoqiujie/airsim
src/main/java/com/gscopetech/entity/WiFiDevice.java
Java
apache-2.0
1,625
// Code generated by "stringer -type=Token tokens.go"; DO NOT EDIT. package traversal import "strconv" const _Token_name = "ILLEGALEOFWSIDENTCOMMADOTLEFTPARENTHESISRIGHTPARENTHESISSTRINGNUMBERGVEHASHASKEYHASNOTHASEITHEROUTINOUTVINVBOTHVOUTEINEBOTHEDEDUPWITHINWITHOUTMETADATASHORTESTPATHTONENEEBOTHCONTEXTREGEXLTGTLTEGTEINSIDEOUTSIDEBETWEENCOUNTRANGELIMITSORTVALUESKEYSSUMASCDESCIPV4RANGESUBGRAPHFOREVERNOWASSELECTTRUEFALSE" var _Token_index = [...]uint16{0, 7, 10, 12, 17, 22, 25, 40, 56, 62, 68, 69, 70, 71, 74, 80, 86, 95, 98, 100, 104, 107, 112, 116, 119, 124, 129, 135, 142, 150, 164, 166, 169, 173, 180, 185, 187, 189, 192, 195, 201, 208, 215, 220, 225, 230, 234, 240, 244, 247, 250, 254, 263, 271, 278, 281, 283, 289, 293, 298} func (i Token) String() string { if i < 0 || i >= Token(len(_Token_index)-1) { return "Token(" + strconv.FormatInt(int64(i), 10) + ")" } return _Token_name[_Token_index[i]:_Token_index[i+1]] }
skydive-project/skydive
graffiti/graph/traversal/token_string.go
GO
apache-2.0
937
module ConlangWordGenerator VERSION = '0.3.1' end
fluorine/ConlangWordGenerator
lib/conlang/version.rb
Ruby
apache-2.0
51
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.spi.impl.operationservice.impl; import com.hazelcast.core.HazelcastInstanceNotActiveException; import com.hazelcast.core.HazelcastOverloadException; import com.hazelcast.core.MemberLeftException; import com.hazelcast.internal.metrics.MetricsProvider; import com.hazelcast.internal.metrics.MetricsRegistry; import com.hazelcast.internal.metrics.Probe; import com.hazelcast.logging.ILogger; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeoutException; import static com.hazelcast.internal.metrics.ProbeLevel.MANDATORY; import static com.hazelcast.spi.OperationAccessor.deactivate; import static com.hazelcast.spi.OperationAccessor.setCallId; /** * The InvocationsRegistry is responsible for the registration of all pending invocations. Using the InvocationRegistry the * Invocation and its response(s) can be linked to each other. * <p/> * When an invocation is registered, a callId is determined. Based on this call-id, when a * {@link com.hazelcast.spi.impl.operationservice.impl.responses.Response} comes in, the * appropriate invocation can be looked up. * <p/> * Some idea's: * - use an ringbuffer to store all invocations instead of a CHM. The call-id can be used as sequence-id for this * ringbuffer. It can be that you run in slots that have not been released; if that happens, just keep increasing * the sequence (although you now get sequence-gaps). * - pre-allocate all invocations. Because the ringbuffer has a fixed capacity, pre-allocation should be easy. Also * the PartitionInvocation and TargetInvocation can be folded into Invocation. */ public class InvocationRegistry implements Iterable<Invocation>, MetricsProvider { private static final int CORE_SIZE_CHECK = 8; private static final int CORE_SIZE_FACTOR = 4; private static final int CONCURRENCY_LEVEL = 16; private static final int INITIAL_CAPACITY = 1000; private static final float LOAD_FACTOR = 0.75f; private static final double HUNDRED_PERCENT = 100d; @Probe(name = "invocations.pending", level = MANDATORY) private final ConcurrentMap<Long, Invocation> invocations; private final ILogger logger; private final CallIdSequence callIdSequence; private volatile boolean alive = true; public InvocationRegistry(ILogger logger, CallIdSequence callIdSequence) { this.logger = logger; this.callIdSequence = callIdSequence; int coreSize = Runtime.getRuntime().availableProcessors(); boolean reallyMultiCore = coreSize >= CORE_SIZE_CHECK; int concurrencyLevel = reallyMultiCore ? coreSize * CORE_SIZE_FACTOR : CONCURRENCY_LEVEL; this.invocations = new ConcurrentHashMap<Long, Invocation>(INITIAL_CAPACITY, LOAD_FACTOR, concurrencyLevel); } @Override public void provideMetrics(MetricsRegistry registry) { registry.scanAndRegister(this, "operation"); } @Probe(name = "invocations.usedPercentage") private double invocationsUsedPercentage() { int maxConcurrentInvocations = callIdSequence.getMaxConcurrentInvocations(); if (maxConcurrentInvocations == Integer.MAX_VALUE) { return 0; } return (HUNDRED_PERCENT * invocations.size()) / maxConcurrentInvocations; } @Probe(name = "invocations.lastCallId") long getLastCallId() { return callIdSequence.getLastCallId(); } /** * Registers an invocation. * * @param invocation The invocation to register. * @return false when InvocationRegistry is not alive and registration is not successful, true otherwise */ public boolean register(Invocation invocation) { final long callId; try { boolean force = invocation.op.isUrgent() || invocation.isRetryCandidate(); callId = callIdSequence.next(force); } catch (TimeoutException e) { throw new HazelcastOverloadException("Failed to start invocation due to overload: " + invocation, e); } try { // Fails with IllegalStateException if the operation is already active setCallId(invocation.op, callId); } catch (IllegalStateException e) { callIdSequence.complete(); throw e; } invocations.put(callId, invocation); if (!alive) { invocation.notifyError(new HazelcastInstanceNotActiveException()); return false; } return true; } /** * Deregisters an invocation. If the associated operation is inactive, takes no action and returns {@code false}. * This ensures the idempotence of deregistration. * @param invocation The Invocation to deregister. * @return {@code true} if this call deregistered the invocation; {@code false} if the invocation wasn't registered */ public boolean deregister(Invocation invocation) { if (!deactivate(invocation.op)) { return false; } invocations.remove(invocation.op.getCallId()); callIdSequence.complete(); return true; } /** * Returns the number of pending invocations. * * @return the number of pending invocations. */ public int size() { return invocations.size(); } @Override public Iterator<Invocation> iterator() { return invocations.values().iterator(); } /** * Intention to expose the entry set is to mutate it. * * @return set of invocations in this registry */ public Set<Map.Entry<Long, Invocation>> entrySet() { return invocations.entrySet(); } /** * Gets the invocation for the given call id. * * @param callId the callId. * @return the Invocation for the given callId, or null if no invocation was found. */ public Invocation get(long callId) { return invocations.get(callId); } public void reset() { for (Invocation invocation : this) { try { invocation.notifyError(new MemberLeftException()); } catch (Throwable e) { logger.warning(invocation + " could not be notified with reset message -> " + e.getMessage()); } } } public void shutdown() { alive = false; for (Invocation invocation : this) { try { invocation.notifyError(new HazelcastInstanceNotActiveException()); } catch (Throwable e) { logger.warning(invocation + " could not be notified with shutdown message -> " + e.getMessage(), e); } } } }
lmjacksoniii/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/InvocationRegistry.java
Java
apache-2.0
7,381
package name.kuznetsov.andrei.scoresightreading.views; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.View; import java.util.LinkedList; import java.util.List; import java.util.Observable; import java.util.Observer; import name.kuznetsov.andrei.scoresightreading.model.Note; import name.kuznetsov.andrei.scoresightreading.model.NoteImpl; import name.kuznetsov.andrei.scoresightreading.model.NotesEnum; import name.kuznetsov.andrei.scoresightreading.model.PolyChord; import name.kuznetsov.andrei.scoresightreading.model.PolySeqRep; /** * Created by andrei on 8/25/16. */ public class StaveView extends View { private static class InlineNote { int column; int noteLine; int voice; Note originalNote; public InlineNote() { } public InlineNote(int column, int noteLine, int voice, Note originalNote) { this.column = column; this.noteLine = noteLine; this.voice = voice; this.originalNote = originalNote; } } private List<InlineNote> notesToRender; private PolySeqRep notes; public StaveView(Context context) { super(context); initStaveLinePoints(); } public StaveView(Context context, AttributeSet attrs) { super(context, attrs); initStaveLinePoints(); } public StaveView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initStaveLinePoints(); } private ColorMapper colorMapper = new DefaultColorMapper(); private float staveLinePoints[]; private float measureBarPoints[]; private int interlineInterval12 = 20; // (1/2) half of interline interval private int midLineOffset = interlineInterval12 * 2 * 7; private int maxColumn = 16; private final int measureColumn = 4; public int getMaxColumn() { return maxColumn; } // 1/2nd of interline interval private int getInterlineInterval12() { return interlineInterval12; } // interline interval private int getInterlineInterval() { return interlineInterval12 * 2; } private int getPosXInterval() { return getInterlineInterval() * 2; } private void initStaveLinePoints() { staveLinePoints = new float[5 * 4 + 5 * 4]; measureBarPoints = new float[2 * (4 * getMaxColumn() / measureColumn)]; initSample(); } private void initSample() { List<PolyChord> chords = new LinkedList<>(); PolySeqRep seq = new PolySeqRep(chords); int v0 = 6 * 7; int v1 = 2 * 7; for (int i = 0; i < 24; i++, v0--, v1++) { NotesEnum v0note = NotesEnum.values()[v0 % 7]; int v0octave = v0 / 7; NotesEnum v1note = NotesEnum.values()[v1 % 7]; int v1octave = v1 / 7; chords.add(PolyChord.mkChord( new NoteImpl(v0note, v0octave, 0, 0), new NoteImpl(v1note, v1octave, 0, 1) )); for (NotesEnum nn : NotesEnum.values()) { // chords.add(PolyChord.mkChord(new NoteImpl(nn, i, -1))); // chords.add(PolyChord.mkChord(new NoteImpl(nn, i, 1))); } } renderNotes(seq, colorMapper); } private static Paint strokePaint = new Paint(); private static Paint strokeAndFillPaint = new Paint(); static { strokePaint.setColor(Color.BLACK); strokePaint.setStrokeWidth(2.f); strokePaint.setStyle(Paint.Style.STROKE); strokeAndFillPaint.setColor(Color.BLACK); strokeAndFillPaint.setStrokeWidth(2.f); strokeAndFillPaint.setStyle(Paint.Style.FILL_AND_STROKE); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); midLineOffset = (bottom + top) / 2; maxColumn = (right - left) / getPosXInterval(); interlineInterval12 = (bottom - top) / ((7 * 2 + 5) * 2); for (int i = 0; i < 5; i++) { final int idxBase = i * 8; staveLinePoints[idxBase + 2] = staveLinePoints[idxBase + 6] = right - left; staveLinePoints[idxBase + 1] = staveLinePoints[idxBase + 3] = midLineOffset + ((i + 1) * getInterlineInterval()); staveLinePoints[idxBase + 5] = staveLinePoints[idxBase + 7] = midLineOffset - ((i + 1) * getInterlineInterval()); } for (int i = 0; i < maxColumn / measureColumn; i++) { final int idxBase = i * 8; measureBarPoints[idxBase + 0] = measureBarPoints[idxBase + 2] = measureBarPoints[idxBase + 4] = measureBarPoints[idxBase + 6] = (i + 1) * getPosXInterval() * measureColumn; measureBarPoints[idxBase + 1] = midLineOffset - 5 * getInterlineInterval(); measureBarPoints[idxBase + 3] = midLineOffset - 1 * getInterlineInterval(); measureBarPoints[idxBase + 5] = midLineOffset + 5 * getInterlineInterval(); measureBarPoints[idxBase + 7] = midLineOffset + 1 * getInterlineInterval(); } } final static float _1sqrt2 = 0.707106781f; // 1/sqrt(2) @Override public void draw(Canvas canvas) { super.draw(canvas); // draw horizontal stave lines canvas.drawLines(staveLinePoints, strokePaint); // draw vertical measure bars canvas.drawLines(measureBarPoints, strokePaint); canvas.translate(getInterlineInterval(), 0); Path bezierPath = new Path(); for (InlineNote i : notesToRender) { strokeAndFillPaint.setColor(colorMapper.mapColor(i.originalNote)); float cx = i.column * getPosXInterval(); float cy = midLineOffset - i.noteLine * getInterlineInterval12(); float ovalR = getInterlineInterval12() * 0.65f; float ovalRX = (ovalR * 1.3f) / 0.75f; //getInterlineInterval12() + 4; float ovalRY = ovalR; //getInterlineInterval12() - 4; bezierPath.rewind(); bezierPath.moveTo(cx - ovalRY * _1sqrt2, cy - ovalRY * _1sqrt2); bezierPath.cubicTo( cx + (ovalRX - ovalRY) * _1sqrt2, cy - (ovalRY + ovalRX) * _1sqrt2, cx + (ovalRX + ovalRY) * _1sqrt2, cy + (ovalRY - ovalRX) * _1sqrt2, cx + ovalRY * _1sqrt2, cy + ovalRY * _1sqrt2); bezierPath.cubicTo( cx + (ovalRY - ovalRX) * _1sqrt2, cy + (ovalRX + ovalRY) * _1sqrt2, cx - (ovalRX + ovalRY) * _1sqrt2, cy + (ovalRX - ovalRY) * _1sqrt2, cx - ovalRY * _1sqrt2, cy - ovalRY * _1sqrt2 ); bezierPath.close(); canvas.drawPath(bezierPath, strokeAndFillPaint); boolean flagUp = ((i.voice & 1) == 0); if (flagUp) { float lnx = cx + getInterlineInterval12() - 3; float ystem = cy - getInterlineInterval12() * 7 + 5; canvas.drawLine(lnx, cy, lnx, ystem, strokePaint); // // draw note flags // /// note flag 1 // bezierPath.moveTo(lnx, ystem); // bezierPath.cubicTo( // lnx, ystem + getInterlineInterval12(), // lnx + getInterlineInterval12() * 2.5f, ystem + getInterlineInterval12() * 2, // lnx + getInterlineInterval12() * 1.5f, ystem + getInterlineInterval12() * 4 // ); // bezierPath.cubicTo( // lnx + getInterlineInterval12() * 2.5f, ystem + getInterlineInterval12() * 2, // lnx, ystem + 1.5f * getInterlineInterval12(), // lnx, ystem + 1.5f * getInterlineInterval12() // ); // bezierPath.close(); // canvas.drawPath(bezierPath, strokeAndFillPaint); // // canvas.translate(0, getInterlineInterval12() * 1.5f); // // /// note flag 2 // bezierPath.reset(); // bezierPath.moveTo(lnx, ystem); // bezierPath.cubicTo( // lnx, ystem + getInterlineInterval12(), // lnx + getInterlineInterval12() * 2.5f, ystem + getInterlineInterval12() * 2, // lnx + getInterlineInterval12() * 1.5f, ystem + getInterlineInterval12() * 4 // ); // bezierPath.cubicTo( // lnx + getInterlineInterval12() * 2.5f, ystem + getInterlineInterval12() * 2, // lnx, ystem + 1.5f * getInterlineInterval12(), // lnx, ystem + 1.5f * getInterlineInterval12() // ); // bezierPath.close(); // canvas.drawPath(bezierPath, strokeAndFillPaint); // canvas.translate(0, -getInterlineInterval12() * 1.5f); // /// end of note flag } else { float lnx = cx - getInterlineInterval12() + 3; canvas.drawLine(lnx, cy, lnx, cy + getInterlineInterval12() * 5, strokePaint); } // draw additional lines if needed if (i.noteLine < -11 || i.noteLine > 11 || i.noteLine == 0) { final int lnStart, lnEnd; if (i.noteLine == 0) { lnStart = lnEnd = 0; } else if (i.noteLine < -11) { lnStart = (i.noteLine | 1) - 1; lnEnd = -11; } else { lnStart = 12; lnEnd = (i.noteLine | 1) - 1; } for (int exln = lnStart; exln <= lnEnd; exln += 2) { final int lny = midLineOffset - exln * getInterlineInterval12(); canvas.drawLine(cx - getInterlineInterval() * 3 / 4, lny, cx + getInterlineInterval() * 3 / 4, lny, strokePaint); } } } canvas.translate(-getInterlineInterval(), 0); } public void renderNotes(PolySeqRep seq, ColorMapper colorMapper) { this.colorMapper = colorMapper; int posX = 0; notesToRender = new LinkedList<>(); for (PolyChord chord : seq.getChords()) { for (Note n : chord.getNotes()) { int offset = n.getNoteName().ordinal(); int octaveBaseLine = (n.getOctave() - 4) * 7; int noteLine = octaveBaseLine + offset; notesToRender.add(new InlineNote(posX, noteLine, n.getVoice(), n)); } posX++; } invalidate(); seq.addObserver(new Observer() { @Override public void update(Observable observable, Object data) { StaveView.this.postInvalidate(); } }); } public PolySeqRep getNotes() { return notes; } }
andrei-kuznetsov/notes-sight-reading-trainer
app/src/main/java/name/kuznetsov/andrei/scoresightreading/views/StaveView.java
Java
apache-2.0
11,264
<HTML> <HEAD> <meta charset="UTF-8"> <title>AutoAdapters.addLabelClass - biomedicus-uima</title> <link rel="stylesheet" href="../../../style.css"> </HEAD> <BODY> <a href="../../index.html">biomedicus-uima</a>&nbsp;/&nbsp;<a href="../index.html">edu.umn.biomedicus.uima.labels</a>&nbsp;/&nbsp;<a href="index.html">AutoAdapters</a>&nbsp;/&nbsp;<a href="./add-label-class.html">addLabelClass</a><br/> <br/> <h1>addLabelClass</h1> <a name="edu.umn.biomedicus.uima.labels.AutoAdapters$addLabelClass(java.lang.Class((edu.umn.nlpengine.Label)))"></a> <code><span class="keyword">fun </span><span class="identifier">addLabelClass</span><span class="symbol">(</span><span class="identifier" id="edu.umn.biomedicus.uima.labels.AutoAdapters$addLabelClass(java.lang.Class((edu.umn.nlpengine.Label)))/clazz">clazz</span><span class="symbol">:</span>&nbsp;<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html"><span class="identifier">Class</span></a><span class="symbol">&lt;</span><span class="keyword">out</span>&nbsp;<span class="identifier">Label</span><span class="symbol">&gt;</span><span class="symbol">)</span><span class="symbol">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html"><span class="identifier">Unit</span></a></code> </BODY> </HTML>
NLPIE/BioMedICUS
doc/dokka/biomedicus-uima/edu.umn.biomedicus.uima.labels/-auto-adapters/add-label-class.html
HTML
apache-2.0
1,296
/* * #%L * omakase * %% * Copyright (C) 2015 Project Omakase LLC * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.projectomakase.omakase.content.rest.v1.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.projectomakase.omakase.rest.model.v1.RepresentationBaseModel; import java.util.List; /** * REST Variant Representation * * @author Richard Lucas */ @JsonPropertyOrder({"id", "name", "external_ids", "created", "created_by", "last_modified", "last_modified_by", "links"}) public class VariantModel extends RepresentationBaseModel { private String id; private String name; @JsonProperty("external_ids") private List<String> externalIds; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getExternalIds() { return externalIds; } public void setExternalIds(List<String> externalIds) { this.externalIds = externalIds; } }
projectomakase/omakase
omakase/src/main/java/org/projectomakase/omakase/content/rest/v1/model/VariantModel.java
Java
apache-2.0
1,718
# Copyright (c) 2015 Dell 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. from cinder import context from cinder import exception from cinder.openstack.common import log as logging from cinder import test from cinder.volume.drivers.dell import dell_storagecenter_api import mock from requests import models import uuid LOG = logging.getLogger(__name__) # We patch these here as they are used by every test to keep # from trying to contact a Dell Storage Center. @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '__init__', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'open_connection') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'close_connection') class DellSCSanAPITestCase(test.TestCase): '''DellSCSanAPITestCase Class to test the Storage Center API using Mock. ''' SC = {u'IPv6ManagementIPPrefix': 128, u'connectionError': u'', u'instanceId': u'64702', u'scSerialNumber': 64702, u'dataProgressionRunning': False, u'hostOrIpAddress': u'192.168.0.80', u'userConnected': True, u'portsBalanced': True, u'managementIp': u'192.168.0.80', u'version': u'6.5.1.269', u'location': u'', u'objectType': u'StorageCenter', u'instanceName': u'Storage Center 64702', u'statusMessage': u'', u'status': u'Up', u'flashOptimizedConfigured': False, u'connected': True, u'operationMode': u'Normal', u'userName': u'Admin', u'nonFlashOptimizedConfigured': True, u'name': u'Storage Center 64702', u'scName': u'Storage Center 64702', u'notes': u'', u'serialNumber': 64702, u'raidRebalanceRunning': False, u'userPasswordExpired': False, u'contact': u'', u'IPv6ManagementIP': u'::'} VOLUME = {u'instanceId': u'64702.3494', u'scSerialNumber': 64702, u'replicationSource': False, u'liveVolume': False, u'vpdId': 3496, u'objectType': u'ScVolume', u'index': 3494, u'volumeFolderPath': u'devstackvol/fcvm/', u'hostCacheEnabled': False, u'usedByLegacyFluidFsNasVolume': False, u'inRecycleBin': False, u'volumeFolderIndex': 17, u'instanceName': u'volume-37883deb-85cd-426a-9a98-62eaad8671ea', u'statusMessage': u'', u'status': u'Up', u'storageType': {u'instanceId': u'64702.1', u'instanceName': u'Assigned - Redundant - 2 MB', u'objectType': u'ScStorageType'}, u'cmmDestination': False, u'replicationDestination': False, u'volumeFolder': {u'instanceId': u'64702.17', u'instanceName': u'fcvm', u'objectType': u'ScVolumeFolder'}, u'deviceId': u'6000d31000fcbe000000000000000da8', u'active': True, u'portableVolumeDestination': False, u'deleteAllowed': True, u'name': u'volume-37883deb-85cd-426a-9a98-62eaad8671ea', u'scName': u'Storage Center 64702', u'secureDataUsed': False, u'serialNumber': u'0000fcbe-00000da8', u'replayAllowed': True, u'flashOptimized': False, u'configuredSize': u'1.073741824E9 Bytes', u'mapped': False, u'cmmSource': False} INACTIVE_VOLUME = \ {u'instanceId': u'64702.3494', u'scSerialNumber': 64702, u'replicationSource': False, u'liveVolume': False, u'vpdId': 3496, u'objectType': u'ScVolume', u'index': 3494, u'volumeFolderPath': u'devstackvol/fcvm/', u'hostCacheEnabled': False, u'usedByLegacyFluidFsNasVolume': False, u'inRecycleBin': False, u'volumeFolderIndex': 17, u'instanceName': u'volume-37883deb-85cd-426a-9a98-62eaad8671ea', u'statusMessage': u'', u'status': u'Up', u'storageType': {u'instanceId': u'64702.1', u'instanceName': u'Assigned - Redundant - 2 MB', u'objectType': u'ScStorageType'}, u'cmmDestination': False, u'replicationDestination': False, u'volumeFolder': {u'instanceId': u'64702.17', u'instanceName': u'fcvm', u'objectType': u'ScVolumeFolder'}, u'deviceId': u'6000d31000fcbe000000000000000da8', u'active': False, u'portableVolumeDestination': False, u'deleteAllowed': True, u'name': u'volume-37883deb-85cd-426a-9a98-62eaad8671ea', u'scName': u'Storage Center 64702', u'secureDataUsed': False, u'serialNumber': u'0000fcbe-00000da8', u'replayAllowed': True, u'flashOptimized': False, u'configuredSize': u'1.073741824E9 Bytes', u'mapped': False, u'cmmSource': False} SCSERVER = {u'scName': u'Storage Center 64702', u'volumeCount': 0, u'removeHbasAllowed': True, u'legacyFluidFs': False, u'serverFolderIndex': 4, u'alertOnConnectivity': True, u'objectType': u'ScPhysicalServer', u'instanceName': u'Server_21000024ff30441d', u'instanceId': u'64702.47', u'serverFolderPath': u'devstacksrv/', u'portType': [u'FibreChannel'], u'type': u'Physical', u'statusMessage': u'Only 5 of 6 expected paths are up', u'status': u'Degraded', u'scSerialNumber': 64702, u'serverFolder': {u'instanceId': u'64702.4', u'instanceName': u'devstacksrv', u'objectType': u'ScServerFolder'}, u'parentIndex': 0, u'connectivity': u'Partial', u'hostCacheIndex': 0, u'deleteAllowed': True, u'pathCount': 5, u'name': u'Server_21000024ff30441d', u'hbaPresent': True, u'hbaCount': 2, u'notes': u'Created by Dell Cinder Driver', u'mapped': False, u'operatingSystem': {u'instanceId': u'64702.38', u'instanceName': u'Red Hat Linux 6.x', u'objectType': u'ScServerOperatingSystem'} } # ScServer where deletedAllowed=False (not allowed to be deleted) SCSERVER_NO_DEL = {u'scName': u'Storage Center 64702', u'volumeCount': 0, u'removeHbasAllowed': True, u'legacyFluidFs': False, u'serverFolderIndex': 4, u'alertOnConnectivity': True, u'objectType': u'ScPhysicalServer', u'instanceName': u'Server_21000024ff30441d', u'instanceId': u'64702.47', u'serverFolderPath': u'devstacksrv/', u'portType': [u'FibreChannel'], u'type': u'Physical', u'statusMessage': u'Only 5 of 6 expected paths are up', u'status': u'Degraded', u'scSerialNumber': 64702, u'serverFolder': {u'instanceId': u'64702.4', u'instanceName': u'devstacksrv', u'objectType': u'ScServerFolder'}, u'parentIndex': 0, u'connectivity': u'Partial', u'hostCacheIndex': 0, u'deleteAllowed': False, u'pathCount': 5, u'name': u'Server_21000024ff30441d', u'hbaPresent': True, u'hbaCount': 2, u'notes': u'Created by Dell Cinder Driver', u'mapped': False, u'operatingSystem': {u'instanceId': u'64702.38', u'instanceName': u'Red Hat Linux 6.x', u'objectType': u'ScServerOperatingSystem'} } SCSERVERS = [{u'scName': u'Storage Center 64702', u'volumeCount': 5, u'removeHbasAllowed': True, u'legacyFluidFs': False, u'serverFolderIndex': 0, u'alertOnConnectivity': True, u'objectType': u'ScPhysicalServer', u'instanceName': u'openstack4', u'instanceId': u'64702.1', u'serverFolderPath': u'', u'portType': [u'Iscsi'], u'type': u'Physical', u'statusMessage': u'', u'status': u'Up', u'scSerialNumber': 64702, u'serverFolder': {u'instanceId': u'64702.0', u'instanceName': u'Servers', u'objectType': u'ScServerFolder'}, u'parentIndex': 0, u'connectivity': u'Up', u'hostCacheIndex': 0, u'deleteAllowed': True, u'pathCount': 0, u'name': u'openstack4', u'hbaPresent': True, u'hbaCount': 1, u'notes': u'', u'mapped': True, u'operatingSystem': {u'instanceId': u'64702.3', u'instanceName': u'Other Multipath', u'objectType': u'ScServerOperatingSystem'}}, {u'scName': u'Storage Center 64702', u'volumeCount': 1, u'removeHbasAllowed': True, u'legacyFluidFs': False, u'serverFolderIndex': 0, u'alertOnConnectivity': True, u'objectType': u'ScPhysicalServer', u'instanceName': u'openstack5', u'instanceId': u'64702.2', u'serverFolderPath': u'', u'portType': [u'Iscsi'], u'type': u'Physical', u'statusMessage': u'', u'status': u'Up', u'scSerialNumber': 64702, u'serverFolder': {u'instanceId': u'64702.0', u'instanceName': u'Servers', u'objectType': u'ScServerFolder'}, u'parentIndex': 0, u'connectivity': u'Up', u'hostCacheIndex': 0, u'deleteAllowed': True, u'pathCount': 0, u'name': u'openstack5', u'hbaPresent': True, u'hbaCount': 1, u'notes': u'', u'mapped': True, u'operatingSystem': {u'instanceId': u'64702.2', u'instanceName': u'Other Singlepath', u'objectType': u'ScServerOperatingSystem'}}] # ScServers list where status = Down SCSERVERS_DOWN = \ [{u'scName': u'Storage Center 64702', u'volumeCount': 5, u'removeHbasAllowed': True, u'legacyFluidFs': False, u'serverFolderIndex': 0, u'alertOnConnectivity': True, u'objectType': u'ScPhysicalServer', u'instanceName': u'openstack4', u'instanceId': u'64702.1', u'serverFolderPath': u'', u'portType': [u'Iscsi'], u'type': u'Physical', u'statusMessage': u'', u'status': u'Down', u'scSerialNumber': 64702, u'serverFolder': {u'instanceId': u'64702.0', u'instanceName': u'Servers', u'objectType': u'ScServerFolder'}, u'parentIndex': 0, u'connectivity': u'Up', u'hostCacheIndex': 0, u'deleteAllowed': True, u'pathCount': 0, u'name': u'openstack4', u'hbaPresent': True, u'hbaCount': 1, u'notes': u'', u'mapped': True, u'operatingSystem': {u'instanceId': u'64702.3', u'instanceName': u'Other Multipath', u'objectType': u'ScServerOperatingSystem'}}] MAP_PROFILES = [{u'instanceId': u'64702.2941', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64703', u'instanceName': u'SN 64703', u'objectType': u'ScController'}, u'lunUsed': [1], u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'connectivity': u'Up', u'readOnly': False, u'objectType': u'ScMappingProfile', u'hostCache': False, u'mappedVia': u'Server', u'mapCount': 3, u'instanceName': u'6025-47', u'lunRequested': u'N/A'}] MAP_PROFILE = {u'instanceId': u'64702.2941', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64703', u'instanceName': u'SN 64703', u'objectType': u'ScController'}, u'lunUsed': [1], u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'connectivity': u'Up', u'readOnly': False, u'objectType': u'ScMappingProfile', u'hostCache': False, u'mappedVia': u'Server', u'mapCount': 3, u'instanceName': u'6025-47', u'lunRequested': u'N/A'} MAPPINGS = [{u'profile': {u'instanceId': u'64702.104', u'instanceName': u'92-30', u'objectType': u'ScMappingProfile'}, u'status': u'Down', u'statusMessage': u'', u'instanceId': u'64702.969.64702', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64702', u'instanceName': u'SN 64702', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.30', u'instanceName': u'Server_iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.92', u'instanceName': u'volume-74a21934-60ad-4cf2-b89b-1f0dda309ddf', u'objectType': u'ScVolume'}, u'readOnly': False, u'lun': 1, u'lunUsed': [1], u'serverHba': {u'instanceId': u'64702.3454975614', u'instanceName': u'iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScServerHba'}, u'path': {u'instanceId': u'64702.64702.64702.31.8', u'instanceName': u'iqn.1993-08.org.debian:' '01:3776df826e4f-5000D31000FCBE43', u'objectType': u'ScServerHbaPath'}, u'controllerPort': {u'instanceId': u'64702.5764839588723736131.91', u'instanceName': u'5000D31000FCBE43', u'objectType': u'ScControllerPort'}, u'instanceName': u'64702-969', u'transport': u'Iscsi', u'objectType': u'ScMapping'}] # Multiple mappings to test find_iscsi_properties with multiple portals MAPPINGS_MULTI_PORTAL = \ [{u'profile': {u'instanceId': u'64702.104', u'instanceName': u'92-30', u'objectType': u'ScMappingProfile'}, u'status': u'Down', u'statusMessage': u'', u'instanceId': u'64702.969.64702', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64702', u'instanceName': u'SN 64702', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.30', u'instanceName': u'Server_iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.92', u'instanceName': u'volume-74a21934-60ad-4cf2-b89b-1f0dda309ddf', u'objectType': u'ScVolume'}, u'readOnly': False, u'lun': 1, u'lunUsed': [1], u'serverHba': {u'instanceId': u'64702.3454975614', u'instanceName': u'iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScServerHba'}, u'path': {u'instanceId': u'64702.64702.64702.31.8', u'instanceName': u'iqn.1993-08.org.debian:' '01:3776df826e4f-5000D31000FCBE43', u'objectType': u'ScServerHbaPath'}, u'controllerPort': {u'instanceId': u'64702.5764839588723736131.91', u'instanceName': u'5000D31000FCBE43', u'objectType': u'ScControllerPort'}, u'instanceName': u'64702-969', u'transport': u'Iscsi', u'objectType': u'ScMapping'}, {u'profile': {u'instanceId': u'64702.104', u'instanceName': u'92-30', u'objectType': u'ScMappingProfile'}, u'status': u'Down', u'statusMessage': u'', u'instanceId': u'64702.969.64702', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64702', u'instanceName': u'SN 64702', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.30', u'instanceName': u'Server_iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.92', u'instanceName': u'volume-74a21934-60ad-4cf2-b89b-1f0dda309ddf', u'objectType': u'ScVolume'}, u'readOnly': False, u'lun': 1, u'lunUsed': [1], u'serverHba': {u'instanceId': u'64702.3454975614', u'instanceName': u'iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScServerHba'}, u'path': {u'instanceId': u'64702.64702.64702.31.8', u'instanceName': u'iqn.1993-08.org.debian:' '01:3776df826e4f-5000D31000FCBE43', u'objectType': u'ScServerHbaPath'}, u'controllerPort': {u'instanceId': u'64702.5764839588723736131.91', u'instanceName': u'5000D31000FCBE43', u'objectType': u'ScControllerPort'}, u'instanceName': u'64702-969', u'transport': u'Iscsi', u'objectType': u'ScMapping'}] MAPPINGS_READ_ONLY = \ [{u'profile': {u'instanceId': u'64702.104', u'instanceName': u'92-30', u'objectType': u'ScMappingProfile'}, u'status': u'Down', u'statusMessage': u'', u'instanceId': u'64702.969.64702', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64702', u'instanceName': u'SN 64702', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.30', u'instanceName': u'Server_iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.92', u'instanceName': u'volume-74a21934-60ad-4cf2-b89b-1f0dda309ddf', u'objectType': u'ScVolume'}, u'readOnly': True, u'lun': 1, u'lunUsed': [1], u'serverHba': {u'instanceId': u'64702.3454975614', u'instanceName': u'iqn.1993-08.org.debian:01:3776df826e4f', u'objectType': u'ScServerHba'}, u'path': {u'instanceId': u'64702.64702.64702.31.8', u'instanceName': u'iqn.1993-08.org.debian:' '01:3776df826e4f-5000D31000FCBE43', u'objectType': u'ScServerHbaPath'}, u'controllerPort': {u'instanceId': u'64702.5764839588723736131.91', u'instanceName': u'5000D31000FCBE43', u'objectType': u'ScControllerPort'}, u'instanceName': u'64702-969', u'transport': u'Iscsi', u'objectType': u'ScMapping'}] FC_MAPPINGS = [{u'profile': {u'instanceId': u'64702.2941', u'instanceName': u'6025-47', u'objectType': u'ScMappingProfile'}, u'status': u'Up', u'statusMessage': u'', u'instanceId': u'64702.7639.64702', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64703', u'instanceName': u'SN 64703', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'readOnly': False, u'lun': 1, u'serverHba': {u'instanceId': u'64702.3282218607', u'instanceName': u'21000024FF30441C', u'objectType': u'ScServerHba'}, u'path': {u'instanceId': u'64702.64702.64703.27.73', u'instanceName': u'21000024FF30441C-5000D31000FCBE36', u'objectType': u'ScServerHbaPath'}, u'controllerPort': {u'instanceId': u'64702.5764839588723736118.50', u'instanceName': u'5000D31000FCBE36', u'objectType': u'ScControllerPort'}, u'instanceName': u'64702-7639', u'transport': u'FibreChannel', u'objectType': u'ScMapping'}, {u'profile': {u'instanceId': u'64702.2941', u'instanceName': u'6025-47', u'objectType': u'ScMappingProfile'}, u'status': u'Up', u'statusMessage': u'', u'instanceId': u'64702.7640.64702', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64703', u'instanceName': u'SN 64703', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'readOnly': False, u'lun': 1, u'serverHba': {u'instanceId': u'64702.3282218606', u'instanceName': u'21000024FF30441D', u'objectType': u'ScServerHba'}, u'path': {u'instanceId': u'64702.64702.64703.27.78', u'instanceName': u'21000024FF30441D-5000D31000FCBE36', u'objectType': u'ScServerHbaPath'}, u'controllerPort': {u'instanceId': u'64702.5764839588723736118.50', u'instanceName': u'5000D31000FCBE36', u'objectType': u'ScControllerPort'}, u'instanceName': u'64702-7640', u'transport': u'FibreChannel', u'objectType': u'ScMapping'}, {u'profile': {u'instanceId': u'64702.2941', u'instanceName': u'6025-47', u'objectType': u'ScMappingProfile'}, u'status': u'Up', u'statusMessage': u'', u'instanceId': u'64702.7638.64702', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'controller': {u'instanceId': u'64702.64703', u'instanceName': u'SN 64703', u'objectType': u'ScController'}, u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'volume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'readOnly': False, u'lun': 1, u'serverHba': {u'instanceId': u'64702.3282218606', u'instanceName': u'21000024FF30441D', u'objectType': u'ScServerHba'}, u'path': {u'instanceId': u'64702.64702.64703.28.76', u'instanceName': u'21000024FF30441D-5000D31000FCBE3E', u'objectType': u'ScServerHbaPath'}, u'controllerPort': {u'instanceId': u'64702.5764839588723736126.60', u'instanceName': u'5000D31000FCBE3E', u'objectType': u'ScControllerPort'}, u'instanceName': u'64702-7638', u'transport': u'FibreChannel', u'objectType': u'ScMapping'}] RPLAY = {u'scSerialNumber': 64702, u'globalIndex': u'64702-46-250', u'description': u'Cinder Clone Replay', u'parent': {u'instanceId': u'64702.46.249', u'instanceName': u'64702-46-249', u'objectType': u'ScReplay'}, u'instanceId': u'64702.46.250', u'scName': u'Storage Center 64702', u'consistent': False, u'expires': True, u'freezeTime': u'12/09/2014 03:52:08 PM', u'createVolume': {u'instanceId': u'64702.46', u'instanceName': u'volume-ff9589d3-2d41-48d5-9ef5-2713a875e85b', u'objectType': u'ScVolume'}, u'expireTime': u'12/09/2014 04:52:08 PM', u'source': u'Manual', u'spaceRecovery': False, u'writesHeldDuration': 7910, u'active': False, u'markedForExpiration': False, u'objectType': u'ScReplay', u'instanceName': u'12/09/2014 03:52:08 PM', u'size': u'0.0 Bytes' } RPLAYS = [{u'scSerialNumber': 64702, u'globalIndex': u'64702-6025-5', u'description': u'Manually Created', u'parent': {u'instanceId': u'64702.6025.4', u'instanceName': u'64702-6025-4', u'objectType': u'ScReplay'}, u'instanceId': u'64702.6025.5', u'scName': u'Storage Center 64702', u'consistent': False, u'expires': True, u'freezeTime': u'02/02/2015 08:23:55 PM', u'createVolume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'expireTime': u'02/02/2015 09:23:55 PM', u'source': u'Manual', u'spaceRecovery': False, u'writesHeldDuration': 7889, u'active': False, u'markedForExpiration': False, u'objectType': u'ScReplay', u'instanceName': u'02/02/2015 08:23:55 PM', u'size': u'0.0 Bytes'}, {u'scSerialNumber': 64702, u'globalIndex': u'64702-6025-4', u'description': u'Cinder Test Replay012345678910', u'parent': {u'instanceId': u'64702.6025.3', u'instanceName': u'64702-6025-3', u'objectType': u'ScReplay'}, u'instanceId': u'64702.6025.4', u'scName': u'Storage Center 64702', u'consistent': False, u'expires': True, u'freezeTime': u'02/02/2015 08:23:47 PM', u'createVolume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'expireTime': u'02/02/2015 09:23:47 PM', u'source': u'Manual', u'spaceRecovery': False, u'writesHeldDuration': 7869, u'active': False, u'markedForExpiration': False, u'objectType': u'ScReplay', u'instanceName': u'02/02/2015 08:23:47 PM', u'size': u'0.0 Bytes'}] TST_RPLAY = {u'scSerialNumber': 64702, u'globalIndex': u'64702-6025-4', u'description': u'Cinder Test Replay012345678910', u'parent': {u'instanceId': u'64702.6025.3', u'instanceName': u'64702-6025-3', u'objectType': u'ScReplay'}, u'instanceId': u'64702.6025.4', u'scName': u'Storage Center 64702', u'consistent': False, u'expires': True, u'freezeTime': u'02/02/2015 08:23:47 PM', u'createVolume': {u'instanceId': u'64702.6025', u'instanceName': u'Server_21000024ff30441d Test Vol', u'objectType': u'ScVolume'}, u'expireTime': u'02/02/2015 09:23:47 PM', u'source': u'Manual', u'spaceRecovery': False, u'writesHeldDuration': 7869, u'active': False, u'markedForExpiration': False, u'objectType': u'ScReplay', u'instanceName': u'02/02/2015 08:23:47 PM', u'size': u'0.0 Bytes'} FLDR = {u'status': u'Up', u'instanceName': u'opnstktst', u'name': u'opnstktst', u'parent': {u'instanceId': u'64702.0', u'instanceName': u'Volumes', u'objectType': u'ScVolumeFolder'}, u'instanceId': u'64702.43', u'scName': u'Storage Center 64702', u'notes': u'Folder for OpenStack Cinder Driver', u'scSerialNumber': 64702, u'parentIndex': 0, u'okToDelete': True, u'folderPath': u'', u'root': False, u'statusMessage': u'', u'objectType': u'ScVolumeFolder'} SVR_FLDR = {u'status': u'Up', u'instanceName': u'devstacksrv', u'name': u'devstacksrv', u'parent': {u'instanceId': u'64702.0', u'instanceName': u'Servers', u'objectType': u'ScServerFolder'}, u'instanceId': u'64702.4', u'scName': u'Storage Center 64702', u'notes': u'Folder for OpenStack Cinder Driver', u'scSerialNumber': 64702, u'parentIndex': 0, u'okToDelete': False, u'folderPath': u'', u'root': False, u'statusMessage': u'', u'objectType': u'ScServerFolder'} ISCSI_HBA = {u'portWwnList': [], u'iscsiIpAddress': u'0.0.0.0', u'pathCount': 1, u'name': u'iqn.1993-08.org.debian:01:52332b70525', u'connectivity': u'Down', u'instanceId': u'64702.3786433166', u'scName': u'Storage Center 64702', u'notes': u'', u'scSerialNumber': 64702, u'server': {u'instanceId': u'64702.38', u'instanceName': u'Server_iqn.1993-08.org.debian:01:52332b70525', u'objectType': u'ScPhysicalServer'}, u'remoteStorageCenter': False, u'iscsiName': u'', u'portType': u'Iscsi', u'instanceName': u'iqn.1993-08.org.debian:01:52332b70525', u'objectType': u'ScServerHba'} FC_HBAS = [{u'portWwnList': [], u'iscsiIpAddress': u'0.0.0.0', u'pathCount': 2, u'name': u'21000024FF30441C', u'connectivity': u'Up', u'instanceId': u'64702.3282218607', u'scName': u'Storage Center 64702', u'notes': u'', u'scSerialNumber': 64702, u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'remoteStorageCenter': False, u'iscsiName': u'', u'portType': u'FibreChannel', u'instanceName': u'21000024FF30441C', u'objectType': u'ScServerHba'}, {u'portWwnList': [], u'iscsiIpAddress': u'0.0.0.0', u'pathCount': 3, u'name': u'21000024FF30441D', u'connectivity': u'Partial', u'instanceId': u'64702.3282218606', u'scName': u'Storage Center 64702', u'notes': u'', u'scSerialNumber': 64702, u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'remoteStorageCenter': False, u'iscsiName': u'', u'portType': u'FibreChannel', u'instanceName': u'21000024FF30441D', u'objectType': u'ScServerHba'}] FC_HBA = {u'portWwnList': [], u'iscsiIpAddress': u'0.0.0.0', u'pathCount': 3, u'name': u'21000024FF30441D', u'connectivity': u'Partial', u'instanceId': u'64702.3282218606', u'scName': u'Storage Center 64702', u'notes': u'', u'scSerialNumber': 64702, u'server': {u'instanceId': u'64702.47', u'instanceName': u'Server_21000024ff30441d', u'objectType': u'ScPhysicalServer'}, u'remoteStorageCenter': False, u'iscsiName': u'', u'portType': u'FibreChannel', u'instanceName': u'21000024FF30441D', u'objectType': u'ScServerHba'} SVR_OS_S = [{u'allowsLunGaps': True, u'product': u'Red Hat Linux', u'supportsActiveMappingDeletion': True, u'version': u'6.x', u'requiresLunZero': False, u'scName': u'Storage Center 64702', u'virtualMachineGuest': True, u'virtualMachineHost': False, u'allowsCrossTransportMapping': False, u'objectType': u'ScServerOperatingSystem', u'instanceId': u'64702.38', u'lunCanVaryAcrossPaths': False, u'scSerialNumber': 64702, u'maximumVolumeSize': u'0.0 Bytes', u'multipath': True, u'instanceName': u'Red Hat Linux 6.x', u'supportsActiveMappingCreation': True, u'name': u'Red Hat Linux 6.x'}] ISCSI_FLT_DOMAINS = [{u'headerDigestEnabled': False, u'classOfServicePriority': 0, u'wellKnownIpAddress': u'192.168.0.21', u'scSerialNumber': 64702, u'iscsiName': u'iqn.2002-03.com.compellent:5000d31000fcbe42', u'portNumber': 3260, u'subnetMask': u'255.255.255.0', u'gateway': u'192.168.0.1', u'objectType': u'ScIscsiFaultDomain', u'chapEnabled': False, u'instanceId': u'64702.6.5.3', u'childStatus': u'Up', u'defaultTimeToRetain': u'SECONDS_20', u'dataDigestEnabled': False, u'instanceName': u'iSCSI 10G 2', u'statusMessage': u'', u'status': u'Up', u'transportType': u'Iscsi', u'vlanId': 0, u'windowSize': u'131072.0 Bytes', u'defaultTimeToWait': u'SECONDS_2', u'scsiCommandTimeout': u'MINUTES_1', u'deleteAllowed': False, u'name': u'iSCSI 10G 2', u'immediateDataWriteEnabled': False, u'scName': u'Storage Center 64702', u'notes': u'', u'mtu': u'MTU_1500', u'bidirectionalChapSecret': u'', u'keepAliveTimeout': u'SECONDS_30'}] # For testing find_iscsi_properties where multiple portals are found ISCSI_FLT_DOMAINS_MULTI_PORTALS = \ [{u'headerDigestEnabled': False, u'classOfServicePriority': 0, u'wellKnownIpAddress': u'192.168.0.21', u'scSerialNumber': 64702, u'iscsiName': u'iqn.2002-03.com.compellent:5000d31000fcbe42', u'portNumber': 3260, u'subnetMask': u'255.255.255.0', u'gateway': u'192.168.0.1', u'objectType': u'ScIscsiFaultDomain', u'chapEnabled': False, u'instanceId': u'64702.6.5.3', u'childStatus': u'Up', u'defaultTimeToRetain': u'SECONDS_20', u'dataDigestEnabled': False, u'instanceName': u'iSCSI 10G 2', u'statusMessage': u'', u'status': u'Up', u'transportType': u'Iscsi', u'vlanId': 0, u'windowSize': u'131072.0 Bytes', u'defaultTimeToWait': u'SECONDS_2', u'scsiCommandTimeout': u'MINUTES_1', u'deleteAllowed': False, u'name': u'iSCSI 10G 2', u'immediateDataWriteEnabled': False, u'scName': u'Storage Center 64702', u'notes': u'', u'mtu': u'MTU_1500', u'bidirectionalChapSecret': u'', u'keepAliveTimeout': u'SECONDS_30'}, {u'headerDigestEnabled': False, u'classOfServicePriority': 0, u'wellKnownIpAddress': u'192.168.0.25', u'scSerialNumber': 64702, u'iscsiName': u'iqn.2002-03.com.compellent:5000d31000fcbe42', u'portNumber': 3260, u'subnetMask': u'255.255.255.0', u'gateway': u'192.168.0.1', u'objectType': u'ScIscsiFaultDomain', u'chapEnabled': False, u'instanceId': u'64702.6.5.3', u'childStatus': u'Up', u'defaultTimeToRetain': u'SECONDS_20', u'dataDigestEnabled': False, u'instanceName': u'iSCSI 10G 2', u'statusMessage': u'', u'status': u'Up', u'transportType': u'Iscsi', u'vlanId': 0, u'windowSize': u'131072.0 Bytes', u'defaultTimeToWait': u'SECONDS_2', u'scsiCommandTimeout': u'MINUTES_1', u'deleteAllowed': False, u'name': u'iSCSI 10G 2', u'immediateDataWriteEnabled': False, u'scName': u'Storage Center 64702', u'notes': u'', u'mtu': u'MTU_1500', u'bidirectionalChapSecret': u'', u'keepAliveTimeout': u'SECONDS_30'}] ISCSI_FLT_DOMAIN = {u'headerDigestEnabled': False, u'classOfServicePriority': 0, u'wellKnownIpAddress': u'192.168.0.21', u'scSerialNumber': 64702, u'iscsiName': u'iqn.2002-03.com.compellent:5000d31000fcbe42', u'portNumber': 3260, u'subnetMask': u'255.255.255.0', u'gateway': u'192.168.0.1', u'objectType': u'ScIscsiFaultDomain', u'chapEnabled': False, u'instanceId': u'64702.6.5.3', u'childStatus': u'Up', u'defaultTimeToRetain': u'SECONDS_20', u'dataDigestEnabled': False, u'instanceName': u'iSCSI 10G 2', u'statusMessage': u'', u'status': u'Up', u'transportType': u'Iscsi', u'vlanId': 0, u'windowSize': u'131072.0 Bytes', u'defaultTimeToWait': u'SECONDS_2', u'scsiCommandTimeout': u'MINUTES_1', u'deleteAllowed': False, u'name': u'iSCSI 10G 2', u'immediateDataWriteEnabled': False, u'scName': u'Storage Center 64702', u'notes': u'', u'mtu': u'MTU_1500', u'bidirectionalChapSecret': u'', u'keepAliveTimeout': u'SECONDS_30'} CTRLR_PORT = {u'status': u'Up', u'iscsiIpAddress': u'0.0.0.0', u'WWN': u'5000D31000FCBE06', u'name': u'5000D31000FCBE06', u'iscsiGateway': u'0.0.0.0', u'instanceId': u'64702.5764839588723736070.51', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'transportType': u'FibreChannel', u'virtual': False, u'controller': {u'instanceId': u'64702.64702', u'instanceName': u'SN 64702', u'objectType': u'ScController'}, u'iscsiName': u'', u'purpose': u'FrontEnd', u'iscsiSubnetMask': u'0.0.0.0', u'faultDomain': {u'instanceId': u'64702.4.3', u'instanceName': u'Domain 1', u'objectType': u'ScControllerPortFaultDomain'}, u'instanceName': u'5000D31000FCBE06', u'statusMessage': u'', u'objectType': u'ScControllerPort'} ISCSI_CTRLR_PORT = {u'preferredParent': {u'instanceId': u'64702.5764839588723736074.69', u'instanceName': u'5000D31000FCBE0A', u'objectType': u'ScControllerPort'}, u'status': u'Up', u'iscsiIpAddress': u'10.23.8.235', u'WWN': u'5000D31000FCBE43', u'name': u'5000D31000FCBE43', u'parent': {u'instanceId': u'64702.5764839588723736074.69', u'instanceName': u'5000D31000FCBE0A', u'objectType': u'ScControllerPort'}, u'iscsiGateway': u'0.0.0.0', u'instanceId': u'64702.5764839588723736131.91', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'transportType': u'Iscsi', u'virtual': True, u'controller': {u'instanceId': u'64702.64702', u'instanceName': u'SN 64702', u'objectType': u'ScController'}, u'iscsiName': u'iqn.2002-03.com.compellent:5000d31000fcbe43', u'purpose': u'FrontEnd', u'iscsiSubnetMask': u'0.0.0.0', u'faultDomain': {u'instanceId': u'64702.6.5', u'instanceName': u'iSCSI 10G 2', u'objectType': u'ScControllerPortFaultDomain'}, u'instanceName': u'5000D31000FCBE43', u'childStatus': u'Up', u'statusMessage': u'', u'objectType': u'ScControllerPort'} FC_CTRLR_PORT = {u'preferredParent': {u'instanceId': u'64702.5764839588723736093.57', u'instanceName': u'5000D31000FCBE1D', u'objectType': u'ScControllerPort'}, u'status': u'Up', u'iscsiIpAddress': u'0.0.0.0', u'WWN': u'5000D31000FCBE36', u'name': u'5000D31000FCBE36', u'parent': {u'instanceId': u'64702.5764839588723736093.57', u'instanceName': u'5000D31000FCBE1D', u'objectType': u'ScControllerPort'}, u'iscsiGateway': u'0.0.0.0', u'instanceId': u'64702.5764839588723736118.50', u'scName': u'Storage Center 64702', u'scSerialNumber': 64702, u'transportType': u'FibreChannel', u'virtual': True, u'controller': {u'instanceId': u'64702.64703', u'instanceName': u'SN 64703', u'objectType': u'ScController'}, u'iscsiName': u'', u'purpose': u'FrontEnd', u'iscsiSubnetMask': u'0.0.0.0', u'faultDomain': {u'instanceId': u'64702.1.0', u'instanceName': u'Domain 0', u'objectType': u'ScControllerPortFaultDomain'}, u'instanceName': u'5000D31000FCBE36', u'childStatus': u'Up', u'statusMessage': u'', u'objectType': u'ScControllerPort'} STRG_USAGE = {u'systemSpace': u'7.38197504E8 Bytes', u'freeSpace': u'1.297659461632E13 Bytes', u'oversubscribedSpace': u'0.0 Bytes', u'instanceId': u'64702', u'scName': u'Storage Center 64702', u'savingVsRaidTen': u'1.13737990144E11 Bytes', u'allocatedSpace': u'1.66791217152E12 Bytes', u'usedSpace': u'3.25716017152E11 Bytes', u'configuredSpace': u'9.155796533248E12 Bytes', u'alertThresholdSpace': u'1.197207956992E13 Bytes', u'availableSpace': u'1.3302310633472E13 Bytes', u'badSpace': u'0.0 Bytes', u'time': u'02/02/2015 02:23:39 PM', u'scSerialNumber': 64702, u'instanceName': u'Storage Center 64702', u'storageAlertThreshold': 10, u'objectType': u'StorageCenterStorageUsage'} IQN = 'iqn.2002-03.com.compellent:5000D31000000001' WWN = u'21000024FF30441C' WWNS = [u'21000024FF30441C', u'21000024FF30441D'] FLDR_PATH = 'StorageCenter/ScVolumeFolder/' # Create a Response object that indicates OK response_ok = models.Response() response_ok.status_code = 200 response_ok.reason = u'ok' RESPONSE_200 = response_ok # Create a Response object that indicates created response_created = models.Response() response_created.status_code = 201 response_created.reason = u'created' RESPONSE_201 = response_created # Create a Response object that indicates a failure (no content) response_nc = models.Response() response_nc.status_code = 204 response_nc.reason = u'duplicate' RESPONSE_204 = response_nc def setUp(self): super(DellSCSanAPITestCase, self).setUp() # Configuration is a mock. A mock is pretty much a blank # slate. I believe mock's done in setup are not happy time # mocks. So we just do a few things like driver config here. self.configuration = mock.Mock() self.configuration.san_is_local = False self.configuration.san_ip = "192.168.0.1" self.configuration.san_login = "admin" self.configuration.san_password = "mmm" self.configuration.dell_sc_ssn = 12345 self.configuration.dell_sc_server_folder = 'opnstktst' self.configuration.dell_sc_volume_folder = 'opnstktst' self.configuration.dell_sc_api_port = 3033 self.configuration.iscsi_ip_address = '192.168.1.1' self.configuration.iscsi_port = 3260 self._context = context.get_admin_context() # Set up the StorageCenterApi self.scapi = dell_storagecenter_api.StorageCenterApi( self.configuration.san_ip, self.configuration.dell_sc_api_port, self.configuration.san_login, self.configuration.san_password) self.volid = str(uuid.uuid4()) self.volume_name = "volume" + self.volid def test_path_to_array(self, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._path_to_array(u'folder1/folder2/folder3') expected = [u'folder1', u'folder2', u'folder3'] self.assertEqual(expected, res, 'Unexpected folder path') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_result', return_value=SC) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_sc(self, mock_get, mock_get_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.find_sc(64702) mock_get.assert_called_once_with('StorageCenter/StorageCenter') mock_get_result.assert_called() self.assertEqual(u'64702', res, 'Unexpected SSN') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_result', return_value=None) def test_find_sc_failure(self, mock_get_result, mock_get, mock_close_connection, mock_open_connection, mock_init): self.assertRaises(exception.VolumeBackendAPIException, self.scapi.find_sc, 12345) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_folder(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._create_folder( 'StorageCenter/ScVolumeFolder', 12345, '', self.configuration.dell_sc_volume_folder) mock_post.assert_called() mock_first_result.assert_called() self.assertEqual(self.FLDR, res, 'Unexpected Folder') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_folder_with_parent(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): # Test case where parent folder name is specified res = self.scapi._create_folder( 'StorageCenter/ScVolumeFolder', 12345, 'parentFolder', self.configuration.dell_sc_volume_folder) mock_post.assert_called() mock_first_result.assert_called() self.assertEqual(self.FLDR, res, 'Unexpected Folder') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_create_folder_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._create_folder( 'StorageCenter/ScVolumeFolder', 12345, '', self.configuration.dell_sc_volume_folder) self.assertIsNone(res, 'Test Create folder - None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_folder', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_path_to_array', return_value=['Cinder_Test_Folder']) def test_create_folder_path(self, mock_path_to_array, mock_find_folder, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._create_folder_path( 'StorageCenter/ScVolumeFolder', 12345, self.configuration.dell_sc_volume_folder) mock_path_to_array.assert_called_once_with( self.configuration.dell_sc_volume_folder) mock_find_folder.assert_called() self.assertEqual(self.FLDR, res, 'Unexpected ScFolder') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_folder', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_path_to_array', return_value=['Cinder_Test_Folder']) def test_create_folder_path_create_fldr(self, mock_path_to_array, mock_find_folder, mock_create_folder, mock_close_connection, mock_open_connection, mock_init): # Test case where folder is not found and must be created res = self.scapi._create_folder_path( 'StorageCenter/ScVolumeFolder', 12345, self.configuration.dell_sc_volume_folder) mock_path_to_array.assert_called_once_with( self.configuration.dell_sc_volume_folder) mock_find_folder.assert_called() mock_create_folder.assert_called() self.assertEqual(self.FLDR, res, 'Unexpected ScFolder') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_path_to_array', return_value=['Cinder_Test_Folder']) def test_create_folder_path_failure(self, mock_path_to_array, mock_find_folder, mock_create_folder, mock_close_connection, mock_open_connection, mock_init): # Test case where folder is not found, must be created # and creation fails res = self.scapi._create_folder_path( 'StorageCenter/ScVolumeFolder', 12345, self.configuration.dell_sc_volume_folder) mock_path_to_array.assert_called_once_with( self.configuration.dell_sc_volume_folder) mock_find_folder.assert_called() mock_create_folder.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_result', return_value=u'devstackvol/fcvm/') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_folder(self, mock_post, mock_get_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_folder( 'StorageCenter/ScVolumeFolder', 12345, self.configuration.dell_sc_volume_folder) mock_post.assert_called() mock_get_result.assert_called() self.assertEqual(u'devstackvol/fcvm/', res, 'Unexpected folder') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_result', return_value=u'devstackvol/fcvm/') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_folder_multi_fldr(self, mock_post, mock_get_result, mock_close_connection, mock_open_connection, mock_init): # Test case for folder path with multiple folders res = self.scapi._find_folder( 'StorageCenter/ScVolumeFolder', 12345, u'testParentFolder/opnstktst') mock_post.assert_called() mock_get_result.assert_called() self.assertEqual(u'devstackvol/fcvm/', res, 'Unexpected folder') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_find_folder_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_folder( 'StorageCenter/ScVolumeFolder', 12345, self.configuration.dell_sc_volume_folder) self.assertIsNone(res, 'Test find folder - None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_folder_path', return_value=FLDR) def test_create_volume_folder_path(self, mock_create_vol_fldr_path, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._create_volume_folder_path( 12345, self.configuration.dell_sc_volume_folder) mock_create_vol_fldr_path.assert_called_once_with( 'StorageCenter/ScVolumeFolder', 12345, self.configuration.dell_sc_volume_folder) self.assertEqual(self.FLDR, res, 'Unexpected ScFolder') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_folder', return_value=FLDR) def test_find_volume_folder(self, mock_find_folder, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_volume_folder( 12345, self.configuration.dell_sc_volume_folder) mock_find_folder.assert_called_once_with( 'StorageCenter/ScVolumeFolder/GetList', 12345, self.configuration.dell_sc_volume_folder) self.assertEqual(self.FLDR, res, 'Unexpected Folder') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'unmap_volume', return_value=True) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'map_volume', return_value=MAPPINGS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=SCSERVERS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_init_volume(self, mock_post, mock_get_json, mock_map_volume, mock_unmap_volume, mock_close_connection, mock_open_connection, mock_init): self.scapi._init_volume(self.VOLUME) mock_map_volume.assert_called() mock_unmap_volume.assert_called() @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_init_volume_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): # Test case where ScServer list fails self.scapi._init_volume(self.VOLUME) mock_post.assert_called() @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'unmap_volume', return_value=True) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'map_volume', return_value=MAPPINGS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=SCSERVERS_DOWN) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_init_volume_servers_down(self, mock_post, mock_get_json, mock_map_volume, mock_unmap_volume, mock_close_connection, mock_open_connection, mock_init): # Test case where ScServer Status = Down self.scapi._init_volume(self.VOLUME) mock_map_volume.assert_called() mock_unmap_volume.assert_called() @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_volume(self, mock_post, mock_find_volume_folder, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_volume( self.volume_name, 1, 12345, self.configuration.dell_sc_volume_folder) mock_post.assert_called() mock_get_json.assert_called() mock_find_volume_folder.assert_called_once_with( 12345, self.configuration.dell_sc_volume_folder) self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_volume_folder_path', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_vol_and_folder(self, mock_post, mock_find_volume_folder, mock_create_vol_folder_path, mock_get_json, mock_close_connection, mock_open_connection, mock_init): # Test calling create_volume where volume folder has to be created res = self.scapi.create_volume( self.volume_name, 1, 12345, self.configuration.dell_sc_volume_folder) mock_post.assert_called() mock_get_json.assert_called() mock_create_vol_folder_path.assert_called_once_with( 12345, self.configuration.dell_sc_volume_folder) mock_find_volume_folder.assert_called_once_with( 12345, self.configuration.dell_sc_volume_folder) self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_volume_folder_path', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_vol_folder_fail(self, mock_post, mock_find_volume_folder, mock_create_vol_folder_path, mock_get_json, mock_close_connection, mock_open_connection, mock_init): # Test calling create_volume where volume folder does not exist and # fails to be created res = self.scapi.create_volume( self.volume_name, 1, 12345, self.configuration.dell_sc_volume_folder) mock_post.assert_called() mock_get_json.assert_called() mock_create_vol_folder_path.assert_called_once_with( 12345, self.configuration.dell_sc_volume_folder) mock_find_volume_folder.assert_called_once_with( 12345, self.configuration.dell_sc_volume_folder) self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_create_volume_failure(self, mock_post, mock_find_volume_folder, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_volume( self.volume_name, 1, 12345, self.configuration.dell_sc_volume_folder) mock_find_volume_folder.assert_called_once_with( 12345, self.configuration.dell_sc_volume_folder) self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_volume_by_name(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): # Test case to find volume by name res = self.scapi.find_volume(12345, self.volume_name) mock_post.assert_called() mock_first_result.assert_called() self.assertEqual(self.VOLUME, res, 'Unexpected volume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) # Test case to find volume by InstancedId def test_find_volume_by_instanceid(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.find_volume(12345, None, '64702.3494') mock_post.assert_called() mock_first_result.assert_called() self.assertEqual(self.VOLUME, res, 'Unexpected volume') def test_find_volume_no_name_or_instance(self, mock_close_connection, mock_open_connection, mock_init): # Test calling find_volume with no name or instanceid res = self.scapi.find_volume(12345) self.assertEqual(res, None, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_find_volume_not_found(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): # Test calling find_volume with result of no volume found res = self.scapi.find_volume(12345, self.volume_name) self.assertEqual(None, res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=True) @mock.patch.object(dell_storagecenter_api.HttpClient, 'delete', return_value=RESPONSE_200) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'find_volume', return_value=VOLUME) def test_delete_volume(self, mock_find_volume, mock_delete, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.delete_volume(12345, self.volume_name) mock_delete.assert_called() mock_find_volume.assert_called_once_with(12345, self.volume_name, None) mock_get_json.assert_called() self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.HttpClient, 'delete', return_value=RESPONSE_204) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'find_volume', return_value=VOLUME) def test_delete_volume_failure(self, mock_find_volume, mock_delete, mock_close_connection, mock_open_connection, mock_init): self.assertRaises(exception.VolumeBackendAPIException, self.scapi.delete_volume, 12345, self.volume_name) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'find_volume', return_value=None) def test_delete_volume_no_vol_found(self, mock_find_volume, mock_close_connection, mock_open_connection, mock_init): # Test case where volume to be deleted does not exist res = self.scapi.delete_volume(12345, self.volume_name) self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_folder_path', return_value=SVR_FLDR) def test_create_server_folder_path(self, mock_create_svr_fldr_path, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._create_server_folder_path( 12345, self.configuration.dell_sc_server_folder) mock_create_svr_fldr_path.assert_called_once_with( 'StorageCenter/ScServerFolder', 12345, self.configuration.dell_sc_server_folder) self.assertEqual(self.SVR_FLDR, res, 'Unexpected server folder') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_folder', return_value=SVR_FLDR) def test_find_server_folder(self, mock_find_folder, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_server_folder( 12345, self.configuration.dell_sc_server_folder) mock_find_folder.assert_called_once_with( 'StorageCenter/ScServerFolder/GetList', 12345, self.configuration.dell_sc_server_folder) self.assertEqual(self.SVR_FLDR, res, 'Unexpected server folder') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_add_hba(self, mock_post, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._add_hba(self.SCSERVER, self.IQN, False) mock_post.assert_called() self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_add_hba_fc(self, mock_post, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._add_hba(self.SCSERVER, self.WWN, True) mock_post.assert_called() self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_add_hba_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._add_hba(self.SCSERVER, self.IQN, False) mock_post.assert_called() self.assertFalse(res, 'Expected False') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=SVR_OS_S) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_serveros(self, mock_post, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_serveros(12345, 'Red Hat Linux 6.x') mock_get_json.assert_called() mock_post.assert_called() self.assertEqual('64702.38', res, 'Wrong InstanceId') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=SVR_OS_S) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_serveros_not_found(self, mock_post, mock_get_json, mock_close_connection, mock_open_connection, mock_init): # Test requesting a Server OS that will not be found res = self.scapi._find_serveros(12345, 'Non existent OS') mock_get_json.assert_called() mock_post.assert_called() self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_find_serveros_failed(self, mock_post, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_serveros(12345, 'Red Hat Linux 6.x') self.assertEqual(None, res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_add_hba', return_value=FC_HBA) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'create_server', return_value=SCSERVER) def test_create_server_multiple_hbas(self, mock_create_server, mock_add_hba, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_server_multiple_hbas( 12345, self.configuration.dell_sc_server_folder, self.WWNS) mock_create_server.assert_called() mock_add_hba.assert_called() self.assertEqual(self.SCSERVER, res, 'Unexpected ScServer') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_add_hba', return_value=True) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=SCSERVER) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_server_folder', return_value=SVR_FLDR) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serveros', return_value='64702.38') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_server(self, mock_post, mock_find_serveros, mock_find_server_folder, mock_first_result, mock_add_hba, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_server( 12345, self.configuration.dell_sc_server_folder, self.IQN, False) mock_find_serveros.assert_called() mock_find_server_folder.assert_called() mock_first_result.assert_called() mock_add_hba.assert_called() self.assertEqual(self.SCSERVER, res, 'Unexpected ScServer') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_add_hba', return_value=True) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=SCSERVER) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_server_folder', return_value=SVR_FLDR) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serveros', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_server_os_not_found(self, mock_post, mock_find_serveros, mock_find_server_folder, mock_first_result, mock_add_hba, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_server( 12345, self.configuration.dell_sc_server_folder, self.IQN, False) mock_find_serveros.assert_called() self.assertEqual(self.SCSERVER, res, 'Unexpected ScServer') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_add_hba', return_value=True) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=SCSERVER) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_server_folder_path', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_server_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serveros', return_value='64702.38') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_server_fldr_not_found(self, mock_post, mock_find_serveros, mock_find_server_folder, mock_create_svr_fldr_path, mock_first_result, mock_add_hba, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_server( 12345, self.configuration.dell_sc_server_folder, self.IQN, False) mock_find_server_folder.assert_called() mock_create_svr_fldr_path.assert_called() self.assertEqual(self.SCSERVER, res, 'Unexpected ScServer') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_add_hba', return_value=True) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=SCSERVER) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_server_folder_path', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_server_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serveros', return_value='64702.38') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_create_server_failure(self, mock_post, mock_find_serveros, mock_find_server_folder, mock_create_svr_fldr_path, mock_first_result, mock_add_hba, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_server( 12345, self.configuration.dell_sc_server_folder, self.IQN, False) self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_add_hba', return_value=True) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_server_folder_path', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_server_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serveros', return_value='64702.38') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_server_not_found(self, mock_post, mock_find_serveros, mock_find_server_folder, mock_create_svr_fldr_path, mock_first_result, mock_add_hba, mock_close_connection, mock_open_connection, mock_init): # Test create server where _first_result is None res = self.scapi.create_server( 12345, self.configuration.dell_sc_server_folder, self.IQN, False) self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_delete_server', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_add_hba', return_value=False) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=SCSERVER) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_server_folder', return_value=SVR_FLDR) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serveros', return_value='64702.38') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_201) def test_create_server_addhba_fail(self, mock_post, mock_find_serveros, mock_find_server_folder, mock_first_result, mock_add_hba, mock_delete_server, mock_close_connection, mock_open_connection, mock_init): # Tests create server where add hba fails res = self.scapi.create_server( 12345, self.configuration.dell_sc_server_folder, self.IQN, False) mock_delete_server.assert_called() self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=SCSERVER) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serverhba', return_value=ISCSI_HBA) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_server(self, mock_post, mock_find_serverhba, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.find_server(12345, self.IQN) mock_find_serverhba.assert_called() mock_first_result.assert_called() self.assertIsNotNone(res, 'Expected ScServer') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serverhba', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_server_no_hba(self, mock_post, mock_find_serverhba, mock_close_connection, mock_open_connection, mock_init): # Test case where a ScServer HBA does not exist with the specified IQN # or WWN res = self.scapi.find_server(12345, self.IQN) mock_find_serverhba.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_serverhba', return_value=ISCSI_HBA) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_find_server_failure(self, mock_post, mock_find_serverhba, mock_close_connection, mock_open_connection, mock_init): # Test case where a ScServer does not exist with the specified # ScServerHba res = self.scapi.find_server(12345, self.IQN) mock_find_serverhba.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=ISCSI_HBA) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_find_serverhba(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.find_server(12345, self.IQN) mock_post.assert_called() mock_first_result.assert_called() self.assertIsNotNone(res, 'Expected ScServerHba') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_find_serverhba_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): # Test case where a ScServer does not exist with the specified # ScServerHba res = self.scapi.find_server(12345, self.IQN) self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_domains(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_domains(u'64702.5764839588723736074.69') mock_get .assert_called() mock_get_json.assert_called() self.assertEqual( self.ISCSI_FLT_DOMAINS, res, 'Unexpected ScIscsiFaultDomain') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_find_domains_error(self, mock_get, mock_close_connection, mock_open_connection, mock_init): # Test case where get of ScControllerPort FaultDomainList fails res = self.scapi._find_domains(u'64702.5764839588723736074.69') self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_domain(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_domain(u'64702.5764839588723736074.69', u'192.168.0.21') mock_get .assert_called() mock_get_json.assert_called() self.assertIsNotNone(res, 'Expected ScIscsiFaultDomain') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_find_domain_error(self, mock_get, mock_close_connection, mock_open_connection, mock_init): # Test case where get of ScControllerPort FaultDomainList fails res = self.scapi._find_domain(u'64702.5764839588723736074.69', u'192.168.0.21') self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_domain_not_found(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): # Test case where domainip does not equal any WellKnownIpAddress # of the fault domains res = self.scapi._find_domain(u'64702.5764839588723736074.69', u'192.168.0.22') self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=FC_HBAS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_fc_initiators(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_fc_initiators(self.SCSERVER) mock_get.assert_called() mock_get_json.assert_called() self.assertIsNotNone(res, 'Expected WWN list') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_find_fc_initiators_error(self, mock_get, mock_close_connection, mock_open_connection, mock_init): # Test case where get of ScServer HbaList fails res = self.scapi._find_fc_initiators(self.SCSERVER) self.assertListEqual([], res, 'Expected empty list') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=MAPPINGS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_get_volume_count(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.get_volume_count(self.SCSERVER) mock_get.assert_called() mock_get_json.assert_called() self.assertEqual(len(self.MAPPINGS), res, 'Mapping count mismatch') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_get_volume_count_failure(self, mock_get, mock_close_connection, mock_open_connection, mock_init): # Test case of where get of ScServer MappingList fails res = self.scapi.get_volume_count(self.SCSERVER) mock_get.assert_called() self.assertEqual(-1, res, 'Mapping count not -1') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=[]) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_get_volume_count_no_volumes(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.get_volume_count(self.SCSERVER) mock_get.assert_called() mock_get_json.assert_called() self.assertEqual(len([]), res, 'Mapping count mismatch') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=MAPPINGS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_mappings(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_mappings(self.VOLUME) mock_get.assert_called() mock_get_json.assert_called() self.assertEqual(self.MAPPINGS, res, 'Mapping mismatch') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_mappings_inactive_vol(self, mock_get, mock_close_connection, mock_open_connection, mock_init): # Test getting volume mappings on inactive volume res = self.scapi._find_mappings(self.INACTIVE_VOLUME) mock_get.assert_called() self.assertEqual([], res, 'No mappings expected') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_find_mappings_failure(self, mock_get, mock_close_connection, mock_open_connection, mock_init): # Test case of where get of ScVolume MappingList fails res = self.scapi._find_mappings(self.VOLUME) mock_get.assert_called() self.assertEqual([], res, 'Mapping count not empty') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=[]) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_mappings_no_mappings(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): # Test case where ScVolume has no mappings res = self.scapi._find_mappings(self.VOLUME) mock_get.assert_called() mock_get_json.assert_called() self.assertEqual([], res, 'Mapping count mismatch') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_controller_port(self, mock_get, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._find_controller_port(u'64702.5764839588723736070.51') mock_get.assert_called() mock_first_result.assert_called() self.assertEqual(self.CTRLR_PORT, res, 'ScControllerPort mismatch') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_find_controller_port_failure(self, mock_get, mock_close_connection, mock_open_connection, mock_init): # Test case where get of ScVolume MappingList fails res = self.scapi._find_controller_port(self.VOLUME) mock_get.assert_called() self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=FC_CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=FC_MAPPINGS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_fc_initiators', return_value=WWNS) def test_find_wwns(self, mock_find_fc_initiators, mock_find_mappings, mock_find_controller_port, mock_close_connection, mock_open_connection, mock_init): lun, wwns, itmap = self.scapi.find_wwns(self.VOLUME, self.SCSERVER) mock_find_fc_initiators.assert_called() mock_find_mappings.assert_called() mock_find_controller_port.assert_called() # The _find_controller_port is Mocked, so all mapping pairs # will have the same WWN for the ScControllerPort itmapCompare = {u'21000024FF30441C': [u'5000D31000FCBE36'], u'21000024FF30441D': [u'5000D31000FCBE36', u'5000D31000FCBE36']} self.assertEqual(1, lun, 'Incorrect LUN') self.assertIsNotNone(wwns, 'WWNs is None') self.assertEqual(itmapCompare, itmap, 'WWN mapping incorrect') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=[]) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_fc_initiators', return_value=FC_HBAS) def test_find_wwns_no_mappings(self, mock_find_fc_initiators, mock_find_mappings, mock_close_connection, mock_open_connection, mock_init): # Test case where there are no ScMapping(s) lun, wwns, itmap = self.scapi.find_wwns(self.VOLUME, self.SCSERVER) mock_find_fc_initiators.assert_called() mock_find_mappings.assert_called() self.assertEqual(None, lun, 'Incorrect LUN') self.assertEqual([], wwns, 'WWNs is not empty') self.assertEqual({}, itmap, 'WWN mapping not empty') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=FC_MAPPINGS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_fc_initiators', return_value=WWNS) def test_find_wwns_no_ctlr_port(self, mock_find_fc_initiators, mock_find_mappings, mock_find_controller_port, mock_close_connection, mock_open_connection, mock_init): # Test case where ScControllerPort is none lun, wwns, itmap = self.scapi.find_wwns(self.VOLUME, self.SCSERVER) mock_find_fc_initiators.assert_called() mock_find_mappings.assert_called() mock_find_controller_port.assert_called() self.assertEqual(None, lun, 'Incorrect LUN') self.assertEqual([], wwns, 'WWNs is not empty') self.assertEqual({}, itmap, 'WWN mapping not empty') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=ISCSI_CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_domains', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=MAPPINGS) def test_find_iscsi_properties_mappings(self, mock_find_mappings, mock_find_domain, mock_find_ctrl_port, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.find_iscsi_properties(self.VOLUME) mock_find_mappings.assert_called() mock_find_domain.assert_called() mock_find_ctrl_port.assert_called() expected = {'access_mode': 'rw', 'target_discovered': False, 'target_iqns': [u'iqn.2002-03.com.compellent:5000d31000fcbe43'], 'target_luns': [1], 'target_portals': [u'192.168.0.21:3260']} self.assertEqual(expected, res, 'Wrong Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=ISCSI_CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_domains', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=MAPPINGS) def test_find_iscsi_properties_by_address(self, mock_find_mappings, mock_find_domain, mock_find_ctrl_port, mock_close_connection, mock_open_connection, mock_init): # Test case to find iSCSI mappings by IP Address & port res = self.scapi.find_iscsi_properties( self.VOLUME, '192.168.0.21', 3260) mock_find_mappings.assert_called() mock_find_domain.assert_called() mock_find_ctrl_port.assert_called() expected = {'access_mode': 'rw', 'target_discovered': False, 'target_iqns': [u'iqn.2002-03.com.compellent:5000d31000fcbe43'], 'target_luns': [1], 'target_portals': [u'192.168.0.21:3260']} self.assertEqual(expected, res, 'Wrong Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=ISCSI_CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_domains', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=MAPPINGS) def test_find_iscsi_properties_by_address_not_found(self, mock_find_mappings, mock_find_domain, mock_find_ctrl_port, mock_close_connection, mock_open_connection, mock_init): # Test case to find iSCSI mappings by IP Address & port are not found res = self.scapi.find_iscsi_properties( self.VOLUME, '192.168.1.21', 3260) mock_find_mappings.assert_called() mock_find_domain.assert_called() mock_find_ctrl_port.assert_called() expected = {'access_mode': 'rw', 'target_discovered': False, 'target_iqns': [], 'target_luns': [], 'target_portals': []} self.assertEqual(expected, res, 'Wrong Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=[]) def test_find_iscsi_properties_no_mapping(self, mock_find_mappings, mock_close_connection, mock_open_connection, mock_init): # Test case where there are no ScMapping(s) res = self.scapi.find_iscsi_properties(self.VOLUME) mock_find_mappings.assert_called() expected = {'access_mode': 'rw', 'target_discovered': False, 'target_iqns': [], 'target_luns': [], 'target_portals': []} self.assertEqual(expected, res, 'Expected empty Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=ISCSI_CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_domains', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=MAPPINGS) def test_find_iscsi_properties_no_domain(self, mock_find_mappings, mock_find_domain, mock_find_ctrl_port, mock_close_connection, mock_open_connection, mock_init): # Test case where there are no ScFaultDomain(s) res = self.scapi.find_iscsi_properties(self.VOLUME) mock_find_mappings.assert_called() mock_find_domain.assert_called() mock_find_ctrl_port.assert_called() expected = {'access_mode': 'rw', 'target_discovered': False, 'target_iqns': [], 'target_luns': [], 'target_portals': []} self.assertEqual(expected, res, 'Expected empty Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_domains', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=MAPPINGS) def test_find_iscsi_properties_no_ctrl_port(self, mock_find_mappings, mock_find_domain, mock_find_ctrl_port, mock_close_connection, mock_open_connection, mock_init): # Test case where there are no ScFaultDomain(s) res = self.scapi.find_iscsi_properties(self.VOLUME) mock_find_mappings.assert_called() mock_find_domain.assert_called() mock_find_ctrl_port.assert_called() expected = {'access_mode': 'rw', 'target_discovered': False, 'target_iqns': [], 'target_luns': [], 'target_portals': []} self.assertEqual(expected, res, 'Expected empty Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=ISCSI_CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_domains', return_value=ISCSI_FLT_DOMAINS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=MAPPINGS_READ_ONLY) def test_find_iscsi_properties_ro(self, mock_find_mappings, mock_find_domain, mock_find_ctrl_port, mock_close_connection, mock_open_connection, mock_init): # Test case where Read Only mappings are found res = self.scapi.find_iscsi_properties(self.VOLUME) mock_find_mappings.assert_called() mock_find_domain.assert_called() mock_find_ctrl_port.assert_called() expected = {'access_mode': 'ro', 'target_discovered': False, 'target_iqns': [u'iqn.2002-03.com.compellent:5000d31000fcbe43'], 'target_luns': [1], 'target_portals': [u'192.168.0.21:3260']} self.assertEqual(expected, res, 'Wrong Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_controller_port', return_value=ISCSI_CTRLR_PORT) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_domains', return_value=ISCSI_FLT_DOMAINS_MULTI_PORTALS) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_mappings', return_value=MAPPINGS_MULTI_PORTAL) def test_find_iscsi_properties_multi_portals(self, mock_find_mappings, mock_find_domain, mock_find_ctrl_port, mock_close_connection, mock_open_connection, mock_init): # Test case where there are multiple portals res = self.scapi.find_iscsi_properties(self.VOLUME) mock_find_mappings.assert_called() mock_find_domain.assert_called() mock_find_ctrl_port.assert_called() expected = {'access_mode': 'rw', 'target_discovered': False, 'target_iqns': [u'iqn.2002-03.com.compellent:5000d31000fcbe43'], 'target_luns': [1], 'target_portals': [u'192.168.0.21:3260', u'192.168.0.25:3260']} self.assertEqual(expected, res, 'Wrong Target Info') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=MAP_PROFILE) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_map_volume(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.map_volume(self.VOLUME, self.SCSERVER) mock_post.assert_called() mock_first_result.assert_called() self.assertEqual(self.MAP_PROFILE, res, 'Incorrect ScMappingProfile') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_map_volume_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): # Test case where mapping volume to server fails res = self.scapi.map_volume(self.VOLUME, self.SCSERVER) mock_post.assert_called() self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.HttpClient, 'delete', return_value=RESPONSE_200) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=MAP_PROFILES) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_unmap_volume(self, mock_get, mock_get_json, mock_delete, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.unmap_volume(self.VOLUME, self.SCSERVER) mock_get.assert_called() mock_get_json.assert_called() mock_delete.assert_called() self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_unmap_volume_failure(self, mock_get, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.unmap_volume(self.VOLUME, self.SCSERVER) mock_get.assert_called() self.assertFalse(res, 'Expected False') @mock.patch.object(dell_storagecenter_api.HttpClient, 'delete', return_value=RESPONSE_200) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=[]) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_unmap_volume_no_map_profile(self, mock_get, mock_get_json, mock_delete, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.unmap_volume(self.VOLUME, self.SCSERVER) mock_get.assert_called() mock_get_json.assert_called() mock_delete.assert_called() self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.HttpClient, 'delete', return_value=RESPONSE_204) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=MAP_PROFILES) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_unmap_volume_del_fail(self, mock_get, mock_get_json, mock_delete, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.unmap_volume(self.VOLUME, self.SCSERVER) mock_get.assert_called() mock_get_json.assert_called() mock_delete.assert_called() self.assertFalse(res, 'Expected False') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=STRG_USAGE) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_get_storage_usage(self, mock_get, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.get_storage_usage(64702) mock_get.assert_called() mock_get_json.assert_called() self.assertEqual(self.STRG_USAGE, res, 'Unexpected ScStorageUsage') def test_get_storage_usage_no_ssn(self, mock_close_connection, mock_open_connection, mock_init): # Test case where SSN is none res = self.scapi.get_storage_usage(None) self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) # Test case where get of Storage Usage fails def test_get_storage_usage_failure(self, mock_get, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.get_storage_usage(64702) mock_get.assert_called() self.assertIsNone(res, 'None expected') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=RPLAY) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_create_replay(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_replay(self.VOLUME, 'Test Replay', 60) mock_post.assert_called() mock_first_result.assert_called() self.assertEqual(self.RPLAY, res, 'Unexpected ScReplay') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=RPLAY) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_init_volume') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_create_replay_inact_vol(self, mock_post, mock_init_volume, mock_first_result, mock_close_connection, mock_open_connection, mock_init): # Test case where the specified volume is inactive res = self.scapi.create_replay(self.INACTIVE_VOLUME, 'Test Replay', 60) mock_post.assert_called() mock_init_volume.assert_called_once_with(self.INACTIVE_VOLUME) mock_first_result.assert_called() self.assertEqual(self.RPLAY, res, 'Unexpected ScReplay') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=RPLAY) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_create_replay_no_expire(self, mock_post, mock_first_result, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.create_replay(self.VOLUME, 'Test Replay', 0) mock_post.assert_called() mock_first_result.assert_called() self.assertEqual(self.RPLAY, res, 'Unexpected ScReplay') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_create_replay_no_volume(self, mock_post, mock_close_connection, mock_open_connection, mock_init): # Test case where no ScVolume is specified res = self.scapi.create_replay(None, 'Test Replay', 60) self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_create_replay_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): # Test case where create ScReplay fails res = self.scapi.create_replay(self.VOLUME, 'Test Replay', 60) mock_post.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=RPLAYS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_replay(self, mock_post, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.find_replay(self.VOLUME, u'Cinder Test Replay012345678910') mock_post.assert_called() mock_get_json.assert_called() self.assertEqual(self.TST_RPLAY, res, 'Unexpected ScReplay') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=[]) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_200) def test_find_replay_no_replays(self, mock_post, mock_get_json, mock_close_connection, mock_open_connection, mock_init): # Test case where no replays are found res = self.scapi.find_replay(self.VOLUME, u'Cinder Test Replay012345678910') mock_post.assert_called() mock_get_json.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'get', return_value=RESPONSE_204) def test_find_replay_failure(self, mock_post, mock_get_json, mock_close_connection, mock_open_connection, mock_init): # Test case where None is returned for replays res = self.scapi.find_replay(self.VOLUME, u'Cinder Test Replay012345678910') mock_post.assert_called() mock_get_json.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'find_replay', return_value=RPLAYS) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_delete_replay(self, mock_post, mock_find_replay, mock_close_connection, mock_open_connection, mock_init): replayId = u'Cinder Test Replay012345678910' res = self.scapi.delete_replay(self.VOLUME, replayId) mock_post.assert_called() mock_find_replay.assert_called_once_with(self.VOLUME, replayId) self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'find_replay', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_delete_replay_no_replay(self, mock_post, mock_find_replay, mock_close_connection, mock_open_connection, mock_init): # Test case where specified ScReplay does not exist replayId = u'Cinder Test Replay012345678910' res = self.scapi.delete_replay(self.VOLUME, replayId) mock_post.assert_called() mock_find_replay.assert_called_once_with(self.VOLUME, replayId) self.assertTrue(res, 'Expected True') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'find_replay', return_value=TST_RPLAY) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_delete_replay_failure(self, mock_post, mock_find_replay, mock_close_connection, mock_open_connection, mock_init): # Test case where delete ScReplay results in an error replayId = u'Cinder Test Replay012345678910' res = self.scapi.delete_replay(self.VOLUME, replayId) mock_post.assert_called() mock_find_replay.assert_called_once_with(self.VOLUME, replayId) self.assertFalse(res, 'Expected False') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_create_view_volume(self, mock_post, mock_find_volume_folder, mock_first_result, mock_close_connection, mock_open_connection, mock_init): vol_name = u'Test_create_vol' res = self.scapi.create_view_volume( vol_name, self.configuration.dell_sc_volume_folder, self.TST_RPLAY) mock_post.assert_called() mock_find_volume_folder.assert_called_once_with( 64702, self.configuration.dell_sc_volume_folder) mock_first_result.assert_called() self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_volume_folder_path', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_create_view_volume_create_fldr(self, mock_post, mock_find_volume_folder, mock_create_volume_folder, mock_first_result, mock_close_connection, mock_open_connection, mock_init): # Test case where volume folder does not exist and must be created vol_name = u'Test_create_vol' res = self.scapi.create_view_volume( vol_name, self.configuration.dell_sc_volume_folder, self.TST_RPLAY) mock_post.assert_called() mock_find_volume_folder.assert_called_once_with( 64702, self.configuration.dell_sc_volume_folder) mock_create_volume_folder.assert_called_once_with( 64702, self.configuration.dell_sc_volume_folder) mock_first_result.assert_called() self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_first_result', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_create_volume_folder_path', return_value=None) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=None) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_create_view_volume_no_vol_fldr(self, mock_post, mock_find_volume_folder, mock_create_volume_folder, mock_first_result, mock_close_connection, mock_open_connection, mock_init): # Test case where volume folder does not exist and cannot be created vol_name = u'Test_create_vol' res = self.scapi.create_view_volume( vol_name, self.configuration.dell_sc_volume_folder, self.TST_RPLAY) mock_post.assert_called() mock_find_volume_folder.assert_called_once_with( 64702, self.configuration.dell_sc_volume_folder) mock_create_volume_folder.assert_called_once_with( 64702, self.configuration.dell_sc_volume_folder) mock_first_result.assert_called() self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_find_volume_folder', return_value=FLDR) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_create_view_volume_failure(self, mock_post, mock_find_volume_folder, mock_close_connection, mock_open_connection, mock_init): # Test case where view volume create fails vol_name = u'Test_create_vol' res = self.scapi.create_view_volume( vol_name, self.configuration.dell_sc_volume_folder, self.TST_RPLAY) mock_post.assert_called() mock_find_volume_folder.assert_called_once_with( 64702, self.configuration.dell_sc_volume_folder) self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'create_view_volume', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'create_replay', return_value=RPLAY) def test_create_cloned_volume(self, mock_create_replay, mock_create_view_volume, mock_close_connection, mock_open_connection, mock_init): vol_name = u'Test_create_clone_vol' res = self.scapi.create_cloned_volume( vol_name, self.configuration.dell_sc_volume_folder, self.VOLUME) mock_create_replay.assert_called_once_with(self.VOLUME, 'Cinder Clone Replay', 60) mock_create_view_volume.assert_called_once_with( vol_name, self.configuration.dell_sc_volume_folder, self.RPLAY) self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, 'create_replay', return_value=None) def test_create_cloned_volume_failure(self, mock_create_replay, mock_close_connection, mock_open_connection, mock_init): # Test case where create cloned volumes fails because create_replay # fails vol_name = u'Test_create_clone_vol' res = self.scapi.create_cloned_volume( vol_name, self.configuration.dell_sc_volume_folder, self.VOLUME) mock_create_replay.assert_called_once_with(self.VOLUME, 'Cinder Clone Replay', 60) self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.StorageCenterApi, '_get_json', return_value=VOLUME) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_expand_volume(self, mock_post, mock_get_json, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.expand_volume(self.VOLUME, 550) mock_post.assert_called() mock_get_json.assert_called() self.assertEqual(self.VOLUME, res, 'Unexpected ScVolume') @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_expand_volume_failure(self, mock_post, mock_close_connection, mock_open_connection, mock_init): res = self.scapi.expand_volume(self.VOLUME, 550) mock_post.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.HttpClient, 'delete', return_value=RESPONSE_200) def test_delete_server(self, mock_delete, mock_close_connection, mock_open_connection, mock_init): res = self.scapi._delete_server(self.SCSERVER) mock_delete.assert_called() self.assertIsNone(res, 'Expected None') @mock.patch.object(dell_storagecenter_api.HttpClient, 'delete', return_value=RESPONSE_200) def test_delete_server_del_not_allowed(self, mock_delete, mock_close_connection, mock_open_connection, mock_init): # Test case where delete of ScServer not allowed res = self.scapi._delete_server(self.SCSERVER_NO_DEL) mock_delete.assert_called() self.assertIsNone(res, 'Expected None') class DellSCSanAPIConnectionTestCase(test.TestCase): '''DellSCSanAPIConnectionTestCase Class to test the Storage Center API connection using Mock. ''' # Create a Response object that indicates OK response_ok = models.Response() response_ok.status_code = 200 response_ok.reason = u'ok' RESPONSE_200 = response_ok # Create a Response object that indicates a failure (no content) response_nc = models.Response() response_nc.status_code = 204 response_nc.reason = u'duplicate' RESPONSE_204 = response_nc def setUp(self): super(DellSCSanAPIConnectionTestCase, self).setUp() # Configuration is a mock. A mock is pretty much a blank # slate. I believe mock's done in setup are not happy time # mocks. So we just do a few things like driver config here. self.configuration = mock.Mock() self.configuration.san_is_local = False self.configuration.san_ip = "192.168.0.1" self.configuration.san_login = "admin" self.configuration.san_password = "mmm" self.configuration.dell_sc_ssn = 12345 self.configuration.dell_sc_server_folder = 'opnstktst' self.configuration.dell_sc_volume_folder = 'opnstktst' self.configuration.dell_sc_api_port = 3033 self.configuration.iscsi_ip_address = '192.168.1.1' self.configuration.iscsi_port = 3260 self._context = context.get_admin_context() # Set up the StorageCenterApi self.scapi = dell_storagecenter_api.StorageCenterApi( self.configuration.san_ip, self.configuration.dell_sc_api_port, self.configuration.san_login, self.configuration.san_password) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_open_connection(self, mock_post): self.scapi.open_connection() mock_post.assert_called() @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_open_connection_failure(self, mock_post): self.assertRaises(exception.VolumeBackendAPIException, self.scapi.open_connection) @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_204) def test_close_connection(self, mock_post): self.scapi.close_connection() mock_post.assert_called() @mock.patch.object(dell_storagecenter_api.HttpClient, 'post', return_value=RESPONSE_200) def test_close_connection_failure(self, mock_post): self.scapi.close_connection() mock_post.assert_called()
Akrog/cinder
cinder/tests/test_dellscapi.py
Python
apache-2.0
155,946
import click @click.command('config', short_help='Display remote client config') @click.pass_obj def cli(obj): """Display client config downloaded from API server.""" for k, v in obj.items(): if isinstance(v, list): v = ', '.join(v) click.echo(f'{k:20}: {v}')
alerta/python-alerta-client
alertaclient/commands/cmd_config.py
Python
apache-2.0
298
<?php /** * Admin user suggestion page * * @see, controllers/admin/user_suggestion.php */ ?> <script type="text/javascript"> jQuery(function($){ $(document).ready(function(){ }); }); </script> <?php /* <div id="right_panel"> <h2><?php echo $page_title;?></h2> <div id="accountlist"> <div> <form id="filter" action="" method="post"> <label>user suggestion : </label> <input id="s_suggestion" name="s_suggestion" value="<?=@$posted["s_suggestion"];?>"> <label>Type :</label><?=form_dropdown("e_type",dd_user_suggestion_type(),@$posted["e_type"],'id="e_type"');?> <input type="submit" name="submit" value="Submit">&nbsp;<input type="reset" name="reset" value="Reset"> &nbsp;<input type="submit" name="all" value="Show All"> </form> </div> <h4><?=$add_link;?></h4> <div><?=$table;?></div> <div><?=$pager;?></div> </div> </div> */?> <div id="listing" class="widget"> <div class="whead"><h6><?php echo $page_title;?></h6></div> <div id="dyn2" class="shownpars"> <a class="tOptions act" title="Options"><img src="<?=base_url(get_theme_path())."/";?>images/icons/options" alt="" /></a> <div id="DataTables_Table_0_wrapper" class="dataTables_wrapper" role="grid"> <div class="tablePars"> <div class="dataTables_filter" id="DataTables_Table_0_filter"> <form id="filter" action="" method="post"> <label>User suggestion : <input type="text" id="s_suggestion" name="s_suggestion" value="<?=@$posted["s_suggestion"];?>"> <? /*<label>Type : <?=form_dropdown("e_type",dd_user_suggestion_type(),@$posted["e_type"],'id="e_type"');?>*/ ?> <input type="submit" name="submit" value="Submit">&nbsp;<input type="reset" name="reset" value="Reset"> &nbsp;<input type="submit" name="all" value="Show All"> </label> </form> </div> <?php /*<div id="DataTables_Table_0_length" class="dataTables_length"><label><?=$add_link;?></label></div> */?> </div> <?=$table;?> </div> </div> </div>
mrinsss/Full-Repo
guru/application/views/admin/user_suggestion/index.tpl.php
PHP
apache-2.0
2,121
# Xerotes juncea F.Muell. 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/Asparagaceae/Lomandra/Lomandra juncea/ Syn. Xerotes juncea/README.md
Markdown
apache-2.0
180
# Nepenthes phyllamphora var. macrantha Hook.f. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Nepenthaceae/Nepenthes/Nepenthes mirabilis/Nepenthes phyllamphora macrantha/README.md
Markdown
apache-2.0
195
# Diaporthe fuegiana Speg. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Boletín de la Academia Nacional de Ciencias de Córdoba 11(2): 213 (1888) #### Original name Diaporthe fuegiana Speg. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Diaporthaceae/Diaporthe/Diaporthe fuegiana/README.md
Markdown
apache-2.0
247
# Indigofera longibractea J.M.Black SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Indigofera/Indigofera longibractea/README.md
Markdown
apache-2.0
183
# Delitschia spiralirima Jeng, Luck-Allen & Cain SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Can. J. Bot. 55(4): 388 (1977) #### Original name Delitschia spiralirima Jeng, Luck-Allen & Cain ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Delitschiaceae/Delitschia/Delitschia spiralirima/README.md
Markdown
apache-2.0
247
# Rubus floribundus var. nimbatus J.F.Macbr. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rubus/Rubus floribundus/Rubus floribundus nimbatus/README.md
Markdown
apache-2.0
192
# Potentilla jacquemontii (Franch.) Soják SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Potentilla/Potentilla jacquemontii/README.md
Markdown
apache-2.0
190
package ca.waterloo.dsg.graphflow.query.parser; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.atn.ATNConfigSet; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.ParseCancellationException; import java.util.BitSet; /** * This class is used to throw parse exceptions. */ public class ErrorListener extends BaseErrorListener { public static final ErrorListener INSTANCE = new ErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException { throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg); } @Override public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, ATNConfigSet configs) throws ParseCancellationException { throw new ParseCancellationException("Ambiguity Exception startIndex:stopIndex=" + startIndex + ":" + stopIndex); } @Override public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, ATNConfigSet configs) throws ParseCancellationException { throw new ParseCancellationException("AttemptingFullContext Exception " + "startIndex:stopIndex=" + startIndex + ":" + stopIndex); } @Override public void reportContextSensitivity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, int prediction, ATNConfigSet configs) throws ParseCancellationException { throw new ParseCancellationException("ContextSensitivity Exception startIndex:stopIndex=" + startIndex + ":" + stopIndex); } }
graphflow/graphflow
src/main/java/ca/waterloo/dsg/graphflow/query/parser/ErrorListener.java
Java
apache-2.0
1,951
/* * Copyright 2016-2018 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 org.example.api; import griffon.annotations.core.Nonnull; import griffon.annotations.core.Nullable; import java.util.regex.Matcher; import java.util.regex.Pattern; import static griffon.util.GriffonNameUtils.isNotBlank; public class Links { private static final Pattern REL_PATTERN = Pattern.compile("rel=\"(.*)\""); private String first; private String next; private String prev; private String last; public static Links of(@Nonnull String input) { return new Links(input); } private Links(@Nonnull String input) { if (isNotBlank(input)) { for (String s : input.split(",")) { String[] parts = s.split(";"); Matcher matcher = REL_PATTERN.matcher(parts[1].trim()); if (matcher.matches()) { switch (matcher.group(1).toLowerCase()) { case "first": first = normalize(parts[0]); break; case "next": next = normalize(parts[0]); break; case "prev": prev = normalize(parts[0]); break; case "last": last = normalize(parts[0]); break; } } } } } private String normalize(String url) { url = url.trim(); if (url.startsWith("<") && url.endsWith(">")) { url = url.substring(1, url.length() - 1); } return url; } public boolean hasFirst() { return isNotBlank(first); } public boolean hasNext() { return isNotBlank(next); } public boolean hasPrev() { return isNotBlank(prev); } public boolean hasLast() { return isNotBlank(last); } @Nullable public String first() { return first; } @Nullable public String next() { return next; } @Nullable public String prev() { return prev; } @Nullable public String last() { return last; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Links{"); sb.append("first='").append(first).append('\''); sb.append(", next='").append(next).append('\''); sb.append(", prev='").append(prev).append('\''); sb.append(", last='").append(last).append('\''); sb.append('}'); return sb.toString(); } }
griffon/griffon
tutorials/reactive/src/main/java/org/example/api/Links.java
Java
apache-2.0
3,255
/** * @require common:widget/jquery/jqueryEx.js * @require common:widget/utils/underscore.js * @require common:widget/dhtmlxSuite/dhtmlxEx.js */ $(window).resize(function() { GPW.layout.mainLayout.setSizes(); }); var GPC = { url:{ refreshGridUrl:GLOBAL.S.URL+GLOBAL.P.MODULES+"/a/resLoadRole?_value="+GLOBAL.P.value, queryUrl:GLOBAL.S.URL+GLOBAL.P.MODULES+"/a/resQueryRole?_value="+GLOBAL.P.value, updateUrl:GLOBAL.S.URL+GLOBAL.P.MODULES+"/a/updateResourceRole/Roles?format=xml&_value="+GLOBAL.P.value }, constant:{add:"add",edit:"edit",delect:"delect",query:"query", update:"update",detailQuery:"detailQuery",between:"between"} } var GPW = { layout : {}, toolbar : {}, grid : {} }; GPW.layout = { mainLayout : {}, mainGridLayout:{}, init : function() { this.mainLayout = new dhtmlXLayoutObject("layoutObj", "1C"); this.mainGridLayout=this.mainLayout.cells("a"); this.mainGridLayout.hideHeader(); } } GPW.grid = { mainGrid : {}, gridDataProcessor : {}, init : function() { this.mainGrid = GPW.layout.mainGridLayout.attachGrid(); this.mainGrid.setImagePath(GLOBAL.IconsPath); this.mainGrid.setHeader("角色编码,角色名称,授权名称"); this.mainGrid.setColumnIds("name,alias,permissionStr"); this.mainGrid.setInitWidths("120,120,*"); this.mainGrid.setColAlign("left,left,left"); this.mainGrid.setColTypes("ro,ro,clist"); this.mainGrid.setColSorting("str,str,str"); this.mainGrid.registerCList(2,GLOBAL.P.P_PERMISSION); var pagingContainer="<div id='recinfoArea' /><div id='pagingArea' style='border:none;'/>"; var statusBar=GPW.layout.mainGridLayout.attachStatusBar({height: 28}); statusBar.setText(pagingContainer); this.mainGrid.enablePaging(true,20,5,"pagingArea",true,"recInfoArea"); this.mainGrid.setPagingSkin("toolbar", "dhx_skyblue"); //this.mainGrid.enableAutoWidth(true) this.mainGrid.i18n.paging=GLOBAL.paging; this.mainGrid.init(); this.mainGrid.attachEvent("onValidationError", function(id,index,value,rule){ parent.dhtmlx.message({ type:"error", expire: -1, text:"校验错误:"+GPW.grid.mainGrid.getColLabel(index)+","+GLOBAL.validText(rule)+",字段值不能为["+value+"]!"}); }); this.gridDataProcessor = new dataProcessor(GPC.url.updateUrl); //lock feed url //this.gridDataProcessor.setTransactionMode("POST",false); //set mode as send-all-by-post this.gridDataProcessor.setTransactionMode("REST"); this.gridDataProcessor.setUpdateMode("off"); //disable auto-update this.gridDataProcessor.enableDataNames(true); //只发送更改的项目 this.gridDataProcessor.enablePartialDataSend(true); this.gridDataProcessor.init(this.mainGrid); //link dataprocessor to the grid this.gridDataProcessor.attachEvent("onBeforeDataSending", function(id, state, data){ //去除Data数据的发送 _.each(data,function (v, k, value) { if(!!v.data){ v.data=null; delete v.data; } }); return true; }); this.gridDataProcessor.attachEvent("onAfterUpdate", function(id, action, tid, element){ if(element instanceof Element){ if(element.getElementsByTagName("code").item(0)!=null){ var code=element.getElementsByTagName("code").item(0).childNodes[0].nodeValue; var message=element.getElementsByTagName("message").item(0).childNodes[0].nodeValue; if(code==-1){ parent.dhtmlx.message({ type:"error", expire: -1, text:message}); } } } }); this.refreshMainGrid(); }, sendGridData : function(){ this.gridDataProcessor.sendData(); }, refreshMainGrid : function(url) { if(!url){ url=GPC.url.refreshGridUrl; } this.mainGrid.clearAll(); this.mainGrid.load(url,"js"); } } GPW.toolbar = { mainToolbar : {}, init : function() { this.mainToolbar=GPW.layout.mainGridLayout.attachToolbar(); var toolbar = this.mainToolbar; toolbar.setIconsPath(GLOBAL.IconsPath); toolbar.addText("text_select", 0, "选"); this.mainToolbar.addSelectEx("queryName", 1, [{"text":"编码","value":"name"},{"text":"名称","value":"alias"}], 100); toolbar.addInput("queryValue", 3, "", 200); toolbar.addButton("query", 9, "查询", "new.gif", "new_dis.gif"); toolbar.addSeparator("sep1", 10); toolbar.addButton("update", 16, "更新", "new.gif", "new_dis.gif"); this.mainToolbarClick(); }, mainToolbarClick:function(){ this.mainToolbar.attachEvent("onClick", function(id) { switch(id) { case GPC.constant.query: var toolbar = GPW.toolbar.mainToolbar; var where = toolbar.getInput("queryName").value; var queryValue = toolbar.getInput("queryValue").value; var url=GPC.url.queryUrl+"&where="+encodeURI(where)+"&whereValue="+encodeURI(queryValue); GPW.grid.refreshMainGrid(url); break; case GPC.constant.update: GPW.grid.sendGridData(); break; default: } }); } }//end GPW.toolbar $(function() { GPW.layout.init(); GPW.grid.init(); GPW.toolbar.init(); });
LittleLazyCat/TXEYXXK
2017workspace/go-public/go-show/src/main/webapp/WEB-INF/core/scripts/resourceRole.js
JavaScript
apache-2.0
5,019
// Copyright (c) 2017 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vppcalls import ( "errors" "net" l2ba "github.com/ligato/vpp-agent/plugins/vpp/binapi/l2" l2nb "github.com/ligato/vpp-agent/plugins/vppv2/model/l2" ) // AddL2FIB creates L2 FIB table entry. func (h *FIBVppHandler) AddL2FIB(fib *l2nb.FIBEntry) error { return h.l2fibAddDel(fib, true) } // DeleteL2FIB removes existing L2 FIB table entry. func (h *FIBVppHandler) DeleteL2FIB(fib *l2nb.FIBEntry) error { return h.l2fibAddDel(fib, false) } func (h *FIBVppHandler) l2fibAddDel(fib *l2nb.FIBEntry, isAdd bool) (err error) { // get bridge domain metadata bdMeta, found := h.bdIndexes.LookupByName(fib.BridgeDomain) if !found { return errors.New("failed to get bridge domain metadata") } // get outgoing interface index swIfIndex := ^uint32(0) // ~0 is used by DROP entries if fib.Action == l2nb.FIBEntry_FORWARD { ifaceMeta, found := h.ifIndexes.LookupByName(fib.OutgoingInterface) if !found { return errors.New("failed to get interface metadata") } swIfIndex = ifaceMeta.GetIndex() } // parse MAC address var mac []byte if fib.PhysAddress != "" { mac, err = net.ParseMAC(fib.PhysAddress) if err != nil { return err } } // add L2 FIB req := &l2ba.L2fibAddDel{ IsAdd: boolToUint(isAdd), Mac: mac, BdID: bdMeta.GetIndex(), SwIfIndex: swIfIndex, BviMac: boolToUint(fib.BridgedVirtualInterface), StaticMac: boolToUint(fib.StaticConfig), FilterMac: boolToUint(fib.Action == l2nb.FIBEntry_DROP), } reply := &l2ba.L2fibAddDelReply{} if err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil { return err } return nil }
milanlenco/vpp-1
vendor/github.com/ligato/vpp-agent/plugins/vppv2/l2plugin/vppcalls/l2fib_vppcalls.go
GO
apache-2.0
2,231
# DemoTiles A playground for tile based UI designs ## Animated responsive design Built following seeing a website with an animated responsive design. Created using Isotope, MetroUI and CSS transforms for the hover tilt effect.
jonathanody/DemoTiles
README.md
Markdown
apache-2.0
229
/* Copyright 2017 Vector Creations Ltd. Copyright 2017, 2018 New Vector Ltd. Copyright 2019 The Matrix.org Foundation C.I.C. 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 React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { Group } from "matrix-js-sdk/src/models/group"; import { sleep } from "matrix-js-sdk/src/utils"; import { logger } from "matrix-js-sdk/src/logger"; import { MatrixClientPeg } from '../../MatrixClientPeg'; import * as sdk from '../../index'; import dis from '../../dispatcher/dispatcher'; import { getHostingLink } from '../../utils/HostingLink'; import { sanitizedHtmlNode } from '../../HtmlUtils'; import { _t, _td } from '../../languageHandler'; import AccessibleButton from '../views/elements/AccessibleButton'; import GroupHeaderButtons from '../views/right_panel/GroupHeaderButtons'; import MainSplit from './MainSplit'; import RightPanel from './RightPanel'; import Modal from '../../Modal'; import GroupStore from '../../stores/GroupStore'; import FlairStore from '../../stores/FlairStore'; import { showGroupAddRoomDialog } from '../../GroupAddressPicker'; import { makeGroupPermalink, makeUserPermalink } from "../../utils/permalinks/Permalinks"; import RightPanelStore from "../../stores/right-panel/RightPanelStore"; import AutoHideScrollbar from "./AutoHideScrollbar"; import { mediaFromMxc } from "../../customisations/Media"; import { replaceableComponent } from "../../utils/replaceableComponent"; import { createSpaceFromCommunity } from "../../utils/space"; import { Action } from "../../dispatcher/actions"; import { RightPanelPhases } from "../../stores/right-panel/RightPanelStorePhases"; import { UPDATE_EVENT } from "../../stores/AsyncStore"; const LONG_DESC_PLACEHOLDER = _td( `<h1>HTML for your community's page</h1> <p> Use the long description to introduce new members to the community, or distribute some important <a href="foo">links</a> </p> <p> You can even add images with Matrix URLs <img src="mxc://url" /> </p> `); const RoomSummaryType = PropTypes.shape({ room_id: PropTypes.string.isRequired, profile: PropTypes.shape({ name: PropTypes.string, avatar_url: PropTypes.string, canonical_alias: PropTypes.string, }).isRequired, }); const UserSummaryType = PropTypes.shape({ summaryInfo: PropTypes.shape({ user_id: PropTypes.string.isRequired, role_id: PropTypes.string, avatar_url: PropTypes.string, displayname: PropTypes.string, }).isRequired, }); class CategoryRoomList extends React.Component { static propTypes = { rooms: PropTypes.arrayOf(RoomSummaryType).isRequired, category: PropTypes.shape({ profile: PropTypes.shape({ name: PropTypes.string, }).isRequired, }), groupId: PropTypes.string.isRequired, // Whether the list should be editable editing: PropTypes.bool.isRequired, }; onAddRoomsToSummaryClicked = (ev) => { ev.preventDefault(); const AddressPickerDialog = sdk.getComponent("dialogs.AddressPickerDialog"); Modal.createTrackedDialog('Add Rooms to Group Summary', '', AddressPickerDialog, { title: _t('Add rooms to the community summary'), description: _t("Which rooms would you like to add to this summary?"), placeholder: _t("Room name or address"), button: _t("Add to summary"), pickerType: 'room', validAddressTypes: ['mx-room-id'], groupId: this.props.groupId, onFinished: (success, addrs) => { if (!success) return; const errorList = []; Promise.allSettled(addrs.map((addr) => { return GroupStore .addRoomToGroupSummary(this.props.groupId, addr.address) .catch(() => { errorList.push(addr.address); }); })).then(() => { if (errorList.length === 0) { return; } const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog( 'Failed to add the following room to the group summary', '', ErrorDialog, { title: _t( "Failed to add the following rooms to the summary of %(groupId)s:", { groupId: this.props.groupId }, ), description: errorList.join(", "), }, ); }); }, }, /*className=*/null, /*isPriority=*/false, /*isStatic=*/true); }; render() { const addButton = this.props.editing ? (<AccessibleButton className="mx_GroupView_featuredThings_addButton" onClick={this.onAddRoomsToSummaryClicked} > <img src={require("../../../res/img/icons-create-room.svg").default} width="64" height="64" /> <div className="mx_GroupView_featuredThings_addButton_label"> { _t('Add a Room') } </div> </AccessibleButton>) : <div />; const roomNodes = this.props.rooms.map((r) => { return <FeaturedRoom key={r.room_id} groupId={this.props.groupId} editing={this.props.editing} summaryInfo={r} />; }); let catHeader = <div />; if (this.props.category && this.props.category.profile) { catHeader = <div className="mx_GroupView_featuredThings_category"> { this.props.category.profile.name } </div>; } return <div className="mx_GroupView_featuredThings_container"> { catHeader } { roomNodes } { addButton } </div>; } } class FeaturedRoom extends React.Component { static propTypes = { summaryInfo: RoomSummaryType.isRequired, editing: PropTypes.bool.isRequired, groupId: PropTypes.string.isRequired, }; onClick = (e) => { e.preventDefault(); e.stopPropagation(); dis.dispatch({ action: Action.ViewRoom, room_alias: this.props.summaryInfo.profile.canonical_alias, room_id: this.props.summaryInfo.room_id, }); }; onDeleteClicked = (e) => { e.preventDefault(); e.stopPropagation(); GroupStore.removeRoomFromGroupSummary( this.props.groupId, this.props.summaryInfo.room_id, ).catch((err) => { logger.error('Error whilst removing room from group summary', err); const roomName = this.props.summaryInfo.name || this.props.summaryInfo.canonical_alias || this.props.summaryInfo.room_id; const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog( 'Failed to remove room from group summary', '', ErrorDialog, { title: _t( "Failed to remove the room from the summary of %(groupId)s", { groupId: this.props.groupId }, ), description: _t("The room '%(roomName)s' could not be removed from the summary.", { roomName }), }, ); }); }; render() { const RoomAvatar = sdk.getComponent("avatars.RoomAvatar"); const roomName = this.props.summaryInfo.profile.name || this.props.summaryInfo.profile.canonical_alias || _t("Unnamed Room"); const oobData = { roomId: this.props.summaryInfo.room_id, avatarUrl: this.props.summaryInfo.profile.avatar_url, name: roomName, }; let permalink = null; if (this.props.summaryInfo.profile && this.props.summaryInfo.profile.canonical_alias) { permalink = makeGroupPermalink(this.props.summaryInfo.profile.canonical_alias); } let roomNameNode = null; if (permalink) { roomNameNode = <a href={permalink} onClick={this.onClick}>{ roomName }</a>; } else { roomNameNode = <span>{ roomName }</span>; } const deleteButton = this.props.editing ? <img className="mx_GroupView_featuredThing_deleteButton" src={require("../../../res/img/cancel-small.svg").default} width="14" height="14" alt="Delete" onClick={this.onDeleteClicked} /> : <div />; return <AccessibleButton className="mx_GroupView_featuredThing" onClick={this.onClick}> <RoomAvatar oobData={oobData} width={64} height={64} /> <div className="mx_GroupView_featuredThing_name">{ roomNameNode }</div> { deleteButton } </AccessibleButton>; } } class RoleUserList extends React.Component { static propTypes = { users: PropTypes.arrayOf(UserSummaryType).isRequired, role: PropTypes.shape({ profile: PropTypes.shape({ name: PropTypes.string, }).isRequired, }), groupId: PropTypes.string.isRequired, // Whether the list should be editable editing: PropTypes.bool.isRequired, }; onAddUsersClicked = (ev) => { ev.preventDefault(); const AddressPickerDialog = sdk.getComponent("dialogs.AddressPickerDialog"); Modal.createTrackedDialog('Add Users to Group Summary', '', AddressPickerDialog, { title: _t('Add users to the community summary'), description: _t("Who would you like to add to this summary?"), placeholder: _t("Name or Matrix ID"), button: _t("Add to summary"), validAddressTypes: ['mx-user-id'], groupId: this.props.groupId, shouldOmitSelf: false, onFinished: (success, addrs) => { if (!success) return; const errorList = []; Promise.allSettled(addrs.map((addr) => { return GroupStore .addUserToGroupSummary(addr.address) .catch(() => { errorList.push(addr.address); }); })).then(() => { if (errorList.length === 0) { return; } const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog( 'Failed to add the following users to the community summary', '', ErrorDialog, { title: _t( "Failed to add the following users to the summary of %(groupId)s:", { groupId: this.props.groupId }, ), description: errorList.join(", "), }, ); }); }, }, /*className=*/null, /*isPriority=*/false, /*isStatic=*/true); }; render() { const addButton = this.props.editing ? (<AccessibleButton className="mx_GroupView_featuredThings_addButton" onClick={this.onAddUsersClicked}> <img src={require("../../../res/img/icons-create-room.svg").default} width="64" height="64" /> <div className="mx_GroupView_featuredThings_addButton_label"> { _t('Add a User') } </div> </AccessibleButton>) : <div />; const userNodes = this.props.users.map((u) => { return <FeaturedUser key={u.user_id} summaryInfo={u} editing={this.props.editing} groupId={this.props.groupId} />; }); let roleHeader = <div />; if (this.props.role && this.props.role.profile) { roleHeader = <div className="mx_GroupView_featuredThings_category">{ this.props.role.profile.name }</div>; } return <div className="mx_GroupView_featuredThings_container"> { roleHeader } { userNodes } { addButton } </div>; } } class FeaturedUser extends React.Component { static propTypes = { summaryInfo: UserSummaryType.isRequired, editing: PropTypes.bool.isRequired, groupId: PropTypes.string.isRequired, }; onClick = (e) => { e.preventDefault(); e.stopPropagation(); dis.dispatch({ action: Action.ViewStartChatOrReuse, user_id: this.props.summaryInfo.user_id, }); }; onDeleteClicked = (e) => { e.preventDefault(); e.stopPropagation(); GroupStore.removeUserFromGroupSummary( this.props.groupId, this.props.summaryInfo.user_id, ).catch((err) => { logger.error('Error whilst removing user from group summary', err); const displayName = this.props.summaryInfo.displayname || this.props.summaryInfo.user_id; const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog( 'Failed to remove user from community summary', '', ErrorDialog, { title: _t( "Failed to remove a user from the summary of %(groupId)s", { groupId: this.props.groupId }, ), description: _t( "The user '%(displayName)s' could not be removed from the summary.", { displayName }, ), }, ); }); }; render() { const BaseAvatar = sdk.getComponent("avatars.BaseAvatar"); const name = this.props.summaryInfo.displayname || this.props.summaryInfo.user_id; const permalink = makeUserPermalink(this.props.summaryInfo.user_id); const userNameNode = <a href={permalink} onClick={this.onClick}>{ name }</a>; const httpUrl = mediaFromMxc(this.props.summaryInfo.avatar_url).getSquareThumbnailHttp(64); const deleteButton = this.props.editing ? <img className="mx_GroupView_featuredThing_deleteButton" src={require("../../../res/img/cancel-small.svg").default} width="14" height="14" alt="Delete" onClick={this.onDeleteClicked} /> : <div />; return <AccessibleButton className="mx_GroupView_featuredThing" onClick={this.onClick}> <BaseAvatar name={name} url={httpUrl} width={64} height={64} /> <div className="mx_GroupView_featuredThing_name">{ userNameNode }</div> { deleteButton } </AccessibleButton>; } } const GROUP_JOINPOLICY_OPEN = "open"; const GROUP_JOINPOLICY_INVITE = "invite"; const UPGRADE_NOTICE_LS_KEY = "mx_hide_community_upgrade_notice"; @replaceableComponent("structures.GroupView") export default class GroupView extends React.Component { static propTypes = { groupId: PropTypes.string.isRequired, // Whether this is the first time the group admin is viewing the group groupIsNew: PropTypes.bool, }; state = { summary: null, isGroupPublicised: null, isUserPrivileged: null, groupRooms: null, groupRoomsLoading: null, error: null, editing: false, saving: false, uploadingAvatar: false, avatarChanged: false, membershipBusy: false, publicityBusy: false, inviterProfile: null, showRightPanel: RightPanelStore.instance.isOpenForGroup, showUpgradeNotice: !localStorage.getItem(UPGRADE_NOTICE_LS_KEY), }; componentDidMount() { this._unmounted = false; this._matrixClient = MatrixClientPeg.get(); this._matrixClient.on("Group.myMembership", this._onGroupMyMembership); this._initGroupStore(this.props.groupId, true); this._dispatcherRef = dis.register(this._onAction); RightPanelStore.instance.on(UPDATE_EVENT, this._onRightPanelStoreUpdate); } componentWillUnmount() { this._unmounted = true; this._matrixClient.removeListener("Group.myMembership", this._onGroupMyMembership); dis.unregister(this._dispatcherRef); RightPanelStore.instance.off(UPDATE_EVENT, this._onRightPanelStoreUpdate); } // TODO: [REACT-WARNING] Replace with appropriate lifecycle event // eslint-disable-next-line camelcase UNSAFE_componentWillReceiveProps(newProps) { if (this.props.groupId !== newProps.groupId) { this.setState({ summary: null, error: null, }, () => { this._initGroupStore(newProps.groupId); }); } } _onRightPanelStoreUpdate = () => { this.setState({ showRightPanel: RightPanelStore.instance.isOpenForGroup, }); }; _onGroupMyMembership = (group) => { if (this._unmounted || group.groupId !== this.props.groupId) return; if (group.myMembership === 'leave') { // Leave settings - the user might have clicked the "Leave" button this._closeSettings(); } this.setState({ membershipBusy: false }); }; _initGroupStore(groupId, firstInit) { const group = this._matrixClient.getGroup(groupId); if (group && group.inviter && group.inviter.userId) { this._fetchInviterProfile(group.inviter.userId); } GroupStore.registerListener(groupId, this.onGroupStoreUpdated.bind(this, firstInit)); let willDoOnboarding = false; // XXX: This should be more fluxy - let's get the error from GroupStore .getError or something GroupStore.on('error', (err, errorGroupId, stateKey) => { if (this._unmounted || groupId !== errorGroupId) return; if (err.errcode === 'M_GUEST_ACCESS_FORBIDDEN' && !willDoOnboarding) { dis.dispatch({ action: Action.DoAfterSyncPrepared, deferred_action: { action: 'view_group', group_id: groupId, }, }); dis.dispatch({ action: 'require_registration', screen_after: { screen: `group/${groupId}` } }); willDoOnboarding = true; } if (stateKey === GroupStore.STATE_KEY.Summary) { this.setState({ summary: null, error: err, editing: false, }); } }); } onGroupStoreUpdated = (firstInit) => { if (this._unmounted) return; const summary = GroupStore.getSummary(this.props.groupId); if (summary.profile) { // Default profile fields should be "" for later sending to the server (which // requires that the fields are strings, not null) ["avatar_url", "long_description", "name", "short_description"].forEach((k) => { summary.profile[k] = summary.profile[k] || ""; }); } this.setState({ summary, summaryLoading: !GroupStore.isStateReady(this.props.groupId, GroupStore.STATE_KEY.Summary), isGroupPublicised: GroupStore.getGroupPublicity(this.props.groupId), isUserPrivileged: GroupStore.isUserPrivileged(this.props.groupId), groupRooms: GroupStore.getGroupRooms(this.props.groupId), groupRoomsLoading: !GroupStore.isStateReady(this.props.groupId, GroupStore.STATE_KEY.GroupRooms), isUserMember: GroupStore.getGroupMembers(this.props.groupId).some( (m) => m.userId === this._matrixClient.credentials.userId, ), }); // XXX: This might not work but this.props.groupIsNew unused anyway if (this.props.groupIsNew && firstInit) { this._onEditClick(); } }; _fetchInviterProfile(userId) { this.setState({ inviterProfileBusy: true, }); this._matrixClient.getProfileInfo(userId).then((resp) => { if (this._unmounted) return; this.setState({ inviterProfile: { avatarUrl: resp.avatar_url, displayName: resp.displayname, }, }); }).catch((e) => { logger.error('Error getting group inviter profile', e); }).finally(() => { if (this._unmounted) return; this.setState({ inviterProfileBusy: false, }); }); } _onEditClick = () => { this.setState({ editing: true, profileForm: Object.assign({}, this.state.summary.profile), joinableForm: { policyType: this.state.summary.profile.is_openly_joinable ? GROUP_JOINPOLICY_OPEN : GROUP_JOINPOLICY_INVITE, }, }); }; _onShareClick = () => { const ShareDialog = sdk.getComponent("dialogs.ShareDialog"); Modal.createTrackedDialog('share community dialog', '', ShareDialog, { target: this._matrixClient.getGroup(this.props.groupId) || new Group(this.props.groupId), }); }; _onCancelClick = () => { this._closeSettings(); }; _onAction = (payload) => { switch (payload.action) { // NOTE: close_settings is an app-wide dispatch; as it is dispatched from MatrixChat case 'close_settings': this.setState({ editing: false, profileForm: null, }); break; default: break; } }; _closeSettings = () => { dis.dispatch({ action: 'close_settings' }); }; _onNameChange = (value) => { const newProfileForm = Object.assign(this.state.profileForm, { name: value }); this.setState({ profileForm: newProfileForm, }); }; _onShortDescChange = (value) => { const newProfileForm = Object.assign(this.state.profileForm, { short_description: value }); this.setState({ profileForm: newProfileForm, }); }; _onLongDescChange = (e) => { const newProfileForm = Object.assign(this.state.profileForm, { long_description: e.target.value }); this.setState({ profileForm: newProfileForm, }); }; _onAvatarSelected = ev => { const file = ev.target.files[0]; if (!file) return; this.setState({ uploadingAvatar: true }); this._matrixClient.uploadContent(file).then((url) => { const newProfileForm = Object.assign(this.state.profileForm, { avatar_url: url }); this.setState({ uploadingAvatar: false, profileForm: newProfileForm, // Indicate that FlairStore needs to be poked to show this change // in TagTile (GroupFilterPanel), Flair and GroupTile (MyGroups). avatarChanged: true, }); }).catch((e) => { this.setState({ uploadingAvatar: false }); const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); logger.error("Failed to upload avatar image", e); Modal.createTrackedDialog('Failed to upload image', '', ErrorDialog, { title: _t('Error'), description: _t('Failed to upload image'), }); }); }; _onJoinableChange = ev => { this.setState({ joinableForm: { policyType: ev.target.value }, }); }; _onSaveClick = () => { this.setState({ saving: true }); const savePromise = this.state.isUserPrivileged ? this._saveGroup() : Promise.resolve(); savePromise.then((result) => { this.setState({ saving: false, editing: false, summary: null, }); this._initGroupStore(this.props.groupId); if (this.state.avatarChanged) { // XXX: Evil - poking a store should be done from an async action FlairStore.refreshGroupProfile(this._matrixClient, this.props.groupId); } }).catch((e) => { this.setState({ saving: false, }); const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); logger.error("Failed to save community profile", e); Modal.createTrackedDialog('Failed to update group', '', ErrorDialog, { title: _t('Error'), description: _t('Failed to update community'), }); }).finally(() => { this.setState({ avatarChanged: false, }); }); }; async _saveGroup() { await this._matrixClient.setGroupProfile(this.props.groupId, this.state.profileForm); await this._matrixClient.setGroupJoinPolicy(this.props.groupId, { type: this.state.joinableForm.policyType, }); } _onAcceptInviteClick = async () => { this.setState({ membershipBusy: true }); // Wait 500ms to prevent flashing. Do this before sending a request otherwise we risk the // spinner disappearing after we have fetched new group data. await sleep(500); GroupStore.acceptGroupInvite(this.props.groupId).then(() => { // don't reset membershipBusy here: wait for the membership change to come down the sync }).catch((e) => { this.setState({ membershipBusy: false }); const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog('Error accepting invite', '', ErrorDialog, { title: _t("Error"), description: _t("Unable to accept invite"), }); }); }; _onRejectInviteClick = async () => { this.setState({ membershipBusy: true }); // Wait 500ms to prevent flashing. Do this before sending a request otherwise we risk the // spinner disappearing after we have fetched new group data. await sleep(500); GroupStore.leaveGroup(this.props.groupId).then(() => { // don't reset membershipBusy here: wait for the membership change to come down the sync }).catch((e) => { this.setState({ membershipBusy: false }); const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog('Error rejecting invite', '', ErrorDialog, { title: _t("Error"), description: _t("Unable to reject invite"), }); }); }; _onJoinClick = async () => { if (this._matrixClient.isGuest()) { dis.dispatch({ action: 'require_registration', screen_after: { screen: `group/${this.props.groupId}` } }); return; } this.setState({ membershipBusy: true }); // Wait 500ms to prevent flashing. Do this before sending a request otherwise we risk the // spinner disappearing after we have fetched new group data. await sleep(500); GroupStore.joinGroup(this.props.groupId).then(() => { // don't reset membershipBusy here: wait for the membership change to come down the sync }).catch((e) => { this.setState({ membershipBusy: false }); const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog('Error joining room', '', ErrorDialog, { title: _t("Error"), description: _t("Unable to join community"), }); }); }; _leaveGroupWarnings() { const warnings = []; if (this.state.isUserPrivileged) { warnings.push(( <span className="warning"> { " " /* Whitespace, otherwise the sentences get smashed together */ } { _t("You are an administrator of this community. You will not be " + "able to rejoin without an invite from another administrator.") } </span> )); } return warnings; } _onLeaveClick = () => { const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); const warnings = this._leaveGroupWarnings(); Modal.createTrackedDialog('Leave Group', '', QuestionDialog, { title: _t("Leave Community"), description: ( <span> { _t("Leave %(groupName)s?", { groupName: this.props.groupId }) } { warnings } </span> ), button: _t("Leave"), danger: this.state.isUserPrivileged, onFinished: async (confirmed) => { if (!confirmed) return; this.setState({ membershipBusy: true }); // Wait 500ms to prevent flashing. Do this before sending a request otherwise we risk the // spinner disappearing after we have fetched new group data. await sleep(500); GroupStore.leaveGroup(this.props.groupId).then(() => { // don't reset membershipBusy here: wait for the membership change to come down the sync }).catch((e) => { this.setState({ membershipBusy: false }); const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog"); Modal.createTrackedDialog('Error leaving community', '', ErrorDialog, { title: _t("Error"), description: _t("Unable to leave community"), }); }); }, }); }; _onAddRoomsClick = () => { showGroupAddRoomDialog(this.props.groupId); }; _dismissUpgradeNotice = () => { localStorage.setItem(UPGRADE_NOTICE_LS_KEY, "true"); this.setState({ showUpgradeNotice: false }); }; _onCreateSpaceClick = () => { createSpaceFromCommunity(this._matrixClient, this.props.groupId); }; _onAdminsLinkClick = () => { RightPanelStore.instance.setCard({ phase: RightPanelPhases.GroupMemberList }); }; _getGroupSection() { const groupSettingsSectionClasses = classnames({ "mx_GroupView_group": this.state.editing, "mx_GroupView_group_disabled": this.state.editing && !this.state.isUserPrivileged, }); const header = this.state.editing ? <h2> { _t('Community Settings') } </h2> : <div />; const hostingSignupLink = getHostingLink('community-settings'); let hostingSignup = null; if (hostingSignupLink && this.state.isUserPrivileged) { hostingSignup = <div className="mx_GroupView_hostingSignup"> { _t( "Want more than a community? <a>Get your own server</a>", {}, { a: sub => <a href={hostingSignupLink} target="_blank" rel="noreferrer noopener">{ sub }</a>, }, ) } <a href={hostingSignupLink} target="_blank" rel="noreferrer noopener"> <img src={require("../../../res/img/external-link.svg").default} width="11" height="10" alt='' /> </a> </div>; } const changeDelayWarning = this.state.editing && this.state.isUserPrivileged ? <div className="mx_GroupView_changeDelayWarning"> { _t( 'Changes made to your community <bold1>name</bold1> and <bold2>avatar</bold2> ' + 'might not be seen by other users for up to 30 minutes.', {}, { 'bold1': (sub) => <b> { sub } </b>, 'bold2': (sub) => <b> { sub } </b>, }, ) } </div> : <div />; let communitiesUpgradeNotice; if (this.state.showUpgradeNotice) { let text; if (this.state.isUserPrivileged) { text = _t("You can create a Space from this community <a>here</a>.", {}, { a: sub => <AccessibleButton onClick={this._onCreateSpaceClick} kind="link"> { sub } </AccessibleButton>, }); } else { text = _t("Ask the <a>admins</a> of this community to make it into a Space " + "and keep a look out for the invite.", {}, { a: sub => <AccessibleButton onClick={this._onAdminsLinkClick} kind="link"> { sub } </AccessibleButton>, }); } communitiesUpgradeNotice = <div className="mx_GroupView_spaceUpgradePrompt"> <h2>{ _t("Communities can now be made into Spaces") }</h2> <p> { _t("Spaces are a new way to make a community, with new features coming.") } &nbsp; { text } &nbsp; { _t("Communities won't receive further updates.") } </p> <AccessibleButton className="mx_GroupView_spaceUpgradePrompt_close" onClick={this._dismissUpgradeNotice} /> </div>; } return <div className={groupSettingsSectionClasses}> { header } { hostingSignup } { changeDelayWarning } { communitiesUpgradeNotice } { this._getJoinableNode() } { this._getLongDescriptionNode() } { this._getRoomsNode() } </div>; } _getRoomsNode() { const RoomDetailList = sdk.getComponent('rooms.RoomDetailList'); const AccessibleButton = sdk.getComponent('elements.AccessibleButton'); const Spinner = sdk.getComponent('elements.Spinner'); const TooltipButton = sdk.getComponent('elements.TooltipButton'); const roomsHelpNode = this.state.editing ? <TooltipButton helpText={ _t( 'These rooms are displayed to community members on the community page. '+ 'Community members can join the rooms by clicking on them.', ) } /> : <div />; const addRoomRow = this.state.editing ? (<AccessibleButton className="mx_GroupView_rooms_header_addRow" onClick={this._onAddRoomsClick} > <div className="mx_GroupView_rooms_header_addRow_button"> <img src={require("../../../res/img/icons-room-add.svg").default} width="24" height="24" /> </div> <div className="mx_GroupView_rooms_header_addRow_label"> { _t('Add rooms to this community') } </div> </AccessibleButton>) : <div />; return <div className="mx_GroupView_rooms"> <div className="mx_GroupView_rooms_header"> <h3> { _t('Rooms') } { roomsHelpNode } </h3> { addRoomRow } </div> { this.state.groupRoomsLoading ? <Spinner /> : <RoomDetailList rooms={this.state.groupRooms} /> } </div>; } _getFeaturedRoomsNode() { const summary = this.state.summary; const defaultCategoryRooms = []; const categoryRooms = {}; summary.rooms_section.rooms.forEach((r) => { if (r.category_id === null) { defaultCategoryRooms.push(r); } else { let list = categoryRooms[r.category_id]; if (list === undefined) { list = []; categoryRooms[r.category_id] = list; } list.push(r); } }); const defaultCategoryNode = <CategoryRoomList rooms={defaultCategoryRooms} groupId={this.props.groupId} editing={this.state.editing} />; const categoryRoomNodes = Object.keys(categoryRooms).map((catId) => { const cat = summary.rooms_section.categories[catId]; return <CategoryRoomList key={catId} rooms={categoryRooms[catId]} category={cat} groupId={this.props.groupId} editing={this.state.editing} />; }); return <div className="mx_GroupView_featuredThings"> <div className="mx_GroupView_featuredThings_header"> { _t('Featured Rooms:') } </div> { defaultCategoryNode } { categoryRoomNodes } </div>; } _getFeaturedUsersNode() { const summary = this.state.summary; const noRoleUsers = []; const roleUsers = {}; summary.users_section.users.forEach((u) => { if (u.role_id === null) { noRoleUsers.push(u); } else { let list = roleUsers[u.role_id]; if (list === undefined) { list = []; roleUsers[u.role_id] = list; } list.push(u); } }); const noRoleNode = <RoleUserList users={noRoleUsers} groupId={this.props.groupId} editing={this.state.editing} />; const roleUserNodes = Object.keys(roleUsers).map((roleId) => { const role = summary.users_section.roles[roleId]; return <RoleUserList key={roleId} users={roleUsers[roleId]} role={role} groupId={this.props.groupId} editing={this.state.editing} />; }); return <div className="mx_GroupView_featuredThings"> <div className="mx_GroupView_featuredThings_header"> { _t('Featured Users:') } </div> { noRoleNode } { roleUserNodes } </div>; } _getMembershipSection() { const Spinner = sdk.getComponent("elements.Spinner"); const BaseAvatar = sdk.getComponent("avatars.BaseAvatar"); const group = this._matrixClient.getGroup(this.props.groupId); if (group && group.myMembership === 'invite') { if (this.state.membershipBusy || this.state.inviterProfileBusy) { return <div className="mx_GroupView_membershipSection"> <Spinner /> </div>; } const httpInviterAvatar = this.state.inviterProfile && this.state.inviterProfile.avatarUrl ? mediaFromMxc(this.state.inviterProfile.avatarUrl).getSquareThumbnailHttp(36) : null; const inviter = group.inviter || {}; let inviterName = inviter.userId; if (this.state.inviterProfile) { inviterName = this.state.inviterProfile.displayName || inviter.userId; } return <div className="mx_GroupView_membershipSection mx_GroupView_membershipSection_invited"> <div className="mx_GroupView_membershipSubSection"> <div className="mx_GroupView_membershipSection_description"> <BaseAvatar url={httpInviterAvatar} name={inviterName} width={36} height={36} /> { _t("%(inviter)s has invited you to join this community", { inviter: inviterName || _t("Someone"), }) } </div> <div className="mx_GroupView_membership_buttonContainer"> <AccessibleButton className="mx_GroupView_textButton mx_RoomHeader_textButton" onClick={this._onAcceptInviteClick} > { _t("Accept") } </AccessibleButton> <AccessibleButton className="mx_GroupView_textButton mx_RoomHeader_textButton" onClick={this._onRejectInviteClick} > { _t("Decline") } </AccessibleButton> </div> </div> </div>; } let membershipContainerExtraClasses; let membershipButtonExtraClasses; let membershipButtonTooltip; let membershipButtonText; let membershipButtonOnClick; // User is not in the group if ((!group || group.myMembership === 'leave') && this.state.summary && this.state.summary.profile && Boolean(this.state.summary.profile.is_openly_joinable) ) { membershipButtonText = _t("Join this community"); membershipButtonOnClick = this._onJoinClick; membershipButtonExtraClasses = 'mx_GroupView_joinButton'; membershipContainerExtraClasses = 'mx_GroupView_membershipSection_leave'; } else if ( group && group.myMembership === 'join' && this.state.editing ) { membershipButtonText = _t("Leave this community"); membershipButtonOnClick = this._onLeaveClick; membershipButtonTooltip = this.state.isUserPrivileged ? _t("You are an administrator of this community") : _t("You are a member of this community"); membershipButtonExtraClasses = { 'mx_GroupView_leaveButton': true, 'mx_RoomHeader_textButton_danger': this.state.isUserPrivileged, }; membershipContainerExtraClasses = 'mx_GroupView_membershipSection_joined'; } else { return null; } const membershipButtonClasses = classnames( [ 'mx_RoomHeader_textButton', 'mx_GroupView_textButton', ], membershipButtonExtraClasses, ); const membershipContainerClasses = classnames( 'mx_GroupView_membershipSection', membershipContainerExtraClasses, ); return <div className={membershipContainerClasses}> <div className="mx_GroupView_membershipSubSection"> { /* The <div /> is for flex alignment */ } { this.state.membershipBusy ? <Spinner /> : <div /> } <div className="mx_GroupView_membership_buttonContainer"> <AccessibleButton className={membershipButtonClasses} onClick={membershipButtonOnClick} title={membershipButtonTooltip} > { membershipButtonText } </AccessibleButton> </div> </div> </div>; } _getJoinableNode() { const InlineSpinner = sdk.getComponent('elements.InlineSpinner'); return this.state.editing ? <div> <h3> { _t('Who can join this community?') } { this.state.groupJoinableLoading ? <InlineSpinner /> : <div /> } </h3> <div> <label> <input type="radio" value={GROUP_JOINPOLICY_INVITE} checked={this.state.joinableForm.policyType === GROUP_JOINPOLICY_INVITE} onChange={this._onJoinableChange} /> <div className="mx_GroupView_label_text"> { _t('Only people who have been invited') } </div> </label> </div> <div> <label> <input type="radio" value={GROUP_JOINPOLICY_OPEN} checked={this.state.joinableForm.policyType === GROUP_JOINPOLICY_OPEN} onChange={this._onJoinableChange} /> <div className="mx_GroupView_label_text"> { _t('Everyone') } </div> </label> </div> </div> : null; } _getLongDescriptionNode() { const summary = this.state.summary; let description = null; if (summary.profile && summary.profile.long_description) { description = sanitizedHtmlNode(summary.profile.long_description); } else if (this.state.isUserPrivileged) { description = <div className="mx_GroupView_groupDesc_placeholder" onClick={this._onEditClick} > { _t( 'Your community hasn\'t got a Long Description, a HTML page to show to community members.<br />' + 'Click here to open settings and give it one!', {}, { 'br': <br /> }, ) } </div>; } const groupDescEditingClasses = classnames({ "mx_GroupView_groupDesc": true, "mx_GroupView_groupDesc_disabled": !this.state.isUserPrivileged, }); return this.state.editing ? <div className={groupDescEditingClasses}> <h3> { _t("Long Description (HTML)") } </h3> <textarea value={this.state.profileForm.long_description} placeholder={_t(LONG_DESC_PLACEHOLDER)} onChange={this._onLongDescChange} tabIndex="4" key="editLongDesc" /> </div> : <div className="mx_GroupView_groupDesc"> { description } </div>; } render() { const GroupAvatar = sdk.getComponent("avatars.GroupAvatar"); const Spinner = sdk.getComponent("elements.Spinner"); if (this.state.summaryLoading && this.state.error === null || this.state.saving) { return <Spinner />; } else if (this.state.summary && !this.state.error) { const summary = this.state.summary; let avatarNode; let nameNode; let shortDescNode; const rightButtons = []; if (this.state.editing && this.state.isUserPrivileged) { let avatarImage; if (this.state.uploadingAvatar) { avatarImage = <Spinner />; } else { const GroupAvatar = sdk.getComponent('avatars.GroupAvatar'); avatarImage = <GroupAvatar groupId={this.props.groupId} groupName={this.state.profileForm.name} groupAvatarUrl={this.state.profileForm.avatar_url} width={28} height={28} resizeMethod='crop' />; } avatarNode = ( <div className="mx_GroupView_avatarPicker"> <label htmlFor="avatarInput" className="mx_GroupView_avatarPicker_label"> { avatarImage } </label> <div className="mx_GroupView_avatarPicker_edit"> <label htmlFor="avatarInput" className="mx_GroupView_avatarPicker_label"> <img src={require("../../../res/img/camera.svg").default} alt={_t("Upload avatar")} title={_t("Upload avatar")} width="17" height="15" /> </label> <input id="avatarInput" className="mx_GroupView_uploadInput" type="file" onChange={this._onAvatarSelected} /> </div> </div> ); const EditableText = sdk.getComponent("elements.EditableText"); nameNode = <EditableText className="mx_GroupView_editable" placeholderClassName="mx_GroupView_placeholder" placeholder={_t('Community Name')} blurToCancel={false} initialValue={this.state.profileForm.name} onValueChanged={this._onNameChange} tabIndex="0" dir="auto" />; shortDescNode = <EditableText className="mx_GroupView_editable" placeholderClassName="mx_GroupView_placeholder" placeholder={_t("Description")} blurToCancel={false} initialValue={this.state.profileForm.short_description} onValueChanged={this._onShortDescChange} tabIndex="0" dir="auto" />; } else { const onGroupHeaderItemClick = this.state.isUserMember ? this._onEditClick : null; const groupAvatarUrl = summary.profile ? summary.profile.avatar_url : null; const groupName = summary.profile ? summary.profile.name : null; avatarNode = <GroupAvatar groupId={this.props.groupId} groupAvatarUrl={groupAvatarUrl} groupName={groupName} onClick={onGroupHeaderItemClick} width={28} height={28} />; if (summary.profile && summary.profile.name) { nameNode = <div onClick={onGroupHeaderItemClick}> <span>{ summary.profile.name }</span> <span className="mx_GroupView_header_groupid"> ({ this.props.groupId }) </span> </div>; } else { nameNode = <span onClick={onGroupHeaderItemClick}>{ this.props.groupId }</span>; } if (summary.profile && summary.profile.short_description) { shortDescNode = <span onClick={onGroupHeaderItemClick}>{ summary.profile.short_description }</span>; } } if (this.state.editing) { rightButtons.push( <AccessibleButton className="mx_GroupView_textButton mx_RoomHeader_textButton" key="_saveButton" onClick={this._onSaveClick} > { _t('Save') } </AccessibleButton>, ); rightButtons.push( <AccessibleButton className="mx_RoomHeader_cancelButton" key="_cancelButton" onClick={this._onCancelClick} > <img src={require("../../../res/img/cancel.svg").default} className="mx_filterFlipColor" width="18" height="18" alt={_t("Cancel")} /> </AccessibleButton>, ); } else { if (summary.user && summary.user.membership === 'join') { rightButtons.push( <AccessibleButton className="mx_GroupHeader_button mx_GroupHeader_editButton" key="_editButton" onClick={this._onEditClick} title={_t("Community Settings")} />, ); } rightButtons.push( <AccessibleButton className="mx_GroupHeader_button mx_GroupHeader_shareButton" key="_shareButton" onClick={this._onShareClick} title={_t('Share Community')} />, ); } const rightPanel = this.state.showRightPanel ? <RightPanel groupId={this.props.groupId} /> : undefined; const headerClasses = { "mx_GroupView_header": true, "light-panel": true, "mx_GroupView_header_view": !this.state.editing, "mx_GroupView_header_isUserMember": this.state.isUserMember, }; return ( <main className="mx_GroupView"> <div className={classnames(headerClasses)}> <div className="mx_GroupView_header_leftCol"> <div className="mx_GroupView_header_avatar"> { avatarNode } </div> <div className="mx_GroupView_header_info"> <div className="mx_GroupView_header_name"> { nameNode } </div> <div className="mx_GroupView_header_shortDesc"> { shortDescNode } </div> </div> </div> <div className="mx_GroupView_header_rightCol"> { rightButtons } </div> <GroupHeaderButtons /> </div> <MainSplit panel={rightPanel} resizeNotifier={this.props.resizeNotifier}> <AutoHideScrollbar className="mx_GroupView_body"> { this._getMembershipSection() } { this._getGroupSection() } </AutoHideScrollbar> </MainSplit> </main> ); } else if (this.state.error) { if (this.state.error.httpStatus === 404) { return ( <div className="mx_GroupView_error"> { _t('Community %(groupId)s not found', { groupId: this.props.groupId }) } </div> ); } else { let extraText; if (this.state.error.errcode === 'M_UNRECOGNIZED') { extraText = <div>{ _t('This homeserver does not support communities') }</div>; } return ( <div className="mx_GroupView_error"> { _t('Failed to load %(groupId)s', { groupId: this.props.groupId }) } { extraText } </div> ); } } else { logger.error("Invalid state for GroupView"); return <div />; } } }
matrix-org/matrix-react-sdk
src/components/structures/GroupView.js
JavaScript
apache-2.0
56,656
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dataflow.sdk.transforms; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.cloud.dataflow.sdk.transforms.DoFnTester.OutputElementWithTimestamp; import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.List; /** * Tests for {@link DoFnTester}. */ @RunWith(JUnit4.class) public class DoFnTesterTest { @Test public void processElement() { CounterDoFn counterDoFn = new CounterDoFn(); DoFnTester<Long, String> tester = DoFnTester.of(counterDoFn); tester.processElement(1L); List<String> take = tester.takeOutputElements(); assertThat(take, hasItems("1")); // Following takeOutputElements(), neither takeOutputElements() // nor peekOutputElements() return anything. assertTrue(tester.takeOutputElements().isEmpty()); assertTrue(tester.peekOutputElements().isEmpty()); // processElement() caused startBundle() to be called, but finishBundle() was never called. CounterDoFn deserializedDoFn = (CounterDoFn) tester.fn; assertTrue(deserializedDoFn.wasStartBundleCalled()); assertFalse(deserializedDoFn.wasFinishBundleCalled()); } @Test public void processElementsWithPeeks() { CounterDoFn counterDoFn = new CounterDoFn(); DoFnTester<Long, String> tester = DoFnTester.of(counterDoFn); // Explicitly call startBundle(). tester.startBundle(); // verify startBundle() was called but not finishBundle(). CounterDoFn deserializedDoFn = (CounterDoFn) tester.fn; assertTrue(deserializedDoFn.wasStartBundleCalled()); assertFalse(deserializedDoFn.wasFinishBundleCalled()); // process a couple of elements. tester.processElement(1L); tester.processElement(2L); // peek the first 2 outputs. List<String> peek = tester.peekOutputElements(); assertThat(peek, hasItems("1", "2")); // process a couple more. tester.processElement(3L); tester.processElement(4L); // peek all the outputs so far. peek = tester.peekOutputElements(); assertThat(peek, hasItems("1", "2", "3", "4")); // take the outputs. List<String> take = tester.takeOutputElements(); assertThat(take, hasItems("1", "2", "3", "4")); // Following takeOutputElements(), neither takeOutputElements() // nor peekOutputElements() return anything. assertTrue(tester.peekOutputElements().isEmpty()); assertTrue(tester.takeOutputElements().isEmpty()); // verify finishBundle() hasn't been called yet. assertTrue(deserializedDoFn.wasStartBundleCalled()); assertFalse(deserializedDoFn.wasFinishBundleCalled()); // process a couple more. tester.processElement(5L); tester.processElement(6L); // peek and take now have only the 2 last outputs. peek = tester.peekOutputElements(); assertThat(peek, hasItems("5", "6")); take = tester.takeOutputElements(); assertThat(take, hasItems("5", "6")); tester.finishBundle(); // verify finishBundle() was called. assertTrue(deserializedDoFn.wasStartBundleCalled()); assertTrue(deserializedDoFn.wasFinishBundleCalled()); } @Test public void processBatch() { CounterDoFn counterDoFn = new CounterDoFn(); DoFnTester<Long, String> tester = DoFnTester.of(counterDoFn); // processBatch() returns all the output like takeOutputElements(). List<String> take = tester.processBatch(1L, 2L, 3L, 4L); assertThat(take, hasItems("1", "2", "3", "4")); // peek now returns nothing. assertTrue(tester.peekOutputElements().isEmpty()); // verify startBundle() and finishBundle() were both called. CounterDoFn deserializedDoFn = (CounterDoFn) tester.fn; assertTrue(deserializedDoFn.wasStartBundleCalled()); assertTrue(deserializedDoFn.wasFinishBundleCalled()); } @Test public void processElementWithTimestamp() { CounterDoFn counterDoFn = new CounterDoFn(); DoFnTester<Long, String> tester = DoFnTester.of(counterDoFn); tester.processElement(1L); tester.processElement(2L); List<OutputElementWithTimestamp<String>> peek = tester.peekOutputElementsWithTimestamp(); OutputElementWithTimestamp<String> one = new OutputElementWithTimestamp<>("1", new Instant(1000L)); OutputElementWithTimestamp<String> two = new OutputElementWithTimestamp<>("2", new Instant(2000L)); assertThat(peek, hasItems(one, two)); tester.processElement(3L); tester.processElement(4L); OutputElementWithTimestamp<String> three = new OutputElementWithTimestamp<>("3", new Instant(3000L)); OutputElementWithTimestamp<String> four = new OutputElementWithTimestamp<>("4", new Instant(4000L)); peek = tester.peekOutputElementsWithTimestamp(); assertThat(peek, hasItems(one, two, three, four)); List<OutputElementWithTimestamp<String>> take = tester.takeOutputElementsWithTimestamp(); assertThat(take, hasItems(one, two, three, four)); // Following takeOutputElementsWithTimestamp(), neither takeOutputElementsWithTimestamp() // nor peekOutputElementsWithTimestamp() return anything. assertTrue(tester.takeOutputElementsWithTimestamp().isEmpty()); assertTrue(tester.peekOutputElementsWithTimestamp().isEmpty()); // peekOutputElements() and takeOutputElements() also return nothing. assertTrue(tester.peekOutputElements().isEmpty()); assertTrue(tester.takeOutputElements().isEmpty()); } @Test public void getAggregatorValuesShouldGetValueOfCounter() { CounterDoFn counterDoFn = new CounterDoFn(); DoFnTester<Long, String> tester = DoFnTester.of(counterDoFn); tester.processBatch(1L, 2L, 4L, 8L); Long aggregatorVal = tester.getAggregatorValue(counterDoFn.agg); assertThat(aggregatorVal, equalTo(15L)); } @Test public void getAggregatorValuesWithEmptyCounterShouldSucceed() { CounterDoFn counterDoFn = new CounterDoFn(); DoFnTester<Long, String> tester = DoFnTester.of(counterDoFn); tester.processBatch(); Long aggregatorVal = tester.getAggregatorValue(counterDoFn.agg); // empty bundle assertThat(aggregatorVal, equalTo(0L)); } @Test public void getAggregatorValuesInStartFinishBundleShouldGetValues() { CounterDoFn fn = new CounterDoFn(1L, 2L); DoFnTester<Long, String> tester = DoFnTester.of(fn); tester.processBatch(0L, 0L); Long aggValue = tester.getAggregatorValue(fn.agg); assertThat(aggValue, equalTo(1L + 2L)); } /** * A DoFn that adds values to an aggregator and converts input to String in processElement. */ private static class CounterDoFn extends DoFn<Long, String> { Aggregator<Long, Long> agg = createAggregator("ctr", new Sum.SumLongFn()); private final long startBundleVal; private final long finishBundleVal; private boolean startBundleCalled; private boolean finishBundleCalled; public CounterDoFn() { this(0L, 0L); } public CounterDoFn(long start, long finish) { this.startBundleVal = start; this.finishBundleVal = finish; } @Override public void startBundle(Context c) { agg.addValue(startBundleVal); startBundleCalled = true; } @Override public void processElement(ProcessContext c) throws Exception { agg.addValue(c.element()); Instant instant = new Instant(1000L * c.element()); c.outputWithTimestamp(c.element().toString(), instant); } @Override public void finishBundle(Context c) { agg.addValue(finishBundleVal); finishBundleCalled = true; } boolean wasStartBundleCalled() { return startBundleCalled; } boolean wasFinishBundleCalled() { return finishBundleCalled; } } }
shakamunyi/beam
sdks/java/core/src/test/java/com/google/cloud/dataflow/sdk/transforms/DoFnTesterTest.java
Java
apache-2.0
8,727
/* * Copyright (C) 2014 ZYYX, 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. */ #include <stdio.h> #include <stdlib.h> #include "random.h" static unsigned long next = 1; int dynamicApp_rand(void) { next = next * 1103515245 + 12345; return((unsigned)(next/65536) % 32768); } void dynamicApp_srand(unsigned seed) { next = seed; }
dynamicapp/dynamicapp
lib/iOS/DynamicApp/Classes/random.c
C
apache-2.0
863
package org.wso2.carbon.apimgt.rest.api.gateway.v1.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import javax.validation.constraints.*; import io.swagger.annotations.*; import java.util.Objects; import javax.xml.bind.annotation.*; import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; import com.fasterxml.jackson.annotation.JsonCreator; public class ErrorListItemDTO { private String code = null; private String message = null; /** * Error code **/ public ErrorListItemDTO code(String code) { this.code = code; return this; } @ApiModelProperty(required = true, value = "Error code") @JsonProperty("code") @NotNull public String getCode() { return code; } public void setCode(String code) { this.code = code; } /** * Description about individual errors occurred **/ public ErrorListItemDTO message(String message) { this.message = message; return this; } @ApiModelProperty(required = true, value = "Description about individual errors occurred ") @JsonProperty("message") @NotNull public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ErrorListItemDTO errorListItem = (ErrorListItemDTO) o; return Objects.equals(code, errorListItem.code) && Objects.equals(message, errorListItem.message); } @Override public int hashCode() { return Objects.hash(code, message); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ErrorListItemDTO {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" message: ").append(toIndentedString(message)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
jaadds/carbon-apimgt
components/apimgt/org.wso2.carbon.apimgt.rest.api.gateway.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/gateway/v1/dto/ErrorListItemDTO.java
Java
apache-2.0
2,344
/* mbed Microcontroller Library * Copyright (c) 2017 ARM 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. */ #include "flash_api.h" #include "flash_data.h" #include "platform/mbed_critical.h" // This file is automatically generated #if DEVICE_FLASH // This is a flash algo binary blob. It is PIC (position independent code) that should be stored in RAM static uint32_t FLASH_ALGO[] = { 0x28100b00, 0x210ed302, 0x00d0eb01, 0xf44f4770, 0xfbb1707a, 0x4933f0f0, 0x60084449, 0x20014932, 0x20006408, 0x20004770, 0xe92d4770, 0xf7ff41f0, 0x4d2effe7, 0x444d4604, 0xe9c52032, 0xf1050400, 0x4e2b0114, 0x4628460f, 0x47b060ac, 0xb9686968, 0xe9c52034, 0x48230400, 0x444860ac, 0x68004639, 0x462860e8, 0x696847b0, 0xd0002800, 0xe8bd2001, 0xe92d81f0, 0x461441f0, 0xd10e0006, 0x0100e9d4, 0xe9d44408, 0x44111202, 0x69214408, 0x69614408, 0x69a14408, 0x42404408, 0x463061e0, 0xffb0f7ff, 0x21324d12, 0x4f12444d, 0x1000e9c5, 0x0114f105, 0x468860a8, 0x47b84628, 0xb9806968, 0xe9c52033, 0xf44f0600, 0xe9c56080, 0x48064002, 0x44484641, 0x61286800, 0x47b84628, 0x28006968, 0x2001d0c7, 0x0000e7c5, 0x00000004, 0x400fc000, 0x00000008, 0x1fff1ff1, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; static const flash_algo_t flash_algo_config = { .init = 0xf, .uninit = 0x27, .erase_sector = 0x2b, .program_page = 0x73, .static_base = 0xf4, .algo_blob = FLASH_ALGO }; static const sector_info_t sectors_info[] = { {0x0, 0x1000}, {0x10000, 0x8000}, }; static const flash_target_config_t flash_target_config = { .page_size = 0x400, .flash_start = 0x0, .flash_size = 0x80000, .sectors = sectors_info, .sector_info_count = sizeof(sectors_info) / sizeof(sector_info_t) }; void flash_set_target_config(flash_t *obj) { obj->flash_algo = &flash_algo_config; obj->target_config = &flash_target_config; } #endif
netzimme/mbed-os
targets/TARGET_NXP/TARGET_LPC176X/device/flash_api.c
C
apache-2.0
2,468
package ga.thesis.gui.table.model; import ga.thesis.hibernate.entities.AbsenceMatrix; import ga.thesis.hibernate.entities.Group; import ga.thesis.hibernate.entities.GroupCode; import ga.thesis.hibernate.entities.Teacher; import ga.thesis.hibernate.service.CRUDService; import ga.thesis.hibernate.service.PersistenceConfig; public class TeacherTableModel extends TimeTableAbstractTableModel<Teacher> { @Override public int getColumnCount() { return 3; } @Override public String[] getColumnNames() { return new String[] {"id", "Name","Absence Matrix"}; } @Override public Class[] getColumnClasses() { return new Class[] {Long.class, String.class, AbsenceMatrix.class}; } @Override public Object getValueAt(int rowIndex, int columnIndex) { Teacher teacher = rows.get(rowIndex); switch (columnIndex) { case 0: return teacher.getId(); case 1: return teacher.getName(); case 2: return teacher.getIdAbsenceMatrix(); default: throw new ColumnNotFoundException(columnIndex); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex != 0; } @Override protected Teacher doUpdate(Teacher teacher, Object aValue, int columnIndex) { switch (columnIndex) { case 0: teacher.setId((Long) aValue); break; case 1: teacher.setName((String) aValue); break; case 2: teacher.setIdAbsenceMatrix((AbsenceMatrix) aValue); break; default: break; } return teacher; } @Override protected CRUDService<Teacher, ?> getService() { return PersistenceConfig.getInstance().getTeacherService(); } }
skylady/GAThesis2
src/main/java/ga/thesis/gui/table/model/TeacherTableModel.java
Java
apache-2.0
1,794
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.ui.toolkit.impl.swt.view.sync; import net.sf.mmm.ui.toolkit.api.view.UiNode; import net.sf.mmm.ui.toolkit.impl.swt.UiFactorySwt; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Widget; /** * This is the abstract base class used for synchronous access on a SWT * {@link org.eclipse.swt.widgets.Widget}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @param <DELEGATE> is the generic type of the {@link #getDelegate() delegate}. * @since 1.0.0 */ public abstract class AbstractSyncWidgetAccess<DELEGATE extends Widget> extends AbstractSyncObjectAccess<DELEGATE> { /** * operation to * {@link org.eclipse.swt.widgets.Widget#addListener(int, org.eclipse.swt.widgets.Listener) * add} a listener to the widget. */ protected static final String OPERATION_ADD_LISTENER = "addListener"; /** * operation to set the {@link #setEnabled(boolean) enabled flag}. */ protected static final String OPERATION_SET_ENABLED = "setEnabled"; /** * operation to set the {@link #setVisible(boolean) visible flag}. */ protected static final String OPERATION_SET_VISIBLE = "setVisible"; /** the event type for the listener to add */ private int eventType; /** the listener to add */ private Listener listener; /** @see #isEnabled() */ private boolean enabled; /** @see #isVisible() */ private boolean visible; /** * The constructor. * * @param uiFactory is used to do the synchronization. * @param node is the owning {@link #getNode() node}. * @param swtStyle is the {@link Widget#getStyle() style} of the widget. */ public AbstractSyncWidgetAccess(UiFactorySwt uiFactory, UiNode node, int swtStyle) { super(uiFactory, node, swtStyle); this.eventType = 0; this.listener = null; this.visible = true; this.enabled = true; } /** * {@inheritDoc} */ @Override protected boolean isDisposedSynchron() { return getDelegate().isDisposed(); } /** * {@inheritDoc} */ @Override protected void disposeSynchron() { getDelegate().dispose(); super.disposeSynchron(); } /** * {@inheritDoc} */ @Override protected void performSynchron(String operation) { if (operation == OPERATION_ADD_LISTENER) { getDelegate().addListener(this.eventType, this.listener); } else { super.performSynchron(operation); } } /** * This method is called for the create operation. */ @Override protected void createSynchron() { if (this.listener != null) { getDelegate().addListener(this.eventType, this.listener); } } /** * This method * {@link org.eclipse.swt.widgets.Widget#addListener(int, org.eclipse.swt.widgets.Listener) * adds} a listener to the widget.<br> * ATTENTION: This implementation expects that this method is NOT called more * than once before {@link #create() creation} is performed. * * @param type is the event type to listen to. * @param handler is the handler that will receive the events. */ public void addListener(int type, Listener handler) { assert (checkReady()); this.eventType = type; this.listener = handler; invoke(OPERATION_ADD_LISTENER); } /** * {@inheritDoc} */ public Widget getToplevelDelegate() { return getDelegate(); } /** * {@inheritDoc} */ public boolean isEnabled() { return this.enabled; } /** * {@inheritDoc} */ @Override public void setEnabled(boolean enabled) { assert (checkReady()); this.enabled = enabled; invoke(OPERATION_SET_ENABLED); } /** * {@inheritDoc} */ @Override public boolean isVisible() { return this.visible; } /** * This method gets the visible flag as set by {@link #setVisible(boolean)}. * Unlike {@link #isVisible()} that may be overridden it will not invoke * synchronous determination of the controls visibility. * * @see #isVisible() * * @return the visible flag as set by {@link #setVisible(boolean)}. */ protected final boolean doIsVisible() { return this.visible; } /** * {@inheritDoc} */ public void setVisible(boolean visible) { assert (checkReady()); this.visible = visible; invoke(OPERATION_SET_VISIBLE); } /** * This method sets the raw visible flag. * * @param newVisible - the {@link #isVisible() visible flag}. */ protected void doSetVisible(boolean newVisible) { this.visible = newVisible; } /** * {@inheritDoc} */ @Override protected void handleDisposed() { super.handleDisposed(); this.visible = false; this.enabled = false; } }
m-m-m/multimedia
mmm-uit/mmm-uit-impl-swt/src/main/java/net/sf/mmm/ui/toolkit/impl/swt/view/sync/AbstractSyncWidgetAccess.java
Java
apache-2.0
4,825
// SAX default implementation for Locator. // http://www.saxproject.org // No warranty; no copyright -- use this as you will. // $Id: LocatorImpl.java,v 1.6 2002/01/30 20:52:27 dbrownell Exp $ namespace Sax.Helpers { /// <summary> /// Provide an optional convenience implementation of <see cref="ILocator"/>. /// </summary> /// <remarks> /// <em>This module, both source code and documentation, is in the /// Public Domain, and comes with<strong> NO WARRANTY</strong>.</em> /// See<a href='http://www.saxproject.org'>http://www.saxproject.org</a> /// for further information. /// <para/> /// This class is available mainly for application writers, who /// can use it to make a persistent snapshot of a locator at any /// point during a document parse: /// <code> /// ILocator locator; /// ILocator startloc; /// /// public void SetLocator(ILocator locator) /// { /// // note the locator /// this.locator = locator; /// } /// /// public void StartDocument() /// { /// // save the location of the start of the document /// // for future use. /// ILocator startloc = new Locator(locator); /// } /// </code> /// <para/> /// Normally, parser writers will not use this class, since it /// is more efficient to provide location information only when /// requested, rather than constantly updating a <see cref="ILocator"/> object. /// </remarks> public class Locator : ILocator { /// <summary> /// Zero-argument constructor. /// <para/>This will not normally be useful, since the main purpose /// of this class is to make a snapshot of an existing <see cref="ILocator"/>. /// </summary> public Locator() { } /// <summary> /// Copy constructor. /// <para/> /// Create a persistent copy of the current state of a locator. /// When the original locator changes, this copy will still keep /// the original values (and it can be used outside the scope of /// DocumentHandler methods). /// </summary> /// <param name="locator">The locator to copy.</param> public Locator(ILocator locator) { publicId = locator.PublicId; systemId = locator.SystemId; lineNumber = locator.LineNumber; columnNumber = locator.ColumnNumber; } //////////////////////////////////////////////////////////////////// // Implementation of org.xml.sax.Locator //////////////////////////////////////////////////////////////////// /// <summary> /// Gets the public identifier as a string, or null if none /// is available. /// </summary> /// <seealso cref="ILocator.PublicId"/> public string PublicId { get { return publicId; } set { publicId = value; } } /// <summary> /// Gets the system identifier as a string, or null if none /// is available. /// </summary> /// <seealso cref="ILocator.SystemId"/> public string SystemId { get { return systemId; } set { systemId = value; } } /// <summary> /// Gets the saved line number (1-based). /// Returns the line number as an integer, or -1 if none is available. /// </summary> /// <seealso cref="ILocator.LineNumber"/> public int LineNumber { get { return lineNumber; } set { lineNumber = value; } } /// <summary> /// Gets the saved column number (1-based). /// Returns the column number as an integer, or -1 if none is available. /// </summary> /// <seealso cref="ILocator.ColumnNumber"/> public int ColumnNumber { get { return columnNumber; } set { columnNumber = value; } } //////////////////////////////////////////////////////////////////// // Internal state. //////////////////////////////////////////////////////////////////// private string publicId; private string systemId; private int lineNumber; private int columnNumber; } }
laimis/lucenenet
src/Lucene.Net.Benchmark/Support/Sax/Helpers/LocatorImpl.cs
C#
apache-2.0
4,360
package tangyong.javaee.understadingcdi.basic06; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertTrue; public class HotelTest { protected static Weld weld; protected static WeldContainer container; @BeforeClass public static void init() { weld = new Weld(); container = weld.initialize(); } @AfterClass public static void close() { weld.shutdown(); } @Test public void checkHotelName() { CommonHotelService commonHotelService = container.instance().select(CommonHotelService.class).get(); assertTrue(commonHotelService.getHotelName().equalsIgnoreCase("ThreeStarHotel")); AdvanceHotelService advanceHotelService = container.instance().select(AdvanceHotelService.class).get(); assertTrue(advanceHotelService.getHotelName().equalsIgnoreCase("FiveStarHotel")); } }
tangyong/JavaEETraining
UnderstandingCDI/basic/src/test/java/tangyong/javaee/understadingcdi/basic06/HotelTest.java
Java
apache-2.0
989
/* * Copyright 2012 Hai Bison * * 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 group.pals.android.lib.ui.filechooser.utils; import group.pals.android.lib.ui.filechooser.DataModel; import group.pals.android.lib.ui.filechooser.FileChooserActivity; import java.util.Comparator; /** * {@link DataModel} comparator. * * @author Hai Bison * @since v.2.0 alpha */ public class DataModelComparator implements Comparator<DataModel> { private final FileComparator _FileComparator; /** * Creates new {@link DataModelComparator} * * @param sortType * see {@link FileChooserActivity#SortType} * @param sortOrder * see {@link FileChooserActivity#SortOrder} */ public DataModelComparator(int sortType, int sortOrder) { _FileComparator = new FileComparator(sortType, sortOrder); } @Override public int compare(DataModel lhs, DataModel rhs) { return _FileComparator.compare(lhs.getFile(), rhs.getFile()); } }
sunilgautam/FileChooserActivity
src/group/pals/android/lib/ui/filechooser/utils/DataModelComparator.java
Java
apache-2.0
1,549
'use strict' var crypto = require('crypto'); var Authenticator = require('./authenticator.js'); /** * A class implementing http digest authentication. * * @constructs Digest * @param {ReplayDetector} detector - A replay detector registering hashes. * @param {Function} identify - A function performing the password lookup. */ var Digest = function (detector, identify) { Authenticator.call(this, identify); this.detector = detector; }; Digest.prototype = Object.create(Authenticator.prototype); var hash = function (array) { return crypto.createHash('md5').update(array.join(':')).digest('hex'); }; Digest.prototype.parse = function (authorization) { var strings = /([a-z]*)=("[^"]*")(,|$)/g; var unquoted = /([a-z]*)=([0-9A-Za-z]*)(,|$)/g; var fields = {}, match; // Parse all quoted values in the authorization header. while (match = strings.exec(authorization)) { fields[match[1]] = JSON.parse(match[2]); } // Parse the unquoted qop and nc values. while (match = unquoted.exec(authorization)) { fields[match[1]] = match[2]; } return fields; }; Digest.prototype.check = function (fields, realm, password, method) { var identity; var resource; if (this.detector.check(fields.nonce, parseInt(fields.nc, 16)) !== true) { return false; } else if (password !== undefined && password !== null) { identity = hash([fields.username, realm, password]); resource = hash([method, fields.uri]); return fields.response === hash([ identity, fields.nonce, fields.nc, fields.cnonce, fields.qop, resource ]); } else { return false; } }; Digest.prototype.nonce = function () { var nonce = Math.random(); this.detector.register(nonce); return nonce; }; Digest.prototype.header = function (realm) { var result = ''; result += 'Digest realm="' + realm + '"'; result += 'qop="auth",nonce="' + this.nonce() + '"'; result += 'opaque="' + hash([realm]) + '"'; return result; }; /** * Request an authentication strategy for the passport module. * * @returns {passport.Strategy} A passport strategy for digest authentication. */ Digest.prototype.passport = function () { this.name = 'digest'; return this; }; module.exports = Digest;
tdecaluwe/http-authentication
digest.js
JavaScript
apache-2.0
2,263
import { asUrlQueryString } from './query-parameters-v2'; describe('asUrlQueryString', () => { it('should create a empty query', () => { expect(asUrlQueryString({})).toBe(''); }); it('should create a query string with one argument', () => { expect(asUrlQueryString({ foo: 'bar' })).toBe('?foo=bar'); }); it('should create a query string with multiple argument', () => { expect(asUrlQueryString({ foo1: 'bar1', foo2: 'bar2' })).toBe('?foo1=bar1&foo2=bar2'); }); it('should expand any array argument', () => { expect(asUrlQueryString({ foo: ['bar1', 'bar2'] })).toBe('?foo=bar1&foo=bar2'); }); it('should skip undefined values', () => { expect(asUrlQueryString({ foo: 'bar', foo1: undefined })).toBe('?foo=bar'); }); it('should skip undefined values in array', () => { expect(asUrlQueryString({ foo: ['bar1', undefined, 'bar2'] })).toBe('?foo=bar1&foo=bar2'); }); });
Taskana/taskana
web/src/app/shared/util/query-parameters-v2.spec.ts
TypeScript
apache-2.0
920
/* * Copyright (C) 2015-2022 Emanuel Moecklin * * 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.onegravity.rteditor.utils; import android.content.Context; import android.content.res.Configuration; import android.net.Uri; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import com.onegravity.rteditor.api.RTApi; import com.onegravity.rteditor.utils.io.IOUtils; import java.io.Closeable; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.Bidi; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; /** * Miscellaneous helper methods */ public abstract class Helper { private static float sDensity = Float.MAX_VALUE; private static float sDensity4Fonts = Float.MAX_VALUE; private static final int LEADING_MARGIN = 28; private static int sLeadingMarging = -1; public static void closeQuietly(Closeable closeable) { IOUtils.closeQuietly(closeable); } public static float getDisplayDensity() { synchronized (Helper.class) { if (sDensity == Float.MAX_VALUE) { sDensity = getDisplayMetrics().density; } return sDensity; } } /** * Convert absolute pixels to scale dependent pixels. * This scales the size by scale dependent screen density (accessibility setting) and * the global display setting for message composition fields */ public static int convertPxToSp(int pxSize) { return Math.round((float) pxSize * getDisplayDensity4Fonts()); } /** * Convert scale dependent pixels to absolute pixels. * This scales the size by scale dependent screen density (accessibility setting) and * the global display setting for message composition fields */ public static int convertSpToPx(int spSize) { return Math.round((float) spSize / getDisplayDensity4Fonts()); } private static DisplayMetrics getDisplayMetrics() { Display display = ((WindowManager) RTApi.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); return metrics; } private static float getDisplayDensity4Fonts() { synchronized (Helper.class) { if (sDensity4Fonts == Float.MAX_VALUE) { sDensity4Fonts = getDisplayMetrics().density * getFontScale(); } return sDensity4Fonts; } } private static float getFontScale() { Configuration config = RTApi.getApplicationContext().getResources().getConfiguration(); return config.fontScale; } public static int getLeadingMarging() { if (sLeadingMarging == -1) { float density = Helper.getDisplayDensity(); sLeadingMarging = Math.round(LEADING_MARGIN * density); } return sLeadingMarging; } /** * This method encodes the query part of an url * @param url an url (e.g. http://www.1gravity.com?query=üö) * @return The url with an encoded query, e.g. http://www.1gravity.com?query%3D%C3%BC%C3%B6 */ public static String encodeUrl(String url) { Uri uri = Uri.parse(url); try { Map<String, List<String>> splitQuery = splitQuery(uri); StringBuilder encodedQuery = new StringBuilder(); for (String key : splitQuery.keySet()) { for (String value : splitQuery.get(key)) { if (encodedQuery.length() > 0) { encodedQuery.append("&"); } encodedQuery.append(key + "=" + URLEncoder.encode(value, "UTF-8")); } } String queryString = encodedQuery != null && encodedQuery.length() > 0 ? "?" + encodedQuery : ""; URI baseUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, uri.getFragment()); return baseUri + queryString; } catch (UnsupportedEncodingException ignore) {} catch (URISyntaxException ignore) {} return uri.toString(); } /** * This method decodes an url with encoded query string * @param url an url with encoded query string (e.g. http://www.1gravity.com?query%C3%BC%C3%B6) * @return The decoded url, e.g. http://www.1gravity.com?query=üö */ public static String decodeQuery(String url) { try { return URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException ignore) {} return url; } /** * Splits the query parameters into key value pairs. * See: http://stackoverflow.com/a/13592567/534471. */ private static Map<String, List<String>> splitQuery(Uri uri) throws UnsupportedEncodingException { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); String query = uri.getQuery(); if (query == null) return query_pairs; final String[] pairs = query.split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<String>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : ""; query_pairs.get(key).add(value); } return query_pairs; } /** * This method determines if the direction of a substring is right-to-left. * If the string is empty that determination is based on the default system language * Locale.getDefault(). * The method can handle invalid substring definitions (start > end etc.), in which case the * method returns False. * * @return True if the text direction is right-to-left, false otherwise. */ public static boolean isRTL(CharSequence s, int start, int end) { if (s == null || s.length() == 0) { // empty string --> determine the direction from the default language return isRTL(Locale.getDefault()); } if (start == end) { // if no character is selected we need to expand the selection start = Math.max(0, --start); if (start == end) { end = Math.min(s.length(), ++end); } } try { Bidi bidi = new Bidi(s.subSequence(start, end).toString(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); return ! bidi.baseIsLeftToRight(); } catch (IndexOutOfBoundsException e) { return false; } } private static boolean isRTL(Locale locale) { int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0)); return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT || directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC; } }
1gravity/Android-RTEditor
RTEditor/src/main/java/com/onegravity/rteditor/utils/Helper.java
Java
apache-2.0
7,834
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/errors/time_zone_error.proto package com.google.ads.googleads.v8.errors; public interface TimeZoneErrorEnumOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v8.errors.TimeZoneErrorEnum) com.google.protobuf.MessageOrBuilder { }
googleads/google-ads-java
google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/errors/TimeZoneErrorEnumOrBuilder.java
Java
apache-2.0
367
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.spanner.changestreams.model; import java.io.Serializable; /** * Represents a Spanner Change Stream Record. It can be one of: {@link DataChangeRecord}, {@link * HeartbeatRecord} or {@link ChildPartitionsRecord}. */ public interface ChangeStreamRecord extends Serializable { }
GoogleCloudPlatform/java-docs-samples
spanner/changestreams/src/main/java/com/example/spanner/changestreams/model/ChangeStreamRecord.java
Java
apache-2.0
891
var Utils = { _parseUrl: function (url) { var query_string = {}; var url = url.substring(url.lastIndexOf("?") + 1).split("&")[0]; var vars = url.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = decodeURIComponent(pair[1]); // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { var arr = [query_string[pair[0]], decodeURIComponent(pair[1])]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(decodeURIComponent(pair[1])); } } return query_string; }, getParameterFromUrl: function (url, parameter) { //TODO: Check if the parameter exists return this._parseUrl(url)[parameter]; } } export {Utils as default}
lopesdasilva/trakt-it
src/services/Utils.js
JavaScript
apache-2.0
1,090
/* * Copyright (c), Recep Aslantas. * * MIT License (MIT), http://opensource.org/licenses/MIT * Full license can be found in the LICENSE file */ /*! * @brief SIMD like functions */ /* Functions: CGLM_INLINE void glm_vec3_broadcast(float val, vec3 d); CGLM_INLINE void glm_vec3_fill(vec3 v, float val); CGLM_INLINE bool glm_vec3_eq(vec3 v, float val); CGLM_INLINE bool glm_vec3_eq_eps(vec3 v, float val); CGLM_INLINE bool glm_vec3_eq_all(vec3 v); CGLM_INLINE bool glm_vec3_eqv(vec3 a, vec3 b); CGLM_INLINE bool glm_vec3_eqv_eps(vec3 a, vec3 b); CGLM_INLINE float glm_vec3_max(vec3 v); CGLM_INLINE float glm_vec3_min(vec3 v); CGLM_INLINE bool glm_vec3_isnan(vec3 v); CGLM_INLINE bool glm_vec3_isinf(vec3 v); CGLM_INLINE bool glm_vec3_isvalid(vec3 v); CGLM_INLINE void glm_vec3_sign(vec3 v, vec3 dest); CGLM_INLINE void glm_vec3_abs(vec3 v, vec3 dest); CGLM_INLINE void glm_vec3_fract(vec3 v, vec3 dest); CGLM_INLINE float glm_vec3_hadd(vec3 v); CGLM_INLINE void glm_vec3_sqrt(vec3 v, vec3 dest); */ #ifndef cglm_vec3_ext_h #define cglm_vec3_ext_h #include "common.h" #include "util.h" /*! * @brief fill a vector with specified value * * @param[in] val value * @param[out] d dest */ CGLM_INLINE void glm_vec3_broadcast(float val, vec3 d) { d[0] = d[1] = d[2] = val; } /*! * @brief fill a vector with specified value * * @param[out] v dest * @param[in] val value */ CGLM_INLINE void glm_vec3_fill(vec3 v, float val) { v[0] = v[1] = v[2] = val; } /*! * @brief check if vector is equal to value (without epsilon) * * @param[in] v vector * @param[in] val value */ CGLM_INLINE bool glm_vec3_eq(vec3 v, float val) { return v[0] == val && v[0] == v[1] && v[0] == v[2]; } /*! * @brief check if vector is equal to value (with epsilon) * * @param[in] v vector * @param[in] val value */ CGLM_INLINE bool glm_vec3_eq_eps(vec3 v, float val) { return fabsf(v[0] - val) <= FLT_EPSILON && fabsf(v[1] - val) <= FLT_EPSILON && fabsf(v[2] - val) <= FLT_EPSILON; } /*! * @brief check if vectors members are equal (without epsilon) * * @param[in] v vector */ CGLM_INLINE bool glm_vec3_eq_all(vec3 v) { return v[0] == v[1] && v[0] == v[2]; } /*! * @brief check if vector is equal to another (without epsilon) * * @param[in] a vector * @param[in] b vector */ CGLM_INLINE bool glm_vec3_eqv(vec3 a, vec3 b) { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2]; } /*! * @brief check if vector is equal to another (with epsilon) * * @param[in] a vector * @param[in] b vector */ CGLM_INLINE bool glm_vec3_eqv_eps(vec3 a, vec3 b) { return fabsf(a[0] - b[0]) <= FLT_EPSILON && fabsf(a[1] - b[1]) <= FLT_EPSILON && fabsf(a[2] - b[2]) <= FLT_EPSILON; } /*! * @brief max value of vector * * @param[in] v vector */ CGLM_INLINE float glm_vec3_max(vec3 v) { float max; max = v[0]; if (v[1] > max) max = v[1]; if (v[2] > max) max = v[2]; return max; } /*! * @brief min value of vector * * @param[in] v vector */ CGLM_INLINE float glm_vec3_min(vec3 v) { float min; min = v[0]; if (v[1] < min) min = v[1]; if (v[2] < min) min = v[2]; return min; } /*! * @brief check if all items are NaN (not a number) * you should only use this in DEBUG mode or very critical asserts * * @param[in] v vector */ CGLM_INLINE bool glm_vec3_isnan(vec3 v) { return isnan(v[0]) || isnan(v[1]) || isnan(v[2]); } /*! * @brief check if all items are INFINITY * you should only use this in DEBUG mode or very critical asserts * * @param[in] v vector */ CGLM_INLINE bool glm_vec3_isinf(vec3 v) { return isinf(v[0]) || isinf(v[1]) || isinf(v[2]); } /*! * @brief check if all items are valid number * you should only use this in DEBUG mode or very critical asserts * * @param[in] v vector */ CGLM_INLINE bool glm_vec3_isvalid(vec3 v) { return !glm_vec3_isnan(v) && !glm_vec3_isinf(v); } /*! * @brief get sign of 32 bit float as +1, -1, 0 * * Important: It returns 0 for zero/NaN input * * @param v vector */ CGLM_INLINE void glm_vec3_sign(vec3 v, vec3 dest) { dest[0] = glm_signf(v[0]); dest[1] = glm_signf(v[1]); dest[2] = glm_signf(v[2]); } /*! * @brief absolute value of each vector item * * @param[in] v vector * @param[out] dest destination vector */ CGLM_INLINE void glm_vec3_abs(vec3 v, vec3 dest) { dest[0] = fabsf(v[0]); dest[1] = fabsf(v[1]); dest[2] = fabsf(v[2]); } /*! * @brief fractional part of each vector item * * @param[in] v vector * @param[out] dest destination vector */ CGLM_INLINE void glm_vec3_fract(vec3 v, vec3 dest) { static union { float f; int32_t i; } num; // Equivalent to 0x1.fffffep-1f. num.i = 0x3f7fffff; dest[0] = fminf(v[0] - floorf(v[0]), num.f); dest[1] = fminf(v[1] - floorf(v[1]), num.f); dest[2] = fminf(v[2] - floorf(v[2]), num.f); } /*! * @brief vector reduction by summation * @warning could overflow * * @param[in] v vector * @return sum of all vector's elements */ CGLM_INLINE float glm_vec3_hadd(vec3 v) { return v[0] + v[1] + v[2]; } /*! * @brief square root of each vector item * * @param[in] v vector * @param[out] dest destination vector */ CGLM_INLINE void glm_vec3_sqrt(vec3 v, vec3 dest) { dest[0] = sqrtf(v[0]); dest[1] = sqrtf(v[1]); dest[2] = sqrtf(v[2]); } #endif /* cglm_vec3_ext_h */
rohdesamuel/cubez
deps/include/cglm/vec3-ext.h
C
apache-2.0
5,466
#!/Users/vishnu/anaconda/bin/python import random import sys """class schema: files=[] def __init__(self): pass def addFile(self,file): self.files.append(file) def setForeignKey(self,primaryFile,theOtherOne): pass""" class JoinReq: def __init__(self,R,S,m,n,fing): self.cost=0 self.first_req=True self.cost = 0 tC,self.t1=R.getFirst(m) #self.cost += tC tC,self.t2=S.getFirst(n) #self.cost += tC self.first_req==False self.R=R self.S=S self.m=m self.n=n self.fing=fing def pull(self): if self.fing==False: temp="" while self.t1 is not None: #print str(t1[m]) + "=" + str(t2[n]) #print "x" while self.t2 is not None: #print str(self.t1[self.m]) + "=" + str(self.t2[self.n]) if self.t1[self.m]==self.t2[self.n]: #self.emit((self.t1,self.t2)) temp= (self.t1,self.t2) self.t2=self.S.getNext(self.n) self.cost+=1 return temp self.t2=self.S.getNext(self.n) self.cost+=1 #print "vishnu" self.t1=self.R.getNext(self.m) self.cost+=1 #print str(t1) + "xx" #if t2==None: tC,self.t2=self.S.getFirst(self.n) self.cost+=tC return "eoo" else: """savedLastKey=-1 while self.t1 is not None: if self.t1>=savedLastKey: while self.t2 is not None: if self.t1[self.m]==self.t2[self.n]: #self.emit((self.t1,self.t2)) temp= (self.t1,self.t2) self.t2=self.S.getNext(self.n) self.cost+=1 return temp self.t2=self.S.getNext(self.n) self.cost+=1 else: tC,self.t2=self.S.getFirst(self.n) self.cost+=tC while self.t2 is not None: if self.t1[self.m]==self.t2[self.n]: #self.emit((self.t1,self.t2)) temp= (self.t1,self.t2) self.t2=self.S.getNext(self.n) self.cost+=1 return temp self.t2=self.S.getNext(self.n) self.cost+=1 savedLastKey=self.t1 self.t1=self.R.getNext(self.m) self.cost+=1 return "eoo" """ savedLastKey=-1 while self.t1 is not None: while self.t1 is not None: while self.t2 is not None and self.t1[self.m]>=self.t2[self.n]: #print str(self.t1[self.m]) + "=" + str(self.t2[self.n]) if self.t1[self.m]==self.t2[self.n]: #self.emit((self.t1,self.t2)) temp= (self.t1,self.t2) self.t2=self.S.getNext(self.n) self.cost+=1 return temp self.t2=self.S.getNext(self.n) self.cost+=1 if self.t2 is None: #print "t2 go non" while self.t1 is not None: self.t1=self.R.getNext(self.m) self.cost+=1 if savedLastKey>self.t1[self.m]: tC,self.t2=self.S.getFirst(self.n) #print tC self.cost+=tC break if self.t2[self.n]>self.t1[self.m]: break while self.t2 is not None: while self.t1 is not None and self.t2[self.n]>=self.t1[self.m]: #print str(self.t1[self.m]) + "=" + str(self.t2[self.n]) if self.t1[self.m]==self.t2[self.n]: #self.emit((self.t1,self.t2)) temp= (self.t1,self.t2) self.t2=self.S.getNext(self.n) self.cost+=1 return temp savedLastKey=self.t1[self.m] self.t1=self.R.getNext(self.m) self.cost+=1 if self.t1 is None: return "eoo" if savedLastKey>self.t1[self.m]: tC,self.t2=self.S.getFirst(self.n) #print tC self.cost+=tC #print self.t2 if self.t1[self.m]>self.t2[self.n]: break return "eoo" def getCost(self): return self.cost class Xf: #max=25 #data={} #stats size,columns,runs,fingers,pkey,max,range #stats=(size,columns,runs,fingers,pkey,max,range) #stats={} #stats = {} def __init__(self,name): self.stats={} self.max=25 self.keyCol=None self.stats["Name"]=name self.data={} self.setStats(0,0,0,0,0,0,0) pass def setStats(self,size,columns,runs,fingers,ordered,pkey,max): #set the status values #print self #print type(self.stats) self.stats["size"]=size self.stats["keyCol"]=pkey self.stats["max"]=max self.stats["columns"]=columns self.stats["runs"]=runs self.stats["cursors"]=[0 for x in range(columns)] self.keyCol=self.stats["keyCol"] self.max=self.stats["max"] self.stats["fingers"]=fingers self.stats["ordered"]=ordered self.fingers=fingers pass def sortCol(self): pass def reset(self): self.stats["fingers"]=[0 if x!=-1 else x for x in self.stats["fingers"]] def getSize(self): return int(self.stats["size"]) def getRuns(self,col): return int(self.stats["runs"][col]) def getFirst(self,col): tuple1 =[] for col in range(self.stats["columns"]): tuple1.append(self.data[str(col)][0]) #print str(self.stats["fingers"][col]) + "*" tCost = self.stats["fingers"][col] #print tCost self.stats["fingers"][col]=0 #if self.stats["Name"] == "s": #print "getFrist " + self.stats["Name"] + str(tuple1[col]) return tCost, tuple1 pass def getNext(self,col): #print self fingerPos=self.stats["fingers"][col] #print str(fingerPos) + "-" + str(len(self.data[str(0)])-2) if int(fingerPos)>=(len(self.data[str(col)])-2): #self.stats["fingers"][col]=0 #print "yo" return None if self.stats["fingers"][col]!=-1 : self.stats["fingers"][col]+=1 #print self.stats["fingers"][col] tuple1 =[] for col in range(self.stats["columns"]): tuple1.append(self.data[str(col)][fingerPos]) #if self.stats["Name"] == "s": #print "getNext " + self.stats["Name"]+ str(tuple1[col]) return tuple1 pass def getFinger(self,col): return self.fingerPos pass def emit(self,x): #print "yo" #print x pass def eJoin(self,S,m,n): cost = 0 tC,t1=self.getFirst(m) cost += tC tC,t2=S.getFirst(n) cost += tC while t1 is not None: #print str(t1[m]) + "=" + str(t2[n]) #print "x" while t2 is not None: #print str(t1[m]) + "=" + str(t2[n]) if t1[m]==t2[n]: self.emit((t1,t2)) t2=S.getNext(n) cost+=1 #print "vishnu" t1=self.getNext(m) cost+=1 #print str(t1) + "xx" #if t2==None: tC,t2=S.getFirst(n) cost+=tC return cost pass def eJoin_pull(self,S,m,n): cost = 0 tC,t1=self.getFirst(m) cost += tC tC,t2=S.getFirst(n) cost += tC while t1 is not None: #print str(t1[m]) + "=" + str(t2[n]) #print "x" while t2 is not None: #print str(t1[m]) + "=" + str(t2[n]) if t1[m]==t2[n]: self.emit((t1,t2)) t2=S.getNext(n) cost+=1 #print "vishnu" t1=self.getNext(m) cost+=1 #print str(t1) + "xx" #if t2==None: tC,t2=S.getFirst(n) cost+=tC return cost pass #def __init__(self): # self.data={} # pass def __repr__(self): t1="" for key in self.data.keys(): t1 = t1 + str(key) + " : " + str(self.data[key]) +"\n" t1= str(t1) + "\nprimary key: " + str(self.keyCol) return t1 def setConstraints(self,key,max): #there is some reduntant code here. Remove self.stats["keyCol"]=key self.keyCol=key self.max=max self.stats["max"]=max pass def printStats(self): print self.stats def replaceDupandSum(self,list1,list2): counter = 0 for i in range(len(list1)): counter=0 for j in range(len(list2)): if list2[j]==list1[i]: #print "xx" + str(list2[j]) #counter+=1 #if counter>1: list2[j]=(list2[j]+list2[j+1])/2 return list1+list2 pass def FormData(self): """ for col in range(self.cols): if col == self.keyCol: #print "key" + str(col) #print runs for r in range(self.runs[col]): temp=sorted(random.sample(range(self.max),size/runs[col])) #print temp self.data[str(col)]=self.replaceDupandSum(self.data.get(str(col),[]),temp) #self.data[str(col)]=set(self.data[str(col)]) #print self.data[str(col)] else: for r in range(self.runs[col]): temp=sorted([random.randrange(self.max) for x in range(size/runs[col])]) self.data[str(col)]=self.data.get(str(col),[])+temp""" self.Generate(self.stats["columns"],self.stats["runs"],self.stats["size"]) def Generate(self,cols,runs,size): for col in range(cols): if col == self.keyCol: #print "key" + str(col) print runs for r in range(runs[col]): temp=sorted(random.sample(range(self.max),size/runs[col])) #print temp self.data[str(col)]=self.replaceDupandSum(self.data.get(str(col),[]),temp) #self.data[str(col)]=set(self.data[str(col)]) #print self.data[str(col)] else: for r in range(runs[col]): temp=sorted([random.randrange(self.max) for x in range(size/runs[col])]) self.data[str(col)]=self.data.get(str(col),[])+temp if self.stats["ordered"][col]==True: self.data[str(col)]=sorted(self.data[str(col)]) def write2File(self,fileName): fp = open(fileName,'w') for col in range(cols): #print self.data[str(col)] stringD="" for x in self.data[str(col)]: stringD=stringD+" "+ str(x) fp.write(stringD+"\n") fp.close() pass def readFile(self,fileName): lines = open(fileName).read().splitlines() for x in range(cols): self.data[str(x)]=lines[0] pass def nJoin(R,S,m,n): t1=R.getFirst(m) t2=S.getFirst(n) while t1 is not None: print str(t1[m]) + "=" + str(t2[n]) #print "x" while t2 is not None: print str(t1[m]) + "=" + str(t2[n]) if t1[m]==t2[n]: R.emit((t1,t2)) t2=S.getNext(n) print "vishnu" t1=R.getNext(m) print str(t1) + "xx" #if t2==None: t2=S.getFirst(n) pass #Generate(3,[3,3,3],9) """inst= file() if len(sys.argv)>1: cols = int(sys.argv[1]) runs = [int(x) for x in sys.argv[2:(len(sys.argv)-1)]] size = int(sys.argv[len(sys.argv)-1]) #print inst.replaceDupandSum([1,6,9,12],[2,5,6,11]) inst.setConstraints(0,200000) inst.Generate(cols,runs,size) inst.write2File("file.txt") """ #inst2=file() #inst2.readFile("file.txt") #print inst2 """ inst3=Xf("r") inst3.setStats(10,2,(2,3),[-1,0],0,40) inst3.FormData() inst4=Xf("s") inst4.setStats(20,2,(2,3),[-1,0],0,40) inst4.FormData() print inst3 print inst4 """ #print inst3.getFirst(1) #print inst4.getFirst(1) #print inst3.getNext(1) #print inst4.getNext(1) #print inst3.getNext(1) #print inst4.getNext(1) #nJoin(inst3,inst4,1,1) #print inst3.eJoin(inst4,1,1) """ inst3.printStats() print inst3.getFirst() print inst3.getNext(1) print inst3.getNext(1) print inst3.getNext(1) print inst3.getNext(1) print inst3.getNext(1)""" #print inst
vishnuprathish/constrained-data-generator
fingered_temp.py
Python
apache-2.0
10,459
/* * Copyright 2012-2020 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 laika.parse.css import laika.ast._ import laika.parse.Parser import laika.parse.markup.InlineParsers import laika.parse.builders._ import laika.parse.implicits._ /** * Parsers for the subset of CSS supported by Laika. * * Not supported are attribute selectors, pseudo classes, namespaces and media queries. * * @author Jens Halm */ object CSSParsers { /** Represents a combinator between two predicates. */ sealed abstract class Combinator /** A combinator for a descendant on any nesting * level. */ case object Descendant extends Combinator /** A combinator for an immediate child. */ case object Child extends Combinator /** Represents a single style within a style * declaration. */ case class Style (name: String, value: String) /** Parses horizontal whitespace or newline characters. */ val wsOrNl: Parser[String] = anyOf(' ', '\t', '\n', '\r') /** Parses the name of a style. The name must start * with a letter, while subsequent characters can be * letters, digits or one of the symbols `'-'` or `'_'`. */ val styleRefName: Parser[String] = { val alpha = someWhile(c => Character.isLetter(c)) val alphaNum = someWhile(c => Character.isDigit(c) || Character.isLetter(c)) val symbol = anyOf('-', '_').max(1) val name = alpha ~ (symbol ~ alphaNum).rep (("fox:" ~ name) | name).source } /** Parses a combinator between two predicates. */ val combinator: Parser[Combinator] = (ws ~ ">" ~ ws).as(Child) | ws.min(1).as(Descendant) /** Parses a single type selector. */ val typeSelector: Parser[List[StylePredicate]] = styleRefName.map { name => List(StylePredicate.ElementType(name)) } | literal("*").as(Nil) /** Parses a single predicate. */ val predicate: Parser[StylePredicate] = { val id: Parser[StylePredicate] = "#" ~> styleRefName.map(StylePredicate.Id.apply) val styleName: Parser[StylePredicate] = "." ~> styleRefName.map(StylePredicate.StyleName.apply) id | styleName } /** Parses the sub-part of a selector without any combinators, e.g. `Paragraph#title`. */ val simpleSelectorSequence: Parser[StyleSelector] = ((typeSelector ~ predicate.rep).concat | predicate.rep.min(1)).map(preds => StyleSelector(preds.toSet)) /** Parses a single selector. */ val selector: Parser[StyleSelector] = simpleSelectorSequence ~ (combinator ~ simpleSelectorSequence).rep ^^ { case sel ~ sels => sels.foldLeft(sel) { case (parent, Child ~ sel) => sel.copy(parent = Some(ParentSelector(parent, immediate = true))) case (parent, Descendant ~ sel) => sel.copy(parent = Some(ParentSelector(parent, immediate = false))) } } /** Parses a sequence of selectors, separated by a comma. */ val selectorGroup: Parser[Seq[StyleSelector]] = selector.rep((ws ~ "," ~ ws).void).min(1) /** Parses the value of a single style, ignoring * any comments.. */ val styleValue: Parser[String] = { val comment = ("/*" ~ delimitedBy("*/") ~ wsOrNl).as("") InlineParsers.text(delimitedBy(';')).embed(comment) } /** Parses a single style within a declaration. */ val style: Parser[Style] = ((styleRefName <~ ws ~ ":" ~ ws) ~ (styleValue <~ wsOrNl)).mapN(Style.apply) /** Parses a single CSS comment. */ val comment: Parser[Unit] = ("/*" ~ delimitedBy("*/") ~ wsOrNl).void /** Parses a sequence of style declarations, ignoring * any comments. */ val styleDeclarations: Parser[Seq[StyleDeclaration]] = ((selectorGroup <~ wsOrNl ~ "{" ~ wsOrNl) ~ (comment | style).rep <~ (wsOrNl ~ "}")) .mapN { (selectors, stylesAndComments) => val styles = stylesAndComments collect { case st: Style => (st.name, st.value) } toMap; selectors map (StyleDeclaration(_, styles)) } /** Parses an entire set of style declarations. * This is the top level parser of this trait. */ lazy val styleDeclarationSet: Parser[Set[StyleDeclaration]] = { (wsOrNl ~ comment.rep ~> (styleDeclarations <~ wsOrNl ~ comment.rep).rep).map { _.flatten.zipWithIndex.map({ case (decl,pos) => decl.increaseOrderBy(pos) }).toSet } } }
planet42/Laika
core/shared/src/main/scala/laika/parse/css/CSSParsers.scala
Scala
apache-2.0
4,875
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/webkit_test_runner.h" #include <algorithm> #include <clocale> #include <cmath> #include "base/base64.h" #include "base/debug/debugger.h" #include "base/md5.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_visitor.h" #include "content/public/test/layouttest_support.h" #include "content/shell/shell_messages.h" #include "content/shell/shell_render_process_observer.h" #include "content/shell/webkit_test_helpers.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "skia/ext/platform_canvas.h" #include "third_party/WebKit/Source/Platform/chromium/public/Platform.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebCString.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebPoint.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebRect.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebSize.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebString.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebURL.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebURLError.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebURLRequest.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebURLResponse.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebArrayBufferView.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDevToolsAgent.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDeviceOrientation.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebHistoryItem.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptSource.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebTestingSupport.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTask.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestInterfaces.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestProxy.h" #include "third_party/WebKit/Tools/DumpRenderTree/chromium/TestRunner/public/WebTestRunner.h" #include "ui/gfx/rect.h" #include "webkit/base/file_path_string_conversions.h" #include "webkit/glue/glue_serialize.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/webpreferences.h" #include "webkit/mocks/test_media_stream_client.h" using WebKit::Platform; using WebKit::WebArrayBufferView; using WebKit::WebContextMenuData; using WebKit::WebDevToolsAgent; using WebKit::WebDeviceOrientation; using WebKit::WebElement; using WebKit::WebFrame; using WebKit::WebGamepads; using WebKit::WebHistoryItem; using WebKit::WebMediaPlayer; using WebKit::WebMediaPlayerClient; using WebKit::WebPoint; using WebKit::WebRect; using WebKit::WebScriptSource; using WebKit::WebSize; using WebKit::WebString; using WebKit::WebURL; using WebKit::WebURLError; using WebKit::WebURLRequest; using WebKit::WebTestingSupport; using WebKit::WebVector; using WebKit::WebView; using WebTestRunner::WebPreferences; using WebTestRunner::WebTask; using WebTestRunner::WebTestInterfaces; using WebTestRunner::WebTestProxyBase; namespace content { namespace { void InvokeTaskHelper(void* context) { WebTask* task = reinterpret_cast<WebTask*>(context); task->run(); delete task; } #if !defined(OS_MACOSX) void MakeBitmapOpaque(SkBitmap* bitmap) { SkAutoLockPixels lock(*bitmap); DCHECK(bitmap->config() == SkBitmap::kARGB_8888_Config); for (int y = 0; y < bitmap->height(); ++y) { uint32_t* row = bitmap->getAddr32(0, y); for (int x = 0; x < bitmap->width(); ++x) row[x] |= 0xFF000000; // Set alpha bits to 1. } } #endif void CopyCanvasToBitmap(SkCanvas* canvas, SkBitmap* snapshot) { SkDevice* device = skia::GetTopDevice(*canvas); const SkBitmap& bitmap = device->accessBitmap(false); bitmap.copyTo(snapshot, SkBitmap::kARGB_8888_Config); #if !defined(OS_MACOSX) // Only the expected PNGs for Mac have a valid alpha channel. MakeBitmapOpaque(snapshot); #endif } class SyncNavigationStateVisitor : public RenderViewVisitor { public: SyncNavigationStateVisitor() {} virtual ~SyncNavigationStateVisitor() {} virtual bool Visit(RenderView* render_view) OVERRIDE { SyncNavigationState(render_view); return true; } private: DISALLOW_COPY_AND_ASSIGN(SyncNavigationStateVisitor); }; class ProxyToRenderViewVisitor : public RenderViewVisitor { public: explicit ProxyToRenderViewVisitor(WebTestProxyBase* proxy) : proxy_(proxy), render_view_(NULL) { } virtual ~ProxyToRenderViewVisitor() {} RenderView* render_view() const { return render_view_; } virtual bool Visit(RenderView* render_view) OVERRIDE { WebKitTestRunner* test_runner = WebKitTestRunner::Get(render_view); if (!test_runner) { NOTREACHED(); return true; } if (test_runner->proxy() == proxy_) { render_view_ = render_view; return false; } return true; } private: WebTestProxyBase* proxy_; RenderView* render_view_; DISALLOW_COPY_AND_ASSIGN(ProxyToRenderViewVisitor); }; class NavigateAwayVisitor : public RenderViewVisitor { public: NavigateAwayVisitor(RenderView* main_render_view) : main_render_view_(main_render_view) {} virtual ~NavigateAwayVisitor() {} virtual bool Visit(RenderView* render_view) OVERRIDE { if (render_view == main_render_view_) return true; render_view->GetWebView()->mainFrame() ->loadRequest(WebURLRequest(GURL("about:blank"))); return true; } private: RenderView* main_render_view_; DISALLOW_COPY_AND_ASSIGN(NavigateAwayVisitor); }; } // namespace WebKitTestRunner::WebKitTestRunner(RenderView* render_view) : RenderViewObserver(render_view), RenderViewObserverTracker<WebKitTestRunner>(render_view), proxy_(NULL), focused_view_(NULL), is_main_window_(false), focus_on_next_commit_(false) { } WebKitTestRunner::~WebKitTestRunner() { } // WebTestDelegate ----------------------------------------------------------- void WebKitTestRunner::clearEditCommand() { render_view()->ClearEditCommands(); } void WebKitTestRunner::setEditCommand(const std::string& name, const std::string& value) { render_view()->SetEditCommandForNextKeyEvent(name, value); } void WebKitTestRunner::setGamepadData(const WebGamepads& gamepads) { SetMockGamepads(gamepads); } void WebKitTestRunner::printMessage(const std::string& message) { Send(new ShellViewHostMsg_PrintMessage(routing_id(), message)); } void WebKitTestRunner::postTask(WebTask* task) { Platform::current()->callOnMainThread(InvokeTaskHelper, task); } void WebKitTestRunner::postDelayedTask(WebTask* task, long long ms) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&WebTask::run, base::Owned(task)), base::TimeDelta::FromMilliseconds(ms)); } WebString WebKitTestRunner::registerIsolatedFileSystem( const WebKit::WebVector<WebKit::WebString>& absolute_filenames) { std::vector<base::FilePath> files; for (size_t i = 0; i < absolute_filenames.size(); ++i) files.push_back(webkit_base::WebStringToFilePath(absolute_filenames[i])); std::string filesystem_id; Send(new ShellViewHostMsg_RegisterIsolatedFileSystem( routing_id(), files, &filesystem_id)); return WebString::fromUTF8(filesystem_id); } long long WebKitTestRunner::getCurrentTimeInMillisecond() { return base::TimeDelta(base::Time::Now() - base::Time::UnixEpoch()).ToInternalValue() / base::Time::kMicrosecondsPerMillisecond; } WebString WebKitTestRunner::getAbsoluteWebStringFromUTF8Path( const std::string& utf8_path) { #if defined(OS_WIN) base::FilePath path(UTF8ToWide(utf8_path)); #else base::FilePath path(base::SysWideToNativeMB(base::SysUTF8ToWide(utf8_path))); #endif if (!path.IsAbsolute()) { GURL base_url = net::FilePathToFileURL(test_config_.current_working_directory.Append( FILE_PATH_LITERAL("foo"))); net::FileURLToFilePath(base_url.Resolve(utf8_path), &path); } return webkit_base::FilePathToWebString(path); } WebURL WebKitTestRunner::localFileToDataURL(const WebURL& file_url) { base::FilePath local_path; if (!net::FileURLToFilePath(file_url, &local_path)) return WebURL(); std::string contents; Send(new ShellViewHostMsg_ReadFileToString( routing_id(), local_path, &contents)); std::string contents_base64; if (!base::Base64Encode(contents, &contents_base64)) return WebURL(); const char data_url_prefix[] = "data:text/css:charset=utf-8;base64,"; return WebURL(GURL(data_url_prefix + contents_base64)); } WebURL WebKitTestRunner::rewriteLayoutTestsURL(const std::string& utf8_url) { const char kPrefix[] = "file:///tmp/LayoutTests/"; const int kPrefixLen = arraysize(kPrefix) - 1; if (utf8_url.compare(0, kPrefixLen, kPrefix, kPrefixLen)) return WebURL(GURL(utf8_url)); base::FilePath replace_path = ShellRenderProcessObserver::GetInstance()->webkit_source_dir().Append( FILE_PATH_LITERAL("LayoutTests/")); #if defined(OS_WIN) std::string utf8_path = WideToUTF8(replace_path.value()); #else std::string utf8_path = WideToUTF8(base::SysNativeMBToWide(replace_path.value())); #endif std::string new_url = std::string("file://") + utf8_path + utf8_url.substr(kPrefixLen); return WebURL(GURL(new_url)); } WebPreferences* WebKitTestRunner::preferences() { return &prefs_; } void WebKitTestRunner::applyPreferences() { webkit_glue::WebPreferences prefs = render_view()->GetWebkitPreferences(); ExportLayoutTestSpecificPreferences(prefs_, &prefs); render_view()->SetWebkitPreferences(prefs); Send(new ShellViewHostMsg_OverridePreferences(routing_id(), prefs)); } std::string WebKitTestRunner::makeURLErrorDescription( const WebURLError& error) { std::string domain = error.domain.utf8(); int code = error.reason; if (domain == net::kErrorDomain) { domain = "NSURLErrorDomain"; switch (error.reason) { case net::ERR_ABORTED: code = -999; // NSURLErrorCancelled break; case net::ERR_UNSAFE_PORT: // Our unsafe port checking happens at the network stack level, but we // make this translation here to match the behavior of stock WebKit. domain = "WebKitErrorDomain"; code = 103; break; case net::ERR_ADDRESS_INVALID: case net::ERR_ADDRESS_UNREACHABLE: case net::ERR_NETWORK_ACCESS_DENIED: code = -1004; // NSURLErrorCannotConnectToHost break; } } else { DLOG(WARNING) << "Unknown error domain"; } return base::StringPrintf("<NSError domain %s, code %d, failing URL \"%s\">", domain.c_str(), code, error.unreachableURL.spec().data()); } void WebKitTestRunner::setClientWindowRect(const WebRect& rect) { ForceResizeRenderView(render_view(), WebSize(rect.width, rect.height)); } void WebKitTestRunner::showDevTools() { Send(new ShellViewHostMsg_ShowDevTools(routing_id())); } void WebKitTestRunner::closeDevTools() { Send(new ShellViewHostMsg_CloseDevTools(routing_id())); } void WebKitTestRunner::evaluateInWebInspector(long call_id, const std::string& script) { WebDevToolsAgent* agent = render_view()->GetWebView()->devToolsAgent(); if (agent) agent->evaluateInWebInspector(call_id, WebString::fromUTF8(script)); } void WebKitTestRunner::clearAllDatabases() { Send(new ShellViewHostMsg_ClearAllDatabases(routing_id())); } void WebKitTestRunner::setDatabaseQuota(int quota) { Send(new ShellViewHostMsg_SetDatabaseQuota(routing_id(), quota)); } void WebKitTestRunner::setDeviceScaleFactor(float factor) { SetDeviceScaleFactor(render_view(), factor); } void WebKitTestRunner::setFocus(WebTestProxyBase* proxy, bool focus) { ProxyToRenderViewVisitor visitor(proxy); RenderView::ForEach(&visitor); if (!visitor.render_view()) { NOTREACHED(); return; } // Check whether the focused view was closed meanwhile. if (!WebKitTestRunner::Get(focused_view_)) focused_view_ = NULL; if (focus) { if (focused_view_ != visitor.render_view()) { if (focused_view_) SetFocusAndActivate(focused_view_, false); SetFocusAndActivate(visitor.render_view(), true); focused_view_ = visitor.render_view(); } } else { if (focused_view_ == visitor.render_view()) { SetFocusAndActivate(visitor.render_view(), false); focused_view_ = NULL; } } } void WebKitTestRunner::setAcceptAllCookies(bool accept) { Send(new ShellViewHostMsg_AcceptAllCookies(routing_id(), accept)); } std::string WebKitTestRunner::pathToLocalResource(const std::string& resource) { #if defined(OS_WIN) if (resource.find("/tmp/") == 0) { // We want a temp file. GURL base_url = net::FilePathToFileURL(test_config_.temp_path); return base_url.Resolve(resource.substr(strlen("/tmp/"))).spec(); } #endif // Some layout tests use file://// which we resolve as a UNC path. Normalize // them to just file:///. std::string result = resource; while (StringToLowerASCII(result).find("file:////") == 0) { result = result.substr(0, strlen("file:///")) + result.substr(strlen("file:////")); } return rewriteLayoutTestsURL(result).spec(); } void WebKitTestRunner::setLocale(const std::string& locale) { setlocale(LC_ALL, locale.c_str()); } void WebKitTestRunner::testFinished() { if (!is_main_window_) { Send(new ShellViewHostMsg_TestFinishedInSecondaryWindow(routing_id())); return; } WebTestInterfaces* interfaces = ShellRenderProcessObserver::GetInstance()->test_interfaces(); interfaces->setTestIsRunning(false); if (interfaces->testRunner()->shouldDumpBackForwardList()) { SyncNavigationStateVisitor visitor; RenderView::ForEach(&visitor); Send(new ShellViewHostMsg_CaptureSessionHistory(routing_id())); } else { CaptureDump(); } } void WebKitTestRunner::testTimedOut() { if (!is_main_window_) return; WebTestInterfaces* interfaces = ShellRenderProcessObserver::GetInstance()->test_interfaces(); interfaces->setTestIsRunning(false); Send(new ShellViewHostMsg_TestFinished(routing_id(), true)); } bool WebKitTestRunner::isBeingDebugged() { return base::debug::BeingDebugged(); } int WebKitTestRunner::layoutTestTimeout() { return test_config_.layout_test_timeout; } void WebKitTestRunner::closeRemainingWindows() { NavigateAwayVisitor visitor(render_view()); RenderView::ForEach(&visitor); Send(new ShellViewHostMsg_CloseRemainingWindows(routing_id())); } int WebKitTestRunner::navigationEntryCount() { return GetLocalSessionHistoryLength(render_view()); } void WebKitTestRunner::goToOffset(int offset) { Send(new ShellViewHostMsg_GoToOffset(routing_id(), offset)); } void WebKitTestRunner::reload() { Send(new ShellViewHostMsg_Reload(routing_id())); } void WebKitTestRunner::loadURLForFrame(const WebURL& url, const std::string& frame_name) { Send(new ShellViewHostMsg_LoadURLForFrame( routing_id(), url, frame_name)); } bool WebKitTestRunner::allowExternalPages() { return test_config_.allow_external_pages; } void WebKitTestRunner::captureHistoryForWindow( WebTestProxyBase* proxy, WebVector<WebKit::WebHistoryItem>* history, size_t* currentEntryIndex) { size_t pos = 0; std::vector<int>::iterator id; for (id = routing_ids_.begin(); id != routing_ids_.end(); ++id, ++pos) { RenderView* render_view = RenderView::FromRoutingID(*id); if (!render_view) { NOTREACHED(); continue; } if (WebKitTestRunner::Get(render_view)->proxy() == proxy) break; } if (id == routing_ids_.end()) { NOTREACHED(); return; } size_t num_entries = session_histories_[pos].size(); *currentEntryIndex = current_entry_indexes_[pos]; WebVector<WebHistoryItem> result(num_entries); for (size_t entry = 0; entry < num_entries; ++entry) { result[entry] = webkit_glue::HistoryItemFromString(session_histories_[pos][entry]); } history->swap(result); } WebMediaPlayer* WebKitTestRunner::createWebMediaPlayer( WebFrame* frame, const WebURL& url, WebMediaPlayerClient* client) { if (!test_media_stream_client_) { test_media_stream_client_.reset( new webkit_glue::TestMediaStreamClient()); } return webkit_glue::CreateMediaPlayer( frame, url, client, test_media_stream_client_.get()); } // RenderViewObserver -------------------------------------------------------- void WebKitTestRunner::DidClearWindowObject(WebFrame* frame) { WebTestingSupport::injectInternalsObject(frame); ShellRenderProcessObserver::GetInstance()->test_interfaces()->bindTo(frame); } bool WebKitTestRunner::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(WebKitTestRunner, message) IPC_MESSAGE_HANDLER(ShellViewMsg_SetTestConfiguration, OnSetTestConfiguration) IPC_MESSAGE_HANDLER(ShellViewMsg_SessionHistory, OnSessionHistory) IPC_MESSAGE_HANDLER(ShellViewMsg_Reset, OnReset) IPC_MESSAGE_HANDLER(ShellViewMsg_NotifyDone, OnNotifyDone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void WebKitTestRunner::Navigate(const GURL& url) { focus_on_next_commit_ = true; if (!is_main_window_ && ShellRenderProcessObserver::GetInstance()->main_test_runner() == this) { WebTestInterfaces* interfaces = ShellRenderProcessObserver::GetInstance()->test_interfaces(); interfaces->setTestIsRunning(true); interfaces->configureForTestWithURL(GURL(), false); } } void WebKitTestRunner::DidCommitProvisionalLoad(WebFrame* frame, bool is_new_navigation) { if (!focus_on_next_commit_) return; focus_on_next_commit_ = false; render_view()->GetWebView()->setFocusedFrame(frame); } void WebKitTestRunner::DidFailProvisionalLoad(WebFrame* frame, const WebURLError& error) { focus_on_next_commit_ = false; } // Public methods - ----------------------------------------------------------- void WebKitTestRunner::Reset() { // The proxy_ is always non-NULL, it is set right after construction. proxy_->reset(); prefs_.reset(); routing_ids_.clear(); session_histories_.clear(); current_entry_indexes_.clear(); render_view()->ClearEditCommands(); render_view()->GetWebView()->mainFrame()->setName(WebString()); render_view()->GetWebView()->mainFrame()->clearOpener(); render_view()->GetWebView()->setPageScaleFactorLimits(-1, -1); render_view()->GetWebView()->setPageScaleFactor(1, WebPoint(0, 0)); render_view()->GetWebView()->enableFixedLayoutMode(false); render_view()->GetWebView()->setFixedLayoutSize(WebSize(0, 0)); // Resetting the internals object also overrides the WebPreferences, so we // have to sync them to WebKit again. WebTestingSupport::resetInternalsObject( render_view()->GetWebView()->mainFrame()); render_view()->SetWebkitPreferences(render_view()->GetWebkitPreferences()); } // Private methods ----------------------------------------------------------- void WebKitTestRunner::CaptureDump() { WebTestInterfaces* interfaces = ShellRenderProcessObserver::GetInstance()->test_interfaces(); if (interfaces->testRunner()->shouldDumpAsAudio()) { const WebArrayBufferView* audio_data = interfaces->testRunner()->audioData(); std::vector<unsigned char> vector_data( static_cast<const unsigned char*>(audio_data->baseAddress()), static_cast<const unsigned char*>(audio_data->baseAddress()) + audio_data->byteLength()); Send(new ShellViewHostMsg_AudioDump(routing_id(), vector_data)); } else { Send(new ShellViewHostMsg_TextDump(routing_id(), proxy()->captureTree(false))); if (test_config_.enable_pixel_dumping && interfaces->testRunner()->shouldGeneratePixelResults()) { SkBitmap snapshot; CopyCanvasToBitmap(proxy()->capturePixels(), &snapshot); SkAutoLockPixels snapshot_lock(snapshot); base::MD5Digest digest; #if defined(OS_ANDROID) // On Android, pixel layout is RGBA, however, other Chrome platforms use // BGRA. const uint8_t* raw_pixels = reinterpret_cast<const uint8_t*>(snapshot.getPixels()); size_t snapshot_size = snapshot.getSize(); scoped_ptr<uint8_t[]> reordered_pixels(new uint8_t[snapshot_size]); for (size_t i = 0; i < snapshot_size; i += 4) { reordered_pixels[i] = raw_pixels[i + 2]; reordered_pixels[i + 1] = raw_pixels[i + 1]; reordered_pixels[i + 2] = raw_pixels[i]; reordered_pixels[i + 3] = raw_pixels[i + 3]; } base::MD5Sum(reordered_pixels.get(), snapshot_size, &digest); #else base::MD5Sum(snapshot.getPixels(), snapshot.getSize(), &digest); #endif std::string actual_pixel_hash = base::MD5DigestToBase16(digest); if (actual_pixel_hash == test_config_.expected_pixel_hash) { SkBitmap empty_image; Send(new ShellViewHostMsg_ImageDump( routing_id(), actual_pixel_hash, empty_image)); } else { Send(new ShellViewHostMsg_ImageDump( routing_id(), actual_pixel_hash, snapshot)); } } } MessageLoop::current()->PostTask( FROM_HERE, base::Bind(base::IgnoreResult(&WebKitTestRunner::Send), base::Unretained(this), new ShellViewHostMsg_TestFinished(routing_id(), false))); } void WebKitTestRunner::OnSetTestConfiguration( const ShellTestConfiguration& params) { test_config_ = params; is_main_window_ = true; setFocus(proxy_, true); WebTestInterfaces* interfaces = ShellRenderProcessObserver::GetInstance()->test_interfaces(); interfaces->setTestIsRunning(true); interfaces->configureForTestWithURL(params.test_url, params.enable_pixel_dumping); } void WebKitTestRunner::OnSessionHistory( const std::vector<int>& routing_ids, const std::vector<std::vector<std::string> >& session_histories, const std::vector<unsigned>& current_entry_indexes) { routing_ids_ = routing_ids; session_histories_ = session_histories; current_entry_indexes_ = current_entry_indexes; CaptureDump(); } void WebKitTestRunner::OnReset() { ShellRenderProcessObserver::GetInstance()->test_interfaces()->resetAll(); Reset(); // Navigating to about:blank will make sure that no new loads are initiated // by the renderer. render_view()->GetWebView()->mainFrame() ->loadRequest(WebURLRequest(GURL("about:blank"))); Send(new ShellViewHostMsg_ResetDone(routing_id())); } void WebKitTestRunner::OnNotifyDone() { render_view()->GetWebView()->mainFrame()->executeScript( WebScriptSource(WebString::fromUTF8("testRunner.notifyDone();"))); } } // namespace content
plxaye/chromium
src/content/shell/webkit_test_runner.cc
C++
apache-2.0
24,003
# UPGRADE FROM X to 4.1.9 When using this bundle with Symfony 4.3 you should configure the templating engine: ```yaml framework: templating: engines: - twig ``` # UPGRADE FROM 3.X to 4.X This release makes error reporting more specific. This release changed the API of the `ReceivedAuthnRequestQueryString::getSignatureAlgorithm` method, returning the signature algorithm url decoded. Any code using this method should be updated removing the url_decode call to prevent double decoding of the sigalg value. # UPGRADE FROM 2.X to 3.X ## SimpleSamlPHP SAML2 The most noticable change is the upgrade of the `simplesamlphp/saml2` library upgrade from version 1 to 3. This resulted in a bundle wide upgrade of the SAML2 namespaces and the implementation of the SAML2 NameID implementaion. ### Update instruction When upgrading the library some other dependencies are to be upgraded most notable is `robrichards/xmlseclibs`. To streamline the upgrade the following installtion instructions are recommended: ``` composer remove surfnet/stepup-saml-bundle --ignore-platform-reqs composer require surfnet/stepup-saml-bundle "^3.0" --ignore-platform-reqs ``` :grey_exclamation: Simply running `composer update surfnet/stepup-saml-bundle "^3.0"` will probably fail as other dependencies will block the update of the package. ### Code changes After updating the SAML2 library, we advice you to scan your project for usages of the SAML2 library. You can do this by grepping your project for usages of the old PEAR style SAML2 classnames. **Namespace** Grep for usages `SAML2_` in your application. PEAR style class references should be updated to their PSR counterparts. Doing so is quite easy. ``` // old style use SAML2_Assertion; // new style use SAML2\Assertion; ``` **NameID** Using NameID values was changed in the SAML2 library. Instead of receiving an array representation of the NameId `['Value' => 'john_doe', 'Format' => 'unspecified')`, a value object is returned. Please inspect your project for usages of the getNameId method on assertions. **XMLSecurityKey** Finally all usages of `XMLSecurityKey` should be checked. The `XMLSecurityKey` objects are now loaded from the `RobRichards` namespace. # UPGRADE FROM 1.X to 2.X ## Multiplicity The multiplicity functionality has been removed from `Surfnet\SamlBundle\SAML2\Attribute\AttributeDefinition`. This means that the method `AttributeDefinition::getMultiplicity()` no longer exists. Furthermore, the related constants `AttributeDefinition::MULTIPLICITY_SINGLE` and `AttributeDefinition::MULTIPLICITY_MULTIPLE` have been removed. **WARNING** The value of an attribute is now always an array of strings, it can no longer be `null` or `string`. This means code relying on the values of attributes should be modified to always accept `string[]` as return value and handle accordingly. The following deprecated methods have been removed: | Class | Removed method | Replaced with | | ---------------------------------------------------- | ---------------- | --------------------- | | `Surfnet\SamlBundle\SAML2\Response\AssertionAdapter` | `getAttribute()` | `getAttributeValue()` |
SURFnet/Stepup-saml-bundle
UPGRADING.md
Markdown
apache-2.0
3,252
/* * Copyright (C) 2018 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.e2e.serenity.web.logging; import net.thucydides.core.annotations.Step; import net.thucydides.core.steps.ScenarioSteps; public class LoggingSettingsSteps extends ScenarioSteps { AcpLoggingSettingsPage loggingSettingsPage; RemovingRootLoggerInvalidPage removingRootLoggerInvalidPage; @Step public void open_logging_settings_page() { loggingSettingsPage.open(); } @Step public void send_logging_settings_form() { loggingSettingsPage.clickSaveButton(); } @Step public void click_for_add_new_console_appender() { loggingSettingsPage.clickAddConsoleAppenderLink(); } @Step public void type_console_appender_name(String appenderName) { loggingSettingsPage.typeConsoleAppenderName(appenderName); } @Step public void type_log_pattern(String pattern) { loggingSettingsPage.typeLogPattern(pattern); } @Step public void send_appender_form() { loggingSettingsPage.clickSaveButton(); } @Step public void should_contain_warn_about_blank_field() { loggingSettingsPage.shouldContainWarnAboutBlankField(); } @Step public void should_contain_warn_about_busy_appender_name() { loggingSettingsPage.shouldContainWarnAboutBusyAppenderName(); } @Step public void should_contain_info_about_success() { loggingSettingsPage.shouldContainInfoAboutSuccess(); } @Step public void should_contain_appender_name(String appenderName) { loggingSettingsPage.shouldContainAppenderName(appenderName); } @Step public void click_edit_appender(String appenderName) { loggingSettingsPage.clickEditLinkForAppender(appenderName); } @Step public void click_delete_appender(String appenderName) { loggingSettingsPage.clickDeleteForAppender(appenderName); } @Step public void should_not_contain_appender_name(String appenderName) { loggingSettingsPage.shouldNotContainAppenderName(appenderName); } @Step public void click_for_add_new_file_appender() { loggingSettingsPage.clickAddFileAppenderLink(); } @Step public void type_file_appender_name(String appenderName) { loggingSettingsPage.typeFileAppenderName(appenderName); } @Step public void type_current_log_file_name(String currentLogFileName) { loggingSettingsPage.typeCurrentLogFileName(currentLogFileName); } @Step public void type_rotation_file_name_pattern(String rotationPattern) { loggingSettingsPage.typeRotationFileNamePattern(rotationPattern); } @Step public void type_max_size_file(String maxSizeFile) { loggingSettingsPage.typeMaxSizeFile(maxSizeFile); } @Step public void type_max_history(String maxHistory) { loggingSettingsPage.typeMaxHistory(maxHistory); } @Step public void should_contain_warn_about_incorrect_max_file_size() { loggingSettingsPage.shouldContainWarnAboutIncorrectMaxFileSize(); } @Step public void should_contain_warn_about_negative_value() { loggingSettingsPage.shouldContainsWarnAboutNegativeValue(); } @Step public void should_contain_warn_about_invalid_value() { loggingSettingsPage.shouldContainWarnAboutInvalidValue(); } @Step public void click_for_add_new_logger() { loggingSettingsPage.clickAddLoggerLink(); } @Step public void type_logger_name(String loggerName) { loggingSettingsPage.typeLoggerName(loggerName); } @Step public void send_logger_form() { loggingSettingsPage.clickSaveButton(); } @Step public void should_contain_warn_about_incorrect_logger_name() { loggingSettingsPage.shouldContainWarnAboutIncorrectLoggerName(); } @Step public void should_contain_warn_about_busy_logger_name() { loggingSettingsPage.shouldContainWarnAboutBusyLoggerName(); } @Step public void should_contain_logger_name(String loggerName) { loggingSettingsPage.shouldContainLoggerName(loggerName); } @Step public void click_delete_logger(String loggerName) { loggingSettingsPage.clickDeleteForLogger(loggerName); } @Step public void should_not_contain_logger_name(String loggerName) { loggingSettingsPage.shouldNotContainLoggerName(loggerName); } @Step public void open_address_for_removing_root_logger() { removingRootLoggerInvalidPage.open(); } @Step public void should_contain_error_about_attempting_to_remove_root_logger() { removingRootLoggerInvalidPage.shouldContainErrorAboutAttemptingToRemoveRootLogger(); } }
jbb-project/jbb
jbb-web-app-e2e-tests/src/test/java/org/jbb/e2e/serenity/web/logging/LoggingSettingsSteps.java
Java
apache-2.0
5,031
# Inocephalus rhombisporus (Kühner & Boursier) Largent, 1994 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Entolomatoid fungi of the Western United States and Alaska (Eureka) 388 (1994) #### Original name Leptonia rhombispora Kühner & Boursier, 1929 ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Entolomataceae/Entoloma/Entoloma rhombisporum/ Syn. Inocephalus rhombisporus/README.md
Markdown
apache-2.0
331
/** * Copyright 2014 Kosta Korenkov * * 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.bitcoinj.wallet; import org.bitcoinj.core.ECKey; import org.bitcoinj.script.Script; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; /** * This class aggregates data required to spend transaction output. * * For pay-to-address and pay-to-pubkey transactions it will have only a single key and CHECKSIG program as redeemScript. * For multisignature transactions there will be multiple keys one of which will be a full key and the rest are watch only, * redeem script will be a CHECKMULTISIG program. Keys will be sorted in the same order they appear in * a program (lexicographical order). */ public class RedeemData { public final Script redeemScript; public final List<ECKey> keys; private RedeemData(List<ECKey> keys, Script redeemScript) { this.redeemScript = redeemScript; List<ECKey> sortedKeys = new ArrayList<ECKey>(keys); Collections.sort(sortedKeys, ECKey.PUBKEY_COMPARATOR); this.keys = sortedKeys; } public static RedeemData of(List<ECKey> keys, Script redeemScript) { return new RedeemData(keys, redeemScript); } /** * Creates RedeemData for pay-to-address or pay-to-pubkey input. Provided key is a single private key needed * to spend such inputs and provided program should be a proper CHECKSIG program. */ public static RedeemData of(ECKey key, Script program) { checkArgument(program.isSentToAddress() || program.isSentToRawPubKey()); return key != null ? new RedeemData(Arrays.asList(key), program) : null; } /** * Returns the first key that has private bytes */ public ECKey getFullKey() { for (ECKey key : keys) if (key.hasPrivKey()) return key; return null; } }
jife94/bitcoinj
core/src/main/java/org/bitcoinj/wallet/RedeemData.java
Java
apache-2.0
2,503
# Contributing Guidelines Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional documentation, we greatly value feedback and contributions from our community. Please read through this document before submitting any issues or pull requests to ensure we have all the necessary information to effectively respond to your bug report or contribution. ## Reporting Bugs/Feature Requests We welcome you to use the GitHub issue tracker to report bugs or suggest features. When filing an issue, please check [existing open](https://github.com/amzn/amazon-pay-sdk-samples/issues), or [recently closed](https://github.com/amzn/amazon-pay-sdk-samples/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: * A reproducible test case or series of steps * The version of our code being used * Any modifications you've made relevant to the bug * Anything unusual about your environment or deployment ## Contributing via Pull Requests Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 1. You are working against the latest source on the *master* branch. 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. To send us a pull request, please: 1. Fork the repository. 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 3. Ensure local tests pass. 4. Commit to your fork using clear commit messages. 5. Send us a pull request, answering any default questions in the pull request interface. 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). ## Finding contributions to work on Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/amzn/amazon-pay-sdk-samples/labels/help%20wanted) issues is a great place to start. ## Code of Conduct This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact opensource-codeofconduct@amazon.com with any additional questions or comments. ## Security issue notifications If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. ## Licensing See the [LICENSE](https://github.com/amzn/amazon-pay-sdk-samples/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes.
amzn/login-and-pay-with-amazon-sdk-samples
CONTRIBUTING.md
Markdown
apache-2.0
3,603
package com.github.aalleexxeeii.hocon.sbt import java.io.{FileOutputStream, OutputStream, PrintStream, PrintWriter} import com.github.aalleexxeeii.hocon.sbt.opt.Common.{CommentMode, _} import com.github.aalleexxeeii.hocon.sbt.opt.{Common, Defaults, Purify} import com.typesafe.config._ import sbt.Keys._ import sbt.classpath.ClasspathUtilities import sbt.{AutoPlugin, _} import scala.collection.JavaConverters._ import scala.io.Source object HoconPlugin extends AutoPlugin { object autoImport { lazy val hoconExtraResources = settingKey[Seq[String]]("additional reference files to consider") lazy val hoconPurify = inputKey[String]("Purify source HOCON configuration removing settings coniciding with defaults") lazy val hoconDefaults = inputKey[String]("Generate joint HOCON configuration with defaults") lazy val baseHoconSettings: Seq[Def.Setting[_]] = Seq( hoconExtraResources := Nil, hoconPurify := { val args = Def.spaceDelimited(Purify.parser.usage).parsed Purify.parser.parse(args, Purify()) map { opt ⇒ purify( loader = createLoader((fullClasspath in Compile).value), input = readInput(opt.input), output = outputWriter(opt.output), extraResources = hoconExtraResources.value, options = opt ) } getOrElse sys.error("Wrong arguments") }, hoconDefaults := { val args = Def.spaceDelimited(Defaults.parser.usage).parsed Defaults.parser.parse(args, Defaults()) map { opt ⇒ defaults( loader = createLoader((fullClasspath in Compile).value), output = outputWriter(opt.output), extraResources = hoconExtraResources.value, options = opt ) } getOrElse sys.error("Wrong arguments") } ) } import autoImport._ override def trigger = allRequirements def createLoader(cp: Seq[Attributed[File]]) = ClasspathUtilities.toLoader(cp map (_.data)) override lazy val projectSettings = baseHoconSettings //inConfig(Compile)(baseHoconSettings) def readDefaults(loader: ClassLoader, extraResources: Seq[String] = Nil, options: Common) = { def parseResource(path: String) = escapeUnresolved( ConfigFactory.parseResources(loader, path, parseOptions), options ) val referenceConfig = parseResource("reference.conf") extraResources.foldRight(referenceConfig)(parseResource(_) withFallback _) } def purify(loader: ClassLoader, input: String, output: OutputStream, extraResources: Seq[String] = Nil, options: Purify) = { val inputConfig = escapeUnresolved(ConfigFactory.parseString(input, parseOptions), options.common) val defaults = readDefaults(loader, extraResources, options.common) val inputSet = toPairSet(inputConfig) val defaultsSet = toPairSet(defaults) val defaultsMap = defaultsSet.toMap var diff = inputSet.diff(defaultsSet) if (options.common.commentMode != CommentMode.Off) { diff = diff map { case (key, value) ⇒ key → { defaultsMap.get(key) map { v ⇒ val referenceComments = comments(v) val inputComments = comments(value) value.withOrigin( v.origin.withComments( (options.common.commentMode match { case CommentMode.Override ⇒ if (inputComments.isEmpty) referenceComments else inputComments case CommentMode.Merge ⇒ referenceComments ::: inputComments case unsupported ⇒ sys.error(s"Unsupported comment mode: $unsupported") }).asJava ) ) } getOrElse value } } } val restored = ConfigFactory.parseMap(diff.toMap.asJava) val raw = render(restored, options.common) val unescaped = unescape(raw) dump(unescaped, output) } def defaults(loader: ClassLoader, output: OutputStream, extraResources: Seq[String] = Nil, options: Defaults) = { val config = readDefaults(loader, extraResources, options.common) dump(unescape(render(config, options.common)), output) } private val EscapePrefix = "\ufff0" private val EscapeSuffix = "\ufff1" private val EscapedPattern = s"""(?m)\"$EscapePrefix(.+)$EscapeSuffix\"""".r def escapeUnresolved(config: Config, options: Common): Config = { val unmergeables = toPairSet(config) collect { case (path, v@UnmergeableBridge()) ⇒ val raw = v.render(renderOptions.setOriginComments(options.originComments)) path → ConfigValueFactory.fromAnyRef(s"$EscapePrefix$raw$EscapeSuffix").withOrigin(v.origin()) } unmergeables.foldLeft(config) { case (c, (path, value)) ⇒ c.withValue(path, value) } } protected def unescape(text: String) = EscapedPattern.replaceAllIn(text, { m ⇒ val quoted = m.group(1) val unquoted = ConfigFactory.parseString(s"""x="$quoted"""").getString("x") unquoted.replace("$", "\\$") }) protected def dump(config: Config, output: OutputStream): String = { dump(render(config), output) } protected def dump(text: String, output: OutputStream): String = { val writer = new PrintWriter(output) writer.print(text) writer.flush() output match { case _: PrintStream ⇒ case _ ⇒ output.close() } text } protected val resolveOptions = ConfigResolveOptions.defaults().setAllowUnresolved(true).setUseSystemEnvironment(false) protected val parseOptions = ConfigParseOptions.defaults().setAllowMissing(true) protected val renderOptions = ConfigRenderOptions.defaults().setOriginComments(false).setJson(false) protected def readInput(path: String): String = { path match { case StdStreamSymbol ⇒ Source.fromInputStream(System.in) case _ ⇒ Source.fromFile(path) } }.getLines() mkString "\n" def outputWriter(path: String) = path match { case StdStreamSymbol ⇒ System.out case _ ⇒ new FileOutputStream(path) } def toPairSet(config: Config) = config.resolve(resolveOptions).entrySet().asScala.map(e ⇒ e.getKey → e.getValue) def render(config: Config, options: Common = Common()) = applyPathRestrictions(config, options).root.render(ConfigRenderOptions.defaults .setComments(options.commentMode != CommentMode.Off) .setOriginComments(options.originComments) .setJson(false) ) def applyPathRestrictions(config: Config, options: Common) = options.exclusions.foldLeft { if (options.inclusions.isEmpty) config else options.inclusions map config.withOnlyPath reduce (_ withFallback _) }(_ withoutPath _) def comments(v: ConfigValue): List[String] = v.origin().comments().asScala.toList private object UnmergeableBridge { // reflection due to package access level in impl.* classes and cross-classloader issues private val classUnmergeable = Class.forName("com.typesafe.config.impl.Unmergeable", true, getClass.getClassLoader) def unapply(v: ConfigValue): Boolean = classUnmergeable isInstance v } }
aalleexxeeii/sbt-hocon
project/plugin.scala
Scala
apache-2.0
7,133
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_32603_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=2485#src-2485" >testAbaNumberCheck_32603_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:44:47 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_32603_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=22592#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
dcarda/aba.route.validator
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15_testAbaNumberCheck_32603_good_hfk.html
HTML
apache-2.0
9,179
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_17b.html">Class Test_AbaRouteValidator_17b</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_37277_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17b.html?line=52649#src-52649" >testAbaNumberCheck_37277_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:46:57 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_37277_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=9981#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
dcarda/aba.route.validator
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17b_testAbaNumberCheck_37277_good_7p9.html
HTML
apache-2.0
9,183
/* * 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. */ /** * @author Igor V. Stolyarov * @version $Revision$ */ #ifndef __GDI_BLITTER__ #define __GDI_BLITTER__ #include <Windows.h> #include <Wingdi.h> #include <jni.h> #include "LUTTables.h" #include "SurfaceDataStructure.h" #define BIT_BLT 0 #define TRANSPARENT_BLT 1 #define ALPHA_BLEND 2 #define NULL_BLT 3 void findNonExistColor(DWORD &, DWORD *, UINT); BOOL isRepeatColor(UINT , DWORD *, UINT); BOOL initBlitData(SURFACE_STRUCTURE *srcSurf, JNIEnv *env, jobject srcData, UINT compType, UCHAR srcConstAlpha, BLITSTRUCT *blitStruct); BOOL initBitmap(SURFACE_STRUCTURE *srcSurf, JNIEnv *env, jobject srcData, BOOL alphaPre); #endif
freeVM/freeVM
enhanced/archive/classlib/java6/modules/awt/src/main/native/gl/windows/GDIBlitter.h
C
apache-2.0
1,506
using System; using System.Collections.Generic; namespace TheUnacademicPortfolio.ViewModels { public class StudentViewModel { public Guid Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string MothersLastName { get; set; } public string StudentNumber { get; set; } public string Email { get; set; } public int Semester { get; set; } public MajorViewModel Major { get; set; } public List<SubjectViewModel> Subjects { get; set; } } }
pichardoJ/TheUnacademicPortfolio
src/TheUnacademicPortfolio/ViewModels/StudentViewModel.cs
C#
apache-2.0
569
/** * Appcelerator Titanium Mobile * Copyright (c) 2011 by ListAndPicker, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * * WARNING: This is generated code. Modify at your own risk and without support. */ #if defined(USE_TI_XML) || defined(USE_TI_NETWORK) #import "TiProxy.h" #import "TiDOMNodeProxy.h" @interface TiDOMCharacterDataProxy : TiDOMNodeProxy { @private } @property(nonatomic,copy,readwrite) NSString * data; @property(nonatomic,readonly) NSNumber * length; -(NSString *) substringData:(id)args; -(void) appendData:(id)args; -(void) insertData:(id)args; -(void) deleteData:(id)args; -(void) replaceData:(id)args; @end #endif
TShelton41/ListAndPicker
build/iphone/Classes/TIDOMCharacterDataProxy.h
C
apache-2.0
756
namespace Data { using System; using System.Collections.Generic; using System.Data.Entity; using Data.Repositories; using Model; public class BullsAndCowsData : IBullsAndCowsData { private DbContext context; private IDictionary<Type, object> repositories; public BullsAndCowsData(DbContext context) { this.context = context; this.repositories = new Dictionary<Type, object>(); } public BullsAndCowsData() : this(new ApplicationDbContext()) { } public IRepository<Player> Users { get { return GetRepository<Player>(); } } public IRepository<Game> Games { get { return GetRepository<Game>(); } } public IRepository<Guess> Guesses { get { return GetRepository<Guess>(); } } public IRepository<Notification> Notifications { get { return GetRepository<Notification>(); } } public int SaveChanges() { return this.context.SaveChanges(); } private IRepository<T> GetRepository<T>() where T : class { var typeOfRepository = typeof(T); if (!this.repositories.ContainsKey(typeOfRepository)) { var newRepository = Activator.CreateInstance(typeof(EFRepository<T>), this.context); this.repositories.Add(typeOfRepository, newRepository); } return (IRepository<T>)this.repositories[typeOfRepository]; } } }
iliantrifonov/TelerikAcademy
Web services and Cloud/ExamWebApi/Data/BullsAndCowsData.cs
C#
apache-2.0
1,793
require 'aws-sigv4' module Aws module EC2 module Plugins # This plugin auto populates the following request params for the # CopySnapshot API: # # * `:destination_region` # * `:presigned_url` # # These params are required by EC2 when copying an encrypted snapshot. # @api private class CopyEncryptedSnapshot < Seahorse::Client::Plugin # @api private class Handler < Seahorse::Client::Handler def call(context) params = context.params params[:destination_region] = context.config.region params[:presigned_url] = presigned_url(context, params) @handler.call(context) end private def presigned_url(context, params) param_list = Aws::Query::ParamList.new param_list.set('Action', 'CopySnapshot') param_list.set('DestinationRegion', context.config.region) param_list.set('Version', context.config.api.version) Aws::Query::EC2ParamBuilder.new(param_list).apply(context.operation.input, params) signer = Aws::Sigv4::Signer.new( service: 'ec2', region: params[:source_region], credentials_provider: context.config.credentials ) url = Aws::Partitions::EndpointProvider.resolve(signer.region, 'ec2') url += "?#{param_list.to_s}" signer.presign_url( http_method: 'GET', url: url, body: '', expires_in: 3600 ).to_s end end handler(Handler, step: :initialize, operations: [:copy_snapshot]) end end end end
llooker/aws-sdk-ruby
gems/aws-sdk-ec2/lib/aws-sdk-ec2/plugins/copy_encrypted_snapshot.rb
Ruby
apache-2.0
1,736
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.trans.steps.parallelgzipcsv; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Read a simple CSV file * Just output Strings found in the file... * * @author Matt * @since 2007-07-05 */ public class ParGzipCsvInput extends BaseStep implements StepInterface { private static Class<?> PKG = ParGzipCsvInputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private ParGzipCsvInputMeta meta; private ParGzipCsvInputData data; public ParGzipCsvInput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ParGzipCsvInputMeta)smi; data=(ParGzipCsvInputData)sdi; if (first) { first=false; data.outputRowMeta = new RowMeta(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); if (data.filenames==null) { // We're expecting the list of filenames from the previous step(s)... // getFilenamesFromPreviousSteps(); } // We only run in parallel if we have at least one file to process // AND if we have more than one step copy running... // data.parallel = meta.isRunningInParallel() && data.totalNumberOfSteps>1; // The conversion logic for when the lazy conversion is turned of is simple: // Pretend it's a lazy conversion object anyway and get the native type during conversion. // data.convertRowMeta = data.outputRowMeta.clone(); for (ValueMetaInterface valueMeta : data.convertRowMeta.getValueMetaList()) { valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING); } // Calculate the indexes for the filename and row number fields // data.filenameFieldIndex = -1; if (!Const.isEmpty(meta.getFilenameField()) && meta.isIncludingFilename()) { data.filenameFieldIndex = meta.getInputFields().length; } data.rownumFieldIndex = -1; if (!Const.isEmpty(meta.getRowNumField())) { data.rownumFieldIndex = meta.getInputFields().length; if (data.filenameFieldIndex>=0) { data.rownumFieldIndex++; } } // Open the next file... // boolean opened = false; while (data.filenr<data.filenames.length) { if (openNextFile()) { opened=true; break; } } if (!opened) { setOutputDone(); // last file, end here return false; } } Object[] outputRowData=readOneRow(true); // get row, set busy! if (outputRowData==null) // no more input to be expected... { if (skipToNextBlock()) { // If we need to open a new file, make sure we don't stop when we get a false from the openNextFile() algorithm. // It can also mean that the file is smaller than the block size // In that case, check the file number and retry until we get a valid file position to work with. // boolean opened = false; while (data.filenr<data.filenames.length) { if (openNextFile()) { opened=true; break; } } if (opened) { return true; // try again on the next loop in the next file... } else { incrementLinesUpdated(); setOutputDone(); // last file, end here return false; } } else { return true; // try again on the next loop in the next block... } } else { putRow(data.outputRowMeta, outputRowData); // copy row to possible alternate rowset(s). if (checkFeedback(getLinesInput())) { if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "ParGzipCsvInput.Log.LineNumber", Long.toString(getLinesInput()))); //$NON-NLS-1$ } } return true; } private boolean skipToNextBlock() throws KettleException { if (data.eofReached) { return true; // next file please! } // Reset the bytes read in the current block of data // data.totalBytesRead=0L; data.blockNr++; if (data.parallel) { // So our first act is to skip to the correct position in the compressed stream... // The number of bytes to skip is nrOfSteps*BufferSize // long positionToReach = (data.blockNr*data.blockSize*data.totalNumberOfSteps) + data.stepNumber*data.blockSize; // How many bytes do we need to skip to get where we need to be? // long bytesToSkip = positionToReach - data.fileReadPosition; logBasic("Skipping "+bytesToSkip+" bytes to go to position "+positionToReach+" for step copy "+data.stepNumber); // Get into position... // try { long bytesSkipped = 0; while (bytesSkipped<bytesToSkip) { long n=data.gzis.skip(bytesToSkip-bytesSkipped); if (n<=0) { // EOF reached... // data.eofReached=true; data.fileReadPosition+=bytesSkipped; return true; // nothing more to be found in the file, stop right here. } bytesSkipped+=n; } data.fileReadPosition+=bytesSkipped; // Now we need to clear the buffer, reset everything... // clearBuffer(); // Now get read until the next CR: // readOneRow(false); return false; } catch(IOException e) { throw new KettleException("Error skipping "+bytesToSkip+" bytes to the next block of data", e); } } else { // this situation should never happen. // return true; // stop processing the file } } private void getFilenamesFromPreviousSteps() throws KettleException { List<String> filenames = new ArrayList<String>(); boolean firstRow = true; int index=-1; Object[] row = getRow(); while (row!=null) { if (firstRow) { firstRow=false; // Get the filename field index... // String filenameField = environmentSubstitute(meta.getFilenameField()); index = getInputRowMeta().indexOfValue(filenameField); if (index<0) { throw new KettleException(BaseMessages.getString(PKG, "ParGzipCsvInput.Exception.FilenameFieldNotFound", filenameField)); } } String filename = getInputRowMeta().getString(row, index); filenames.add(filename); // add it to the list... row = getRow(); // Grab another row... } data.filenames = filenames.toArray(new String[filenames.size()]); logBasic(BaseMessages.getString(PKG, "ParGzipCsvInput.Log.ReadingFromNrFiles", Integer.toString(data.filenames.length))); } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { try { closeFile(); // close the final file } catch (Exception ignored) { // Exceptions on stream / file closing should be ignored. } super.dispose(smi, sdi); } private boolean openNextFile() throws KettleException { try { // Close the previous file... // closeFile(); if (data.filenr>=data.filenames.length) { return false; } // Open the next one... // logBasic("Opening file #"+data.filenr+" : "+data.filenames[data.filenr]); FileObject fileObject = KettleVFS.getFileObject(data.filenames[data.filenr], getTransMeta()); data.fis = KettleVFS.getInputStream(fileObject); if (meta.isLazyConversionActive()) { data.binaryFilename=data.filenames[data.filenr].getBytes(); } data.gzis = new GZIPInputStream(data.fis, data.bufferSize); clearBuffer(); data.fileReadPosition = 0L; data.blockNr=0; data.eofReached = false; // Skip to the next file... // data.filenr++; // If we are running in parallel and we need to skip bytes in the first file, let's do so here. // if (data.parallel) { // Calculate the first block of data to read from the file // If the buffer size is 500, we read 0-499 for the first file, // 500-999 for the second, 1000-1499 for the third, etc. // // After that we need to get 1500-1999 for the first step again, // 2000-2499 for the second, 2500-2999 for the third, etc. // // This is equivalent : // // FROM : stepNumber * bufferSize + blockNr*bufferSize*nrOfSteps // TO : FROM + bufferSize - 1 // // Example : step 0, block 0, size 500: // From: 0*500+0*500*3=0 To: 0+500-1=499 // // Example : step 0, block 1, size 500: // From: 0*500+1*500*3=1500 To: 1500+500-1=1999 // // So our first act is to skip to the correct position in the compressed stream... // data.blockSize = 2*data.bufferSize; // for now. long bytesToSkip = data.stepNumber*data.blockSize; if (bytesToSkip>0) { // Get into position for block 0 // logBasic("Skipping "+bytesToSkip+" bytes to go to position "+bytesToSkip+" for step copy "+data.stepNumber); long bytesSkipped=0L; while (bytesSkipped<bytesToSkip) { long n = data.gzis.skip(bytesToSkip-bytesSkipped); if (n<=0) { // EOF in this file, can't read a block in this step copy data.eofReached=true; return false; } bytesSkipped+=n; } // Keep track of the file pointer! // data.fileReadPosition+=bytesSkipped; // Reset the bytes read in the current block of data // data.totalBytesRead=0L; // Skip the first row until the next CR // readOneRow(false); } else { // Reset the bytes read in the current block of data // data.totalBytesRead=0L; // See if we need to skip a header row... // if (meta.isHeaderPresent()) { readOneRow(false); } } } else { // Just one block: read it all until we hit an EOF. // data.blockSize = Long.MAX_VALUE; // 9,223,372,036 GB // Also see here if we need to skip a header row... // if (meta.isHeaderPresent()) { readOneRow(false); } } // Add filename to result filenames ? if(meta.isAddResultFile()) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject, getTransMeta().getName(), toString()); resultFile.setComment("File was read by a Csv input step"); addResultFile(resultFile); } // Reset the row number pointer... // data.rowNumber = 1L; return true; } catch(Exception e) { throw new KettleException(e); } } private void clearBuffer() { data.startBuffer=0; data.endBuffer=0; data.maxBuffer=0; } /** * Check to see if the buffer size is large enough given the data.endBuffer pointer.<br> * Resize the buffer if there is not enough room. * * @return false if everything is OK, true if there is a problem and we should stop. * @throws IOException in case there is a I/O problem (read error) */ private boolean checkBufferSize() throws KettleException { if (data.endBuffer>=data.maxBuffer) { // Oops, we need to read more data... // Better resize this before we read other things in it... // if (data.eofReached || data.getMoreData()) { // If we didn't manage to read anything, we return true to indicate we're done // return true; } } return false; } /** Read a single row of data from the file... * * @param doConversions if you want to do conversions, set to false for the header row. * @return a row of data... * @throws KettleException */ private Object[] readOneRow(boolean doConversions) throws KettleException { // First see if we haven't gone past our block boundary! // Not >= because a block can start smack at the beginning of a line. // Since we always skip the first row after skipping a block that would mean we drop rows here and there. // So keep this > (larger than) // if (data.totalBytesRead>data.blockSize) { // skip to the next block or file by returning null // return null; } try { Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size()); int outputIndex=0; boolean newLineFound = false; int newLines = 0; // The strategy is as follows... // We read a block of byte[] from the file. // We scan for the separators in the file (NOT for line feeds etc) // Then we scan that block of data. // We keep a byte[] that we extend if needed.. // At the end of the block we read another, etc. // // Let's start by looking where we left off reading. // while (!newLineFound && outputIndex<meta.getInputFields().length) { if (checkBufferSize()) { // Last row was being discarded if the last item is null and // there is no end of line delimiter if (outputRowData != null) { // Make certain that at least one record exists before // filling the rest of them with null if (outputIndex > 0) { return (outputRowData); } } return null; // nothing more to read, call it a day. } // OK, at this point we should have data in the byteBuffer and we should be able to scan for the next // delimiter (;) // So let's look for a delimiter. // Also skip over the enclosures ("), it is NOT taking into account escaped enclosures. // Later we can add an option for having escaped or double enclosures in the file. <sigh> // boolean delimiterFound = false; boolean enclosureFound = false; int escapedEnclosureFound = 0; while (!delimiterFound) { // If we find the first char, we might find others as well ;-) // Single byte delimiters only for now. // if (data.byteBuffer[data.endBuffer]==data.delimiter[0]) { delimiterFound = true; } // Perhaps we found a new line? // "\n\r".getBytes() // else if (data.byteBuffer[data.endBuffer]=='\n' || data.byteBuffer[data.endBuffer]=='\r') { data.endBuffer++; data.totalBytesRead++; newLines=1; if (!checkBufferSize()) { // re-check for double delimiters... if (data.byteBuffer[data.endBuffer]=='\n' || data.byteBuffer[data.endBuffer]=='\r') { data.endBuffer++; data.totalBytesRead++; newLines=2; checkBufferSize(); } } newLineFound = true; delimiterFound = true; } // Perhaps we need to skip over an enclosed part? // We always expect exactly one enclosure character // If we find the enclosure doubled, we consider it escaped. // --> "" is converted to " later on. // else if (data.enclosure != null && data.byteBuffer[data.endBuffer]==data.enclosure[0]) { enclosureFound=true; boolean keepGoing; do { data.endBuffer++; if (checkBufferSize()) { enclosureFound=false; break; } keepGoing = data.byteBuffer[data.endBuffer]!=data.enclosure[0]; if (!keepGoing) { // We found an enclosure character. // Read another byte... // data.endBuffer++; if (checkBufferSize()) { enclosureFound=false; break; } // If this character is also an enclosure, we can consider the enclosure "escaped". // As such, if this is an enclosure, we keep going... // keepGoing = data.byteBuffer[data.endBuffer]==data.enclosure[0]; if (keepGoing) escapedEnclosureFound++; } } while (keepGoing); // Did we reach the end of the buffer? // if (data.endBuffer>=data.bufferSize) { newLineFound=true; // consider it a newline to break out of the upper while loop newLines+=2; // to remove the enclosures in case of missing newline on last line. break; } } else { data.endBuffer++; data.totalBytesRead++; if (checkBufferSize()) { if (data.endBuffer>=data.bufferSize) { newLineFound=true; break; } } } } // If we're still here, we found a delimiter.. // Since the starting point never changed really, we just can grab range: // // [startBuffer-endBuffer[ // // This is the part we want. // int length = data.endBuffer-data.startBuffer; if (newLineFound) { length-=newLines; if (length<=0) length=0; } if (enclosureFound) { data.startBuffer++; length-=2; if (length<=0) length=0; } if (length<=0) length=0; byte[] field = new byte[length]; System.arraycopy(data.byteBuffer, data.startBuffer, field, 0, length); // Did we have any escaped characters in there? // if (escapedEnclosureFound>0) { if (log.isRowLevel()) logRowlevel("Escaped enclosures found in "+new String(field)); field = data.removeEscapedEnclosures(field, escapedEnclosureFound); } if (doConversions) { if (meta.isLazyConversionActive()) { outputRowData[outputIndex++] = field; } else { // We're not lazy so we convert the data right here and now. // The convert object uses binary storage as such we just have to ask the native type from it. // That will do the actual conversion. // ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(outputIndex); outputRowData[outputIndex++] = sourceValueMeta.convertBinaryStringToNativeType(field); } } else { outputRowData[outputIndex++] = null; // nothing for the header, no conversions here. } // if (outputRowData[0]!=null && (outputRowData[0] instanceof Long) && ((Long)outputRowData[0]).longValue()==95174) { // System.out.println(outputRowData[0]); // } // OK, move on to the next field... if( !newLineFound) { data.endBuffer++; data.totalBytesRead++; } data.startBuffer = data.endBuffer; } // See if we reached the end of the line. // If not, we need to skip the remaining items on the line until the next newline... // if (!newLineFound && !checkBufferSize()) { do { data.endBuffer++; data.totalBytesRead++; if (checkBufferSize()) { break; // nothing more to read. } // TODO: if we're using quoting we might be dealing with a very dirty file with quoted newlines in trailing fields. (imagine that) // In that particular case we want to use the same logic we use above (refactored a bit) to skip these fields. } while (data.byteBuffer[data.endBuffer]!='\n' && data.byteBuffer[data.endBuffer]!='\r'); if (!checkBufferSize()) { while (data.byteBuffer[data.endBuffer]=='\n' || data.byteBuffer[data.endBuffer]=='\r') { data.endBuffer++; data.totalBytesRead++; if (checkBufferSize()) { break; // nothing more to read. } } } // Make sure we start at the right position the next time around. data.startBuffer = data.endBuffer; } // Optionally add the current filename to the mix as well... // if (meta.isIncludingFilename() && !Const.isEmpty(meta.getFilenameField())) { if (meta.isLazyConversionActive()) { outputRowData[data.filenameFieldIndex] = data.binaryFilename; } else { outputRowData[data.filenameFieldIndex] = data.filenames[data.filenr-1]; } } if (data.isAddingRowNumber) { outputRowData[data.rownumFieldIndex] = new Long(data.rowNumber++); } incrementLinesInput(); return outputRowData; } catch (Exception e) { throw new KettleFileException("Exception reading line of data", e); } } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(ParGzipCsvInputMeta)smi; data=(ParGzipCsvInputData)sdi; if (super.init(smi, sdi)) { data.bufferSize = Integer.parseInt(environmentSubstitute(meta.getBufferSize())); data.byteBuffer = new byte[] {}; // empty // If the step doesn't have any previous steps, we just get the filename. // Otherwise, we'll grab the list of filenames later... // if (getTransMeta().findNrPrevSteps(getStepMeta())==0) { String filename = environmentSubstitute(meta.getFilename()); if (Const.isEmpty(filename)) { logError(BaseMessages.getString(PKG, "ParGzipCsvInput.MissingFilename.Message")); return false; } data.filenames = new String[] { filename, }; } else { data.filenames = null; data.filenr = 0; } data.delimiter = environmentSubstitute(meta.getDelimiter()).getBytes(); if( Const.isEmpty(meta.getEnclosure()) ) { data.enclosure = null; } else { data.enclosure = environmentSubstitute(meta.getEnclosure()).getBytes(); } data.isAddingRowNumber = !Const.isEmpty(meta.getRowNumField()); // Handle parallel reading capabilities... // if (meta.isRunningInParallel()) { data.stepNumber = getUniqueStepNrAcrossSlaves(); data.totalNumberOfSteps = getUniqueStepCountAcrossSlaves(); } return true; } return false; } public void closeFile() throws KettleException { try { if (data.gzis!=null) { data.gzis.close(); } if (data.fis!=null) { incrementLinesUpdated(); data.fis.close(); } } catch (IOException e) { throw new KettleException("Unable to close file '"+data.filenames[data.filenr-1],e); } } }
jjeb/kettle-trunk
engine/src/org/pentaho/di/trans/steps/parallelgzipcsv/ParGzipCsvInput.java
Java
apache-2.0
23,573
/* * @(#)dds_cpp_flowcontroller.h generated by: makeheader Mon Dec 3 23:08:33 2007 * * built from: flowcontroller.ifcxx */ #ifndef dds_cpp_flowcontroller_h #define dds_cpp_flowcontroller_h #ifndef dds_cpp_infrastructure_h #include "dds_cpp/dds_cpp_infrastructure.h" #endif #ifndef dds_c_flowcontroller_h #include "dds_c/dds_c_flowcontroller.h" #endif #ifndef dds_cpp_dll_h #include "dds_cpp/dds_cpp_dll.h" #endif class DDSFlowController_impl; class DDSDomainParticipant; class DDSCPPDllExport DDSFlowController { public: /*i @brief Get the underlying implementation class object. */ virtual DDSFlowController_impl* get_impl_FlowControllerI() = 0; public: /*e \dref_FlowController_set_property */ virtual DDS_ReturnCode_t set_property( const struct DDS_FlowControllerProperty_t &property) = 0; /*e \dref_FlowController_get_property */ virtual DDS_ReturnCode_t get_property( struct DDS_FlowControllerProperty_t &property) = 0; /*e \dref_FlowController_trigger_flow */ virtual DDS_ReturnCode_t trigger_flow() = 0; /*e \dref_FlowController_get_name */ virtual const char* get_name() = 0; /*e \dref_FlowController_get_participant */ virtual DDSDomainParticipant* get_participant() = 0; protected: virtual ~DDSFlowController(); }; #endif /* dds_cpp_flowcontroller_h */
OpenVnmrJ/ovjTools
NDDS/ndds.4.2e/include/ndds/dds_cpp/dds_cpp_flowcontroller.h
C
apache-2.0
1,479
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - dir_nav_kernel_1.cpp</title></head><body bgcolor='white'><pre> <font color='#009900'>// Copyright (C) 2003 Davis E. King (davis@dlib.net) </font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license. </font><font color='#0000FF'>#ifndef</font> DLIB_DIR_NAV_KERNEL_1_CPp_ <font color='#0000FF'>#define</font> DLIB_DIR_NAV_KERNEL_1_CPp_ <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../platform.h.html'>../platform.h</a>" <font color='#0000FF'>#ifdef</font> WIN32 <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='dir_nav_kernel_1.h.html'>dir_nav_kernel_1.h</a>" <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='../string.h.html'>../string.h</a>" <font color='#0000FF'>#ifdef</font> __BORLANDC__ <font color='#009900'>// Apparently the borland compiler doesn't define this. </font><font color='#0000FF'>#define</font> INVALID_FILE_ATTRIBUTES <font face='Lucida Console'>(</font><font face='Lucida Console'>(</font>DWORD<font face='Lucida Console'>)</font><font color='#5555FF'>-</font><font color='#979000'>1</font><font face='Lucida Console'>)</font> <font color='#0000FF'>#endif</font> <font color='#0000FF'>namespace</font> dlib <b>{</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#009900'>// file object implementation </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> file:: <b><a name='init'></a>init</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::string<font color='#5555FF'>&amp;</font> name <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#0000FF'><u>char</u></font> buf[<font color='#979000'>3000</font>]; <font color='#0000FF'><u>char</u></font><font color='#5555FF'>*</font> str; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font><font color='#BB00BB'>GetFullPathNameA</font><font face='Lucida Console'>(</font>name.<font color='#BB00BB'>c_str</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>,<font color='#0000FF'>sizeof</font><font face='Lucida Console'>(</font>buf<font face='Lucida Console'>)</font>,buf,<font color='#5555FF'>&amp;</font>str<font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#979000'>0</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// the file was not found </font> <font color='#0000FF'>throw</font> <font color='#BB00BB'>file_not_found</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>Unable to find file </font>" <font color='#5555FF'>+</font> name<font face='Lucida Console'>)</font>; <b>}</b> state.full_name <font color='#5555FF'>=</font> buf; string::size_type pos <font color='#5555FF'>=</font> state.full_name.<font color='#BB00BB'>find_last_of</font><font face='Lucida Console'>(</font>directory::<font color='#BB00BB'>get_separator</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>pos <font color='#5555FF'>=</font><font color='#5555FF'>=</font> string::npos<font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// no valid full path has no separator characters. </font> <font color='#0000FF'>throw</font> <font color='#BB00BB'>file_not_found</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>Unable to find file </font>" <font color='#5555FF'>+</font> name<font face='Lucida Console'>)</font>; <b>}</b> state.name <font color='#5555FF'>=</font> state.full_name.<font color='#BB00BB'>substr</font><font face='Lucida Console'>(</font>pos<font color='#5555FF'>+</font><font color='#979000'>1</font><font face='Lucida Console'>)</font>; <font color='#009900'>// now find the size of this file </font> WIN32_FIND_DATAA data; HANDLE ffind <font color='#5555FF'>=</font> <font color='#BB00BB'>FindFirstFileA</font><font face='Lucida Console'>(</font>state.full_name.<font color='#BB00BB'>c_str</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>, <font color='#5555FF'>&amp;</font>data<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>ffind <font color='#5555FF'>=</font><font color='#5555FF'>=</font> INVALID_HANDLE_VALUE <font color='#5555FF'>|</font><font color='#5555FF'>|</font> <font face='Lucida Console'>(</font>data.dwFileAttributes<font color='#5555FF'>&amp;</font>FILE_ATTRIBUTE_DIRECTORY<font face='Lucida Console'>)</font> <font color='#5555FF'>!</font><font color='#5555FF'>=</font> <font color='#979000'>0</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>throw</font> <font color='#BB00BB'>file_not_found</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>Unable to find file </font>" <font color='#5555FF'>+</font> name<font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'>else</font> <b>{</b> uint64 temp <font color='#5555FF'>=</font> data.nFileSizeHigh; temp <font color='#5555FF'>&lt;</font><font color='#5555FF'>&lt;</font><font color='#5555FF'>=</font> <font color='#979000'>32</font>; temp <font color='#5555FF'>|</font><font color='#5555FF'>=</font> data.nFileSizeLow; state.file_size <font color='#5555FF'>=</font> temp; <font color='#BB00BB'>FindClose</font><font face='Lucida Console'>(</font>ffind<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>bool</u></font> file:: <b><a name='operator'></a>operator</b> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> file<font color='#5555FF'>&amp;</font> rhs <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>state.full_name.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>!</font><font color='#5555FF'>=</font> rhs.state.full_name.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <font color='#0000FF'>return</font> <font color='#979000'>false</font>; <font color='#009900'>// compare the strings but ignore the case because file names </font> <font color='#009900'>// are not case sensitive on windows </font> <font color='#0000FF'>return</font> <font color='#BB00BB'>tolower</font><font face='Lucida Console'>(</font>state.full_name<font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#BB00BB'>tolower</font><font face='Lucida Console'>(</font>rhs.state.full_name<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#009900'>// directory object implementation </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> directory:: <b><a name='init'></a>init</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::string<font color='#5555FF'>&amp;</font> name <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#0000FF'><u>char</u></font> buf[<font color='#979000'>3000</font>]; <font color='#0000FF'><u>char</u></font><font color='#5555FF'>*</font> str; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font><font color='#BB00BB'>GetFullPathNameA</font><font face='Lucida Console'>(</font>name.<font color='#BB00BB'>c_str</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>,<font color='#0000FF'>sizeof</font><font face='Lucida Console'>(</font>buf<font face='Lucida Console'>)</font>,buf,<font color='#5555FF'>&amp;</font>str<font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#979000'>0</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// the directory was not found </font> <font color='#0000FF'>throw</font> <font color='#BB00BB'>dir_not_found</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>Unable to find directory </font>" <font color='#5555FF'>+</font> name<font face='Lucida Console'>)</font>; <b>}</b> state.full_name <font color='#5555FF'>=</font> buf; <font color='#0000FF'>const</font> <font color='#0000FF'><u>char</u></font> sep <font color='#5555FF'>=</font> <font color='#BB00BB'>get_separator</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font><font color='#BB00BB'>is_root_path</font><font face='Lucida Console'>(</font>state.full_name<font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#979000'>false</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// ensure that thre is not a trialing separator </font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>state.full_name[state.full_name.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font color='#5555FF'>-</font><font color='#979000'>1</font>] <font color='#5555FF'>=</font><font color='#5555FF'>=</font> sep<font face='Lucida Console'>)</font> state.full_name.<font color='#BB00BB'>erase</font><font face='Lucida Console'>(</font>state.full_name.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font color='#5555FF'>-</font><font color='#979000'>1</font><font face='Lucida Console'>)</font>; <font color='#009900'>// pick out the directory name </font> string::size_type pos <font color='#5555FF'>=</font> state.full_name.<font color='#BB00BB'>find_last_of</font><font face='Lucida Console'>(</font>sep<font face='Lucida Console'>)</font>; state.name <font color='#5555FF'>=</font> state.full_name.<font color='#BB00BB'>substr</font><font face='Lucida Console'>(</font>pos<font color='#5555FF'>+</font><font color='#979000'>1</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'>else</font> <b>{</b> <font color='#009900'>// ensure that there is a trailing separator </font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>state.full_name[state.full_name.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font color='#5555FF'>-</font><font color='#979000'>1</font>] <font color='#5555FF'>!</font><font color='#5555FF'>=</font> sep<font face='Lucida Console'>)</font> state.full_name <font color='#5555FF'>+</font><font color='#5555FF'>=</font> sep; <b>}</b> <font color='#009900'>// now check that this is actually a valid directory </font> DWORD attribs <font color='#5555FF'>=</font> <font color='#BB00BB'>GetFileAttributesA</font><font face='Lucida Console'>(</font>state.full_name.<font color='#BB00BB'>c_str</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>attribs <font color='#5555FF'>=</font><font color='#5555FF'>=</font> INVALID_FILE_ATTRIBUTES <font color='#5555FF'>|</font><font color='#5555FF'>|</font> <font face='Lucida Console'>(</font>attribs<font color='#5555FF'>&amp;</font>FILE_ATTRIBUTE_DIRECTORY<font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#979000'>0</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// the directory was not found </font> <font color='#0000FF'>throw</font> <font color='#BB00BB'>dir_not_found</font><font face='Lucida Console'>(</font>"<font color='#CC0000'>Unable to find directory </font>" <font color='#5555FF'>+</font> name<font face='Lucida Console'>)</font>; <b>}</b> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>char</u></font> directory:: <b><a name='get_separator'></a>get_separator</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>return</font> '<font color='#FF0000'>\\</font>'; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>bool</u></font> directory:: <b><a name='operator'></a>operator</b> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> directory<font color='#5555FF'>&amp;</font> rhs <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>state.full_name.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>!</font><font color='#5555FF'>=</font> rhs.state.full_name.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <font color='#0000FF'>return</font> <font color='#979000'>false</font>; <font color='#009900'>// compare the strings but ignore the case because file names </font> <font color='#009900'>// are not case sensitive on windows </font> <font color='#0000FF'>return</font> <font color='#BB00BB'>tolower</font><font face='Lucida Console'>(</font>state.full_name<font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#BB00BB'>tolower</font><font face='Lucida Console'>(</font>rhs.state.full_name<font face='Lucida Console'>)</font>; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> directory directory:: <b><a name='get_parent'></a>get_parent</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#009900'>// if *this is the root then just return *this </font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font><font color='#BB00BB'>is_root</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <b>{</b> <font color='#0000FF'>return</font> <font color='#5555FF'>*</font><font color='#0000FF'>this</font>; <b>}</b> <font color='#0000FF'>else</font> <b>{</b> directory temp; <font color='#0000FF'>const</font> <font color='#0000FF'><u>char</u></font> sep <font color='#5555FF'>=</font> <font color='#BB00BB'>get_separator</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; string::size_type pos <font color='#5555FF'>=</font> state.full_name.<font color='#BB00BB'>find_last_of</font><font face='Lucida Console'>(</font>sep<font face='Lucida Console'>)</font>; temp.state.full_name <font color='#5555FF'>=</font> state.full_name.<font color='#BB00BB'>substr</font><font face='Lucida Console'>(</font><font color='#979000'>0</font>,pos<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font> <font color='#BB00BB'>is_root_path</font><font face='Lucida Console'>(</font>temp.state.full_name<font face='Lucida Console'>)</font><font face='Lucida Console'>)</font> <b>{</b> temp.state.full_name <font color='#5555FF'>+</font><font color='#5555FF'>=</font> sep; <b>}</b> <font color='#0000FF'>else</font> <b>{</b> pos <font color='#5555FF'>=</font> temp.state.full_name.<font color='#BB00BB'>find_last_of</font><font face='Lucida Console'>(</font>sep<font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>pos <font color='#5555FF'>!</font><font color='#5555FF'>=</font> string::npos<font face='Lucida Console'>)</font> <b>{</b> temp.state.name <font color='#5555FF'>=</font> temp.state.full_name.<font color='#BB00BB'>substr</font><font face='Lucida Console'>(</font>pos<font color='#5555FF'>+</font><font color='#979000'>1</font><font face='Lucida Console'>)</font>; <b>}</b> <font color='#0000FF'>else</font> <b>{</b> temp.state.full_name <font color='#5555FF'>+</font><font color='#5555FF'>=</font> sep; <b>}</b> <b>}</b> <font color='#0000FF'>return</font> temp; <b>}</b> <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>bool</u></font> directory:: <b><a name='is_root_path'></a>is_root_path</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::string<font color='#5555FF'>&amp;</font> path <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font> <b>{</b> <font color='#0000FF'>using</font> <font color='#0000FF'>namespace</font> std; <font color='#0000FF'>const</font> <font color='#0000FF'><u>char</u></font> sep <font color='#5555FF'>=</font> <font color='#BB00BB'>get_separator</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font>; <font color='#0000FF'><u>bool</u></font> root_path <font color='#5555FF'>=</font> <font color='#979000'>false</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>path.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&gt;</font> <font color='#979000'>2</font> <font color='#5555FF'>&amp;</font><font color='#5555FF'>&amp;</font> path[<font color='#979000'>0</font>] <font color='#5555FF'>=</font><font color='#5555FF'>=</font> sep <font color='#5555FF'>&amp;</font><font color='#5555FF'>&amp;</font> path[<font color='#979000'>1</font>] <font color='#5555FF'>=</font><font color='#5555FF'>=</font> sep<font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// in this case this is a windows share path </font> string::size_type pos <font color='#5555FF'>=</font> path.<font color='#BB00BB'>find_first_of</font><font face='Lucida Console'>(</font>sep,<font color='#979000'>2</font><font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>pos <font color='#5555FF'>!</font><font color='#5555FF'>=</font> string::npos<font face='Lucida Console'>)</font> <b>{</b> pos <font color='#5555FF'>=</font> path.<font color='#BB00BB'>find_first_of</font><font face='Lucida Console'>(</font>sep,pos<font color='#5555FF'>+</font><font color='#979000'>1</font><font face='Lucida Console'>)</font>; <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>pos <font color='#5555FF'>=</font><font color='#5555FF'>=</font> string::npos <font color='#5555FF'>&amp;</font><font color='#5555FF'>&amp;</font> path[path.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font color='#5555FF'>-</font><font color='#979000'>1</font>] <font color='#5555FF'>!</font><font color='#5555FF'>=</font> sep<font face='Lucida Console'>)</font> root_path <font color='#5555FF'>=</font> <font color='#979000'>true</font>; <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font>pos <font color='#5555FF'>=</font><font color='#5555FF'>=</font> path.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font><font color='#5555FF'>-</font><font color='#979000'>1</font><font face='Lucida Console'>)</font> root_path <font color='#5555FF'>=</font> <font color='#979000'>true</font>; <b>}</b> <b>}</b> <font color='#0000FF'>else</font> <font color='#0000FF'>if</font> <font face='Lucida Console'>(</font> <font face='Lucida Console'>(</font>path.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#979000'>2</font> <font color='#5555FF'>|</font><font color='#5555FF'>|</font> path.<font color='#BB00BB'>size</font><font face='Lucida Console'>(</font><font face='Lucida Console'>)</font> <font color='#5555FF'>=</font><font color='#5555FF'>=</font> <font color='#979000'>3</font><font face='Lucida Console'>)</font> <font color='#5555FF'>&amp;</font><font color='#5555FF'>&amp;</font> path[<font color='#979000'>1</font>] <font color='#5555FF'>=</font><font color='#5555FF'>=</font> '<font color='#FF0000'>:</font>'<font face='Lucida Console'>)</font> <b>{</b> <font color='#009900'>// if this is a valid windows path then it must be a root path </font> root_path <font color='#5555FF'>=</font> <font color='#979000'>true</font>; <b>}</b> <font color='#0000FF'>return</font> root_path; <b>}</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <b>}</b> <font color='#0000FF'>#endif</font> <font color='#009900'>// WIN32 </font> <font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_DIR_NAV_KERNEL_1_CPp_ </font> </pre></body></html>
Nekel-Seyew/Complex-3D-Vector-Fields
dlib-18.18/docs/dlib/dir_nav/dir_nav_kernel_1.cpp.html
HTML
apache-2.0
24,472
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.physical.impl.aggregate; import static org.apache.drill.exec.record.RecordBatch.IterOutcome.EMIT; import static org.apache.drill.exec.record.RecordBatch.IterOutcome.NONE; import static org.apache.drill.exec.record.RecordBatch.IterOutcome.OK; import static org.apache.drill.exec.record.RecordBatch.IterOutcome.OK_NEW_SCHEMA; import javax.inject.Named; import org.apache.drill.exec.exception.SchemaChangeException; import org.apache.drill.exec.ops.OperatorContext; import org.apache.drill.exec.record.RecordBatch; import org.apache.drill.exec.record.RecordBatch.IterOutcome; import org.apache.drill.exec.record.VectorWrapper; import org.apache.drill.exec.vector.ValueVector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class StreamingAggTemplate implements StreamingAggregator { private static final Logger logger = LoggerFactory.getLogger(StreamingAggTemplate.class); private static final boolean EXTRA_DEBUG = false; private int maxOutputRows = ValueVector.MAX_ROW_COUNT; // lastOutcome is set ONLY if the lastOutcome was NONE or STOP private IterOutcome lastOutcome; // First batch after build schema phase private boolean first = true; private boolean firstBatchForSchema; // true if the current batch came in with an OK_NEW_SCHEMA. private boolean firstBatchForDataSet = true; // true if the current batch is the first batch in a data set private boolean newSchema; // End of all data private boolean done; // index in the incoming (sv4/sv2/vector) private int underlyingIndex; // The indexes below refer to the actual record indexes in input batch // (i.e if a selection vector the sv4/sv2 entry has been dereferenced or if a vector then the record index itself) private int previousIndex = -1; // the last index that has been processed. Initialized to -1 every time a new // aggregate group begins (including every time a new data set begins) private int currentIndex = Integer.MAX_VALUE; // current index being processed /** * Number of records added to the current aggregation group. */ private long addedRecordCount; // There are two outcomes from the aggregator. One is the aggregator's outcome defined in // StreamingAggregator.AggOutcome. The other is the outcome from the last call to incoming.next private IterOutcome outcome; // Number of aggregation groups added into the output batch private int outputCount; private RecordBatch incoming; // the Streaming Agg Batch that this aggregator belongs to private StreamingAggBatch outgoing; private OperatorContext context; @Override public void setup(OperatorContext context, RecordBatch incoming, StreamingAggBatch outgoing, int outputRowCount) throws SchemaChangeException { this.context = context; this.incoming = incoming; this.outgoing = outgoing; this.maxOutputRows = outputRowCount; setupInterior(incoming, outgoing); } private void allocateOutgoing() { for (VectorWrapper<?> w : outgoing) { w.getValueVector().allocateNew(); } } @Override public IterOutcome getOutcome() { return outcome; } @Override public int getOutputCount() { return outputCount; } @Override public AggOutcome doWork(IterOutcome outerOutcome) { if (done || outerOutcome == NONE) { outcome = IterOutcome.NONE; return AggOutcome.CLEANUP_AND_RETURN; } try { // outside block to ensure that first is set to false after the first run. outputCount = 0; // allocate outgoing since either this is the first time or if a subsequent time we would // have sent the previous outgoing batch to downstream operator allocateOutgoing(); if (firstBatchForDataSet) { this.currentIndex = incoming.getRecordCount() == 0 ? Integer.MAX_VALUE : this.getVectorIndex(underlyingIndex); if (outerOutcome == OK_NEW_SCHEMA) { firstBatchForSchema = true; } // consume empty batches until we get one with data (unless we got an EMIT). If we got an emit // then this is the first batch, it was empty and we also got an emit. if (incoming.getRecordCount() == 0 ) { if (outerOutcome != EMIT) { outer: while (true) { IterOutcome out = outgoing.next(0, incoming); switch (out) { case OK_NEW_SCHEMA: //lastOutcome = out; firstBatchForSchema = true; case OK: if (incoming.getRecordCount() == 0) { continue; } else { currentIndex = this.getVectorIndex(underlyingIndex); break outer; } case EMIT: outerOutcome = EMIT; if (incoming.getRecordCount() == 0) { // When we see an EMIT we let the agg record batch know that it should either // send out an EMIT or an OK_NEW_SCHEMA, followed by an EMIT. To do that we simply return // RETURN_AND_RESET with the outcome so the record batch can take care of it. return setOkAndReturnEmit(); } else { currentIndex = this.getVectorIndex(underlyingIndex); break outer; } case NONE: out = IterOutcome.OK_NEW_SCHEMA; default: lastOutcome = out; outcome = out; done = true; return AggOutcome.CLEANUP_AND_RETURN; } // switch (outcome) } // while empty batches are seen } else { return setOkAndReturnEmit(); } } } if (newSchema) { return AggOutcome.UPDATE_AGGREGATOR; } // if the previous iteration has an outcome that was terminal, don't do anything. if (lastOutcome != null /*&& lastOutcome != IterOutcome.OK_NEW_SCHEMA*/) { outcome = lastOutcome; return AggOutcome.CLEANUP_AND_RETURN; } outside: while(true) { // loop through existing records, adding as necessary. if(!processRemainingRecordsInBatch()) { // output batch is full. Return. return setOkAndReturn(outerOutcome); } // if the current batch came with an EMIT, we're done since if we are here it means output batch consumed all // the rows in incoming batch if(outerOutcome == EMIT) { // output the last record outputToBatch(previousIndex); resetIndex(); return setOkAndReturnEmit(); } /** * Hold onto the previous incoming batch. When the incoming uses an * SV4, the InternalBatch DOES NOT clone or transfer the data. Instead, * it clones only the SV4, and assumes that the same hyper-list of * batches will be offered again after the next call to the incoming * next(). This is, in fact, how the SV4 works, so all is fine. The * trick to be aware of, however, is that this MUST BE TRUE even if * the incoming next() returns NONE: the incoming is obligated to continue * to offer the set of batches. That is, the incoming cannot try to be * tidy and release the batches one end-of-data or the following code * will fail, likely with an IndexOutOfBounds exception. */ InternalBatch previous = new InternalBatch(incoming, context); try { while (true) { IterOutcome out = outgoing.next(0, incoming); if (EXTRA_DEBUG) { logger.debug("Received IterOutcome of {}", out); } switch (out) { case NONE: done = true; lastOutcome = out; if (firstBatchForDataSet && addedRecordCount == 0) { return setOkAndReturn(NONE); } else if (addedRecordCount > 0) { outputToBatchPrev(previous, previousIndex, outputCount); // No need to check the return value // (output container full or not) as we are not going to insert any more records. if (EXTRA_DEBUG) { logger.debug("Received no more batches, returning."); } return setOkAndReturn(NONE); } else { // not first batch and record Count == 0 outcome = out; return AggOutcome.CLEANUP_AND_RETURN; } // EMIT is handled like OK, except that we do not loop back to process the // next incoming batch; we return instead case EMIT: if (incoming.getRecordCount() == 0) { if (addedRecordCount > 0) { outputToBatchPrev(previous, previousIndex, outputCount); } } else { resetIndex(); currentIndex = this.getVectorIndex(underlyingIndex); if (previousIndex != -1 && isSamePrev(previousIndex, previous, currentIndex)) { if (EXTRA_DEBUG) { logger.debug("New value was same as last value of previous batch, adding."); } addRecordInc(currentIndex); previousIndex = currentIndex; incIndex(); if (EXTRA_DEBUG) { logger.debug("Continuing outside"); } } else { // not the same if (EXTRA_DEBUG) { logger.debug("This is not the same as the previous, add record and continue outside."); } if (addedRecordCount > 0) { if (outputToBatchPrev(previous, previousIndex, outputCount)) { if (EXTRA_DEBUG) { logger.debug("Output container is full. flushing it."); } return setOkAndReturn(EMIT); } } // important to set the previous index to -1 since we start a new group previousIndex = -1; } if (!processRemainingRecordsInBatch()) { // output batch is full. Return. return setOkAndReturn(EMIT); } outputToBatch(previousIndex); // currentIndex has been reset to int_max so use previous index. } resetIndex(); return setOkAndReturnEmit(); case NOT_YET: this.outcome = out; return AggOutcome.RETURN_OUTCOME; case OK_NEW_SCHEMA: firstBatchForSchema = true; //lastOutcome = out; if (EXTRA_DEBUG) { logger.debug("Received new schema. Batch has {} records.", incoming.getRecordCount()); } if (addedRecordCount > 0) { outputToBatchPrev(previous, previousIndex, outputCount); // No need to check the return value // (output container full or not) as we are not going to insert anymore records. if (EXTRA_DEBUG) { logger.debug("Wrote out end of previous batch, returning."); } newSchema = true; return setOkAndReturn(OK_NEW_SCHEMA); } cleanup(); return AggOutcome.UPDATE_AGGREGATOR; case OK: resetIndex(); if (incoming.getRecordCount() == 0) { continue; } else { currentIndex = this.getVectorIndex(underlyingIndex); if (previousIndex != -1 && isSamePrev(previousIndex, previous, currentIndex)) { if (EXTRA_DEBUG) { logger.debug("New value was same as last value of previous batch, adding."); } addRecordInc(currentIndex); previousIndex = currentIndex; incIndex(); if (EXTRA_DEBUG) { logger.debug("Continuing outside"); } continue outside; } else { // not the same if (EXTRA_DEBUG) { logger.debug("This is not the same as the previous, add record and continue outside."); } if (addedRecordCount > 0) { if (outputToBatchPrev(previous, previousIndex, outputCount)) { if (EXTRA_DEBUG) { logger.debug("Output container is full. flushing it."); } previousIndex = -1; return setOkAndReturn(OK); } } previousIndex = -1; continue outside; } } default: lastOutcome = out; outcome = out; return AggOutcome.CLEANUP_AND_RETURN; } } } finally { // make sure to clear previous if (previous != null) { previous.clear(); } } } } finally { if (first) { first = false; } } } @Override public boolean isDone() { return done; } /** * Process the remaining records in the batch. Returns false if not all records are processed (if the output * container gets full), true otherwise. * @return Boolean indicating all records were processed */ private boolean processRemainingRecordsInBatch() { for (; underlyingIndex < incoming.getRecordCount(); incIndex()) { if (EXTRA_DEBUG) { logger.debug("Doing loop with values underlying {}, current {}", underlyingIndex, currentIndex); } if (previousIndex == -1) { if (EXTRA_DEBUG) { logger.debug("Adding the initial row's keys and values."); } addRecordInc(currentIndex); } else if (isSame( previousIndex, currentIndex )) { if (EXTRA_DEBUG) { logger.debug("Values were found the same, adding."); } addRecordInc(currentIndex); } else { if (EXTRA_DEBUG) { logger.debug("Values were different, outputting previous batch."); } if(!outputToBatch(previousIndex)) { // There is still space in outgoing container, so proceed to the next input. if (EXTRA_DEBUG) { logger.debug("Output successful."); } addRecordInc(currentIndex); } else { if (EXTRA_DEBUG) { logger.debug("Output container has reached its capacity. Flushing it."); } // Update the indices to set the state for processing next record in incoming batch in subsequent doWork calls. previousIndex = -1; return false; } } previousIndex = currentIndex; } return true; } private final void incIndex() { underlyingIndex++; if (underlyingIndex >= incoming.getRecordCount()) { currentIndex = Integer.MAX_VALUE; return; } currentIndex = getVectorIndex(underlyingIndex); } private final void resetIndex() { underlyingIndex = 0; currentIndex = Integer.MAX_VALUE; } /** * Set the outcome to OK (or OK_NEW_SCHEMA) and return the AggOutcome parameter * * @return outcome */ private final AggOutcome setOkAndReturn(IterOutcome seenOutcome) { IterOutcome outcomeToReturn; firstBatchForDataSet = false; if (firstBatchForSchema) { outcomeToReturn = OK_NEW_SCHEMA; firstBatchForSchema = false; } else { outcomeToReturn = OK; } outcome = outcomeToReturn; outgoing.getContainer().setValueCount(outputCount); return (seenOutcome == EMIT) ? AggOutcome.RETURN_AND_RESET : AggOutcome.RETURN_OUTCOME; } /** * setOkAndReturn (as above) if the iter outcome was EMIT * * @return outcome */ private final AggOutcome setOkAndReturnEmit() { IterOutcome outcomeToReturn; firstBatchForDataSet = true; previousIndex = -1; if (firstBatchForSchema) { outcomeToReturn = OK_NEW_SCHEMA; firstBatchForSchema = false; } else { outcomeToReturn = EMIT; } outcome = outcomeToReturn; outgoing.getContainer().setValueCount(outputCount); return AggOutcome.RETURN_AND_RESET; } // Returns output container status after insertion of the given record. Caller must check the return value if it // plans to insert more records into outgoing container. private final boolean outputToBatch(int inIndex) { assert outputCount < maxOutputRows : "Outgoing RecordBatch is not flushed. It reached its max capacity in the last update"; outputRecordKeys(inIndex, outputCount); outputRecordValues(outputCount); if (EXTRA_DEBUG) { logger.debug("{} values output successfully", outputCount); } resetValues(); outputCount++; addedRecordCount = 0; return outputCount == maxOutputRows; } // Returns output container status after insertion of the given record. Caller must check the return value if it // plans to inserts more record into outgoing container. private final boolean outputToBatchPrev(InternalBatch b1, int inIndex, int outIndex) { assert outputCount < maxOutputRows : "Outgoing RecordBatch is not flushed. It reached its max capacity in the last update"; outputRecordKeysPrev(b1, inIndex, outIndex); outputRecordValues(outIndex); resetValues(); outputCount++; addedRecordCount = 0; return outputCount == maxOutputRows; } private void addRecordInc(int index) { addRecord(index); addedRecordCount++; } @Override public void cleanup() { } @Override public String toString() { return "StreamingAggTemplate[underlyingIndex=" + underlyingIndex + ", previousIndex=" + previousIndex + ", currentIndex=" + currentIndex + ", addedRecordCount=" + addedRecordCount + ", outputCount=" + outputCount + "]"; } @Override public boolean previousBatchProcessed() { return (currentIndex == Integer.MAX_VALUE); } public abstract void setupInterior(@Named("incoming") RecordBatch incoming, @Named("outgoing") RecordBatch outgoing) throws SchemaChangeException; public abstract boolean isSame(@Named("index1") int index1, @Named("index2") int index2); public abstract boolean isSamePrev(@Named("b1Index") int b1Index, @Named("b1") InternalBatch b1, @Named("b2Index") int b2Index); public abstract void addRecord(@Named("index") int index); public abstract void outputRecordKeys(@Named("inIndex") int inIndex, @Named("outIndex") int outIndex); public abstract void outputRecordKeysPrev(@Named("previous") InternalBatch previous, @Named("previousIndex") int previousIndex, @Named("outIndex") int outIndex); public abstract void outputRecordValues(@Named("outIndex") int outIndex); public abstract int getVectorIndex(@Named("recordIndex") int recordIndex); public abstract boolean resetValues(); }
arina-ielchiieva/drill
exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/aggregate/StreamingAggTemplate.java
Java
apache-2.0
20,427
//----------------------------------------------------------------------- // <copyright file="ImageApi.cs" company="Google"> // // Copyright 2018 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using GoogleARCore; #if UNITY_IOS using AndroidImport = GoogleARCoreInternal.DllImportNoop; using IOSImport = System.Runtime.InteropServices.DllImportAttribute; #else using AndroidImport = System.Runtime.InteropServices.DllImportAttribute; using IOSImport = GoogleARCoreInternal.DllImportNoop; #endif internal class ImageApi { private NativeSession m_NativeSession; public ImageApi(NativeSession nativeSession) { m_NativeSession = nativeSession; } public void GetImageBuffer(IntPtr imageHandle, out int width, out int height, out IntPtr yPlane, out IntPtr uPlane, out IntPtr vPlane, out int yRowStride, out int uvPixelStride, out int uvRowStride) { IntPtr ndkImageHandle = IntPtr.Zero; ExternApi.ArImage_getNdkImage(imageHandle, ref ndkImageHandle); width = 0; ExternApi.AImage_getWidth(ndkImageHandle, ref width); height = 0; ExternApi.AImage_getHeight(ndkImageHandle, ref height); const int Y_PLANE = 0; const int U_PLANE = 1; const int V_PLANE = 2; int bufferLength = 0; yPlane = IntPtr.Zero; ExternApi.AImage_getPlaneData(ndkImageHandle, Y_PLANE, ref yPlane, ref bufferLength); uPlane = IntPtr.Zero; ExternApi.AImage_getPlaneData(ndkImageHandle, U_PLANE, ref uPlane, ref bufferLength); vPlane = IntPtr.Zero; ExternApi.AImage_getPlaneData(ndkImageHandle, V_PLANE, ref vPlane, ref bufferLength); yRowStride = 0; ExternApi.AImage_getPlaneRowStride(ndkImageHandle, Y_PLANE, ref yRowStride); uvPixelStride = 0; ExternApi.AImage_getPlanePixelStride(ndkImageHandle, U_PLANE, ref uvPixelStride); uvRowStride = 0; ExternApi.AImage_getPlaneRowStride(ndkImageHandle, U_PLANE, ref uvRowStride); } public void Release(IntPtr imageHandle) { m_NativeSession.MarkHandleReleased(imageHandle); ExternApi.ArImage_release(imageHandle); } private struct ExternApi { #pragma warning disable 626 [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArImage_getNdkImage(IntPtr imageHandle, ref IntPtr ndkImage); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArImage_release(IntPtr imageHandle); [AndroidImport(ApiConstants.MediaNdk)] public static extern int AImage_getWidth(IntPtr ndkImageHandle, ref int width); [AndroidImport(ApiConstants.MediaNdk)] public static extern int AImage_getHeight(IntPtr ndkImageHandle, ref int height); [AndroidImport(ApiConstants.MediaNdk)] public static extern int AImage_getPlaneData(IntPtr imageHandle, int planeIdx, ref IntPtr data, ref int dataLength); [AndroidImport(ApiConstants.MediaNdk)] public static extern int AImage_getPlanePixelStride(IntPtr imageHandle, int planeIdx, ref int pixelStride); [AndroidImport(ApiConstants.MediaNdk)] public static extern int AImage_getPlaneRowStride(IntPtr imageHandle, int planeIdx, ref int rowStride); #pragma warning restore 626 } } }
googlesamples/arcore-lightboard
Assets/GoogleARCore/SDK/Scripts/Api/ImageApi.cs
C#
apache-2.0
4,271
// Copyright 2016 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.skyframe; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.flogger.GoogleLogger; import com.google.devtools.build.lib.collect.compacthashmap.CompactHashMap; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.ExtendedEventHandler; import com.google.devtools.build.lib.events.ExtendedEventHandler.Postable; import com.google.devtools.build.lib.events.StoredEventHandler; import com.google.devtools.build.lib.util.GroupedList; import com.google.devtools.build.lib.util.GroupedList.GroupedListHelper; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.skyframe.EvaluationProgressReceiver.EvaluationState; import com.google.devtools.build.skyframe.NodeEntry.DependencyState; import com.google.devtools.build.skyframe.QueryableGraph.Reason; import com.google.devtools.build.skyframe.proto.GraphInconsistency.Inconsistency; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.CountDownLatch; import javax.annotation.Nullable; /** A {@link SkyFunction.Environment} implementation for {@link ParallelEvaluator}. */ class SkyFunctionEnvironment extends AbstractSkyFunctionEnvironment { private static final GoogleLogger logger = GoogleLogger.forEnclosingClass(); private static final SkyValue NULL_MARKER = new SkyValue() {}; private static final boolean PREFETCH_OLD_DEPS = Boolean.parseBoolean( System.getProperty("skyframe.ParallelEvaluator.PrefetchOldDeps", "true")); private static final boolean PREFETCH_AND_RETAIN_OLD_DEPS = Boolean.parseBoolean( System.getProperty("skyframe.SkyFunctionEnvironment.PrefetchAndRetainOldDeps", "false")); private boolean building = true; private SkyKey depErrorKey = null; private final SkyKey skyKey; /** * The deps requested during the previous build of this node. Used for two reasons: (1) They are * fetched eagerly before the node is built, to potentially prime the graph and speed up requests * for them during evaluation. (2) When the node finishes building, any deps from the previous * build that are not deps from this build must have this node removed from them as a reverse dep. * Thus, it is important that all nodes in this set have the property that they have this node as * a reverse dep from the last build, but that this node has not added them as a reverse dep on * this build. That set is normally {@link NodeEntry#getAllRemainingDirtyDirectDeps()}, but in * certain corner cases, like cycles, further filtering may be needed. */ private final Set<SkyKey> oldDeps; private SkyValue value = null; private ErrorInfo errorInfo = null; private final FunctionHermeticity hermeticity; @Nullable private Version maxChildVersion = null; /** If present, takes precedence over {@link #maxChildVersion}. */ @Nullable private Version injectedVersion = null; /** * This is not {@code null} only during cycle detection and error bubbling. The nullness of this * field is used to detect whether evaluation is in one of those special states. * * <p>When this is not {@code null}, values in this map should be used (while getting * dependencies' values, events, or posts) over values from the graph for keys present in this * map. */ @Nullable private final Map<SkyKey, ValueWithMetadata> bubbleErrorInfo; /** * The current entries of the direct deps this node had at the previous version. * * <p>Used only when {@link #PREFETCH_AND_RETAIN_OLD_DEPS} is {@code true}, and used only for the * values stored in the entries; do not do any NodeEntry operations on these. */ private ImmutableMap<SkyKey, ? extends NodeEntry> oldDepsEntries = ImmutableMap.of(); /** * The values previously declared as dependencies. * * <p>Values in this map are either {@link #NULL_MARKER} or were retrieved via {@link * NodeEntry#getValueMaybeWithMetadata}. In the latter case, they should be processed using the * static methods of {@link ValueWithMetadata}. */ private final ImmutableMap<SkyKey, SkyValue> previouslyRequestedDepsValues; /** * The values newly requested from the graph. * * <p>Values in this map are either {@link #NULL_MARKER} or were retrieved via {@link * NodeEntry#getValueMaybeWithMetadata}. In the latter case, they should be processed using the * static methods of {@link ValueWithMetadata}. */ private final Map<SkyKey, SkyValue> newlyRequestedDepsValues = new HashMap<>(); /** * Keys of dependencies registered via {@link #registerDependencies} if not using {@link * EvaluationVersionBehavior#MAX_CHILD_VERSIONS}. * * <p>The {@link #registerDependencies} method is hacky. Deps registered through it may not have * entries in {@link #newlyRequestedDepsValues}, but they are expected to be done. This set tracks * those keys so that they aren't removed when {@link #removeUndoneNewlyRequestedDeps} is called. */ private final Set<SkyKey> newlyRegisteredDeps = new HashSet<>(); /** * The grouped list of values requested during this build as dependencies. On a subsequent build, * if this value is dirty, all deps in the same dependency group can be checked in parallel for * changes. In other words, if dep1 and dep2 are in the same group, then dep1 will be checked in * parallel with dep2. See {@link #getValues} for more. */ private final GroupedListHelper<SkyKey> newlyRequestedDeps = new GroupedListHelper<>(); /** The set of errors encountered while fetching children. */ private final Set<ErrorInfo> childErrorInfos = new LinkedHashSet<>(); private final StoredEventHandler eventHandler = new StoredEventHandler() { @Override @SuppressWarnings("UnsynchronizedOverridesSynchronized") // only delegates to thread-safe. public void handle(Event e) { checkActive(); if (evaluatorContext.getStoredEventFilter().apply(e)) { super.handle(e); } else { evaluatorContext.getReporter().handle(e); } } @Override @SuppressWarnings("UnsynchronizedOverridesSynchronized") // only delegates to thread-safe. public void post(ExtendedEventHandler.Postable e) { checkActive(); if (e instanceof ExtendedEventHandler.ProgressLike) { evaluatorContext.getReporter().post(e); } else { super.post(e); } } }; private final ParallelEvaluatorContext evaluatorContext; SkyFunctionEnvironment( SkyKey skyKey, GroupedList<SkyKey> directDeps, Set<SkyKey> oldDeps, ParallelEvaluatorContext evaluatorContext) throws InterruptedException, UndonePreviouslyRequestedDeps { super(directDeps); this.skyKey = skyKey; this.oldDeps = oldDeps; this.evaluatorContext = evaluatorContext; this.bubbleErrorInfo = null; this.hermeticity = skyKey.functionName().getHermeticity(); this.previouslyRequestedDepsValues = batchPrefetch(skyKey, directDeps, oldDeps, /*assertDone=*/ true); Preconditions.checkState( !this.previouslyRequestedDepsValues.containsKey(ErrorTransienceValue.KEY), "%s cannot have a dep on ErrorTransienceValue during building", skyKey); } SkyFunctionEnvironment( SkyKey skyKey, GroupedList<SkyKey> directDeps, Map<SkyKey, ValueWithMetadata> bubbleErrorInfo, Set<SkyKey> oldDeps, ParallelEvaluatorContext evaluatorContext) throws InterruptedException { super(directDeps); this.skyKey = skyKey; this.oldDeps = oldDeps; this.evaluatorContext = evaluatorContext; this.bubbleErrorInfo = Preconditions.checkNotNull(bubbleErrorInfo); this.hermeticity = skyKey.functionName().getHermeticity(); try { this.previouslyRequestedDepsValues = batchPrefetch(skyKey, directDeps, oldDeps, /*assertDone=*/ false); } catch (UndonePreviouslyRequestedDeps undonePreviouslyRequestedDeps) { throw new IllegalStateException( "batchPrefetch can't throw UndonePreviouslyRequestedDeps unless assertDone is true", undonePreviouslyRequestedDeps); } Preconditions.checkState( !this.previouslyRequestedDepsValues.containsKey(ErrorTransienceValue.KEY), "%s cannot have a dep on ErrorTransienceValue during building", skyKey); } private ImmutableMap<SkyKey, SkyValue> batchPrefetch( SkyKey requestor, GroupedList<SkyKey> depKeys, Set<SkyKey> oldDeps, boolean assertDone) throws InterruptedException, UndonePreviouslyRequestedDeps { QueryableGraph.PrefetchDepsRequest request = null; if (PREFETCH_OLD_DEPS) { request = new QueryableGraph.PrefetchDepsRequest(requestor, oldDeps, depKeys); evaluatorContext.getGraph().prefetchDeps(request); } else if (PREFETCH_AND_RETAIN_OLD_DEPS) { // TODO(b/175215425): Make PREFETCH_AND_RETAIN_OLD_DEPS the only behavior. this.oldDepsEntries = ImmutableMap.copyOf(evaluatorContext.getBatchValues(requestor, Reason.PREFETCH, oldDeps)); } Map<SkyKey, ? extends NodeEntry> batchMap = evaluatorContext.getBatchValues( requestor, Reason.PREFETCH, (request != null && request.excludedKeys != null) ? request.excludedKeys : depKeys.getAllElementsAsIterable()); if (batchMap.size() != depKeys.numElements()) { Set<SkyKey> difference = Sets.difference(depKeys.toSet(), batchMap.keySet()); evaluatorContext .getGraphInconsistencyReceiver() .noteInconsistencyAndMaybeThrow( requestor, difference, Inconsistency.ALREADY_DECLARED_CHILD_MISSING); throw new UndonePreviouslyRequestedDeps(ImmutableList.copyOf(difference)); } ImmutableMap.Builder<SkyKey, SkyValue> depValuesBuilder = ImmutableMap.builderWithExpectedSize(batchMap.size()); for (Entry<SkyKey, ? extends NodeEntry> entry : batchMap.entrySet()) { SkyValue valueMaybeWithMetadata = entry.getValue().getValueMaybeWithMetadata(); boolean depDone = valueMaybeWithMetadata != null; if (assertDone && !depDone) { // A previously requested dep may have transitioned from done to dirty between when the node // was read during a previous attempt to build this node and now. Notify the graph // inconsistency receiver so that we can crash if that's unexpected. evaluatorContext .getGraphInconsistencyReceiver() .noteInconsistencyAndMaybeThrow( skyKey, ImmutableList.of(entry.getKey()), Inconsistency.BUILDING_PARENT_FOUND_UNDONE_CHILD); throw new UndonePreviouslyRequestedDeps(ImmutableList.of(entry.getKey())); } depValuesBuilder.put(entry.getKey(), !depDone ? NULL_MARKER : valueMaybeWithMetadata); if (depDone) { maybeUpdateMaxChildVersion(entry.getValue()); } } return depValuesBuilder.build(); } private void checkActive() { Preconditions.checkState(building, skyKey); } Pair<NestedSet<TaggedEvents>, NestedSet<Postable>> buildAndReportEventsAndPostables( NodeEntry entry, boolean expectDoneDeps) throws InterruptedException { EventFilter eventFilter = evaluatorContext.getStoredEventFilter(); if (!eventFilter.storeEventsAndPosts()) { return Pair.of( NestedSetBuilder.emptySet(Order.STABLE_ORDER), NestedSetBuilder.emptySet(Order.STABLE_ORDER)); } NestedSetBuilder<TaggedEvents> eventBuilder = NestedSetBuilder.stableOrder(); ImmutableList<Event> events = eventHandler.getEvents(); if (!events.isEmpty()) { eventBuilder.add(new TaggedEvents(getTagFromKey(), events)); } NestedSetBuilder<Postable> postBuilder = NestedSetBuilder.stableOrder(); postBuilder.addAll(eventHandler.getPosts()); GroupedList<SkyKey> depKeys = entry.getTemporaryDirectDeps(); Collection<SkyValue> deps = getDepValuesForDoneNodeFromErrorOrDepsOrGraph( Iterables.filter( depKeys.getAllElementsAsIterable(), eventFilter.depEdgeFilterForEventsAndPosts(skyKey)), expectDoneDeps, depKeys.numElements()); for (SkyValue value : deps) { eventBuilder.addTransitive(ValueWithMetadata.getEvents(value)); postBuilder.addTransitive(ValueWithMetadata.getPosts(value)); } NestedSet<TaggedEvents> taggedEvents = eventBuilder.buildInterruptibly(); NestedSet<Postable> postables = postBuilder.buildInterruptibly(); evaluatorContext.getReplayingNestedSetEventVisitor().visit(taggedEvents); evaluatorContext.getReplayingNestedSetPostableVisitor().visit(postables); return Pair.of(taggedEvents, postables); } void setValue(SkyValue newValue) { Preconditions.checkState( errorInfo == null && bubbleErrorInfo == null, "%s %s %s %s", skyKey, newValue, errorInfo, bubbleErrorInfo); Preconditions.checkState(value == null, "%s %s %s", skyKey, value, newValue); value = newValue; } /** * Set this node to be in error. The node's value must not have already been set. However, all * dependencies of this node <i>must</i> already have been registered, since this method may * register a dependence on the error transience node, which should always be the last dep. */ void setError(NodeEntry state, ErrorInfo errorInfo) throws InterruptedException { Preconditions.checkState(value == null, "%s %s %s", skyKey, value, errorInfo); Preconditions.checkState(this.errorInfo == null, "%s %s %s", skyKey, this.errorInfo, errorInfo); if (errorInfo.isDirectlyTransient()) { NodeEntry errorTransienceNode = Preconditions.checkNotNull( evaluatorContext .getGraph() .get(skyKey, Reason.RDEP_ADDITION, ErrorTransienceValue.KEY), "Null error value? %s", skyKey); DependencyState triState; if (oldDeps.contains(ErrorTransienceValue.KEY)) { triState = errorTransienceNode.checkIfDoneForDirtyReverseDep(skyKey); } else { triState = errorTransienceNode.addReverseDepAndCheckIfDone(skyKey); } Preconditions.checkState( triState == DependencyState.DONE, "%s %s %s", skyKey, triState, errorInfo); state.addTemporaryDirectDeps(GroupedListHelper.create(ErrorTransienceValue.KEY)); state.signalDep(evaluatorContext.getGraphVersion(), ErrorTransienceValue.KEY); maxChildVersion = evaluatorContext.getGraphVersion(); } this.errorInfo = Preconditions.checkNotNull(errorInfo, skyKey); } /** * Returns a map of {@code keys} to values or {@link #NULL_MARKER}s, populating the map's contents * by looking in order at: * * <ol> * <li>{@link #bubbleErrorInfo} * <li>{@link #previouslyRequestedDepsValues} * <li>{@link #newlyRequestedDepsValues} * <li>{@link #evaluatorContext}'s graph accessing methods * </ol> * * <p>All {@code keys} not previously requested will be added to a new group in {@link * #newlyRequestedDeps}. The new group will mirror the order of {@code keys}, minus duplicates. * * <p>Any key whose {@link NodeEntry}--or absence thereof--had to be read from the graph will also * be entered into {@link #newlyRequestedDepsValues} with its value or a {@link #NULL_MARKER}. */ private Map<SkyKey, SkyValue> getValuesFromErrorOrDepsOrGraph(Iterable<? extends SkyKey> keys) throws InterruptedException { // Do not use an ImmutableMap.Builder, because we have not yet deduplicated these keys // and ImmutableMap.Builder does not tolerate duplicates. Map<SkyKey, SkyValue> result = keys instanceof Collection ? CompactHashMap.createWithExpectedSize(((Collection<?>) keys).size()) : new HashMap<>(); Set<SkyKey> missingKeys = new HashSet<>(); newlyRequestedDeps.startGroup(); for (SkyKey key : keys) { Preconditions.checkState( !key.equals(ErrorTransienceValue.KEY), "Error transience key cannot be in requested deps of %s", skyKey); SkyValue value = maybeGetValueFromErrorOrDeps(key); boolean duplicate; if (value == null) { duplicate = !missingKeys.add(key); } else { duplicate = result.put(key, value) != null; } if (!duplicate && !previouslyRequestedDepsValues.containsKey(key)) { newlyRequestedDeps.add(key); } } newlyRequestedDeps.endGroup(); if (missingKeys.isEmpty()) { return result; } Map<SkyKey, ? extends NodeEntry> missingEntries = evaluatorContext.getBatchValues(skyKey, Reason.DEP_REQUESTED, missingKeys); for (SkyKey key : missingKeys) { NodeEntry depEntry = missingEntries.get(key); SkyValue valueOrNullMarker = getValueOrNullMarker(depEntry); result.put(key, valueOrNullMarker); newlyRequestedDepsValues.put(key, valueOrNullMarker); if (valueOrNullMarker != NULL_MARKER) { maybeUpdateMaxChildVersion(depEntry); } } return result; } /** * Similar to {@link #getValuesFromErrorOrDepsOrGraph}, but instead of a Map, return a List of * SkyValue ordered by the given order of SkyKeys. */ private List<SkyValue> getOrderedValuesFromErrorOrDepsOrGraph(Iterable<? extends SkyKey> keys) throws InterruptedException { int capacity = keys instanceof Collection ? ((Collection<?>) keys).size() : 16; List<SkyValue> result = new ArrayList<>(capacity); // Ignoring duplication check here since it's done in GroupedList. List<SkyKey> missingKeys = new ArrayList<>(); newlyRequestedDeps.startGroup(); for (SkyKey key : keys) { Preconditions.checkState( !key.equals(ErrorTransienceValue.KEY), "Error transience key cannot be in requested deps of %s", skyKey); SkyValue value = maybeGetValueFromErrorOrDeps(key); if (value == null) { missingKeys.add(key); } // To maintain the ordering. result.add(value); if (!previouslyRequestedDepsValues.containsKey(key)) { newlyRequestedDeps.add(key); } } newlyRequestedDeps.endGroup(); if (missingKeys.isEmpty()) { return result; } Map<SkyKey, ? extends NodeEntry> missingEntries = evaluatorContext.getBatchValues(skyKey, Reason.DEP_REQUESTED, missingKeys); int i = -1; for (SkyKey key : keys) { i++; if (result.get(i) != null) { continue; } NodeEntry depEntry = missingEntries.get(key); SkyValue valueOrNullMarker = getValueOrNullMarker(depEntry); result.set(i, valueOrNullMarker); newlyRequestedDepsValues.put(key, valueOrNullMarker); if (valueOrNullMarker != NULL_MARKER) { maybeUpdateMaxChildVersion(depEntry); } } return result; } /** * Returns the values of done deps in {@code depKeys}, by looking in order at: * * <ol> * <li>{@link #bubbleErrorInfo} * <li>{@link #previouslyRequestedDepsValues} * <li>{@link #newlyRequestedDepsValues} * <li>{@link #oldDepsEntries} * <li>{@link #evaluatorContext}'s graph accessing methods * </ol> * * <p>Any key whose {@link NodeEntry}--or absence thereof--had to be read from the graph will also * be entered into {@link #newlyRequestedDepsValues} with its value or a {@link #NULL_MARKER}. * * <p>This asserts that only keys in {@link #newlyRegisteredDeps} require reading from the graph, * because this node is done, and so all other deps must have been previously or newly requested. * * <p>If {@code assertDone}, this asserts that all deps in {@code depKeys} are done. */ private Collection<SkyValue> getDepValuesForDoneNodeFromErrorOrDepsOrGraph( Iterable<SkyKey> depKeys, boolean assertDone, int keySize) throws InterruptedException { List<SkyValue> result = new ArrayList<>(keySize); // depKeys may contain keys in newlyRegisteredDeps whose values have not yet been retrieved from // the graph during this environment's lifetime. int expectedMissingKeys = newlyRegisteredDeps.size(); ArrayList<SkyKey> missingKeys = expectedMissingKeys > 0 ? new ArrayList<>(expectedMissingKeys) : null; ArrayList<SkyKey> unexpectedlyMissingKeys = null; for (SkyKey key : depKeys) { SkyValue value = maybeGetValueFromErrorOrDeps(key); if (value == null) { if (key == ErrorTransienceValue.KEY) { continue; } if (!newlyRegisteredDeps.contains(key)) { if (unexpectedlyMissingKeys == null) { unexpectedlyMissingKeys = new ArrayList<>(); } unexpectedlyMissingKeys.add(key); if (missingKeys == null) { missingKeys = new ArrayList<>(); } } missingKeys.add(key); } else if (value == NULL_MARKER) { Preconditions.checkState(!assertDone, "%s had not done %s", skyKey, key); } else { result.add(value); } } if (unexpectedlyMissingKeys != null && !unexpectedlyMissingKeys.isEmpty()) { // This may still crash below, if the dep is not done in the graph, but at least it gives the // dep until now to complete its computation, as opposed to the start of this node's // evaluation, which is when most of the structures used by #maybeGetValueFromErrorOrDeps were // created. evaluatorContext .getGraphInconsistencyReceiver() .noteInconsistencyAndMaybeThrow( skyKey, unexpectedlyMissingKeys, Inconsistency.ALREADY_DECLARED_CHILD_MISSING); } if (missingKeys == null || missingKeys.isEmpty()) { return result; } Map<SkyKey, ? extends NodeEntry> missingEntries = evaluatorContext.getBatchValues(skyKey, Reason.DEP_REQUESTED, missingKeys); for (SkyKey key : missingKeys) { NodeEntry depEntry = missingEntries.get(key); SkyValue valueOrNullMarker = getValueOrNullMarker(depEntry); newlyRequestedDepsValues.put(key, valueOrNullMarker); if (valueOrNullMarker == NULL_MARKER) { // TODO(mschaller): handle registered deps that transitioned from done to dirty during eval // But how? Restarting the current node may not help, because this dep was *registered*, not // requested. For now, no node that gets registered as a dep is eligible for // intra-evaluation dirtying, so let it crash. Preconditions.checkState(!assertDone, "%s had not done: %s", skyKey, key); continue; } maybeUpdateMaxChildVersion(depEntry); result.add(valueOrNullMarker); } return result; } /** * Returns a value or a {@link #NULL_MARKER} associated with {@code key} by looking in order at: * * <ol> * <li>{@code bubbleErrorInfo} * <li>{@link #previouslyRequestedDepsValues} * <li>{@link #newlyRequestedDepsValues} * <li>{@link #oldDepsEntries} * </ol> * * <p>Returns {@code null} if no entries for {@code key} were found in any of those three maps. * (Note that none of the maps can have {@code null} as a value.) */ @Nullable SkyValue maybeGetValueFromErrorOrDeps(SkyKey key) throws InterruptedException { if (bubbleErrorInfo != null) { ValueWithMetadata bubbleErrorInfoValue = bubbleErrorInfo.get(key); if (bubbleErrorInfoValue != null) { return bubbleErrorInfoValue; } } SkyValue directDepsValue = previouslyRequestedDepsValues.get(key); if (directDepsValue != null) { return directDepsValue; } SkyValue newlyRequestedDepsValue = newlyRequestedDepsValues.get(key); if (newlyRequestedDepsValue != null) { return newlyRequestedDepsValue; } SkyValue oldDepsValueOrNullMarker = getValueOrNullMarker(oldDepsEntries.get(key)); if (oldDepsValueOrNullMarker != NULL_MARKER) { return oldDepsValueOrNullMarker; } return null; } private static SkyValue getValueOrNullMarker(@Nullable NodeEntry nodeEntry) throws InterruptedException { if (nodeEntry == null) { return NULL_MARKER; } SkyValue valueMaybeWithMetadata = nodeEntry.getValueMaybeWithMetadata(); if (valueMaybeWithMetadata == null) { return NULL_MARKER; } return valueMaybeWithMetadata; } @Override protected Map<SkyKey, ValueOrUntypedException> getValueOrUntypedExceptions( Iterable<? extends SkyKey> depKeys) throws InterruptedException { checkActive(); Map<SkyKey, SkyValue> values = getValuesFromErrorOrDepsOrGraph(depKeys); for (Map.Entry<SkyKey, SkyValue> depEntry : values.entrySet()) { SkyKey depKey = depEntry.getKey(); SkyValue depValue = depEntry.getValue(); if (depValue == NULL_MARKER) { valuesMissing = true; if (previouslyRequestedDepsValues.containsKey(depKey)) { Preconditions.checkState( bubbleErrorInfo != null, "Undone key %s was already in deps of %s( dep: %s, parent: %s )", depKey, skyKey, evaluatorContext.getGraph().get(skyKey, Reason.OTHER, depKey), evaluatorContext.getGraph().get(null, Reason.OTHER, skyKey)); } continue; } ErrorInfo errorInfo = ValueWithMetadata.getMaybeErrorInfo(depValue); if (errorInfo != null) { errorMightHaveBeenFound = true; childErrorInfos.add(errorInfo); if (bubbleErrorInfo != null) { // Set interrupted status, to try to prevent the calling SkyFunction from doing anything // fancy after this. SkyFunctions executed during error bubbling are supposed to // (quickly) rethrow errors or return a value/null (but there's currently no way to // enforce this). Thread.currentThread().interrupt(); } if ((!evaluatorContext.keepGoing() && bubbleErrorInfo == null) || errorInfo.getException() == null) { valuesMissing = true; // We arbitrarily record the first child error if we are about to abort. if (!evaluatorContext.keepGoing() && depErrorKey == null) { depErrorKey = depKey; } } } } return Maps.transformValues(values, this::transformToValueOrUntypedException); } @Override protected List<ValueOrUntypedException> getOrderedValueOrUntypedExceptions( Iterable<? extends SkyKey> depKeys) throws InterruptedException { checkActive(); List<SkyValue> values = getOrderedValuesFromErrorOrDepsOrGraph(depKeys); int i = 0; for (SkyKey depKey : depKeys) { SkyValue depValue = values.get(i++); if (depValue == NULL_MARKER) { valuesMissing = true; if (previouslyRequestedDepsValues.containsKey(depKey)) { Preconditions.checkState( bubbleErrorInfo != null, "Undone key %s was already in deps of %s( dep: %s, parent: %s )", depKey, skyKey, evaluatorContext.getGraph().get(skyKey, Reason.OTHER, depKey), evaluatorContext.getGraph().get(null, Reason.OTHER, skyKey)); } continue; } ErrorInfo errorInfo = ValueWithMetadata.getMaybeErrorInfo(depValue); if (errorInfo != null) { errorMightHaveBeenFound = true; childErrorInfos.add(errorInfo); if (bubbleErrorInfo != null) { // Set interrupted status, to try to prevent the calling SkyFunction from doing anything // fancy after this. SkyFunctions executed during error bubbling are supposed to // (quickly) rethrow errors or return a value/null (but there's currently no way to // enforce this). Thread.currentThread().interrupt(); } if ((!evaluatorContext.keepGoing() && bubbleErrorInfo == null) || errorInfo.getException() == null) { valuesMissing = true; // We arbitrarily record the first child error if we are about to abort. if (!evaluatorContext.keepGoing() && depErrorKey == null) { depErrorKey = depKey; } } } } return Lists.transform(values, this::transformToValueOrUntypedException); } private ValueOrUntypedException transformToValueOrUntypedException(SkyValue maybeWrappedValue) { if (maybeWrappedValue == NULL_MARKER) { return ValueOrUntypedException.ofNull(); } SkyValue justValue = ValueWithMetadata.justValue(maybeWrappedValue); ErrorInfo errorInfo = ValueWithMetadata.getMaybeErrorInfo(maybeWrappedValue); if (justValue != null && (evaluatorContext.keepGoing() || errorInfo == null)) { // If the dep did compute a value, it is given to the caller if we are in // keepGoing mode or if we are in noKeepGoingMode and there were no errors computing // it. return ValueOrUntypedException.ofValueUntyped(justValue); } // There was an error building the value, which we will either report by throwing an // exception or insulate the caller from by returning null. Preconditions.checkNotNull(errorInfo, "%s %s", skyKey, maybeWrappedValue); Exception exception = errorInfo.getException(); if (!evaluatorContext.keepGoing() && exception != null && bubbleErrorInfo == null) { // Child errors should not be propagated in noKeepGoing mode (except during error // bubbling). Instead we should fail fast. return ValueOrUntypedException.ofNull(); } if (exception != null) { // Give builder a chance to handle this exception. return ValueOrUntypedException.ofExn(exception); } // In a cycle. Preconditions.checkState( !errorInfo.getCycleInfo().isEmpty(), "%s %s %s", skyKey, errorInfo, maybeWrappedValue); return ValueOrUntypedException.ofNull(); } /** * If {@code !keepGoing} and there is at least one dep in error, returns a dep in error. Otherwise * returns {@code null}. */ @Nullable SkyKey getDepErrorKey() { return depErrorKey; } @Override public ExtendedEventHandler getListener() { checkActive(); return eventHandler; } void doneBuilding() { building = false; } GroupedListHelper<SkyKey> getNewlyRequestedDeps() { return newlyRequestedDeps; } void removeUndoneNewlyRequestedDeps() { HashSet<SkyKey> undoneDeps = new HashSet<>(); for (SkyKey newlyRequestedDep : newlyRequestedDeps) { if (newlyRegisteredDeps.contains(newlyRequestedDep)) { continue; } SkyValue newlyRequestedDepValue = Preconditions.checkNotNull( newlyRequestedDepsValues.get(newlyRequestedDep), newlyRequestedDep); if (newlyRequestedDepValue == NULL_MARKER) { // The dep was normally requested, and was not done. undoneDeps.add(newlyRequestedDep); } } newlyRequestedDeps.remove(undoneDeps); } boolean isAnyDirectDepErrorTransitivelyTransient() { Preconditions.checkState( bubbleErrorInfo == null, "Checking dep error transitive transience during error bubbling for: %s", skyKey); for (SkyValue skyValue : previouslyRequestedDepsValues.values()) { ErrorInfo maybeErrorInfo = ValueWithMetadata.getMaybeErrorInfo(skyValue); if (maybeErrorInfo != null && maybeErrorInfo.isTransitivelyTransient()) { return true; } } return false; } boolean isAnyNewlyRequestedDepErrorTransitivelyTransient() { Preconditions.checkState( bubbleErrorInfo == null, "Checking dep error transitive transience during error bubbling for: %s", skyKey); for (SkyValue skyValue : newlyRequestedDepsValues.values()) { ErrorInfo maybeErrorInfo = ValueWithMetadata.getMaybeErrorInfo(skyValue); if (maybeErrorInfo != null && maybeErrorInfo.isTransitivelyTransient()) { return true; } } return false; } Collection<ErrorInfo> getChildErrorInfos() { return childErrorInfos; } /** * Applies the change to the graph (mostly) atomically and returns parents to potentially signal * and enqueue. * * <p>Parents should be enqueued unless (1) this node is being built after the main evaluation has * aborted, or (2) this node is being built with {@code --nokeep_going}, and so we are about to * shut down the main evaluation anyway. */ Set<SkyKey> commitAndGetParents(NodeEntry primaryEntry) throws InterruptedException { // Construct the definitive error info, if there is one. if (errorInfo == null) { errorInfo = evaluatorContext.getErrorInfoManager().getErrorInfoToUse( skyKey, value != null, childErrorInfos); // TODO(b/166268889, b/172223413): remove when fixed. if (errorInfo != null && errorInfo.getException() instanceof IOException) { logger.atInfo().withCause(errorInfo.getException()).log( "Synthetic errorInfo for %s", skyKey); } } // We have the following implications: // errorInfo == null => value != null => enqueueParents. // All these implications are strict: // (1) errorInfo != null && value != null happens for values with recoverable errors. // (2) value == null && enqueueParents happens for values that are found to have errors // during a --keep_going build. Pair<NestedSet<TaggedEvents>, NestedSet<Postable>> eventsAndPostables = buildAndReportEventsAndPostables(primaryEntry, /*expectDoneDeps=*/ true); SkyValue valueWithMetadata; if (value == null) { Preconditions.checkNotNull(errorInfo, "%s %s", skyKey, primaryEntry); valueWithMetadata = ValueWithMetadata.error(errorInfo, eventsAndPostables.first, eventsAndPostables.second); } else { valueWithMetadata = ValueWithMetadata.normal( value, errorInfo, eventsAndPostables.first, eventsAndPostables.second); } GroupedList<SkyKey> temporaryDirectDeps = primaryEntry.getTemporaryDirectDeps(); if (evaluatorContext.getGraph().storesReverseDeps() && !oldDeps.isEmpty()) { // Remove the rdep on this entry for each of its old deps that is no longer a direct dep. Set<SkyKey> depsToRemove = Sets.difference(oldDeps, temporaryDirectDeps.toSet()); Collection<? extends NodeEntry> oldDepEntries = evaluatorContext.getGraph().getBatch(skyKey, Reason.RDEP_REMOVAL, depsToRemove).values(); for (NodeEntry oldDepEntry : oldDepEntries) { oldDepEntry.removeReverseDep(skyKey); } } Version evaluationVersion = maxChildVersion; if (bubbleErrorInfo != null) { // Cycles can lead to a state where the versions of done children don't accurately reflect the // state that led to this node's value. Be conservative then. evaluationVersion = evaluatorContext.getGraphVersion(); } else if (injectedVersion != null) { evaluationVersion = injectedVersion; } else if (evaluatorContext.getEvaluationVersionBehavior() == EvaluationVersionBehavior.GRAPH_VERSION || hermeticity == FunctionHermeticity.NONHERMETIC) { evaluationVersion = evaluatorContext.getGraphVersion(); } else if (evaluationVersion == null) { Preconditions.checkState( temporaryDirectDeps.isEmpty(), "No max child version found, but have direct deps: %s %s", skyKey, primaryEntry); evaluationVersion = evaluatorContext.getGraphVersion(); } Version previousVersion = primaryEntry.getVersion(); // If this entry is dirty, setValue may not actually change it, if it determines that // the data being written now is the same as the data already present in the entry. Set<SkyKey> reverseDeps = primaryEntry.setValue(valueWithMetadata, evaluationVersion); // Note that if this update didn't actually change the entry, this version may not be // evaluationVersion. Version currentVersion = primaryEntry.getVersion(); // Tell the receiver that this value was built. If currentVersion.equals(evaluationVersion), it // was evaluated this run, and so was changed. Otherwise, it is less than evaluationVersion, by // the Preconditions check above, and was not actually changed this run -- when it was written // above, its version stayed below this update's version, so its value remains the same. // We use a SkyValueSupplier here because it keeps a reference to the entry, allowing for // the receiver to be confident that the entry is readily accessible in memory. EvaluationState evaluationState = currentVersion.equals(previousVersion) ? EvaluationState.CLEAN : EvaluationState.BUILT; evaluatorContext .getProgressReceiver() .evaluated( skyKey, evaluationState == EvaluationState.BUILT ? value : null, evaluationState == EvaluationState.BUILT ? errorInfo : null, EvaluationSuccessStateSupplier.fromSkyValue(valueWithMetadata), evaluationState); return reverseDeps; } @Nullable private String getTagFromKey() { return evaluatorContext.getSkyFunctions().get(skyKey.functionName()).extractTag(skyKey); } /** * Gets the latch that is counted down when an exception is thrown in {@code * AbstractQueueVisitor}. For use in tests to check if an exception actually was thrown. Calling * {@code AbstractQueueVisitor#awaitExceptionForTestingOnly} can throw a spurious {@link * InterruptedException} because {@link CountDownLatch#await} checks the interrupted bit before * returning, even if the latch is already at 0. See bug "testTwoErrors is flaky". */ CountDownLatch getExceptionLatchForTesting() { return evaluatorContext.getVisitor().getExceptionLatchForTestingOnly(); } @Override public boolean inErrorBubblingForTesting() { return bubbleErrorInfo != null; } @Override public void registerDependencies(Iterable<SkyKey> keys) throws InterruptedException { if (EvaluationVersionBehavior.MAX_CHILD_VERSIONS.equals( evaluatorContext.getEvaluationVersionBehavior())) { // Need versions when doing MAX_CHILD_VERSIONS, so can't use optimization. To use the // optimization, the caller would have to know the versions of the passed-in keys. Extensions // of the SkyFunction.Environment interface to make that possible could happen. Map<SkyKey, SkyValue> checkSizeMap = getValues(keys); ImmutableSet<SkyKey> keysSet = ImmutableSet.copyOf(keys); if (checkSizeMap.size() != keysSet.size()) { throw new IllegalStateException( "Missing keys when checking dependencies for " + skyKey + ": " + Sets.difference(keysSet, checkSizeMap.keySet())); } return; } newlyRequestedDeps.startGroup(); for (SkyKey key : keys) { if (!previouslyRequestedDepsValues.containsKey(key)) { newlyRequestedDeps.add(key); newlyRegisteredDeps.add(key); } } newlyRequestedDeps.endGroup(); } @Override public void injectVersionForNonHermeticFunction(Version version) { Preconditions.checkState(hermeticity == FunctionHermeticity.NONHERMETIC, skyKey); injectedVersion = version; } private void maybeUpdateMaxChildVersion(NodeEntry depEntry) { if (hermeticity != FunctionHermeticity.NONHERMETIC && evaluatorContext.getEvaluationVersionBehavior() == EvaluationVersionBehavior.MAX_CHILD_VERSIONS) { Version depVersion = depEntry.getVersion(); if (maxChildVersion == null || maxChildVersion.atMost(depVersion)) { maxChildVersion = depVersion; } } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("skyKey", skyKey) .add("oldDeps", oldDeps) .add("value", value) .add("errorInfo", errorInfo) .add("previouslyRequestedDepsValues", previouslyRequestedDepsValues) .add("newlyRequestedDepsValues", newlyRequestedDepsValues) .add("newlyRegisteredDeps", newlyRegisteredDeps) .add("newlyRequestedDeps", newlyRequestedDeps) .add("childErrorInfos", childErrorInfos) .add("depErrorKey", depErrorKey) .add("hermeticity", hermeticity) .add("maxChildVersion", maxChildVersion) .add("injectedVersion", injectedVersion) .add("bubbleErrorInfo", bubbleErrorInfo) .add("evaluatorContext", evaluatorContext) .toString(); } @Override public boolean restartPermitted() { return evaluatorContext.restartPermitted(); } /** Thrown during environment construction if previously requested deps are no longer done. */ static class UndonePreviouslyRequestedDeps extends Exception { private final ImmutableList<SkyKey> depKeys; UndonePreviouslyRequestedDeps(ImmutableList<SkyKey> depKeys) { this.depKeys = depKeys; } ImmutableList<SkyKey> getDepKeys() { return depKeys; } } }
meteorcloudy/bazel
src/main/java/com/google/devtools/build/skyframe/SkyFunctionEnvironment.java
Java
apache-2.0
42,587
export class TopRequest { constructor( public By: string, public Class: number, public Source: number) {} }
4WallpapersNinja/FourWallpapers
FourWallpapers/wwwroot_source/app/core/models/Top.ts
TypeScript
apache-2.0
139
<!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_67) on Mon Mar 23 19:49:38 CET 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>org.jboss.netty.handler.logging (Netty API Reference (3.10.1.Final))</title> <meta name="date" content="2015-03-23"> <meta name="keywords" content="org.jboss.netty.handler.logging package"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../../org/jboss/netty/handler/logging/package-summary.html" target="classFrame">org.jboss.netty.handler.logging</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="LoggingHandler.html" title="class in org.jboss.netty.handler.logging" target="classFrame">LoggingHandler</a></li> </ul> </div> </body> </html>
anmei/netty-3.10.1.Final
doc/api/org/jboss/netty/handler/logging/package-frame.html
HTML
apache-2.0
991
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Inventory { public class Cheat : MonoBehaviour { private InventoryModel model; private InventoryController controller; public enum Inventory { Ship, Base } public Inventory inventoryType; // Use this for initialization void Start() { model = FindObjectOfType<InventoryModel>(); List<InventoryController> controllers = new List<InventoryController>(FindObjectsOfType<InventoryController>()); InventoryController.Inventory type = InventoryController.Inventory.Both; switch (inventoryType) { case Inventory.Ship: type = InventoryController.Inventory.Ship; break; case Inventory.Base: type = InventoryController.Inventory.Base; break; default: break; } controller = controllers.Find(x => x.inventoryType == type); } // Update is called once per frame void Update() { } public void AddItems() { switch (inventoryType) { case Inventory.Ship: for (int i = 0; i < 6; i++) { controller.AddItem(100+i, 5); } break; case Inventory.Base: for (int i = 0; i < 6; i++) { controller.AddItem(100+i, 5); } break; default: break; } } } }
CalinoursIncorporated/8INF830
Assets/Scripts/Cheat.cs
C#
apache-2.0
1,835
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.clustercontroller.core.status; import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageResponse; import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServer; import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServerInterface; import com.yahoo.vespa.clustercontroller.utils.communication.http.HttpRequest; import com.yahoo.vespa.clustercontroller.utils.communication.http.HttpRequestHandler; import com.yahoo.vespa.clustercontroller.utils.communication.http.HttpResult; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StatusHandler implements HttpRequestHandler { private final static Logger log = Logger.getLogger(StatusHandler.class.getName()); public interface ClusterStatusPageServerSet { ContainerStatusPageServer get(String cluster); Map<String, ContainerStatusPageServer> getAll(); } public static class ContainerStatusPageServer implements StatusPageServerInterface { StatusPageServer.HttpRequest request; StatusPageResponse response; // Ensure only only one use the server at a time private final Object queueMonitor = new Object(); // Lock safety with fleetcontroller. Wait until completion private final Object answerMonitor = new Object(); @Override public int getPort() { return 0; } @Override public void shutdown() throws InterruptedException, IOException {} @Override public void setPort(int port) {} @Override public StatusPageServer.HttpRequest getCurrentHttpRequest() { synchronized (answerMonitor) { StatusPageServer.HttpRequest r = request; request = null; return r; } } @Override public void answerCurrentStatusRequest(StatusPageResponse r) { synchronized (answerMonitor) { response = r; answerMonitor.notify(); } } StatusPageResponse getStatus(StatusPageServer.HttpRequest req) throws InterruptedException { synchronized (queueMonitor) { synchronized (answerMonitor) { request = req; while (response == null) { answerMonitor.wait(); } StatusPageResponse res = response; response = null; return res; } } } } private static final Pattern clusterListRequest = Pattern.compile("^/clustercontroller-status/v1/?$"); private static final Pattern statusRequest = Pattern.compile("^/clustercontroller-status/v1/([^/]+)(/.*)?$"); private final ClusterStatusPageServerSet statusClusters; public StatusHandler(ClusterStatusPageServerSet set) { statusClusters = set; } @Override public HttpResult handleRequest(HttpRequest httpRequest) throws Exception { log.fine("Handling status request " + httpRequest); Matcher matcher = statusRequest.matcher(httpRequest.getPath()); if (matcher.matches()) { return handleClusterRequest(matcher.group(1), matcher.group(2)); } matcher = clusterListRequest.matcher(httpRequest.getPath()); if (matcher.matches()) { return handleClusterListRequest(); } return new HttpResult().setHttpCode( 404, "No page for request '" + httpRequest.getPath() + "'."); } private HttpResult handleClusterRequest(String clusterName, String fleetControllerPath) throws InterruptedException { ContainerStatusPageServer statusServer = statusClusters.get(clusterName); if (statusServer == null) { return new HttpResult().setHttpCode( 404, "No controller exists for cluster '" + clusterName + "'."); } if (fleetControllerPath == null || fleetControllerPath.isEmpty()) { fleetControllerPath = "/"; } StatusPageServer.HttpRequest req = new StatusPageServer.HttpRequest(fleetControllerPath); req.setPathPrefix("/clustercontroller-status/v1"); StatusPageResponse response = statusServer.getStatus(req); HttpResult result = new HttpResult(); if (response.getResponseCode() != null) { result.setHttpCode( response.getResponseCode().getCode(), response.getResponseCode().getMessage()); } if (response.getContentType() != null) { result.addHeader("Content-Type", response.getContentType()); } result.setContent(response.getOutputStream().toString(StandardCharsets.UTF_8)); return result; } public HttpResult handleClusterListRequest() { HttpResult result = new HttpResult(); result.addHeader("Content-Type", "text/html"); StringWriter sw = new StringWriter(); sw.append("<title>clusters</title>\n"); for (String s : statusClusters.getAll().keySet()) { sw.append("<a href=\"./").append(s).append("\">").append(s) .append("</a><br>").append("\n"); } result.setContent(sw.toString()); return result; } }
vespa-engine/vespa
clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/status/StatusHandler.java
Java
apache-2.0
5,611
package ru.job4j.dal.dao.queries;
Rmelev/rshmelev
music_store/src/main/java/ru/job4j/dal/dao/queries/package-info.java
Java
apache-2.0
33
# AUTOGENERATED FILE FROM balenalib/artik5-ubuntu:disco-build ENV NODE_VERSION 10.23.1 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "8f965f2757efcf3077d655bfcea36f7a29c58958355e0eb23cfb725740c3ccbe node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu disco \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v10.23.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/node/artik5/ubuntu/disco/10.23.1/build/Dockerfile
Dockerfile
apache-2.0
2,757
/* Copyright 2014-2016 Maurice Laveaux * * 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 "opengl/OpenglContext.h" #include "opengl/Opengl.h" #include "core/Configuration.h" #include "core/Log.h" namespace { using oglr::LogType; static const char* GLContext_name = "GLContext"; void __stdcall debugLog( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const GLvoid* userParam) { std::string debugSource; switch (source) { case GL_DEBUG_SOURCE_API: debugSource = "Opengl API"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: debugSource = "Window System"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: debugSource = "Shader Compiler"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: debugSource = "Third Party"; break; case GL_DEBUG_SOURCE_APPLICATION: debugSource = "Application"; break; case GL_DEBUG_SOURCE_OTHER: debugSource = "Other"; break; } std::string debugType; switch (type) { case GL_DEBUG_TYPE_ERROR: break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: break; case GL_DEBUG_TYPE_PORTABILITY: break; case GL_DEBUG_TYPE_PERFORMANCE: break; case GL_DEBUG_TYPE_OTHER: break; } LogType logType = LogType::Information; // ARB_debug_output : Each debug output message is associated with one of these severity levels. // However NVIDIA also returns 33387 which is not even defined in this table so just ignore that. if (severity == 33387) { return; } switch (severity) { case GL_DEBUG_SEVERITY_HIGH: logType = LogType::Fatal; break; case GL_DEBUG_SEVERITY_MEDIUM: logType = LogType::Error; break; case GL_DEBUG_SEVERITY_LOW: logType = LogType::Information; break; default: assert(false); // Cases must be exhaustive. } // The highest severity has the lowest value. if (severity < GL_DEBUG_SEVERITY_LOW) { oglr::Logger::stream(logType, debugSource) << message; } } } namespace oglr { OpenglContext::OpenglContext() : m_depthEnabled(false) { // Initialize the extension wrangler to load extensions glewExperimental = GL_TRUE; GLuint error = glewInit(); if (error != GLEW_OK) { Logger::stream(LogType::Fatal, GLContext_name) << "glewInit() failed with " << error; } #ifdef DEBUG_BUILD if (GLEW_ARB_debug_output) { // Set the ARB_Debug_Output glDebugMessageCallbackARB(debugLog, nullptr); } else { Logger::stream(LogType::Information, GLContext_name) << "ARB_Debug_Output extension is not available."; } #endif // DEBUG_BUILD // Somehow glewInit generates an error, but that is not reported by the return value. glGetError(); } void OpenglContext::setDepthTest(bool enabled) { if (enabled != m_depthEnabled) { m_depthEnabled = enabled; if (enabled) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } } } void OpenglContext::setWireframe(bool enabled) { if (enabled != m_wireframeEnabled) { m_wireframeEnabled = enabled; if (enabled) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } } void OpenglContext::setTwoSided(bool enabled) { if (enabled != m_twoSidedEnabled) { m_twoSidedEnabled = enabled; if (enabled) { glEnable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); } } } void OpenglContext::setFramebuffer(FrameBuffer* framebuffer) { if (framebuffer == nullptr) { OGLR_CHECKGLERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); } else { framebuffer->use(); } } void OpenglContext::clearColor(float r, float g, float b, float a) { // Clear the current swap buffer glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } Shader::Ptr OpenglContext::createVertexShader(const char* strResourceName, const std::vector<char>& sourceCode) { return Shader::Ptr(new Shader(GL_VERTEX_SHADER, strResourceName, sourceCode)); } Shader::Ptr OpenglContext::createFragmentShader(const char* strResourceName, const std::vector<char>& sourceCode) { return Shader::Ptr(new Shader(GL_FRAGMENT_SHADER, strResourceName, sourceCode)); } } // oglr namespace
mlaveaux/OpenGLRenderer
lib/src/opengl/OpenglContext.cpp
C++
apache-2.0
4,888
package net.steel.circuit; public class CircuitBreaker { public enum CircuitState { CLOSED, HALF_OPEN, OPEN; } }
Mr-Steel/vertx_loadtest
src/main/java/net.steel.circuit/CircuitBreaker.java
Java
apache-2.0
145
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.autoscaler.monitor; import org.apache.stratos.autoscaler.monitor.component.ParentComponentMonitor; import org.apache.stratos.messaging.domain.instance.Instance; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Abstract class for the monitoring functionality in Autoscaler. */ public abstract class Monitor implements EventHandler { //Monitor types public enum MonitorType { Application, Group, Cluster } //Id of the monitor, cluster=clusterId, group=group-alias, application=app-alias protected String id; //The parent app which this monitor relates to protected String appId; //Parent monitor of this monitor, for appMonitor parent will be none. protected ParentComponentMonitor parent; //has startup dependents protected boolean hasStartupDependents; //monitors map, key=InstanceId and value=ClusterInstance/GroupInstance/ApplicationInstance protected Map<String, Instance> instanceIdToInstanceMap; public Monitor() { this.instanceIdToInstanceMap = new HashMap<String, Instance>(); } /** * Implement this method to destroy the monitor thread */ public abstract void destroy(); /** * This will create Instance on demand as requested by monitors * * @param instanceId instance Id of the instance to be created * @return whether it is created or not */ public abstract boolean createInstanceOnDemand(String instanceId); /** * Return the id of the monitor * * @return id */ public String getId() { return id; } /** * Return the type of the monitor. * * @return monitor type */ public abstract MonitorType getMonitorType(); /** * Set the id of the monitor * * @param id id of the monitor */ public void setId(String id) { this.id = id; } /** * To get the appId of the monitor * * @return app id */ public String getAppId() { return appId; } /** * To set the app id of the monitor * * @param appId application id */ public void setAppId(String appId) { this.appId = appId; } /** * To get the parent of the monitor * * @return the parent */ public ParentComponentMonitor getParent() { return parent; } /** * To set the parent of the monitor * * @param parent parent of the monitor */ public void setParent(ParentComponentMonitor parent) { this.parent = parent; this.appId = parent.getAppId(); } /** * Return whether this monitor has startup dependencies * * @return hasStartupDependents */ public boolean hasStartupDependents() { return hasStartupDependents; } /** * To set whether monitor has any startup dependencies * * @param hasDependent whether monitor has dependent or not */ public void setHasStartupDependents(boolean hasDependent) { hasStartupDependents = hasDependent; } /** * This will add the instance * * @param instance instance to be added */ public void addInstance(Instance instance) { instanceIdToInstanceMap.put(instance.getInstanceId(), instance); } /** * Using instanceId, instance can be retrieved * * @param instanceId instance id * @return the instance */ public Instance getInstance(String instanceId) { return instanceIdToInstanceMap.get(instanceId); } /** * This will remove the instance * * @param instanceId instance id */ public void removeInstance(String instanceId) { instanceIdToInstanceMap.remove(instanceId); } /** * This will return all the instances which has the same parent id as given * * @param parentInstanceId parent instance id * @return all the instances */ public List<String> getInstancesByParentInstanceId(String parentInstanceId) { List<String> instances = new ArrayList<String>(); for (Instance instance : instanceIdToInstanceMap.values()) { if (instance.getParentId().equals(parentInstanceId)) { instances.add(instance.getInstanceId()); } } return instances; } /** * This will check whether instances are there in the map * * @return true/false */ public boolean hasInstance() { return !instanceIdToInstanceMap.isEmpty(); } }
agentmilindu/stratos
components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/monitor/Monitor.java
Java
apache-2.0
5,445
var chai = require('chai'); var expect = chai.expect; var sinonChai = require('sinon-chai'); var _ = require("underscore"); var syncClient = require("../../src/feedhenry").sync; chai.use(sinonChai); //work around phantomjs's issue: https://github.com/ariya/phantomjs/issues/10647 var fakeNavigator = {}; for (var i in navigator) { fakeNavigator[i] = navigator[i]; } fakeNavigator.onLine = true; navigator = fakeNavigator; var dataSetId = "myShoppingList"; var onSync = function(cb){ syncClient.forceSync(dataSetId, function(){ setTimeout(function(){ cb(); }, 600); }); } describe("test sync framework cloud handler", function(){ this.timeout(10000); var header = { "Content-Type": "application/json" }; var xhr; var requests; before(function(done){ syncClient.init({ do_console_log: true, sync_frequency: 1, sync_active: false, storage_strategy: ['memory'], crashed_count_wait: 0 }); syncClient.manage(dataSetId, {"sync_active": false, "has_custom_sync": false}, {}, {}, done); }); beforeEach(function(done){ xhr = sinon.useFakeXMLHttpRequest(); requests = []; xhr.onCreate = function(req){ console.log("Got sync request", req); requests.push(req); } syncClient.manage(dataSetId, {}, {}, {}, function(){ syncClient.clearPending(dataSetId, function(){ done(); }); }); }); afterEach(function(done){ xhr.restore(); syncClient.notify(undefined); syncClient.stopSync(dataSetId, done, done); }); it("load initial dataset from remote", function(done){ //since we want to check what requests have been sent and their data, //we turn off sync and use forceSync to control sync loop onSync(function(){ //verify there is one request is in the queue expect(requests.length).to.equal(1); var reqObj = requests[0]; expect(reqObj.url).to.have.string("/mbaas/sync/" + dataSetId); expect(reqObj.method.toLowerCase()).to.equal("post"); var reqBody = JSON.parse(reqObj.requestBody); expect(reqBody.fn).to.equal("sync"); expect(reqBody.pending).is.empty; //return hash var mockHash = "97d170e1550eee4afc0af065b78cda302a97674c"; reqObj.respond(200, header, JSON.stringify({ "hash": mockHash, "updates": {} })); var syncRecorsReq = requests[1]; reqBody = JSON.parse(syncRecorsReq.requestBody); expect(reqBody.fn).to.equal("syncRecords"); syncRecorsReq.respond(200, header, JSON.stringify({ "hash": mockHash })); //server turned empty dataset, then the client dataset should be empty as well syncClient.getDataset(dataSetId, function(dataset){ expect(dataset.data).is.empty; done(); }); }); }); });
feedhenry/fh-js-sdk
test/tests/test_sync.js
JavaScript
apache-2.0
2,821
package scope import ( "fmt" "net/url" "github.com/docker/infrakit/pkg/discovery" "github.com/docker/infrakit/pkg/discovery/local" "github.com/docker/infrakit/pkg/plugin" "github.com/docker/infrakit/pkg/run/scope" "github.com/docker/infrakit/pkg/spi/controller" "github.com/docker/infrakit/pkg/spi/flavor" "github.com/docker/infrakit/pkg/spi/group" "github.com/docker/infrakit/pkg/spi/instance" "github.com/docker/infrakit/pkg/spi/loadbalancer" "github.com/docker/infrakit/pkg/spi/stack" "github.com/docker/infrakit/pkg/template" ) // FakeLeader returns a fake leadership func func FakeLeader(v bool) func() stack.Leadership { return func() stack.Leadership { return fakeLeaderT(v) } } type fakeLeaderT bool func (f fakeLeaderT) IsLeader() (bool, error) { return bool(f), nil } func (f fakeLeaderT) LeaderLocation() (*url.URL, error) { return nil, nil } type fakePlugins map[string]*plugin.Endpoint // Find implements discovery.Plugins func (f fakePlugins) Find(name plugin.Name) (*plugin.Endpoint, error) { if f == nil { return nil, fmt.Errorf("not found") } lookup, _ := name.GetLookupAndType() if v, has := f[lookup]; has { return v, nil } return nil, fmt.Errorf("not found") } // List implements discovery.Plugins func (f fakePlugins) List() (map[string]*plugin.Endpoint, error) { return (map[string]*plugin.Endpoint)(f), nil } // FakeScope returns a fake Scope with given endpoints func FakeScope(endpoints map[string]*plugin.Endpoint) scope.Scope { return scope.DefaultScope(func() discovery.Plugins { return fakePlugins(endpoints) }) } // DefaultScope returns a default scope but customizable for different plugin lookups func DefaultScope() *Scope { f, err := local.NewPluginDiscovery() if err != nil { panic(err) } return &Scope{ Scope: scope.DefaultScope(func() discovery.Plugins { return f }), } } // Scope is the testing scope for looking up components type Scope struct { scope.Scope // ResolvePlugins returns the plugin lookup ResolvePlugins func() discovery.Plugins // ResolveStack returns the stack that entails this scope ResolveStack func(n string) (stack.Interface, error) // ResolveGroup is for looking up an group plugin ResolveGroup func(n string) (group.Plugin, error) // ResolveController returns the controller by name ResolveController func(n string) (controller.Controller, error) // ResolveInstance is for looking up an instance plugin ResolveInstance func(n string) (instance.Plugin, error) // ResolveFlavor is for lookup up a flavor plugin ResolveFlavor func(n string) (flavor.Plugin, error) // ResolveL4 is for lookup up an L4 plugin ResolveL4 func(n string) (loadbalancer.L4, error) // ResolveMetadata is for resolving metadata / path related queries ResolveMetadata func(p string) (*scope.MetadataCall, error) // ResolveTemplateEngine creates a template engine for use. ResolveTemplateEngine func(url string, opts template.Options) (*template.Template, error) } // Plugins returns the plugin lookup func (s *Scope) Plugins() discovery.Plugins { if s.ResolvePlugins != nil { return s.ResolvePlugins() } return s.Scope.Plugins() } // Stack returns the stack that entails this scope func (s *Scope) Stack(name string) (stack.Interface, error) { if s.ResolveStack != nil { return s.ResolveStack(name) } return s.Scope.Stack(name) } // Group is for looking up an group plugin func (s *Scope) Group(name string) (group.Plugin, error) { if s.ResolveGroup != nil { return s.ResolveGroup(name) } return s.Scope.Group(name) } // Controller returns the controller by name func (s *Scope) Controller(name string) (controller.Controller, error) { if s.ResolveController != nil { return s.ResolveController(name) } return s.Scope.Controller(name) } // Instance is for looking up an instance plugin func (s *Scope) Instance(name string) (instance.Plugin, error) { if s.ResolveInstance != nil { return s.ResolveInstance(name) } return s.Scope.Instance(name) } // Flavor is for lookup up a flavor plugin func (s *Scope) Flavor(name string) (flavor.Plugin, error) { if s.ResolveFlavor != nil { return s.ResolveFlavor(name) } return s.Scope.Flavor(name) } // L4 is for lookup up an L4 plugin func (s *Scope) L4(name string) (loadbalancer.L4, error) { if s.ResolveL4 != nil { return s.ResolveL4(name) } return s.Scope.L4(name) } // Metadata is for resolving metadata / path related queries func (s *Scope) Metadata(path string) (*scope.MetadataCall, error) { if s.ResolveMetadata != nil { return s.ResolveMetadata(path) } return s.Scope.Metadata(path) } // TemplateEngine creates a template engine for use. func (s *Scope) TemplateEngine(url string, opts template.Options) (*template.Template, error) { if s.ResolveTemplateEngine != nil { return s.ResolveTemplateEngine(url, opts) } return s.Scope.TemplateEngine(url, opts) }
chungers/infrakit
pkg/testing/scope/scope.go
GO
apache-2.0
4,874
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MvcTestClient.App_Start.NinjectWebCommon), "Start")] [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(MvcTestClient.App_Start.NinjectWebCommon), "Stop")] namespace MvcTestClient.App_Start { using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using MvcTestClient.Controllers; using Ninject; using Ninject.Extensions.TypeAssemblyVersionInformation; using Ninject.Web.Common; using Ninject.Web.Mvc; public static class NinjectWebCommon { private static readonly Bootstrapper Bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); Bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { Bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(new NinjectSettings { LoadExtensions = false }); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } catch { kernel.Dispose(); throw; } } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Load<MvcModule>(); kernel.Load<TypeBasedVersionModule<EntryAssemblyVersionController>>(); } } }
iappert/Ninject.Extensions.AssemblyVersionInformation
source/MvcTestClient/App_Start/NinjectWebCommon.cs
C#
apache-2.0
2,384
package com.olvind sealed trait OutFile case class PrimaryOutFile(filename: CompName, content: String, secondaries: Seq[SecondaryOutFile]) extends OutFile case class SecondaryOutFile(filename: String, content: String) extends OutFile object Printer { case class FieldStats(maxFieldNameLen: Int, maxTypeNameLen: Int) def apply(prefix: String, comp: ParsedComponent): (PrimaryOutFile, Seq[SecondaryOutFile]) = { val fs: FieldStats = FieldStats( maxFieldNameLen = comp.fields.map(_.name.value.length).max, maxTypeNameLen = comp.fields.map(_.typeName.length).max ) val p = PrimaryOutFile( comp.name, Seq( s"\ncase class ${comp.nameDef(prefix, withBounds = true)}(", comp.fields .filterNot(_.name == PropName("children")) .map( p => outProp(p, fs) ) .mkString("", ",\n", ")") + bodyChildren(prefix, comp) ) mkString "\n", comp.methodClassOpt.toSeq map outMethodClass ) (p, comp.enumClases map outEnumClass) } def hack(comp: ParsedComponent): String = comp.genericParams .map { p ⇒ s"""implicit def ev${p.name}(${p.name.toLowerCase}: ${p.name}): js.Any = ${p.name.toLowerCase}.asInstanceOf[js.Any] implicit def ev2${p.name}(${p.name.toLowerCase}: ${p.name} | js.Array[${p.name}]): js.Any = ${p.name.toLowerCase}.asInstanceOf[js.Any]""" } .mkString(";") def bodyChildren(prefix: String, comp: ParsedComponent): String = (comp.childrenOpt, comp.definition.multipleChildren) match { case (None, _) => s"""{ | |${indent(1)}def apply() = { |${indent(2)}${hack(comp)} |${indent(2)}val props = JSMacro[${comp.nameDef(prefix)}](this) |${indent(2)}val f = JsComponent[js.Object, Children.None, Null]($prefix.${comp.name.value}) |${indent(2)}f(props) |${indent(1)}} |} """.stripMargin case (Some(childrenProp), true) => s"""{ | |${outChildrenComment(childrenProp.commentOpt)} |${indent(1)}def apply(children: ${childrenProp.baseType.name}*) = { |${indent(2)}${hack(comp)} |${indent(2)}val props = JSMacro[${comp.nameDef(prefix)}](this) |${indent(2)}val f = JsComponent[js.Object, Children.Varargs, Null]($prefix.${comp.name.value}) |${indent(2)}f(props)(children: _*) |${indent(1)}} |}""".stripMargin case (Some(childrenProp), false) => s"""{ | |${outChildrenComment(childrenProp.commentOpt)} |${indent(1)}def apply(child: ${childrenProp.typeName} = js.undefined) = { |${indent(2)}${if (!childrenProp.isRequired) "import js.UndefOr._"} |${indent(2)}${hack(comp)} |${indent(2)}val props = JSMacro[${comp.nameDef(prefix)}](this) |${indent(2)}val f = JsComponent[js.Object, Children.Varargs, Null]($prefix.${comp.name.value}) |${indent(2)}${if (childrenProp.isRequired) "f(props)(child)" else "child.fold(f(props)())(ch => f(props)(ch))"} |${indent(1)}} |}""".stripMargin } def outChildrenComment(oc: Option[PropComment]): String = oc.flatMap(_.value) match { case Some(c) => c.split("\n") .mkString( s"${indent(1)}/**\n ${indent(1)} * @param children ", "\n" + indent(2), s"\n${indent(1)} */" ) case None => "" } def outComment(_commentOpt: Option[PropComment], inheritedFrom: Option[CompName]): String = { val inheritedLine: Option[String] = inheritedFrom.map(i => s"(Passed on to $i)") val lines: Seq[String] = _commentOpt match { case None => inheritedLine.toSeq case Some(comment) => val anns: Seq[String] = comment.anns.collect { case Param(value) => s"@param $value" } comment.value.toSeq ++ inheritedLine ++ (if (anns.isEmpty) Nil else Seq("\n")) ++ anns } if (lines.isEmpty) "" else lines.flatMap(_.split("\n")).mkString(s"${indent(1)}/** ", s"\n${indent(2)} ", " */\n") } def safeName(name: String): String = { val safeSubstitutions = Map( ("super" -> "`super`"), ("type" -> "`type`") ) val ret = safeSubstitutions.get(name).getOrElse(name) if (ret.contains("-")) { s"`${ret}`" } else { ret } } def outProp(p: ParsedProp, fs: FieldStats): String = { val comment = outComment(p.commentOpt, p.inheritedFrom) val intro: String = { val fixedName: String = safeName(p.name.value) val deprecation: String = (p.deprecatedMsg, p.commentOpt.exists(_.anns.contains(Ignore))) match { case (Some(msg), _) => s"""${indent(1)}@deprecated("$msg", "")\n""" case (None, true) => "" //s"""${indent(1)}@deprecated("Internal API", "")\n""" case _ => "" } s"$comment$deprecation${indent(1)}${padTo(fixedName + ": ")(fs.maxFieldNameLen + 2)}" } p.isRequired match { case true => intro + p.typeName case false => intro + padTo(p.typeName)(fs.maxTypeNameLen) + " = js.undefined" } } def outEnumClass(c: ParsedEnumClass): SecondaryOutFile = { SecondaryOutFile( c.name, s""" |class ${c.name}(val value: String) extends AnyVal |object ${c.name} { |${c.identifiers .map { case (ident, original) => s"""${indent(1)}val ${safeName(ident.value)} = new ${c.name}("$original")""" } .mkString("\n")} |${indent(1)}val values = ${c.identifiers.map(_._1.value).map(safeName).toList} |}""".stripMargin ) } def outMethodClass(c: ParsedMethodClass): SecondaryOutFile = SecondaryOutFile( c.className, s""" |@js.native |trait ${c.className} extends js.Object { |${c.methods .map { m => val deprecated: String = if (m.toString.toLowerCase.contains("deprecated")) s"""${indent(1)}@deprecated("", "")\n""" else "" val comment = outComment(m.commentOpt, None) s"$comment$deprecated${indent(1)}def ${m.definition} = js.native" } .mkString("\n\n")} |}""".stripMargin ) }
aparo/scalajs-react-components
gen/src/main/scala/com/olvind/printers.scala
Scala
apache-2.0
6,481
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Author: Aleh Khomich * * Creation Date: 26.04.2010 * * Completion Time: 26.04.2010 * *******************************************************************************/ package org.oscm.ui.converter; import java.math.BigDecimal; import java.text.ParseException; import java.util.Locale; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import org.oscm.converter.PriceConverter; import org.oscm.ui.beans.BaseBean; import org.oscm.ui.common.JSFUtils; import org.oscm.validation.Invariants; /** * Currency converter for UI. * * @author Aleh Khomich. * */ public class CurrencyConverter implements Converter { /** * Conversion to server representation, so converting currency to internal * integer with cents format. Prior to the conversion the input value is * validated. * * @param context * JSF context. * @param component * Component which value will be processed. * @param value * Value. */ public Object getAsObject(FacesContext context, UIComponent component, String value) { final PriceConverter converter = getConverter(context); try { return converter.parse(value); } catch (ParseException e) { String msg = e.getMessage(); if (msg != null && msg.equals("ERROR_PRICEMODEL_INVALID_FRACTIONAL_PART")) { throw new ConverterException(JSFUtils.getFacesMessage( component, context, BaseBean.ERROR_PRICEMODEL_INVALID_FRACTIONAL_PART)); } throw new ConverterException(JSFUtils.getFacesMessage(component, context, BaseBean.ERROR_PRICEMODEL_INPUT)); } } /** * Conversion to UI representation as String. * * @param context * JSF context. * @param component * Component which value will be processed. * @param object * Value. */ public String getAsString(FacesContext context, UIComponent component, Object object) { if (object == null) { return null; } Invariants.asserType(object, BigDecimal.class); final PriceConverter converter = getConverter(context); return converter.getValueToDisplay((BigDecimal) object, true); } /** * Getting converter with needed local. * * @param context * JSF context. * @return Instance of old price converter. TODO Refactor all code for using * only UI conversion. */ private PriceConverter getConverter(FacesContext context) { Locale locale; if (context.getViewRoot() != null) { locale = context.getViewRoot().getLocale(); } else { locale = context.getApplication().getDefaultLocale(); } final PriceConverter converter = new PriceConverter(locale); return converter; } }
opetrovski/development
oscm-portal/javasrc/org/oscm/ui/converter/CurrencyConverter.java
Java
apache-2.0
3,800
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.hostdb; import java.lang.invoke.MethodHandles; import java.text.SimpleDateFormat; import java.util.Random; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.SequenceFileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.SequenceFileOutputFormat; import org.apache.hadoop.mapred.KeyValueTextInputFormat; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.lib.MultipleInputs; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.crawl.CrawlDb; import org.apache.nutch.crawl.NutchWritable; import org.apache.nutch.util.FSUtils; import org.apache.nutch.util.LockUtil; import org.apache.nutch.util.NutchConfiguration; import org.apache.nutch.util.NutchJob; import org.apache.nutch.util.TimingUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tool to create a HostDB from the CrawlDB. It aggregates fetch status values * by host and checks DNS entries for hosts. */ public class UpdateHostDb extends Configured implements Tool { private static final Logger LOG = LoggerFactory .getLogger(MethodHandles.lookup().lookupClass()); public static final String LOCK_NAME = ".locked"; public static final String HOSTDB_PURGE_FAILED_HOSTS_THRESHOLD = "hostdb.purge.failed.hosts.threshold"; public static final String HOSTDB_NUM_RESOLVER_THREADS = "hostdb.num.resolvers.threads"; public static final String HOSTDB_RECHECK_INTERVAL = "hostdb.recheck.interval"; public static final String HOSTDB_CHECK_FAILED = "hostdb.check.failed"; public static final String HOSTDB_CHECK_NEW = "hostdb.check.new"; public static final String HOSTDB_CHECK_KNOWN = "hostdb.check.known"; public static final String HOSTDB_FORCE_CHECK = "hostdb.force.check"; public static final String HOSTDB_URL_FILTERING = "hostdb.url.filter"; public static final String HOSTDB_URL_NORMALIZING = "hostdb.url.normalize"; public static final String HOSTDB_NUMERIC_FIELDS = "hostdb.numeric.fields"; public static final String HOSTDB_STRING_FIELDS = "hostdb.string.fields"; public static final String HOSTDB_PERCENTILES = "hostdb.percentiles"; private void updateHostDb(Path hostDb, Path crawlDb, Path topHosts, boolean checkFailed, boolean checkNew, boolean checkKnown, boolean force, boolean filter, boolean normalize) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long start = System.currentTimeMillis(); LOG.info("UpdateHostDb: starting at " + sdf.format(start)); JobConf job = new NutchJob(getConf()); boolean preserveBackup = job.getBoolean("db.preserve.backup", true); job.setJarByClass(UpdateHostDb.class); job.setJobName("UpdateHostDb"); // Check whether the urlfilter-domainblacklist plugin is loaded if (filter && new String("urlfilter-domainblacklist").matches(job.get("plugin.includes"))) { throw new Exception("domainblacklist-urlfilter must not be enabled"); } // Check whether the urlnormalizer-host plugin is loaded if (normalize && new String("urlnormalizer-host").matches(job.get("plugin.includes"))) { throw new Exception("urlnormalizer-host must not be enabled"); } FileSystem fs = FileSystem.get(job); Path old = new Path(hostDb, "old"); Path current = new Path(hostDb, "current"); Path tempHostDb = new Path(hostDb, "hostdb-" + Integer.toString(new Random().nextInt(Integer.MAX_VALUE))); // lock an existing hostdb to prevent multiple simultaneous updates Path lock = new Path(hostDb, LOCK_NAME); if (!fs.exists(current)) { fs.mkdirs(current); } LockUtil.createLockFile(fs, lock, false); MultipleInputs.addInputPath(job, current, SequenceFileInputFormat.class); if (topHosts != null) { MultipleInputs.addInputPath(job, topHosts, KeyValueTextInputFormat.class); } if (crawlDb != null) { // Tell the job we read from CrawlDB job.setBoolean("hostdb.reading.crawldb", true); MultipleInputs.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME), SequenceFileInputFormat.class); } FileOutputFormat.setOutputPath(job, tempHostDb); job.setOutputFormat(SequenceFileOutputFormat.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(NutchWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(HostDatum.class); job.setMapperClass(UpdateHostDbMapper.class); job.setReducerClass(UpdateHostDbReducer.class); job.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false); job.setSpeculativeExecution(false); job.setBoolean(HOSTDB_CHECK_FAILED, checkFailed); job.setBoolean(HOSTDB_CHECK_NEW, checkNew); job.setBoolean(HOSTDB_CHECK_KNOWN, checkKnown); job.setBoolean(HOSTDB_FORCE_CHECK, force); job.setBoolean(HOSTDB_URL_FILTERING, filter); job.setBoolean(HOSTDB_URL_NORMALIZING, normalize); job.setClassLoader(Thread.currentThread().getContextClassLoader()); try { JobClient.runJob(job); FSUtils.replace(fs, old, current, true); FSUtils.replace(fs, current, tempHostDb, true); if (!preserveBackup && fs.exists(old)) fs.delete(old, true); } catch (Exception e) { if (fs.exists(tempHostDb)) { fs.delete(tempHostDb, true); } LockUtil.removeLockFile(fs, lock); throw e; } LockUtil.removeLockFile(fs, lock); long end = System.currentTimeMillis(); LOG.info("UpdateHostDb: finished at " + sdf.format(end) + ", elapsed: " + TimingUtil.elapsedTime(start, end)); } public static void main(String args[]) throws Exception { int res = ToolRunner.run(NutchConfiguration.create(), new UpdateHostDb(), args); System.exit(res); } public int run(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: UpdateHostDb -hostdb <hostdb> " + "[-tophosts <tophosts>] [-crawldb <crawldb>] [-checkAll] [-checkFailed]" + " [-checkNew] [-checkKnown] [-force] [-filter] [-normalize]"); return -1; } Path hostDb = null; Path crawlDb = null; Path topHosts = null; boolean checkFailed = false; boolean checkNew = false; boolean checkKnown = false; boolean force = false; boolean filter = false; boolean normalize = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-hostdb")) { hostDb = new Path(args[i + 1]); LOG.info("UpdateHostDb: hostdb: " + hostDb); i++; } if (args[i].equals("-crawldb")) { crawlDb = new Path(args[i + 1]); LOG.info("UpdateHostDb: crawldb: " + crawlDb); i++; } if (args[i].equals("-tophosts")) { topHosts = new Path(args[i + 1]); LOG.info("UpdateHostDb: tophosts: " + topHosts); i++; } if (args[i].equals("-checkFailed")) { LOG.info("UpdateHostDb: checking failed hosts"); checkFailed = true; } if (args[i].equals("-checkNew")) { LOG.info("UpdateHostDb: checking new hosts"); checkNew = true; } if (args[i].equals("-checkKnown")) { LOG.info("UpdateHostDb: checking known hosts"); checkKnown = true; } if (args[i].equals("-checkAll")) { LOG.info("UpdateHostDb: checking all hosts"); checkFailed = true; checkNew = true; checkKnown = true; } if (args[i].equals("-force")) { LOG.info("UpdateHostDb: forced check"); force = true; } if (args[i].equals("-filter")) { LOG.info("UpdateHostDb: filtering enabled"); filter = true; } if (args[i].equals("-normalize")) { LOG.info("UpdateHostDb: normalizing enabled"); normalize = true; } } if (hostDb == null) { System.err.println("hostDb is mandatory"); return -1; } try { updateHostDb(hostDb, crawlDb, topHosts, checkFailed, checkNew, checkKnown, force, filter, normalize); return 0; } catch (Exception e) { LOG.error("UpdateHostDb: " + StringUtils.stringifyException(e)); return -1; } } }
code4wt/nutch-learning
src/java/org/apache/nutch/hostdb/UpdateHostDb.java
Java
apache-2.0
9,742
package http import ( "strconv" "go-common/app/service/main/archive/api" "go-common/library/ecode" bm "go-common/library/net/http/blademaster" ) func pageList(c *bm.Context) { var ( aid int64 err error pages []*api.Page ) aidStr := c.Request.Form.Get("aid") if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 { c.JSON(nil, ecode.RequestErr) return } if pages, err = playSvr.PageList(c, aid); err != nil { c.JSON(nil, err) return } if len(pages) == 0 { c.JSON(nil, ecode.NothingFound) return } c.JSON(pages, nil) } func videoShot(c *bm.Context) { v := new(struct { Aid int64 `form:"aid" validate:"min=1"` Cid int64 `form:"cid"` Index bool `form:"index"` }) if err := c.Bind(v); err != nil { return } c.JSON(playSvr.VideoShot(c, v.Aid, v.Cid, v.Index)) } func playURLToken(c *bm.Context) { var ( aid, cid, mid int64 err error ) params := c.Request.Form aidStr := params.Get("aid") if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil { c.JSON(nil, ecode.RequestErr) return } cid, _ = strconv.ParseInt(params.Get("cid"), 10, 64) midStr, _ := c.Get("mid") mid = midStr.(int64) c.JSON(playSvr.PlayURLToken(c, mid, aid, cid)) }
LQJJ/demo
126-go-common-master/app/interface/main/player/http/archive.go
GO
apache-2.0
1,235
/* * Copyright 2015 RichRelevance * * 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 scalaz package netty import concurrent._ import stream._ import syntax.monad._ import scodec.bits._ import scala.concurrent.duration._ import org.specs2.mutable._ import org.scalacheck._ import java.net.InetSocketAddress import java.util.concurrent.{Executors, ThreadFactory} object NettySpecs extends Specification { sequential val scheduler = { Executors.newScheduledThreadPool(4, new ThreadFactory { def newThread(r: Runnable) = { val t = Executors.defaultThreadFactory.newThread(r) t.setDaemon(true) t.setName("scheduled-task-thread") t } }) } "netty" should { "round trip some simple data" in { val addr = new InetSocketAddress("localhost", 9090) val server = Netty server addr take 1 flatMap { incoming => incoming flatMap { exchange => exchange.read take 1 to exchange.write drain } } val client = Netty connect addr flatMap { exchange => val data = ByteVector(12, 42, 1) val initiate = Process(data) to exchange.write val check = for { results <- exchange.read.runLog timed (5 seconds) _ <- Task delay { results must haveSize(1) results must contain(data) } } yield () Process.eval(initiate.run >> check).drain } val delay = time.sleep(200 millis)(Strategy.DefaultStrategy, scheduler) val test = server.drain merge (delay ++ client) test.run timed (15 seconds) run ok } "round trip some simple data to ten simultaneous clients" in { val addr = new InetSocketAddress("localhost", 9090) val server = merge.mergeN(Netty server addr map { incoming => incoming flatMap { exchange => exchange.read take 1 to exchange.write drain } }) def client(n: Int) = Netty connect addr flatMap { exchange => val data = ByteVector(n) for { _ <- Process(data) to exchange.write results <- Process eval (exchange.read.runLog timed (5 seconds)) bv <- Process emitAll results } yield (n -> bv) } val delay = time.sleep(200 millis)(Strategy.DefaultStrategy, scheduler) val test = (server.drain wye merge.mergeN(Process.range(0, 10) map { n => delay ++ client(n) }))(wye.mergeHaltBoth) val results = test.runLog timed (15 seconds) run results must haveSize(10) results must containAllOf(0 until 10 map { n => n -> ByteVector(n) }) } "terminate a client process with an error if connection failed" in { val addr = new InetSocketAddress("localhost", 51235) // hopefully no one is using this port... val client = Netty connect addr map { _ => () } val result = client.run.attempt.run result must beLike { case -\/(_) => ok } } "terminate a client process if connection times out" in { val addr = new InetSocketAddress("100.64.0.1", 51234) // reserved IP, very weird port val client = Netty connect addr map { _ => () } val result = client.run.attempt.run result must eventually(beLike[Throwable \/ Unit] { case -\/(_) => ok }) } "not lose data on client in rapid-closure scenario" in { forall(0 until 10) { i => val addr = new InetSocketAddress("localhost", 9090 + i) val data = ByteVector(1, 2, 3) val server = for { incoming <- Netty server addr take 1 Exchange(_, write) <- incoming _ <- write take 1 evalMap { _(data) } } yield () // close connection instantly val client = for { _ <- time.sleep(500 millis)(Strategy.DefaultStrategy, scheduler) ++ Process.emit(()) Exchange(read, _) <- Netty connect addr back <- read take 1 } yield back val driver: Process[Task, ByteVector] = server.drain merge client val task = (driver wye time.sleep(3 seconds)(Strategy.DefaultStrategy, scheduler))(wye.mergeHaltBoth).runLast task.run must beSome(data) } } "not lose data on server in rapid-closure scenario" in { forall(0 until 10) { i => val addr = new InetSocketAddress("localhost", 9090 + i) val data = ByteVector(1, 2, 3) val server = for { incoming <- Netty server addr take 1 Exchange(read, _) <- incoming back <- read take 1 } yield back val client = for { _ <- time.sleep(500 millis)(Strategy.DefaultStrategy, scheduler) ++ Process.emit(()) Exchange(_, write) <- Netty connect addr _ <- write take 1 evalMap { _(data) } } yield () // close connection instantly val task = ((server merge client.drain) wye time.sleep(3 seconds)(Strategy.DefaultStrategy, scheduler))(wye.mergeHaltBoth).runLast task.run must beSome(data) } } def roundTripTest(port: Int, noOfPackets: Int, clientBpQueueLimit: Int, serverBpQueueLimit: Int, clientSendSpeed: Int, // messages per second clientReceiveSpeed: Int, // messages per second serverSendSpeed: Int, // messages per second serverReceiveSpeed: Int, // messages per second dataMultiplier: Int = 1 // sizing the packet ) = { val deadbeef = ByteVector(0xDE, 0xAD, 0xBE, 0xEF) //4 bytes val addr = new InetSocketAddress("localhost", port) val data = (1 to dataMultiplier).foldLeft(deadbeef)((a, counter) => a++deadbeef) val clientReceiveClock = time.awakeEvery((1000000 / clientReceiveSpeed).microseconds)(Strategy.DefaultStrategy, Executors.newScheduledThreadPool(1)) val clientSendClock = time.awakeEvery((1000000 / clientSendSpeed).microseconds)(Strategy.DefaultStrategy, Executors.newScheduledThreadPool(1)) val serverReceiveClock = time.awakeEvery((1000000 / serverReceiveSpeed).microseconds)(Strategy.DefaultStrategy, Executors.newScheduledThreadPool(1)) val serverSendClock = time.awakeEvery((1000000 / serverSendSpeed).microseconds)(Strategy.DefaultStrategy, Executors.newScheduledThreadPool(1)) val server = (Netty.server(addr, ServerConfig( keepAlive = true, numThreads = Runtime.getRuntime.availableProcessors, limit = serverBpQueueLimit, codeFrames = true, tcpNoDelay = true, soSndBuf = None, soRcvBuf = None ))) take 1 flatMap { incoming => incoming flatMap { exchange => exchange.read.zip(serverReceiveClock).map { case (a, _) => a }.take(noOfPackets).zip(serverSendClock).map { case (a, _) => a } to exchange.write drain } } val client = Netty.connect(addr, ClientConfig( keepAlive = true, limit = clientBpQueueLimit, tcpNoDelay = true, soSndBuf = None, soRcvBuf = None) ).flatMap { exchange => val initiate = Process(data).repeat.take(noOfPackets).zip(clientSendClock).map { case (a, _) => a } to exchange.write val check = for { results <- exchange.read.zip(clientReceiveClock).map { case (a, _) => a }.runLog _ <- Task delay { results must haveSize(noOfPackets) } } yield () Process.eval_(for (_ <- initiate.run; last <- check) yield (())) } val delay = time.sleep(500 millis)(Strategy.DefaultStrategy, scheduler) val test = server merge (delay ++ client) test.run timed ((10 + noOfPackets / Math.min(Math.min(serverReceiveSpeed, serverSendSpeed), Math.min(clientReceiveSpeed, clientSendSpeed))) seconds) run ok } "round trip more data with slow client receive" in { roundTripTest( port = 51236, noOfPackets = 1000, clientBpQueueLimit = 10, serverBpQueueLimit = 1000, clientSendSpeed = 10000, clientReceiveSpeed = 200, serverSendSpeed = 10000, serverReceiveSpeed = 10000 ) } "round trip more data with slow server receive" in { roundTripTest( port = 51237, noOfPackets = 1000, clientBpQueueLimit = 10, serverBpQueueLimit = 1000, clientSendSpeed = 10000, clientReceiveSpeed = 10000, serverSendSpeed = 10000, serverReceiveSpeed = 200 ) } "round trip lots of data fast with small buffers" in { roundTripTest( port = 51238, noOfPackets = 10000, clientBpQueueLimit = 10, serverBpQueueLimit = 10, clientSendSpeed = 2000, clientReceiveSpeed = 2000, serverSendSpeed = 2000, serverReceiveSpeed = 2000 ) } "round trip some huge packets" in { roundTripTest( port = 51239, noOfPackets = 10, clientBpQueueLimit = 10, serverBpQueueLimit = 10, clientSendSpeed = 10000, clientReceiveSpeed = 10000, serverSendSpeed = 10000, serverReceiveSpeed = 10000, dataMultiplier = 256*256 ) } } }
alissapajer/scalaz-netty
src/test/scala/scalaz/netty/NettySpecs.scala
Scala
apache-2.0
9,952
#define alpha( i,j ) A[ (j)*ldA + (i) ] // map alpha( i,j ) to array A #define beta( i,j ) B[ (j)*ldB + (i) ] // map beta( i,j ) to array B #define gamma( i,j ) C[ (j)*ldC + (i) ] // map gamma( i,j ) to array C #include<immintrin.h> void Gemm_MRxNRKernel( int k, double *A, int ldA, double *B, int ldB, double *C, int ldC ) { /* Declare vector registers to hold 8x6 C and load them */ __m256d gamma_0123_0 = _mm256_loadu_pd( &gamma( 0,0 ) ); __m256d gamma_0123_1 = _mm256_loadu_pd( &gamma( 0,1 ) ); __m256d gamma_0123_2 = _mm256_loadu_pd( &gamma( 0,2 ) ); __m256d gamma_0123_3 = _mm256_loadu_pd( &gamma( 0,3 ) ); __m256d gamma_0123_4 = _mm256_loadu_pd( &gamma( 0,4 ) ); __m256d gamma_0123_5 = _mm256_loadu_pd( &gamma( 0,5 ) ); __m256d gamma_4567_0 = _mm256_loadu_pd( &gamma( 4,0 ) ); __m256d gamma_4567_1 = _mm256_loadu_pd( &gamma( 4,1 ) ); __m256d gamma_4567_2 = _mm256_loadu_pd( &gamma( 4,2 ) ); __m256d gamma_4567_3 = _mm256_loadu_pd( &gamma( 4,3 ) ); __m256d gamma_4567_4 = _mm256_loadu_pd( &gamma( 4,4 ) ); __m256d gamma_4567_5 = _mm256_loadu_pd( &gamma( 4,5 ) ); for ( int p=0; p<k; p++ ){ /* Declare vector register for load/broadcasting beta( p,j ) */ __m256d beta_p_j; /* Declare vector registersx to hold the current column of A and load them with the eight elements of that column. */ __m256d alpha_0123_p = _mm256_loadu_pd( &alpha( 0,p ) ); __m256d alpha_4567_p = _mm256_loadu_pd( &alpha( 4,p ) ); /* Load/broadcast beta( p,0 ). */ beta_p_j = _mm256_broadcast_sd( &beta( p, 0) ); /* update the first column of C with the current column of A times beta ( p,0 ) */ gamma_0123_0 = _mm256_fmadd_pd( alpha_0123_p, beta_p_j, gamma_0123_0 ); gamma_4567_0 = _mm256_fmadd_pd( alpha_4567_p, beta_p_j, gamma_4567_0 ); /* REPEAT for second, third, and fourth columns of C. Notice that the current column of A needs not be reloaded. */ /* Load/broadcast beta( p,1 ). */ beta_p_j = _mm256_broadcast_sd( &beta( p, 1) ); /* update the second column of C with the current column of A times beta ( p,1 ) */ gamma_0123_1 = _mm256_fmadd_pd( alpha_0123_p, beta_p_j, gamma_0123_1 ); gamma_4567_1 = _mm256_fmadd_pd( alpha_4567_p, beta_p_j, gamma_4567_1 ); /* Load/broadcast beta( p,2 ). */ beta_p_j = _mm256_broadcast_sd( &beta( p, 2) ); /* update the third column of C with the current column of A times beta ( p,2 ) */ gamma_0123_2 = _mm256_fmadd_pd( alpha_0123_p, beta_p_j, gamma_0123_2 ); gamma_4567_2 = _mm256_fmadd_pd( alpha_4567_p, beta_p_j, gamma_4567_2 ); /* Load/broadcast beta( p,3 ). */ beta_p_j = _mm256_broadcast_sd( &beta( p, 3) ); /* update the fourth column of C with the current column of A times beta ( p,3 ) */ gamma_0123_3 = _mm256_fmadd_pd( alpha_0123_p, beta_p_j, gamma_0123_3 ); gamma_4567_3 = _mm256_fmadd_pd( alpha_4567_p, beta_p_j, gamma_4567_3 ); /* Load/broadcast beta( p,4 ). */ beta_p_j = _mm256_broadcast_sd( &beta( p, 4) ); /* update the fifth column of C with the current column of A times beta ( p,4 ) */ gamma_0123_4 = _mm256_fmadd_pd( alpha_0123_p, beta_p_j, gamma_0123_4 ); gamma_4567_4 = _mm256_fmadd_pd( alpha_4567_p, beta_p_j, gamma_4567_4 ); /* Load/broadcast beta( p,5 ). */ beta_p_j = _mm256_broadcast_sd( &beta( p, 5) ); /* update the sixth column of C with the current column of A times beta ( p,5 ) */ gamma_0123_5 = _mm256_fmadd_pd( alpha_0123_p, beta_p_j, gamma_0123_5 ); gamma_4567_5 = _mm256_fmadd_pd( alpha_4567_p, beta_p_j, gamma_4567_5 ); } /* Store the updated results */ _mm256_storeu_pd( &gamma(0,0), gamma_0123_0 ); _mm256_storeu_pd( &gamma(0,1), gamma_0123_1 ); _mm256_storeu_pd( &gamma(0,2), gamma_0123_2 ); _mm256_storeu_pd( &gamma(0,3), gamma_0123_3 ); _mm256_storeu_pd( &gamma(0,4), gamma_0123_4 ); _mm256_storeu_pd( &gamma(0,5), gamma_0123_5 ); _mm256_storeu_pd( &gamma(4,0), gamma_4567_0 ); _mm256_storeu_pd( &gamma(4,1), gamma_4567_1 ); _mm256_storeu_pd( &gamma(4,2), gamma_4567_2 ); _mm256_storeu_pd( &gamma(4,3), gamma_4567_3 ); _mm256_storeu_pd( &gamma(4,4), gamma_4567_4 ); _mm256_storeu_pd( &gamma(4,5), gamma_4567_5 ); }
xunilrj/sandbox
courses/UTAustinX UT.PHP.16.01x/Assignments/Week2/C/Gemm_8x6Kernel.c
C
apache-2.0
4,305
LineAnnotate = Rickshaw.Class.create({ initialize: function(args) { var graph = this.graph = args.graph; var element = this.element = document.createElement('div'); element.className = 'line_annotation_parent'; this.visible = true; graph.element.appendChild(element); this.lastEvent = null; this._addListeners(); this.onShow = args.onShow; this.onHide = args.onHide; this.onRender = args.onRender; this.shortFormatter = args.shortFormatter; this.detailedFormatter = args.detailedFormatter; }, update: function() { var graph = this.graph; var j = 0; var points = []; this.graph.series.active().forEach(function(series) { var data = graph.stackedData[j++]; if (data.length < 2) return; var prev = data[0]; data.forEach(function(value, index){ if (index == 0) return; var point = { prev: prev, series: series, value: value }; points.push(point); prev = value; }, this); }, this); this.element.innerHTML = ''; this.element.style.left = '0px'; this.visible && this.render(points); }, hide: function() { this.visible = false; this.element.classList.add('inactive'); if (typeof this.onHide == 'function') { this.onHide(); } }, show: function() { this.visible = true; this.element.classList.remove('inactive'); if (typeof this.onShow == 'function') { this.onShow(); } }, render: function(points) { var graph = this.graph; var alignables = []; this.element.innerHTML = ''; points.forEach(function(point){ if (point.value.y === null || point.prev.y === null) return; var series = point.series; var shortFormatted = this.shortFormatter(series, point.value); if (shortFormatted === null) return; var detailedFormatted = this.detailedFormatter(series, point.value); var outer = document.createElement('div'); outer.className = 'line_annotation_outer'; var x = graph.x(point.value.x); outer.style.left = x + 'px'; outer.style.top = graph.y(point.value.y0 + (point.value.y + point.prev.y) / 2) + 'px'; var item = document.createElement('div'); item.className = 'line_annotation'; function displayShort() { item.innerHTML = shortFormatted; outer.classList.remove('detailed'); } function displayDetailed() { item.innerHTML = detailedFormatted; outer.classList.add('detailed'); } displayShort(); item.addEventListener('mouseenter', displayDetailed); item.addEventListener('mouseleave', displayShort); outer.appendChild(item); this.element.appendChild(outer); item.classList.add('active'); // Assume left alignment until the element has been displayed and // bounding box calculations are possible. alignables.push({ orignalX: x, outer: outer, inner: item }); }, this); alignables.forEach(function(el) { el.outer.classList.add('fromleft'); }, false); this.show(); // If left-alignment results in any error, try right-alignment. alignables.forEach(function(el) { var leftAlignError = this._calcLayoutError(el.inner); if (leftAlignError > 0) { el.outer.style.left = (el.orignalX - 500) + "px"; el.outer.classList.remove('fromleft'); el.outer.classList.add('fromright'); // If right-alignment is worse than left alignment, switch back. var rightAlignError = this._calcLayoutError(el.inner); if (rightAlignError > leftAlignError) { el.outer.style.left = el.orignalX + "px"; el.outer.classList.remove('fromright'); el.outer.classList.add('fromleft'); } } }, this); if (typeof this.onRender == 'function') { this.onRender(points); } }, _calcLayoutError: function(el) { // Layout error is calculated as the number of linear pixels by which // an alignable extends past the left or right edge of the parent. var parentRect = this.element.parentNode.getBoundingClientRect(); var error = 0; var rect = el.getBoundingClientRect(); if (!rect.width) { return; } if (rect.right > parentRect.right) { error += rect.right - parentRect.right; } if (rect.left < parentRect.left) { error += parentRect.left - rect.left; } return error; }, _addListeners: function() { this.graph.onUpdate( function() { this.update() }.bind(this) ); } });
arkadius/micro-burn
src/main/webapp/js/LineAnnotate.js
JavaScript
apache-2.0
4,653
# -*- coding: utf-8 -*- require 'webrick' require 'date' # サーバ設定 config = { :Port => 8099, :DocumentRoot => '.', } # WebrickのHTTP Serverクラスのサーバインスタンス server = WEBrick::HTTPServer.new(config) server.mount_proc("/testprogram") {|req, res| # アクセスした日付をレスポンスの内容に追加 res.body << "<html><body><p>アクセス日時#{Date.today.to_s}</p>" res.body << "<p>リクエストパス#{req.path}</p>" # リクエスト内容を番号なしリストにして追加 res.body << "<ul>" req.each {|key, value| res.body << "<li>#{key}: #{value}</li>" } res.body << "</ul>" res.body << "</body></html>" } # Ctrl-Cで割り込みがあった場合にサーバを停止 trap(:INT) do server.shutdown end server.start
hiroharu8864/ruby_script
webrick.rb
Ruby
apache-2.0
789
""" Find the closest DMC colors for a hex color. Usage: python closest_colors.py <hexcolor> """ import sys from .. import color from .. import dmc_colors def main(): if len(sys.argv) < 2: sys.exit(__doc__) hex_color = sys.argv[1] rgb_color = color.RGBColorFromHexString(hex_color) print 'Given RGB color', rgb_color print print 'Closest DMC colors by distance:' for pair in dmc_colors.GetClosestDMCColorsPairs(rgb_color): print 'Distance:', pair[1], dmc_colors.GetStringForDMCColor(pair[0]) if __name__ == '__main__': main()
nanaze/pystitch
pystitch/examples/closest_colors.py
Python
apache-2.0
562
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.unsafe.impl.batchimport.executor; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.Array; import java.util.Arrays; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.neo4j.function.Supplier; import org.neo4j.function.Suppliers; import static java.lang.Math.min; import static org.neo4j.helpers.Exceptions.launderedException; /** * Implementation of {@link TaskExecutor} with a maximum queue size and where each processor is a dedicated * {@link Thread} pulling queued tasks and executing them. */ public class DynamicTaskExecutor<LOCAL> implements TaskExecutor<LOCAL> { public static final ParkStrategy DEFAULT_PARK_STRATEGY = new ParkStrategy.Park( 10 ); private final BlockingQueue<Task<LOCAL>> queue; private final ParkStrategy parkStrategy; private final String processorThreadNamePrefix; @SuppressWarnings( "unchecked" ) private volatile Processor[] processors = (Processor[]) Array.newInstance( Processor.class, 0 ); private volatile boolean shutDown; private volatile Throwable panic; private final Supplier<LOCAL> initialLocalState; private final int maxProcessorCount; public DynamicTaskExecutor( int initialProcessorCount, int maxProcessorCount, int maxQueueSize, ParkStrategy parkStrategy, String processorThreadNamePrefix ) { this( initialProcessorCount, maxProcessorCount, maxQueueSize, parkStrategy, processorThreadNamePrefix, Suppliers.<LOCAL>singleton( null ) ); } public DynamicTaskExecutor( int initialProcessorCount, int maxProcessorCount, int maxQueueSize, ParkStrategy parkStrategy, String processorThreadNamePrefix, Supplier<LOCAL> initialLocalState ) { this.maxProcessorCount = maxProcessorCount == 0 ? Integer.MAX_VALUE : maxProcessorCount; assert this.maxProcessorCount >= initialProcessorCount : "Unexpected initial processor count " + initialProcessorCount + " for max " + maxProcessorCount; this.parkStrategy = parkStrategy; this.processorThreadNamePrefix = processorThreadNamePrefix; this.initialLocalState = initialLocalState; this.queue = new ArrayBlockingQueue<>( maxQueueSize ); setNumberOfProcessors( initialProcessorCount ); } @Override public synchronized void setNumberOfProcessors( int count ) { assertHealthy(); assert count > 0; if ( count == processors.length ) { return; } count = min( count, maxProcessorCount ); Processor[] newProcessors; if ( count > processors.length ) { // Add one or more newProcessors = Arrays.copyOf( processors, count ); for ( int i = processors.length; i < newProcessors.length; i++ ) { newProcessors[i] = new Processor( processorThreadNamePrefix + "-" + i ); } } else { // Remove one or more newProcessors = Arrays.copyOf( processors, count ); for ( int i = newProcessors.length; i < processors.length; i++ ) { processors[i].shutDown = true; } } this.processors = newProcessors; } @Override public int numberOfProcessors() { return processors.length; } @Override public synchronized boolean incrementNumberOfProcessors() { if ( numberOfProcessors() >= maxProcessorCount ) { return false; } setNumberOfProcessors( numberOfProcessors() + 1 ); return true; } @Override public synchronized boolean decrementNumberOfProcessors() { if ( numberOfProcessors() == 1 ) { return false; } setNumberOfProcessors( numberOfProcessors() - 1 ); return true; } @Override public void submit( Task<LOCAL> task ) { assertHealthy(); while ( !queue.offer( task ) ) { // Then just stay here and try parkAWhile(); assertHealthy(); } notifyProcessors(); } @Override public void assertHealthy() { if ( shutDown ) { String message = "Executor has been shut down"; throw panic != null ? new IllegalStateException( message, panic ) : new IllegalStateException( message ); } } private void notifyProcessors() { for ( Processor processor : processors ) { parkStrategy.unpark( processor ); } } @Override public synchronized void shutdown( boolean awaitAllCompleted ) { if ( shutDown ) { return; } this.shutDown = true; while ( awaitAllCompleted && !queue.isEmpty() && panic == null /*all bets are off in the event of panic*/ ) { parkAWhile(); } for ( Processor processor : processors ) { processor.shutDown = true; } while ( awaitAllCompleted && anyAlive() && panic == null /*all bets are off in the event of panic*/ ) { parkAWhile(); } } private boolean anyAlive() { for ( Processor processor : processors ) { if ( processor.isAlive() ) { return true; } } return false; } private void parkAWhile() { parkStrategy.park( Thread.currentThread() ); } private static final UncaughtExceptionHandler SILENT_UNCAUGHT_EXCEPTION_HANDLER = new UncaughtExceptionHandler() { @Override public void uncaughtException( Thread t, Throwable e ) { // Don't print about it } }; private class Processor extends Thread { private volatile boolean shutDown; private final LOCAL threadLocalState = initialLocalState.get(); Processor( String name ) { super( name ); setUncaughtExceptionHandler( SILENT_UNCAUGHT_EXCEPTION_HANDLER ); start(); } @Override public void run() { while ( !shutDown ) { Task<LOCAL> task = queue.poll(); if ( task != null ) { try { task.run( threadLocalState ); } catch ( Throwable e ) { panic = e; shutdown( false ); throw launderedException( e ); } } else { parkAWhile(); } } } } }
HuangLS/neo4j
community/kernel/src/main/java/org/neo4j/unsafe/impl/batchimport/executor/DynamicTaskExecutor.java
Java
apache-2.0
7,724
# bootstrap-practice Trying to layout Bootstrap from Whiteboard example
CreativeCorrie/bootstrap-practice
README.md
Markdown
apache-2.0
72
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/> <title>Servlet con Sesion</title> </head> <body> <div style="text-align:center;font-family:Arial;color:Blue;font-size:large;"> <b>Servlet que cuenta las conexiones hechas con sesiones</b> <br/> <div style="color:Red;font-size:medium;">Se sigue el metodo POST</div> <br/> <form action="cuentaconexionesconsesion" method="POST"> <div style="color:Black;font-size:medium;"> Nombre del usuario: <input type="text" name="NombreUsuario" width="30"/> <br/> <br/> <input type="submit" value="Enviar datos"/> <input type="reset" value="Limpiar datos"/> <br/> <br/> <a href="cuentaconexionesconsesion">Cerrar Sesion</a> </div> </form> </div> </body> </html>
Danmarjim/mwm-2014-2015
Mod2/JEEBasico/CuentaConexionesConSesion/public_html/Formulario.html
HTML
apache-2.0
1,304
Function Get-TargetResource { Param( [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string]$ZoneName, [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string[]]$MasterServers, [Parameter(Mandatory=$True)] [ValidateSet("None","Domain","Forest","Legacy")] [string]$ReplicationScope, [Parameter(Mandatory=$True)] [ValidateSet("Present","Absent")] [string]$Ensure, [Parameter(Mandatory=$False)] [bool]$DesiredState = $True ) $Forwarders = Get-DnsServerZone | Where ZoneType -eq 'Forwarder' $Forwarder = $Forwarders | Where ZoneName -eq $ZoneName If ($Forwarder -eq $Null) { $ZoneExists = $False } Else { $ZoneExists = $True $CurrentMasterServers = $Forwarder.MasterServers.IPAddressToString $Compare = Compare-Object -ReferenceObject $MasterServers -DifferenceObject $CurrentMasterServers $DesiredMasterServers = If ($Compare.Count -eq 0) { $True } Else { $False } $CurrentReplicationScope = $Forwarder.ReplicationScope $DesiredReplicationScope = $Forwarder.ReplicationScope -eq $ReplicationScope } If ($Ensure -eq 'Present') { If ($ZoneExists -eq $False) { $DesiredState = $False } Elseif ($DesiredMasterServers -eq $False -or $DesiredReplicationScope -eq $False) { $DesiredState = $False } } Elseif ($ZoneExists -eq $True) { $DesiredState = $False } Return @{ ZoneExists = $ZoneExists DesiredMasterServers = $DesiredMasterServers CurrentMasterServers = $CurrentMasterServers DesiredReplicationScope = $DesiredReplicationScope CurrentReplicationScope = $CurrentReplicationScope DesiredState = $DesiredState } } Function Set-TargetResource { Param( [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string]$ZoneName, [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string[]]$MasterServers, [Parameter(Mandatory=$True)] [ValidateSet("None","Domain","Forest","Legacy")] [string]$ReplicationScope, [Parameter(Mandatory=$True)] [ValidateSet("Present","Absent")] [string]$Ensure, [Parameter(Mandatory=$False)] [bool]$DesiredState = $True ) $CurrentState = Get-TargetResource @PSBoundParameters $Parameters = @{ ZoneName = $ZoneName } If ($Ensure -eq 'Present') { If ($CurrentState.ZoneExists -eq $False) { $Parameters.Add('MasterServers',$MasterServers) If ($ReplicationScope -ne 'None') { $Parameters.Add('ReplicationScope',$ReplicationScope) } Add-DnsServerConditionalForwarderZone @Parameters } Else { If ($CurrentState.DesiredReplicationScope -eq $False -and $CurrentState.CurrentReplicationScope -eq 'None') { Remove-DnsServerZone @Parameters -Force $Parameters.Add('MasterServers',$MasterServers) $Parameters.Add('ReplicationScope',$ReplicationScope) Add-DnsServerConditionalForwarderZone @Parameters } Elseif ($CurrentState.DesiredReplicationScope -eq $False -and $ReplicationScope -eq 'None') { Remove-DnsServerZone @Parameters -Force $Parameters.Add('MasterServers',$MasterServers) Add-DnsServerConditionalForwarderZone @Parameters } Else { If ($CurrentState.DesiredReplicationScope -eq $False) { Set-DnsServerConditionalForwarderZone -ZoneName $ZoneName -ReplicationScope $ReplicationScope } If ($CurrentState.DesiredMasterServers -eq $False) { Set-DnsServerConditionalForwarderZone -ZoneName $ZoneName -MasterServers $MasterServers } } } } Else { Remove-DnsServerZone @Parameters -Force } } Function Test-TargetResource { Param( [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string]$ZoneName, [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [string[]]$MasterServers, [Parameter(Mandatory=$True)] [ValidateSet("None","Domain","Forest","Legacy")] [string]$ReplicationScope, [Parameter(Mandatory=$True)] [ValidateSet("Present","Absent")] [string]$Ensure, [Parameter(Mandatory=$False)] [bool]$DesiredState = $True ) Return (Get-TargetResource @PSBoundParameters).DesiredState }
ConclusionMC/puppetlabs-dsc
lib/puppet_x/dsc_resources/cDns/DSCResources/cDns_ConditionalForwarder2/cDns_ConditionalForwarder2.psm1
PowerShell
apache-2.0
4,650
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.forms; import org.hamcrest.Matchers; import org.jboss.arquillian.drone.api.annotation.Drone; import org.keycloak.authentication.actiontoken.resetcred.ResetCredentialsActionToken; import org.jboss.arquillian.graphene.page.Page; import org.keycloak.events.Details; import org.keycloak.events.Errors; import org.keycloak.events.EventType; import org.keycloak.models.Constants; import org.keycloak.models.utils.SystemClientUtil; import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.pages.AppPage; import org.keycloak.testsuite.pages.AppPage.RequestType; import org.keycloak.testsuite.pages.ErrorPage; import org.keycloak.testsuite.pages.InfoPage; import org.keycloak.testsuite.pages.LoginPage; import org.keycloak.testsuite.pages.LoginPasswordResetPage; import org.keycloak.testsuite.pages.LoginPasswordUpdatePage; import org.keycloak.testsuite.pages.VerifyEmailPage; import org.keycloak.testsuite.updaters.ClientAttributeUpdater; import org.keycloak.testsuite.util.GreenMailRule; import org.keycloak.testsuite.util.MailUtils; import org.keycloak.testsuite.util.OAuthClient; import org.keycloak.testsuite.util.SecondBrowser; import org.keycloak.testsuite.util.UserActionTokenBuilder; import org.keycloak.testsuite.util.UserBuilder; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.Closeable; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.junit.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> * @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc. */ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest { private String userId; @Drone @SecondBrowser protected WebDriver driver2; @Override public void configureTestRealm(RealmRepresentation testRealm) { } @Before public void setup() { log.info("Adding login-test user"); UserRepresentation user = UserBuilder.create() .username("login-test") .email("login@test.com") .enabled(true) .build(); userId = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealm(), user, "password"); expectedMessagesCount = 0; getCleanup().addUserId(userId); } @Rule public GreenMailRule greenMail = new GreenMailRule(); @Page protected AppPage appPage; @Page protected LoginPage loginPage; @Page protected ErrorPage errorPage; @Page protected InfoPage infoPage; @Page protected VerifyEmailPage verifyEmailPage; @Page protected LoginPasswordResetPage resetPasswordPage; @Page protected LoginPasswordUpdatePage updatePasswordPage; @Rule public AssertEvents events = new AssertEvents(this); private int expectedMessagesCount; @Test public void resetPasswordLink() throws IOException, MessagingException { String username = "login-test"; String resetUri = oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"; driver.navigate().to(resetUri); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword(username); loginPage.assertCurrent(); assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .user(userId) .detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/") .client("account") .detail(Details.USERNAME, username) .detail(Details.EMAIL, "login@test.com") .session((String)null) .assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); driver.navigate().to(changePasswordUrl.trim()); updatePasswordPage.assertCurrent(); updatePasswordPage.changePassword("resetPassword", "resetPassword"); events.expectRequiredAction(EventType.UPDATE_PASSWORD) .detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/") .client("account") .user(userId).detail(Details.USERNAME, username).assertEvent(); String sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, username) .detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/") .client("account") .assertEvent().getSessionId(); oauth.openLogout(); events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent(); loginPage.open(); loginPage.login("login-test", "resetPassword"); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); } @Test public void resetPassword() throws IOException, MessagingException { resetPassword("login-test"); } @Test public void resetPasswordTwice() throws IOException, MessagingException { String changePasswordUrl = resetPassword("login-test"); events.clear(); assertSecondPasswordResetFails(changePasswordUrl, oauth.getClientId()); // KC_RESTART doesn't exists, it was deleted after first successful reset-password flow was finished } @Test public void resetPasswordTwiceInNewBrowser() throws IOException, MessagingException { String changePasswordUrl = resetPassword("login-test"); events.clear(); String resetUri = oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"; driver.navigate().to(resetUri); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path driver.manage().deleteAllCookies(); assertSecondPasswordResetFails(changePasswordUrl, oauth.getClientId()); } public void assertSecondPasswordResetFails(String changePasswordUrl, String clientId) { driver.navigate().to(changePasswordUrl.trim()); errorPage.assertCurrent(); assertEquals("Action expired. Please continue with login now.", errorPage.getError()); events.expect(EventType.RESET_PASSWORD) .client(clientId) .session((String) null) .user(userId) .error(Errors.EXPIRED_CODE) .assertEvent(); } @Test public void resetPasswordWithSpacesInUsername() throws IOException, MessagingException { resetPassword(" login-test "); } @Test public void resetPasswordCancelChangeUser() throws IOException, MessagingException { initiateResetPasswordFromResetPasswordPage("test-user@localhost"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).detail(Details.USERNAME, "test-user@localhost") .session((String) null) .detail(Details.EMAIL, "test-user@localhost").assertEvent(); loginPage.login("login@test.com", "password"); EventRepresentation loginEvent = events.expectLogin().user(userId).detail(Details.USERNAME, "login@test.com").assertEvent(); String code = oauth.getCurrentQuery().get("code"); OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password"); assertEquals(200, tokenResponse.getStatusCode()); assertEquals(userId, oauth.verifyToken(tokenResponse.getAccessToken()).getSubject()); events.expectCodeToToken(loginEvent.getDetails().get(Details.CODE_ID), loginEvent.getSessionId()).user(userId).assertEvent(); } @Test public void resetPasswordByEmail() throws IOException, MessagingException { resetPassword("login@test.com"); } private String resetPassword(String username) throws IOException, MessagingException { return resetPassword(username, "resetPassword"); } private String resetPassword(String username, String password) throws IOException, MessagingException { initiateResetPasswordFromResetPasswordPage(username); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .user(userId) .detail(Details.USERNAME, username.trim()) .detail(Details.EMAIL, "login@test.com") .session((String)null) .assertEvent(); assertEquals(expectedMessagesCount, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[greenMail.getReceivedMessages().length - 1]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); driver.navigate().to(changePasswordUrl.trim()); updatePasswordPage.assertCurrent(); assertEquals("You need to change your password.", updatePasswordPage.getFeedbackMessage()); updatePasswordPage.changePassword(password, password); events.expectRequiredAction(EventType.UPDATE_PASSWORD).user(userId).detail(Details.USERNAME, username.trim()).assertEvent(); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); String sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, username.trim()).assertEvent().getSessionId(); oauth.openLogout(); events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent(); loginPage.open(); loginPage.login("login-test", password); sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId(); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); oauth.openLogout(); events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent(); return changePasswordUrl; } private void resetPasswordInvalidPassword(String username, String password, String error) throws IOException, MessagingException { initiateResetPasswordFromResetPasswordPage(username); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).user(userId).session((String) null) .detail(Details.USERNAME, username).detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(expectedMessagesCount, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[greenMail.getReceivedMessages().length - 1]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); driver.navigate().to(changePasswordUrl.trim()); updatePasswordPage.assertCurrent(); updatePasswordPage.changePassword(password, password); updatePasswordPage.assertCurrent(); assertEquals(error, updatePasswordPage.getError()); events.expectRequiredAction(EventType.UPDATE_PASSWORD_ERROR).error(Errors.PASSWORD_REJECTED).user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId(); } private void initiateResetPasswordFromResetPasswordPage(String username) { loginPage.open(); loginPage.resetPassword(); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword(username); loginPage.assertCurrent(); assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); expectedMessagesCount++; } @Test public void resetPasswordWrongEmail() throws IOException, MessagingException, InterruptedException { initiateResetPasswordFromResetPasswordPage("invalid"); assertEquals(0, greenMail.getReceivedMessages().length); events.expectRequiredAction(EventType.RESET_PASSWORD).user((String) null).session((String) null).detail(Details.USERNAME, "invalid").removeDetail(Details.EMAIL).removeDetail(Details.CODE_ID).error("user_not_found").assertEvent(); } @Test public void resetPasswordMissingUsername() throws IOException, MessagingException, InterruptedException { loginPage.open(); loginPage.resetPassword(); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword(""); resetPasswordPage.assertCurrent(); assertEquals("Please specify username.", resetPasswordPage.getErrorMessage()); assertEquals(0, greenMail.getReceivedMessages().length); events.expectRequiredAction(EventType.RESET_PASSWORD).user((String) null).session((String) null).clearDetails().error("username_missing").assertEvent(); } @Test public void resetPasswordExpiredCode() throws IOException, MessagingException, InterruptedException { initiateResetPasswordFromResetPasswordPage("login-test"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); try { setTimeOffset(1800 + 23); driver.navigate().to(changePasswordUrl.trim()); loginPage.assertCurrent(); assertEquals("Action expired. Please start again.", loginPage.getError()); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); } } @Test public void resetPasswordExpiredCodeShort() throws IOException, MessagingException, InterruptedException { final AtomicInteger originalValue = new AtomicInteger(); RealmRepresentation realmRep = testRealm().toRepresentation(); originalValue.set(realmRep.getActionTokenGeneratedByUserLifespan()); realmRep.setActionTokenGeneratedByUserLifespan(60); testRealm().update(realmRep); try { initiateResetPasswordFromResetPasswordPage("login-test"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); setTimeOffset(70); driver.navigate().to(changePasswordUrl.trim()); loginPage.assertCurrent(); assertEquals("Action expired. Please start again.", loginPage.getError()); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get()); testRealm().update(realmRep); } } @Test public void resetPasswordExpiredCodeShortPerActionLifespan() throws IOException, MessagingException, InterruptedException { RealmRepresentation realmRep = testRealm().toRepresentation(); Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes())); realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).build()); testRealm().update(realmRep); try { initiateResetPasswordFromResetPasswordPage("login-test"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); setTimeOffset(70); driver.navigate().to(changePasswordUrl.trim()); loginPage.assertCurrent(); assertEquals("Action expired. Please start again.", loginPage.getError()); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setAttributes(originalAttributes); testRealm().update(realmRep); } } @Test public void resetPasswordExpiredCodeShortPerActionMultipleTimeouts() throws IOException, MessagingException, InterruptedException { RealmRepresentation realmRep = testRealm().toRepresentation(); Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes())); //Make sure that one attribute settings won't affect the other realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).verifyEmailLifespan(300).build()); testRealm().update(realmRep); try { initiateResetPasswordFromResetPasswordPage("login-test"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); setTimeOffset(70); driver.navigate().to(changePasswordUrl.trim()); loginPage.assertCurrent(); assertEquals("Action expired. Please start again.", loginPage.getError()); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setAttributes(originalAttributes); testRealm().update(realmRep); } } // KEYCLOAK-4016 @Test public void resetPasswordExpiredCodeAndAuthSession() throws IOException, MessagingException, InterruptedException { final AtomicInteger originalValue = new AtomicInteger(); RealmRepresentation realmRep = testRealm().toRepresentation(); originalValue.set(realmRep.getActionTokenGeneratedByUserLifespan()); realmRep.setActionTokenGeneratedByUserLifespan(60); testRealm().update(realmRep); try { initiateResetPasswordFromResetPasswordPage("login-test"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message).replace("&amp;", "&"); setTimeOffset(70); log.debug("Going to reset password URI."); driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path log.debug("Removing cookies."); driver.manage().deleteAllCookies(); driver.navigate().to(changePasswordUrl.trim()); errorPage.assertCurrent(); Assert.assertEquals("Action expired.", errorPage.getError()); String backToAppLink = errorPage.getBackToApplicationLink(); Assert.assertTrue(backToAppLink.endsWith("/app/auth")); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get()); testRealm().update(realmRep); } } @Test public void resetPasswordExpiredCodeAndAuthSessionPerActionLifespan() throws IOException, MessagingException, InterruptedException { RealmRepresentation realmRep = testRealm().toRepresentation(); Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes())); realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).build()); testRealm().update(realmRep); try { initiateResetPasswordFromResetPasswordPage("login-test"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message).replace("&amp;", "&"); setTimeOffset(70); log.debug("Going to reset password URI."); driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path log.debug("Removing cookies."); driver.manage().deleteAllCookies(); driver.navigate().to(changePasswordUrl.trim()); errorPage.assertCurrent(); Assert.assertEquals("Action expired.", errorPage.getError()); String backToAppLink = errorPage.getBackToApplicationLink(); Assert.assertTrue(backToAppLink.endsWith("/app/auth")); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setAttributes(originalAttributes); testRealm().update(realmRep); } } @Test public void resetPasswordExpiredCodeAndAuthSessionPerActionMultipleTimeouts() throws IOException, MessagingException, InterruptedException { RealmRepresentation realmRep = testRealm().toRepresentation(); Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes())); //Make sure that one attribute settings won't affect the other realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).verifyEmailLifespan(300).build()); testRealm().update(realmRep); try { initiateResetPasswordFromResetPasswordPage("login-test"); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message).replace("&amp;", "&"); setTimeOffset(70); log.debug("Going to reset password URI."); driver.navigate().to(oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path log.debug("Removing cookies."); driver.manage().deleteAllCookies(); driver.navigate().to(changePasswordUrl.trim()); errorPage.assertCurrent(); Assert.assertEquals("Action expired.", errorPage.getError()); String backToAppLink = errorPage.getBackToApplicationLink(); Assert.assertTrue(backToAppLink.endsWith("/app/auth")); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setAttributes(originalAttributes); testRealm().update(realmRep); } } // KEYCLOAK-5061 @Test public void resetPasswordExpiredCodeForgotPasswordFlow() throws IOException, MessagingException, InterruptedException { final AtomicInteger originalValue = new AtomicInteger(); RealmRepresentation realmRep = testRealm().toRepresentation(); originalValue.set(realmRep.getActionTokenGeneratedByUserLifespan()); realmRep.setActionTokenGeneratedByUserLifespan(60); testRealm().update(realmRep); try { // Redirect directly to KC "forgot password" endpoint instead of "authenticate" endpoint String loginUrl = oauth.getLoginFormUrl(); String forgotPasswordUrl = loginUrl.replace("/auth?", "/forgot-credentials?"); // Workaround, but works driver.navigate().to(forgotPasswordUrl); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword("login-test"); loginPage.assertCurrent(); assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); expectedMessagesCount++; events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); setTimeOffset(70); driver.navigate().to(changePasswordUrl.trim()); resetPasswordPage.assertCurrent(); assertEquals("Action expired. Please start again.", loginPage.getError()); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get()); testRealm().update(realmRep); } } @Test public void resetPasswordExpiredCodeForgotPasswordFlowPerActionLifespan() throws IOException, MessagingException, InterruptedException { RealmRepresentation realmRep = testRealm().toRepresentation(); Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes())); realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).build()); testRealm().update(realmRep); try { // Redirect directly to KC "forgot password" endpoint instead of "authenticate" endpoint String loginUrl = oauth.getLoginFormUrl(); String forgotPasswordUrl = loginUrl.replace("/auth?", "/forgot-credentials?"); // Workaround, but works driver.navigate().to(forgotPasswordUrl); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword("login-test"); loginPage.assertCurrent(); assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); expectedMessagesCount++; events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); setTimeOffset(70); driver.navigate().to(changePasswordUrl.trim()); resetPasswordPage.assertCurrent(); assertEquals("Action expired. Please start again.", loginPage.getError()); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setAttributes(originalAttributes); testRealm().update(realmRep); } } @Test public void resetPasswordExpiredCodeForgotPasswordFlowPerActionMultipleTimeouts() throws IOException, MessagingException, InterruptedException { RealmRepresentation realmRep = testRealm().toRepresentation(); Map<String, String> originalAttributes = Collections.unmodifiableMap(new HashMap<>(realmRep.getAttributes())); //Make sure that one attribute settings won't affect the other realmRep.setAttributes(UserActionTokenBuilder.create().resetCredentialsLifespan(60).verifyEmailLifespan(300).build()); testRealm().update(realmRep); try { // Redirect directly to KC "forgot password" endpoint instead of "authenticate" endpoint String loginUrl = oauth.getLoginFormUrl(); String forgotPasswordUrl = loginUrl.replace("/auth?", "/forgot-credentials?"); // Workaround, but works driver.navigate().to(forgotPasswordUrl); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword("login-test"); loginPage.assertCurrent(); assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); expectedMessagesCount++; events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .session((String)null) .user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); setTimeOffset(70); driver.navigate().to(changePasswordUrl.trim()); resetPasswordPage.assertCurrent(); assertEquals("Action expired. Please start again.", loginPage.getError()); events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent(); } finally { setTimeOffset(0); realmRep.setAttributes(originalAttributes); testRealm().update(realmRep); } } @Test public void resetPasswordDisabledUser() throws IOException, MessagingException, InterruptedException { UserRepresentation user = findUser("login-test"); try { user.setEnabled(false); updateUser(user); initiateResetPasswordFromResetPasswordPage("login-test"); assertEquals(0, greenMail.getReceivedMessages().length); events.expectRequiredAction(EventType.RESET_PASSWORD).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("user_disabled").assertEvent(); } finally { user.setEnabled(true); updateUser(user); } } @Test public void resetPasswordNoEmail() throws IOException, MessagingException, InterruptedException { final String email; UserRepresentation user = findUser("login-test"); email = user.getEmail(); try { user.setEmail(""); updateUser(user); initiateResetPasswordFromResetPasswordPage("login-test"); assertEquals(0, greenMail.getReceivedMessages().length); events.expectRequiredAction(EventType.RESET_PASSWORD_ERROR).session((String) null).user(userId).detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error("invalid_email").assertEvent(); } finally { user.setEmail(email); updateUser(user); } } @Test public void resetPasswordWrongSmtp() throws IOException, MessagingException, InterruptedException { final String[] host = new String[1]; Map<String, String> smtpConfig = new HashMap<>(); smtpConfig.putAll(testRealm().toRepresentation().getSmtpServer()); host[0] = smtpConfig.get("host"); smtpConfig.put("host", "invalid_host"); RealmRepresentation realmRep = testRealm().toRepresentation(); Map<String, String> oldSmtp = realmRep.getSmtpServer(); try { realmRep.setSmtpServer(smtpConfig); testRealm().update(realmRep); loginPage.open(); loginPage.resetPassword(); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword("login-test"); errorPage.assertCurrent(); assertEquals("Failed to send email, please try again later.", errorPage.getError()); assertEquals(0, greenMail.getReceivedMessages().length); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD_ERROR).user(userId) .session((String)null) .detail(Details.USERNAME, "login-test").removeDetail(Details.CODE_ID).error(Errors.EMAIL_SEND_FAILED).assertEvent(); } finally { // Revert SMTP back realmRep.setSmtpServer(oldSmtp); testRealm().update(realmRep); } } private void setPasswordPolicy(String policy) { RealmRepresentation realmRep = testRealm().toRepresentation(); realmRep.setPasswordPolicy(policy); testRealm().update(realmRep); } @Test public void resetPasswordWithLengthPasswordPolicy() throws IOException, MessagingException { setPasswordPolicy("length"); initiateResetPasswordFromResetPasswordPage("login-test"); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD).session((String)null).user(userId).detail(Details.USERNAME, "login-test").detail(Details.EMAIL, "login@test.com").assertEvent(); driver.navigate().to(changePasswordUrl.trim()); updatePasswordPage.assertCurrent(); updatePasswordPage.changePassword("invalid", "invalid"); assertEquals("Invalid password: minimum length 8.", resetPasswordPage.getErrorMessage()); events.expectRequiredAction(EventType.UPDATE_PASSWORD_ERROR).error(Errors.PASSWORD_REJECTED).user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId(); updatePasswordPage.changePassword("resetPasswordWithPasswordPolicy", "resetPasswordWithPasswordPolicy"); events.expectRequiredAction(EventType.UPDATE_PASSWORD).user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId(); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); String sessionId = events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent().getSessionId(); oauth.openLogout(); events.expectLogout(sessionId).user(userId).session(sessionId).assertEvent(); loginPage.open(); loginPage.login("login-test", "resetPasswordWithPasswordPolicy"); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); } @Test public void resetPasswordWithPasswordHistoryPolicy() throws IOException, MessagingException { //Block passwords that are equal to previous passwords. Default value is 3. setPasswordPolicy("passwordHistory"); try { setTimeOffset(2000000); resetPassword("login-test", "password1"); resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords."); setTimeOffset(4000000); resetPassword("login-test", "password2"); resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords."); resetPasswordInvalidPassword("login-test", "password2", "Invalid password: must not be equal to any of last 3 passwords."); setTimeOffset(6000000); resetPassword("login-test", "password3"); resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords."); resetPasswordInvalidPassword("login-test", "password2", "Invalid password: must not be equal to any of last 3 passwords."); resetPasswordInvalidPassword("login-test", "password3", "Invalid password: must not be equal to any of last 3 passwords."); setTimeOffset(8000000); resetPassword("login-test", "password"); } finally { setTimeOffset(0); } } @Test public void resetPasswordLinkOpenedInNewBrowser() throws IOException, MessagingException { resetPasswordLinkOpenedInNewBrowser(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID); } private void resetPasswordLinkOpenedInNewBrowser(String expectedSystemClientId) throws IOException, MessagingException { String username = "login-test"; String resetUri = oauth.AUTH_SERVER_ROOT + "/realms/test/login-actions/reset-credentials"; driver.navigate().to(resetUri); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword(username); log.info("Should be at login page again."); loginPage.assertCurrent(); assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); events.expectRequiredAction(EventType.SEND_RESET_PASSWORD) .user(userId) .detail(Details.REDIRECT_URI, oauth.AUTH_SERVER_ROOT + "/realms/test/account/") .client(expectedSystemClientId) .detail(Details.USERNAME, username) .detail(Details.EMAIL, "login@test.com") .session((String)null) .assertEvent(); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); log.debug("Going to reset password URI."); driver.navigate().to(resetUri); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path log.debug("Removing cookies."); driver.manage().deleteAllCookies(); log.debug("Going to URI from e-mail."); driver.navigate().to(changePasswordUrl.trim()); updatePasswordPage.assertCurrent(); updatePasswordPage.changePassword("resetPassword", "resetPassword"); infoPage.assertCurrent(); assertEquals("Your account has been updated.", infoPage.getInfo()); } // KEYCLOAK-5982 @Test public void resetPasswordLinkOpenedInNewBrowserAndAccountClientRenamed() throws IOException, MessagingException { // Temporarily rename client "account" . Revert it back after the test try (Closeable accountClientUpdater = ClientAttributeUpdater.forClient(adminClient, "test", Constants.ACCOUNT_MANAGEMENT_CLIENT_ID) .setClientId("account-changed") .update()) { // Assert resetPassword link opened in new browser works even if client "account" not available resetPasswordLinkOpenedInNewBrowser(SystemClientUtil.SYSTEM_CLIENT_ID); } } @Test public void resetPasswordLinkNewBrowserSessionPreserveClient() throws IOException, MessagingException { loginPage.open(); loginPage.resetPassword(); resetPasswordPage.assertCurrent(); resetPasswordPage.changePassword("login-test"); loginPage.assertCurrent(); assertEquals("You should receive an email shortly with further instructions.", loginPage.getSuccessMessage()); assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message); driver2.navigate().to(changePasswordUrl.trim()); final WebElement newPassword = driver2.findElement(By.id("password-new")); newPassword.sendKeys("resetPassword"); final WebElement confirmPassword = driver2.findElement(By.id("password-confirm")); confirmPassword.sendKeys("resetPassword"); final WebElement submit = driver2.findElement(By.cssSelector("input[type=\"submit\"]")); submit.click(); assertThat(driver2.getCurrentUrl(), Matchers.containsString("client_id=test-app")); assertThat(driver2.getPageSource(), Matchers.containsString("Your account has been updated.")); } }
brat000012001/keycloak
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/ResetPasswordTest.java
Java
apache-2.0
44,355
package oauthserver import ( "io/ioutil" "os" "reflect" "testing" _ "github.com/openshift/origin/pkg/api/install" "github.com/openshift/origin/pkg/cmd/server/apis/config" "github.com/openshift/origin/pkg/cmd/server/apis/config/latest" ) func TestGetDefaultSessionSecrets(t *testing.T) { secrets, err := getSessionSecrets("") if err != nil { t.Errorf("Unexpected error: %v", err) } if len(secrets) != 2 { t.Errorf("Unexpected 2 secrets, got: %#v", secrets) } } func TestGetMissingSessionSecretsFile(t *testing.T) { _, err := getSessionSecrets("missing") if err == nil { t.Errorf("Expected error, got none") } } func TestGetInvalidSessionSecretsFile(t *testing.T) { tmpfile, err := ioutil.TempFile("", "invalid.yaml") if err != nil { t.Fatalf("unexpected error: %v", err) } defer os.Remove(tmpfile.Name()) ioutil.WriteFile(tmpfile.Name(), []byte("invalid content"), os.FileMode(0600)) _, err = getSessionSecrets(tmpfile.Name()) if err == nil { t.Errorf("Expected error, got none") } } func TestGetEmptySessionSecretsFile(t *testing.T) { tmpfile, err := ioutil.TempFile("", "empty.yaml") if err != nil { t.Fatalf("unexpected error: %v", err) } defer os.Remove(tmpfile.Name()) secrets := &config.SessionSecrets{ Secrets: []config.SessionSecret{}, } yaml, err := latest.WriteYAML(secrets) if err != nil { t.Errorf("Unexpected error: %v", err) } ioutil.WriteFile(tmpfile.Name(), []byte(yaml), os.FileMode(0600)) _, err = getSessionSecrets(tmpfile.Name()) if err == nil { t.Errorf("Expected error, got none") } } func TestGetValidSessionSecretsFile(t *testing.T) { tmpfile, err := ioutil.TempFile("", "valid.yaml") if err != nil { t.Fatalf("unexpected error: %v", err) } defer os.Remove(tmpfile.Name()) secrets := &config.SessionSecrets{ Secrets: []config.SessionSecret{ {Authentication: "a1", Encryption: "e1"}, {Authentication: "a2", Encryption: "e2"}, }, } expectedSecrets := []string{"a1", "e1", "a2", "e2"} yaml, err := latest.WriteYAML(secrets) if err != nil { t.Errorf("Unexpected error: %v", err) } ioutil.WriteFile(tmpfile.Name(), []byte(yaml), os.FileMode(0600)) readSecrets, err := getSessionSecrets(tmpfile.Name()) if err != nil { t.Errorf("Unexpected error: %v", err) } if !reflect.DeepEqual(readSecrets, expectedSecrets) { t.Errorf("Unexpected %v, got %v", expectedSecrets, readSecrets) } }
sg00dwin/origin
pkg/oauthserver/oauthserver/oauth_apiserver_test.go
GO
apache-2.0
2,401
<?php Route::get('settings', function () { return View::returnView('settings'); }); Route::post('/settings/changePassword', function () { Authentication::newPassword($_POST["current"], $_POST["repeat"], $_POST["new"]); return Router::redirect('settings'); });
sachaw/framework
controllers/settings.php
PHP
apache-2.0
273
# Dortmanna pinifolia (L.) Kuntze 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/Magnoliopsida/Asterales/Campanulaceae/Lobelia/Lobelia pinifolia/ Syn. Dortmanna pinifolia/README.md
Markdown
apache-2.0
188